Skip to main content

westend_runtime/
lib.rs

1// Copyright (C) Parity Technologies (UK) Ltd.
2// This file is part of Polkadot.
3
4// Polkadot is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// Polkadot is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with Polkadot.  If not, see <http://www.gnu.org/licenses/>.
16
17//! The Westend runtime. This can be compiled with `#[no_std]`, ready for Wasm.
18
19#![cfg_attr(not(feature = "std"), no_std)]
20// `#[frame_support::runtime]!` does a lot of recursion and requires us to increase the limit.
21#![recursion_limit = "512"]
22
23extern crate alloc;
24
25use alloc::{
26	collections::{btree_map::BTreeMap, vec_deque::VecDeque},
27	vec,
28	vec::Vec,
29};
30use codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen};
31use frame_election_provider_support::{bounds::ElectionBoundsBuilder, onchain, SequentialPhragmen};
32use frame_support::{
33	derive_impl,
34	dynamic_params::{dynamic_pallet_params, dynamic_params},
35	genesis_builder_helper::{build_state, get_preset},
36	parameter_types,
37	traits::{
38		fungible::HoldConsideration, tokens::UnityOrOuterConversion, AsEnsureOriginWithArg,
39		ConstU32, Contains, EitherOf, EitherOfDiverse, EnsureOriginWithArg, FromContains,
40		InstanceFilter, KeyOwnerProofSystem, LinearStoragePrice, Nothing, ProcessMessage,
41		ProcessMessageError, VariantCountOf, WithdrawReasons,
42	},
43	weights::{ConstantMultiplier, WeightMeter},
44	PalletId,
45};
46use frame_system::{EnsureRoot, EnsureSigned};
47use pallet_grandpa::{fg_primitives, AuthorityId as GrandpaId};
48use pallet_identity::legacy::IdentityInfo;
49use pallet_nomination_pools::PoolId;
50use pallet_session::historical as session_historical;
51use pallet_staking::UseValidatorsMap;
52use pallet_staking_async_ah_client as ah_client;
53use pallet_staking_async_rc_client as rc_client;
54use pallet_transaction_payment::{FeeDetails, FungibleAdapter, RuntimeDispatchInfo};
55use pallet_xcm::{EnsureXcm, IsVoiceOfBody};
56use polkadot_primitives::{
57	async_backing::Constraints, slashing, AccountId, AccountIndex, ApprovalVotingParams, Balance,
58	BlockNumber, CandidateEvent, CandidateHash,
59	CommittedCandidateReceiptV2 as CommittedCandidateReceipt, CoreIndex, CoreState, DisputeState,
60	ExecutorParams, GroupRotationInfo, Hash, Id as ParaId, InboundDownwardMessage,
61	InboundHrmpMessage, Moment, NodeFeatures, Nonce, OccupiedCoreAssumption,
62	PersistedValidationData, PvfCheckStatement, ScrapedOnChainVotes, SessionInfo, Signature,
63	ValidationCode, ValidationCodeHash, ValidatorId, ValidatorIndex, ValidatorSignature,
64	PARACHAIN_KEY_TYPE_ID,
65};
66use polkadot_runtime_common::{
67	assigned_slots, auctions, crowdloan,
68	elections::OnChainAccuracy,
69	identity_migrator, impl_runtime_weights,
70	impls::{
71		ContainsParts, LocatableAssetConverter, ToAuthor, VersionedLocatableAsset,
72		VersionedLocationConverter,
73	},
74	paras_registrar, paras_sudo_wrapper, prod_or_fast, slots,
75	traits::OnSwap,
76	BalanceToU256, BlockHashCount, BlockLength, SlowAdjustingFeeUpdate, U256ToBalance,
77};
78use polkadot_runtime_parachains::{
79	configuration as parachains_configuration,
80	configuration::ActiveConfigHrmpChannelSizeAndCapacityRatio,
81	coretime, disputes as parachains_disputes,
82	disputes::slashing as parachains_slashing,
83	dmp as parachains_dmp, hrmp as parachains_hrmp, inclusion as parachains_inclusion,
84	inclusion::{AggregateMessageOrigin, UmpQueueId},
85	initializer as parachains_initializer, on_demand as parachains_on_demand,
86	origin as parachains_origin, paras as parachains_paras,
87	paras_inherent as parachains_paras_inherent, reward_points as parachains_reward_points,
88	runtime_api_impl::{
89		v13 as parachains_runtime_api_impl, vstaging as parachains_staging_runtime_api_impl,
90	},
91	scheduler as parachains_scheduler, session_info as parachains_session_info,
92	shared as parachains_shared,
93};
94use scale_info::TypeInfo;
95use sp_authority_discovery::AuthorityId as AuthorityDiscoveryId;
96use sp_consensus_beefy::{
97	ecdsa_crypto::{AuthorityId as BeefyId, Signature as BeefySignature},
98	mmr::{BeefyDataProvider, MmrLeafVersion},
99};
100use sp_core::{ConstBool, ConstU8, ConstUint, OpaqueMetadata, H256};
101#[cfg(any(feature = "std", test))]
102pub use sp_runtime::BuildStorage;
103use sp_runtime::{
104	generic, impl_opaque_keys,
105	traits::{
106		AccountIdConversion, BlakeTwo256, Block as BlockT, ConvertInto, Get, IdentityLookup,
107		Keccak256, OpaqueKeys, SaturatedConversion, Verify,
108	},
109	transaction_validity::{TransactionPriority, TransactionSource, TransactionValidity},
110	ApplyExtrinsicResult, FixedU128, KeyTypeId, MultiSignature, MultiSigner, Percent,
111};
112use sp_staking::{EraIndex, SessionIndex};
113#[cfg(any(feature = "std", test))]
114use sp_version::NativeVersion;
115use sp_version::RuntimeVersion;
116use xcm::{
117	latest::prelude::*, Version as XcmVersion, VersionedAsset, VersionedAssetId, VersionedAssets,
118	VersionedLocation, VersionedXcm,
119};
120use xcm_builder::PayOverXcm;
121use xcm_runtime_apis::{
122	dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects},
123	fees::Error as XcmPaymentApiError,
124};
125
126pub use frame_system::Call as SystemCall;
127pub use pallet_balances::Call as BalancesCall;
128pub use pallet_election_provider_multi_phase::{Call as EPMCall, GeometricDepositBase};
129pub use pallet_timestamp::Call as TimestampCall;
130
131/// Constant values used within the runtime.
132use westend_runtime_constants::{
133	currency::*,
134	fee::*,
135	system_parachain::{coretime::TIMESLICE_PERIOD, ASSET_HUB_ID, BROKER_ID},
136	time::*,
137};
138
139mod bag_thresholds;
140mod genesis_config_presets;
141mod weights;
142pub mod xcm_config;
143
144// Implemented types.
145mod impls;
146use impls::ToParachainIdentityReaper;
147
148// Governance and configurations.
149pub mod governance;
150use governance::{
151	pallet_custom_origins, AuctionAdmin, FellowshipAdmin, GeneralAdmin, LeaseAdmin, StakingAdmin,
152	Treasurer, TreasurySpender,
153};
154use xcm_config::XcmConfig;
155
156#[cfg(test)]
157mod tests;
158
159impl_runtime_weights!(westend_runtime_constants);
160
161// Make the WASM binary available.
162#[cfg(feature = "std")]
163include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
164
165#[cfg(feature = "std")]
166pub mod fast_runtime_binary {
167	include!(concat!(env!("OUT_DIR"), "/fast_runtime_binary.rs"));
168}
169
170/// Runtime version (Westend).
171#[sp_version::runtime_version]
172pub const VERSION: RuntimeVersion = RuntimeVersion {
173	spec_name: alloc::borrow::Cow::Borrowed("westend"),
174	impl_name: alloc::borrow::Cow::Borrowed("parity-westend"),
175	authoring_version: 2,
176	spec_version: 1_022_001,
177	impl_version: 0,
178	apis: RUNTIME_API_VERSIONS,
179	transaction_version: 27,
180	system_version: 1,
181};
182
183/// The BABE epoch configuration at genesis.
184pub const BABE_GENESIS_EPOCH_CONFIG: sp_consensus_babe::BabeEpochConfiguration =
185	sp_consensus_babe::BabeEpochConfiguration {
186		c: PRIMARY_PROBABILITY,
187		allowed_slots: sp_consensus_babe::AllowedSlots::PrimaryAndSecondaryVRFSlots,
188	};
189
190/// Native version.
191#[cfg(any(feature = "std", test))]
192pub fn native_version() -> NativeVersion {
193	NativeVersion { runtime_version: VERSION, can_author_with: Default::default() }
194}
195
196/// A type to identify calls to the Identity pallet. These will be filtered to prevent invocation,
197/// locking the state of the pallet and preventing further updates to identities and sub-identities.
198/// The locked state will be the genesis state of a new system chain and then removed from the Relay
199/// Chain.
200pub struct IsIdentityCall;
201impl Contains<RuntimeCall> for IsIdentityCall {
202	fn contains(c: &RuntimeCall) -> bool {
203		matches!(c, RuntimeCall::Identity(_))
204	}
205}
206
207parameter_types! {
208	pub const Version: RuntimeVersion = VERSION;
209	pub const SS58Prefix: u8 = 42;
210}
211
212#[derive_impl(frame_system::config_preludes::RelayChainDefaultConfig)]
213impl frame_system::Config for Runtime {
214	type BlockWeights = BlockWeights;
215	type BlockLength = BlockLength;
216	type Nonce = Nonce;
217	type Hash = Hash;
218	type AccountId = AccountId;
219	type Block = Block;
220	type BlockHashCount = BlockHashCount;
221	type DbWeight = RocksDbWeight;
222	type Version = Version;
223	type AccountData = pallet_balances::AccountData<Balance>;
224	type SystemWeightInfo = weights::frame_system::WeightInfo<Runtime>;
225	type ExtensionsWeightInfo = weights::frame_system_extensions::WeightInfo<Runtime>;
226	type SS58Prefix = SS58Prefix;
227	type MaxConsumers = frame_support::traits::ConstU32<16>;
228	type MultiBlockMigrator = MultiBlockMigrations;
229	type SingleBlockMigrations = Migrations;
230}
231
232parameter_types! {
233	pub MaximumSchedulerWeight: frame_support::weights::Weight = Perbill::from_percent(80) *
234		BlockWeights::get().max_block;
235	pub const MaxScheduledPerBlock: u32 = 50;
236	pub const NoPreimagePostponement: Option<u32> = Some(10);
237}
238
239impl pallet_scheduler::Config for Runtime {
240	type RuntimeOrigin = RuntimeOrigin;
241	type RuntimeEvent = RuntimeEvent;
242	type PalletsOrigin = OriginCaller;
243	type RuntimeCall = RuntimeCall;
244	type MaximumWeight = MaximumSchedulerWeight;
245	// The goal of having ScheduleOrigin include AuctionAdmin is to allow the auctions track of
246	// OpenGov to schedule periodic auctions.
247	type ScheduleOrigin = EitherOf<EnsureRoot<AccountId>, AuctionAdmin>;
248	type MaxScheduledPerBlock = MaxScheduledPerBlock;
249	type WeightInfo = weights::pallet_scheduler::WeightInfo<Runtime>;
250	type OriginPrivilegeCmp = frame_support::traits::EqualPrivilegeOnly;
251	type Preimages = Preimage;
252	type BlockNumberProvider = System;
253}
254
255parameter_types! {
256	pub const PreimageBaseDeposit: Balance = deposit(2, 64);
257	pub const PreimageByteDeposit: Balance = deposit(0, 1);
258	pub const PreimageHoldReason: RuntimeHoldReason = RuntimeHoldReason::Preimage(pallet_preimage::HoldReason::Preimage);
259}
260
261/// Dynamic params that can be adjusted at runtime.
262#[dynamic_params(RuntimeParameters, pallet_parameters::Parameters::<Runtime>)]
263pub mod dynamic_params {
264	use super::*;
265
266	/// Parameters used to calculate era payouts, see
267	/// [`polkadot_runtime_common::impls::EraPayoutParams`].
268	#[dynamic_pallet_params]
269	#[codec(index = 0)]
270	pub mod inflation {
271		/// Minimum inflation rate used to calculate era payouts.
272		#[codec(index = 0)]
273		pub static MinInflation: Perquintill = Perquintill::from_rational(25u64, 1000u64);
274
275		/// Maximum inflation rate used to calculate era payouts.
276		#[codec(index = 1)]
277		pub static MaxInflation: Perquintill = Perquintill::from_rational(10u64, 100u64);
278
279		/// Ideal stake ratio used to calculate era payouts.
280		#[codec(index = 2)]
281		pub static IdealStake: Perquintill = Perquintill::from_rational(50u64, 100u64);
282
283		/// Falloff used to calculate era payouts.
284		#[codec(index = 3)]
285		pub static Falloff: Perquintill = Perquintill::from_rational(50u64, 1000u64);
286
287		/// Whether to use auction slots or not in the calculation of era payouts. If set to true,
288		/// the `legacy_auction_proportion` of 60% will be used in the calculation of era payouts.
289		#[codec(index = 4)]
290		pub static UseAuctionSlots: bool = false;
291	}
292}
293
294#[cfg(feature = "runtime-benchmarks")]
295impl Default for RuntimeParameters {
296	fn default() -> Self {
297		RuntimeParameters::Inflation(dynamic_params::inflation::Parameters::MinInflation(
298			dynamic_params::inflation::MinInflation,
299			Some(Perquintill::from_rational(25u64, 1000u64)),
300		))
301	}
302}
303
304impl pallet_parameters::Config for Runtime {
305	type RuntimeEvent = RuntimeEvent;
306	type RuntimeParameters = RuntimeParameters;
307	type AdminOrigin = DynamicParameterOrigin;
308	type WeightInfo = weights::pallet_parameters::WeightInfo<Runtime>;
309}
310
311/// Defines what origin can modify which dynamic parameters.
312pub struct DynamicParameterOrigin;
313impl EnsureOriginWithArg<RuntimeOrigin, RuntimeParametersKey> for DynamicParameterOrigin {
314	type Success = ();
315
316	fn try_origin(
317		origin: RuntimeOrigin,
318		key: &RuntimeParametersKey,
319	) -> Result<Self::Success, RuntimeOrigin> {
320		use crate::RuntimeParametersKey::*;
321
322		match key {
323			Inflation(_) => frame_system::ensure_root(origin.clone()),
324		}
325		.map_err(|_| origin)
326	}
327
328	#[cfg(feature = "runtime-benchmarks")]
329	fn try_successful_origin(_key: &RuntimeParametersKey) -> Result<RuntimeOrigin, ()> {
330		// Provide the origin for the parameter returned by `Default`:
331		Ok(RuntimeOrigin::root())
332	}
333}
334
335impl pallet_preimage::Config for Runtime {
336	type WeightInfo = weights::pallet_preimage::WeightInfo<Runtime>;
337	type RuntimeEvent = RuntimeEvent;
338	type Currency = Balances;
339	type ManagerOrigin = EnsureRoot<AccountId>;
340	type Consideration = HoldConsideration<
341		AccountId,
342		Balances,
343		PreimageHoldReason,
344		LinearStoragePrice<PreimageBaseDeposit, PreimageByteDeposit, Balance>,
345	>;
346}
347
348parameter_types! {
349	pub const EpochDuration: u64 = prod_or_fast!(
350		EPOCH_DURATION_IN_SLOTS as u64,
351		2 * MINUTES as u64
352	);
353	pub const ExpectedBlockTime: Moment = MILLISECS_PER_BLOCK;
354	pub const ReportLongevity: u64 =
355		BondingDuration::get() as u64 * SessionsPerEra::get() as u64 * EpochDuration::get();
356}
357
358impl pallet_babe::Config for Runtime {
359	type EpochDuration = EpochDuration;
360	type ExpectedBlockTime = ExpectedBlockTime;
361
362	// session module is the trigger
363	type EpochChangeTrigger = pallet_babe::ExternalTrigger;
364
365	type DisabledValidators = Session;
366
367	type WeightInfo = ();
368
369	type MaxAuthorities = MaxAuthorities;
370	type MaxNominators = MaxNominators;
371
372	type KeyOwnerProof = sp_session::MembershipProof;
373
374	type EquivocationReportSystem =
375		pallet_babe::EquivocationReportSystem<Self, Offences, Historical, ReportLongevity>;
376}
377
378parameter_types! {
379	pub const IndexDeposit: Balance = 100 * CENTS;
380}
381
382impl pallet_indices::Config for Runtime {
383	type AccountIndex = AccountIndex;
384	type Currency = Balances;
385	type Deposit = IndexDeposit;
386	type RuntimeEvent = RuntimeEvent;
387	type WeightInfo = weights::pallet_indices::WeightInfo<Runtime>;
388}
389
390parameter_types! {
391	pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
392	pub const MaxLocks: u32 = 50;
393	pub const MaxReserves: u32 = 50;
394}
395
396impl pallet_balances::Config for Runtime {
397	type Balance = Balance;
398	type DustRemoval = DapSatellite;
399	type RuntimeEvent = RuntimeEvent;
400	type ExistentialDeposit = ExistentialDeposit;
401	type AccountStore = System;
402	type MaxLocks = MaxLocks;
403	type MaxReserves = MaxReserves;
404	type ReserveIdentifier = [u8; 8];
405	type WeightInfo = weights::pallet_balances::WeightInfo<Runtime>;
406	type RuntimeHoldReason = RuntimeHoldReason;
407	type RuntimeFreezeReason = RuntimeFreezeReason;
408	type FreezeIdentifier = RuntimeFreezeReason;
409	type MaxFreezes = VariantCountOf<RuntimeFreezeReason>;
410	type DoneSlashHandler = ();
411}
412
413parameter_types! {
414	pub const BeefySetIdSessionEntries: u32 = BondingDuration::get() * SessionsPerEra::get();
415}
416
417impl pallet_beefy::Config for Runtime {
418	type BeefyId = BeefyId;
419	type MaxAuthorities = MaxAuthorities;
420	type MaxNominators = MaxNominators;
421	type MaxSetIdSessionEntries = BeefySetIdSessionEntries;
422	type OnNewValidatorSet = BeefyMmrLeaf;
423	type AncestryHelper = BeefyMmrLeaf;
424	type WeightInfo = ();
425	type KeyOwnerProof = sp_session::MembershipProof;
426	type EquivocationReportSystem =
427		pallet_beefy::EquivocationReportSystem<Self, Offences, Historical, ReportLongevity>;
428}
429
430impl pallet_mmr::Config for Runtime {
431	const INDEXING_PREFIX: &'static [u8] = mmr::INDEXING_PREFIX;
432	type Hashing = Keccak256;
433	type OnNewRoot = pallet_beefy_mmr::DepositBeefyDigest<Runtime>;
434	type LeafData = pallet_beefy_mmr::Pallet<Runtime>;
435	type BlockHashProvider = pallet_mmr::DefaultBlockHashProvider<Runtime>;
436	type WeightInfo = weights::pallet_mmr::WeightInfo<Runtime>;
437	#[cfg(feature = "runtime-benchmarks")]
438	type BenchmarkHelper = parachains_paras::benchmarking::mmr_setup::MmrSetup<Runtime>;
439}
440
441/// MMR helper types.
442mod mmr {
443	use super::Runtime;
444	pub use pallet_mmr::primitives::*;
445
446	pub type Leaf = <<Runtime as pallet_mmr::Config>::LeafData as LeafDataProvider>::LeafData;
447	pub type Hashing = <Runtime as pallet_mmr::Config>::Hashing;
448	pub type Hash = <Hashing as sp_runtime::traits::Hash>::Output;
449}
450
451parameter_types! {
452	pub LeafVersion: MmrLeafVersion = MmrLeafVersion::new(0, 0);
453}
454
455/// A BEEFY data provider that merkelizes all the parachain heads at the current block
456/// (sorted by their parachain id).
457pub struct ParaHeadsRootProvider;
458impl BeefyDataProvider<H256> for ParaHeadsRootProvider {
459	fn extra_data() -> H256 {
460		let para_heads: Vec<(u32, Vec<u8>)> =
461			parachains_paras::Pallet::<Runtime>::sorted_para_heads();
462		binary_merkle_tree::merkle_root::<mmr::Hashing, _>(
463			para_heads.into_iter().map(|pair| pair.encode()),
464		)
465		.into()
466	}
467}
468
469impl pallet_beefy_mmr::Config for Runtime {
470	type LeafVersion = LeafVersion;
471	type BeefyAuthorityToMerkleLeaf = pallet_beefy_mmr::BeefyEcdsaToEthereum;
472	type LeafExtra = H256;
473	type BeefyDataProvider = ParaHeadsRootProvider;
474	type WeightInfo = weights::pallet_beefy_mmr::WeightInfo<Runtime>;
475}
476
477parameter_types! {
478	pub const TransactionByteFee: Balance = 10 * MILLICENTS;
479	/// This value increases the priority of `Operational` transactions by adding
480	/// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.
481	pub const OperationalFeeMultiplier: u8 = 5;
482	/// Percentage of fees that go to DAP satellite.
483	/// The remainder goes to block author. Tips always go 100% to author.
484	pub const DapSatelliteFeePercent: Percent = Percent::from_percent(100);
485}
486
487/// Fee handler that splits fees between DAP satellite and block author.
488type DealWithFeesSatellite =
489	pallet_dap_satellite::DealWithFeesSplit<Runtime, DapSatelliteFeePercent, ToAuthor<Runtime>>;
490
491impl pallet_transaction_payment::Config for Runtime {
492	type RuntimeEvent = RuntimeEvent;
493	type OnChargeTransaction = FungibleAdapter<Balances, DealWithFeesSatellite>;
494	type OperationalFeeMultiplier = OperationalFeeMultiplier;
495	type WeightToFee = WeightToFee;
496	type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
497	type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
498	type WeightInfo = weights::pallet_transaction_payment::WeightInfo<Runtime>;
499}
500
501parameter_types! {
502	pub const MinimumPeriod: u64 = SLOT_DURATION / 2;
503}
504impl pallet_timestamp::Config for Runtime {
505	type Moment = u64;
506	type OnTimestampSet = Babe;
507	type MinimumPeriod = MinimumPeriod;
508	type WeightInfo = weights::pallet_timestamp::WeightInfo<Runtime>;
509}
510
511impl pallet_authorship::Config for Runtime {
512	type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Babe>;
513	type EventHandler = StakingAhClient;
514}
515
516parameter_types! {
517	pub const Period: BlockNumber = 10 * MINUTES;
518	pub const Offset: BlockNumber = 0;
519}
520
521impl_opaque_keys! {
522	pub struct SessionKeys {
523		pub grandpa: Grandpa,
524		pub babe: Babe,
525		pub para_validator: Initializer,
526		pub para_assignment: ParaSessionInfo,
527		pub authority_discovery: AuthorityDiscovery,
528		pub beefy: Beefy,
529	}
530}
531
532impl pallet_session::Config for Runtime {
533	type RuntimeEvent = RuntimeEvent;
534	type ValidatorId = AccountId;
535	type ValidatorIdOf = ConvertInto;
536	type ShouldEndSession = Babe;
537	type NextSessionRotation = Babe;
538	type SessionManager = session_historical::NoteHistoricalRoot<Self, StakingAhClient>;
539	type SessionHandler = <SessionKeys as OpaqueKeys>::KeyTypeIdProviders;
540	type Keys = SessionKeys;
541	type DisablingStrategy = pallet_session::disabling::UpToLimitWithReEnablingDisablingStrategy;
542	type WeightInfo = weights::pallet_session::WeightInfo<Runtime>;
543	type Currency = Balances;
544	type KeyDeposit = ();
545}
546
547impl pallet_session::historical::Config for Runtime {
548	type RuntimeEvent = RuntimeEvent;
549	type FullIdentification = sp_staking::Exposure<AccountId, Balance>;
550	type FullIdentificationOf = pallet_staking::DefaultExposureOf<Self>;
551}
552
553pub struct MaybeSignedPhase;
554
555impl Get<u32> for MaybeSignedPhase {
556	fn get() -> u32 {
557		// 1 day = 4 eras -> 1 week = 28 eras. We want to disable signed phase once a week to test
558		// the fallback unsigned phase is able to compute elections on Westend.
559		if pallet_staking::CurrentEra::<Runtime>::get().unwrap_or(1).is_multiple_of(28) {
560			0
561		} else {
562			SignedPhase::get()
563		}
564	}
565}
566
567parameter_types! {
568	// phase durations. 1/4 of the last session for each.
569	pub SignedPhase: u32 = prod_or_fast!(
570		EPOCH_DURATION_IN_SLOTS / 4,
571		(1 * MINUTES).min(EpochDuration::get().saturated_into::<u32>() / 2)
572	);
573	pub UnsignedPhase: u32 = prod_or_fast!(
574		EPOCH_DURATION_IN_SLOTS / 4,
575		(1 * MINUTES).min(EpochDuration::get().saturated_into::<u32>() / 2)
576	);
577
578	// signed config
579	pub const SignedMaxSubmissions: u32 = 128;
580	pub const SignedMaxRefunds: u32 = 128 / 4;
581	pub const SignedFixedDeposit: Balance = deposit(2, 0);
582	pub const SignedDepositIncreaseFactor: Percent = Percent::from_percent(10);
583	pub const SignedDepositByte: Balance = deposit(0, 10) / 1024;
584	// Each good submission will get 1 WND as reward
585	pub SignedRewardBase: Balance = 1 * UNITS;
586
587	// 1 hour session, 15 minutes unsigned phase, 4 offchain executions.
588	pub OffchainRepeat: BlockNumber = UnsignedPhase::get() / 4;
589
590	pub const MaxElectingVoters: u32 = 22_500;
591	/// We take the top 22500 nominators as electing voters and all of the validators as electable
592	/// targets. Whilst this is the case, we cannot and shall not increase the size of the
593	/// validator intentions.
594	pub ElectionBounds: frame_election_provider_support::bounds::ElectionBounds =
595		ElectionBoundsBuilder::default().voters_count(MaxElectingVoters::get().into()).build();
596	// Maximum winners that can be chosen as active validators
597	pub const MaxActiveValidators: u32 = 1000;
598	// One page only, fill the whole page with the `MaxActiveValidators`.
599	pub const MaxWinnersPerPage: u32 = MaxActiveValidators::get();
600	// Unbonded, thus the max backers per winner maps to the max electing voters limit.
601	pub const MaxBackersPerWinner: u32 = MaxElectingVoters::get();
602}
603
604frame_election_provider_support::generate_solution_type!(
605	#[compact]
606	pub struct NposCompactSolution16::<
607		VoterIndex = u32,
608		TargetIndex = u16,
609		Accuracy = sp_runtime::PerU16,
610		MaxVoters = MaxElectingVoters,
611	>(16)
612);
613
614pub struct OnChainSeqPhragmen;
615impl onchain::Config for OnChainSeqPhragmen {
616	type Sort = ConstBool<true>;
617	type System = Runtime;
618	type Solver = SequentialPhragmen<AccountId, OnChainAccuracy>;
619	type DataProvider = Staking;
620	type WeightInfo = weights::frame_election_provider_support::WeightInfo<Runtime>;
621	type Bounds = ElectionBounds;
622	type MaxBackersPerWinner = MaxBackersPerWinner;
623	type MaxWinnersPerPage = MaxWinnersPerPage;
624}
625
626impl pallet_election_provider_multi_phase::MinerConfig for Runtime {
627	type AccountId = AccountId;
628	type MaxLength = OffchainSolutionLengthLimit;
629	type MaxWeight = OffchainSolutionWeightLimit;
630	type Solution = NposCompactSolution16;
631	type MaxVotesPerVoter = <
632    <Self as pallet_election_provider_multi_phase::Config>::DataProvider
633    as
634    frame_election_provider_support::ElectionDataProvider
635    >::MaxVotesPerVoter;
636	type MaxBackersPerWinner = MaxBackersPerWinner;
637	type MaxWinners = MaxWinnersPerPage;
638
639	// The unsigned submissions have to respect the weight of the submit_unsigned call, thus their
640	// weight estimate function is wired to this call's weight.
641	fn solution_weight(v: u32, t: u32, a: u32, d: u32) -> Weight {
642		<
643        <Self as pallet_election_provider_multi_phase::Config>::WeightInfo
644        as
645        pallet_election_provider_multi_phase::WeightInfo
646        >::submit_unsigned(v, t, a, d)
647	}
648}
649
650impl pallet_election_provider_multi_phase::Config for Runtime {
651	type RuntimeEvent = RuntimeEvent;
652	type Currency = Balances;
653	type EstimateCallFee = TransactionPayment;
654	type SignedPhase = MaybeSignedPhase;
655	type UnsignedPhase = UnsignedPhase;
656	type SignedMaxSubmissions = SignedMaxSubmissions;
657	type SignedMaxRefunds = SignedMaxRefunds;
658	type SignedRewardBase = SignedRewardBase;
659	type SignedDepositBase =
660		GeometricDepositBase<Balance, SignedFixedDeposit, SignedDepositIncreaseFactor>;
661	type SignedDepositByte = SignedDepositByte;
662	type SignedDepositWeight = ();
663	type SignedMaxWeight =
664		<Self::MinerConfig as pallet_election_provider_multi_phase::MinerConfig>::MaxWeight;
665	type MinerConfig = Self;
666	type SlashHandler = (); // burn slashes
667	type RewardHandler = (); // rewards are minted from the void
668	type BetterSignedThreshold = ();
669	type OffchainRepeat = OffchainRepeat;
670	type MinerTxPriority = NposSolutionPriority;
671	type MaxWinners = MaxWinnersPerPage;
672	type MaxBackersPerWinner = MaxBackersPerWinner;
673	type DataProvider = Staking;
674	#[cfg(any(feature = "fast-runtime", feature = "runtime-benchmarks"))]
675	type Fallback = onchain::OnChainExecution<OnChainSeqPhragmen>;
676	#[cfg(not(any(feature = "fast-runtime", feature = "runtime-benchmarks")))]
677	type Fallback = frame_election_provider_support::NoElection<(
678		AccountId,
679		BlockNumber,
680		Staking,
681		MaxWinnersPerPage,
682		MaxBackersPerWinner,
683	)>;
684	type GovernanceFallback = onchain::OnChainExecution<OnChainSeqPhragmen>;
685	type Solver = SequentialPhragmen<
686		AccountId,
687		pallet_election_provider_multi_phase::SolutionAccuracyOf<Self>,
688		(),
689	>;
690	type BenchmarkingConfig = polkadot_runtime_common::elections::BenchmarkConfig;
691	type ForceOrigin = EnsureRoot<AccountId>;
692	type WeightInfo = weights::pallet_election_provider_multi_phase::WeightInfo<Self>;
693	type ElectionBounds = ElectionBounds;
694}
695
696parameter_types! {
697	pub const BagThresholds: &'static [u64] = &bag_thresholds::THRESHOLDS;
698	pub const AutoRebagNumber: u32 = 10;
699}
700
701type VoterBagsListInstance = pallet_bags_list::Instance1;
702impl pallet_bags_list::Config<VoterBagsListInstance> for Runtime {
703	type RuntimeEvent = RuntimeEvent;
704	type WeightInfo = weights::pallet_bags_list::WeightInfo<Runtime>;
705	type ScoreProvider = Staking;
706	type BagThresholds = BagThresholds;
707	type MaxAutoRebagPerBlock = AutoRebagNumber;
708	type Score = sp_npos_elections::VoteWeight;
709}
710
711pub struct EraPayout;
712impl pallet_staking::EraPayout<Balance> for EraPayout {
713	fn era_payout(
714		_total_staked: Balance,
715		_total_issuance: Balance,
716		era_duration_millis: u64,
717	) -> (Balance, Balance) {
718		const MILLISECONDS_PER_YEAR: u64 = (1000 * 3600 * 24 * 36525) / 100;
719		// A normal-sized era will have 1 / 365.25 here:
720		let relative_era_len =
721			FixedU128::from_rational(era_duration_millis.into(), MILLISECONDS_PER_YEAR.into());
722
723		// Fixed total TI that we use as baseline for the issuance.
724		let fixed_total_issuance: i128 = 5_216_342_402_773_185_773;
725		let fixed_inflation_rate = FixedU128::from_rational(8, 100);
726		let yearly_emission = fixed_inflation_rate.saturating_mul_int(fixed_total_issuance);
727
728		let era_emission = relative_era_len.saturating_mul_int(yearly_emission);
729		// 15% to treasury, as per Polkadot ref 1139.
730		let to_treasury = FixedU128::from_rational(15, 100).saturating_mul_int(era_emission);
731		let to_stakers = era_emission.saturating_sub(to_treasury);
732
733		(to_stakers.saturated_into(), to_treasury.saturated_into())
734	}
735}
736
737parameter_types! {
738	// Six sessions in an era (6 hours).
739	pub const SessionsPerEra: SessionIndex = prod_or_fast!(6, 2);
740	// 2 eras for unbonding (12 hours).
741	pub const BondingDuration: EraIndex = 2;
742	// 1 era in which slashes can be cancelled (6 hours).
743	pub const SlashDeferDuration: EraIndex = 1;
744	pub const MaxExposurePageSize: u32 = 64;
745	// Note: this is not really correct as Max Nominators is (MaxExposurePageSize * page_count) but
746	// this is an unbounded number. We just set it to a reasonably high value, 1 full page
747	// of nominators.
748	pub const MaxNominators: u32 = 64;
749	pub const MaxNominations: u32 = <NposCompactSolution16 as frame_election_provider_support::NposSolution>::LIMIT as u32;
750	pub const MaxControllersInDeprecationBatch: u32 = 751;
751}
752
753impl pallet_staking::Config for Runtime {
754	type OldCurrency = Balances;
755	type Currency = Balances;
756	type CurrencyBalance = Balance;
757	type RuntimeHoldReason = RuntimeHoldReason;
758	type UnixTime = Timestamp;
759	// Westend's total issuance is already more than `u64::MAX`, this will work better.
760	type CurrencyToVote = sp_staking::currency_to_vote::SaturatingCurrencyToVote;
761	type RewardRemainder = ();
762	type RuntimeEvent = RuntimeEvent;
763	type Slash = ();
764	type Reward = ();
765	type SessionsPerEra = SessionsPerEra;
766	type BondingDuration = BondingDuration;
767	type SlashDeferDuration = SlashDeferDuration;
768	type AdminOrigin = EitherOf<EnsureRoot<AccountId>, StakingAdmin>;
769	type SessionInterface = Self;
770	type EraPayout = EraPayout;
771	type MaxExposurePageSize = MaxExposurePageSize;
772	type NextNewSession = Session;
773	type ElectionProvider = ElectionProviderMultiPhase;
774	type GenesisElectionProvider = onchain::OnChainExecution<OnChainSeqPhragmen>;
775	type VoterList = VoterList;
776	type TargetList = UseValidatorsMap<Self>;
777	type MaxValidatorSet = MaxActiveValidators;
778	type NominationsQuota = pallet_staking::FixedNominationsQuota<{ MaxNominations::get() }>;
779	type MaxUnlockingChunks = frame_support::traits::ConstU32<32>;
780	type HistoryDepth = frame_support::traits::ConstU32<84>;
781	type MaxControllersInDeprecationBatch = MaxControllersInDeprecationBatch;
782	type BenchmarkingConfig = polkadot_runtime_common::StakingBenchmarkingConfig;
783	type EventListeners = (NominationPools, DelegatedStaking);
784	type WeightInfo = weights::pallet_staking::WeightInfo<Runtime>;
785	// Genesis benchmarking setup needs this until we remove the pallet completely.
786	#[cfg(not(feature = "on-chain-release-build"))]
787	type Filter = Nothing;
788	#[cfg(feature = "on-chain-release-build")]
789	type Filter = frame_support::traits::Everything;
790}
791
792#[derive(Encode, Decode)]
793enum AssetHubRuntimePallets<AccountId> {
794	// Audit: `StakingRcClient` in asset-hub-westend
795	#[codec(index = 89)]
796	RcClient(RcClientCalls<AccountId>),
797}
798
799#[derive(Encode, Decode)]
800enum RcClientCalls<AccountId> {
801	#[codec(index = 0)]
802	RelaySessionReport(rc_client::SessionReport<AccountId>),
803	#[codec(index = 1)]
804	RelayNewOffencePaged(Vec<(SessionIndex, rc_client::Offence<AccountId>)>),
805}
806
807pub struct AssetHubLocation;
808impl Get<Location> for AssetHubLocation {
809	fn get() -> Location {
810		Location::new(0, [Junction::Parachain(ASSET_HUB_ID)])
811	}
812}
813
814pub struct EnsureAssetHub;
815impl frame_support::traits::EnsureOrigin<RuntimeOrigin> for EnsureAssetHub {
816	type Success = ();
817	fn try_origin(o: RuntimeOrigin) -> Result<Self::Success, RuntimeOrigin> {
818		match <RuntimeOrigin as Into<Result<parachains_origin::Origin, RuntimeOrigin>>>::into(
819			o.clone(),
820		) {
821			Ok(parachains_origin::Origin::Parachain(id)) if id == ASSET_HUB_ID.into() => Ok(()),
822			_ => Err(o),
823		}
824	}
825
826	#[cfg(feature = "runtime-benchmarks")]
827	fn try_successful_origin() -> Result<RuntimeOrigin, ()> {
828		Ok(RuntimeOrigin::root())
829	}
830}
831
832pub struct SessionReportToXcm;
833impl sp_runtime::traits::Convert<rc_client::SessionReport<AccountId>, Xcm<()>>
834	for SessionReportToXcm
835{
836	fn convert(a: rc_client::SessionReport<AccountId>) -> Xcm<()> {
837		Xcm(vec![
838			Instruction::UnpaidExecution {
839				weight_limit: WeightLimit::Unlimited,
840				check_origin: None,
841			},
842			Instruction::Transact {
843				origin_kind: OriginKind::Superuser,
844				fallback_max_weight: None,
845				call: AssetHubRuntimePallets::RcClient(RcClientCalls::RelaySessionReport(a))
846					.encode()
847					.into(),
848			},
849		])
850	}
851}
852
853pub struct QueuedOffenceToXcm;
854impl sp_runtime::traits::Convert<Vec<ah_client::QueuedOffenceOf<Runtime>>, Xcm<()>>
855	for QueuedOffenceToXcm
856{
857	fn convert(offences: Vec<ah_client::QueuedOffenceOf<Runtime>>) -> Xcm<()> {
858		Xcm(vec![
859			Instruction::UnpaidExecution {
860				weight_limit: WeightLimit::Unlimited,
861				check_origin: None,
862			},
863			Instruction::Transact {
864				origin_kind: OriginKind::Superuser,
865				fallback_max_weight: None,
866				call: AssetHubRuntimePallets::RcClient(RcClientCalls::RelayNewOffencePaged(
867					offences,
868				))
869				.encode()
870				.into(),
871			},
872		])
873	}
874}
875
876pub struct StakingXcmToAssetHub;
877impl ah_client::SendToAssetHub for StakingXcmToAssetHub {
878	type AccountId = AccountId;
879
880	fn relay_session_report(
881		session_report: rc_client::SessionReport<Self::AccountId>,
882	) -> Result<(), ()> {
883		rc_client::XCMSender::<
884			xcm_config::XcmRouter,
885			AssetHubLocation,
886			rc_client::SessionReport<AccountId>,
887			SessionReportToXcm,
888		>::send(session_report)
889	}
890
891	fn relay_new_offence_paged(
892		offences: Vec<ah_client::QueuedOffenceOf<Runtime>>,
893	) -> Result<(), ()> {
894		rc_client::XCMSender::<
895			xcm_config::XcmRouter,
896			AssetHubLocation,
897			Vec<ah_client::QueuedOffenceOf<Runtime>>,
898			QueuedOffenceToXcm,
899		>::send(offences)
900	}
901}
902
903impl ah_client::Config for Runtime {
904	type CurrencyBalance = Balance;
905	type AssetHubOrigin =
906		frame_support::traits::EitherOfDiverse<EnsureRoot<AccountId>, EnsureAssetHub>;
907	type AdminOrigin = EnsureRoot<AccountId>;
908	type SessionInterface = Session;
909	type SendToAssetHub = StakingXcmToAssetHub;
910	type MinimumValidatorSetSize = ConstU32<1>;
911	type UnixTime = Timestamp;
912	type PointsPerBlock = ConstU32<20>;
913	type MaxOffenceBatchSize = ConstU32<50>;
914	type Fallback = Staking;
915	type MaximumValidatorsWithPoints = ConstU32<{ MaxActiveValidators::get() * 4 }>;
916	type MaxSessionReportRetries = ConstU32<5>;
917}
918
919impl pallet_fast_unstake::Config for Runtime {
920	type RuntimeEvent = RuntimeEvent;
921	type Currency = Balances;
922	type BatchSize = frame_support::traits::ConstU32<64>;
923	type Deposit = frame_support::traits::ConstU128<{ UNITS }>;
924	type ControlOrigin = EnsureRoot<AccountId>;
925	type Staking = Staking;
926	type MaxErasToCheckPerBlock = ConstU32<1>;
927	type WeightInfo = weights::pallet_fast_unstake::WeightInfo<Runtime>;
928}
929
930parameter_types! {
931	pub const SpendPeriod: BlockNumber = 6 * DAYS;
932	pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry");
933	pub const PayoutSpendPeriod: BlockNumber = 30 * DAYS;
934	// The asset's interior location for the paying account. This is the Treasury
935	// pallet instance (which sits at index 37).
936	pub TreasuryInteriorLocation: InteriorLocation = PalletInstance(37).into();
937
938	pub const TipCountdown: BlockNumber = 1 * DAYS;
939	pub const TipFindersFee: Percent = Percent::from_percent(20);
940	pub const TipReportDepositBase: Balance = 100 * CENTS;
941	pub const DataDepositPerByte: Balance = 1 * CENTS;
942	pub const MaxApprovals: u32 = 100;
943	pub const MaxAuthorities: u32 = 100_000;
944	pub const MaxKeys: u32 = 10_000;
945	pub const MaxPeerInHeartbeats: u32 = 10_000;
946	pub const MaxBalance: Balance = Balance::max_value();
947}
948
949impl pallet_treasury::Config for Runtime {
950	type PalletId = TreasuryPalletId;
951	type Currency = Balances;
952	type RejectOrigin = EitherOfDiverse<EnsureRoot<AccountId>, Treasurer>;
953	type RuntimeEvent = RuntimeEvent;
954	type SpendPeriod = SpendPeriod;
955	// NOTE: Treasury burn is currently disabled. If ever enabled (`Burn > 0`), wire
956	// `BurnDestination` to a DAP satellite so burned funds are not destroyed.
957	type Burn = ();
958	type BurnDestination = ();
959	type MaxApprovals = MaxApprovals;
960	type WeightInfo = weights::pallet_treasury::WeightInfo<Runtime>;
961	type SpendFunds = ();
962	type SpendOrigin = TreasurySpender;
963	type AssetKind = VersionedLocatableAsset;
964	type Beneficiary = VersionedLocation;
965	type BeneficiaryLookup = IdentityLookup<Self::Beneficiary>;
966	type Paymaster = PayOverXcm<
967		TreasuryInteriorLocation,
968		crate::xcm_config::XcmConfig,
969		crate::XcmPallet,
970		ConstU32<{ 6 * HOURS }>,
971		Self::Beneficiary,
972		Self::AssetKind,
973		LocatableAssetConverter,
974		VersionedLocationConverter,
975	>;
976	type BalanceConverter = UnityOrOuterConversion<
977		ContainsParts<
978			FromContains<
979				xcm_builder::IsChildSystemParachain<ParaId>,
980				xcm_builder::IsParentsOnly<ConstU8<1>>,
981			>,
982		>,
983		AssetRate,
984	>;
985	type PayoutPeriod = PayoutSpendPeriod;
986	type BlockNumberProvider = System;
987	#[cfg(feature = "runtime-benchmarks")]
988	type BenchmarkHelper = polkadot_runtime_common::impls::benchmarks::TreasuryArguments;
989}
990
991impl pallet_offences::Config for Runtime {
992	type RuntimeEvent = RuntimeEvent;
993	type IdentificationTuple = session_historical::IdentificationTuple<Self>;
994	type OnOffenceHandler = StakingAhClient;
995}
996
997impl pallet_authority_discovery::Config for Runtime {
998	type MaxAuthorities = MaxAuthorities;
999}
1000
1001parameter_types! {
1002	pub const NposSolutionPriority: TransactionPriority = TransactionPriority::max_value() / 2;
1003}
1004
1005parameter_types! {
1006	pub const MaxSetIdSessionEntries: u32 = BondingDuration::get() * SessionsPerEra::get();
1007}
1008
1009impl pallet_grandpa::Config for Runtime {
1010	type RuntimeEvent = RuntimeEvent;
1011
1012	type WeightInfo = ();
1013	type MaxAuthorities = MaxAuthorities;
1014	type MaxNominators = MaxNominators;
1015	type MaxSetIdSessionEntries = MaxSetIdSessionEntries;
1016
1017	type KeyOwnerProof = sp_session::MembershipProof;
1018
1019	type EquivocationReportSystem =
1020		pallet_grandpa::EquivocationReportSystem<Self, Offences, Historical, ReportLongevity>;
1021}
1022
1023impl frame_system::offchain::SigningTypes for Runtime {
1024	type Public = <Signature as Verify>::Signer;
1025	type Signature = Signature;
1026}
1027
1028impl<C> frame_system::offchain::CreateTransactionBase<C> for Runtime
1029where
1030	RuntimeCall: From<C>,
1031{
1032	type RuntimeCall = RuntimeCall;
1033	type Extrinsic = UncheckedExtrinsic;
1034}
1035
1036impl<LocalCall> frame_system::offchain::CreateTransaction<LocalCall> for Runtime
1037where
1038	RuntimeCall: From<LocalCall>,
1039{
1040	type Extension = TxExtension;
1041
1042	fn create_transaction(call: RuntimeCall, extension: TxExtension) -> UncheckedExtrinsic {
1043		UncheckedExtrinsic::new_transaction(call, extension)
1044	}
1045}
1046
1047/// Submits a transaction with the node's public and signature type. Adheres to the signed extension
1048/// format of the chain.
1049impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for Runtime
1050where
1051	RuntimeCall: From<LocalCall>,
1052{
1053	fn create_signed_transaction<
1054		C: frame_system::offchain::AppCrypto<Self::Public, Self::Signature>,
1055	>(
1056		call: RuntimeCall,
1057		public: <Signature as Verify>::Signer,
1058		account: AccountId,
1059		nonce: <Runtime as frame_system::Config>::Nonce,
1060	) -> Option<UncheckedExtrinsic> {
1061		use sp_runtime::traits::StaticLookup;
1062		// take the biggest period possible.
1063		let period =
1064			BlockHashCount::get().checked_next_power_of_two().map(|c| c / 2).unwrap_or(2) as u64;
1065
1066		let current_block = System::block_number()
1067			.saturated_into::<u64>()
1068			// The `System::block_number` is initialized with `n+1`,
1069			// so the actual block number is `n`.
1070			.saturating_sub(1);
1071		let tip = 0;
1072		let tx_ext: TxExtension = (
1073			frame_system::AuthorizeCall::<Runtime>::new(),
1074			frame_system::CheckNonZeroSender::<Runtime>::new(),
1075			frame_system::CheckSpecVersion::<Runtime>::new(),
1076			frame_system::CheckTxVersion::<Runtime>::new(),
1077			frame_system::CheckGenesis::<Runtime>::new(),
1078			frame_system::CheckMortality::<Runtime>::from(generic::Era::mortal(
1079				period,
1080				current_block,
1081			)),
1082			frame_system::CheckNonce::<Runtime>::from(nonce),
1083			frame_system::CheckWeight::<Runtime>::new(),
1084			pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(tip),
1085			frame_metadata_hash_extension::CheckMetadataHash::<Runtime>::new(true),
1086			frame_system::WeightReclaim::<Runtime>::new(),
1087		)
1088			.into();
1089		let raw_payload = SignedPayload::new(call, tx_ext)
1090			.map_err(|e| {
1091				log::warn!("Unable to create signed payload: {:?}", e);
1092			})
1093			.ok()?;
1094		let signature = raw_payload.using_encoded(|payload| C::sign(payload, public))?;
1095		let (call, tx_ext, _) = raw_payload.deconstruct();
1096		let address = <Runtime as frame_system::Config>::Lookup::unlookup(account);
1097		let transaction = UncheckedExtrinsic::new_signed(call, address, signature, tx_ext);
1098		Some(transaction)
1099	}
1100}
1101
1102impl<LocalCall> frame_system::offchain::CreateBare<LocalCall> for Runtime
1103where
1104	RuntimeCall: From<LocalCall>,
1105{
1106	fn create_bare(call: RuntimeCall) -> UncheckedExtrinsic {
1107		UncheckedExtrinsic::new_bare(call)
1108	}
1109}
1110
1111impl<LocalCall> frame_system::offchain::CreateAuthorizedTransaction<LocalCall> for Runtime
1112where
1113	RuntimeCall: From<LocalCall>,
1114{
1115	fn create_extension() -> Self::Extension {
1116		(
1117			frame_system::AuthorizeCall::<Runtime>::new(),
1118			frame_system::CheckNonZeroSender::<Runtime>::new(),
1119			frame_system::CheckSpecVersion::<Runtime>::new(),
1120			frame_system::CheckTxVersion::<Runtime>::new(),
1121			frame_system::CheckGenesis::<Runtime>::new(),
1122			frame_system::CheckMortality::<Runtime>::from(generic::Era::Immortal),
1123			frame_system::CheckNonce::<Runtime>::from(0),
1124			frame_system::CheckWeight::<Runtime>::new(),
1125			pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(0),
1126			frame_metadata_hash_extension::CheckMetadataHash::<Runtime>::new(false),
1127			frame_system::WeightReclaim::<Runtime>::new(),
1128		)
1129	}
1130}
1131
1132parameter_types! {
1133	// Minimum 100 bytes/KSM deposited (1 CENT/byte)
1134	pub const BasicDeposit: Balance = 1000 * CENTS;       // 258 bytes on-chain
1135	pub const ByteDeposit: Balance = deposit(0, 1);
1136	pub const UsernameDeposit: Balance = deposit(0, 32);
1137	pub const SubAccountDeposit: Balance = 200 * CENTS;   // 53 bytes on-chain
1138	pub const MaxSubAccounts: u32 = 100;
1139	pub const MaxAdditionalFields: u32 = 100;
1140	pub const MaxRegistrars: u32 = 20;
1141}
1142
1143impl pallet_identity::Config for Runtime {
1144	type RuntimeEvent = RuntimeEvent;
1145	type Currency = Balances;
1146	type Slashed = ();
1147	type BasicDeposit = BasicDeposit;
1148	type ByteDeposit = ByteDeposit;
1149	type UsernameDeposit = UsernameDeposit;
1150	type SubAccountDeposit = SubAccountDeposit;
1151	type MaxSubAccounts = MaxSubAccounts;
1152	type IdentityInformation = IdentityInfo<MaxAdditionalFields>;
1153	type MaxRegistrars = MaxRegistrars;
1154	type ForceOrigin = EitherOf<EnsureRoot<Self::AccountId>, GeneralAdmin>;
1155	type RegistrarOrigin = EitherOf<EnsureRoot<Self::AccountId>, GeneralAdmin>;
1156	type OffchainSignature = Signature;
1157	type SigningPublicKey = <Signature as Verify>::Signer;
1158	type UsernameAuthorityOrigin = EnsureRoot<Self::AccountId>;
1159	type PendingUsernameExpiration = ConstU32<{ 7 * DAYS }>;
1160	type UsernameGracePeriod = ConstU32<{ 30 * DAYS }>;
1161	type MaxSuffixLength = ConstU32<7>;
1162	type MaxUsernameLength = ConstU32<32>;
1163	#[cfg(feature = "runtime-benchmarks")]
1164	type BenchmarkHelper = ();
1165	type WeightInfo = weights::pallet_identity::WeightInfo<Runtime>;
1166}
1167
1168impl pallet_utility::Config for Runtime {
1169	type RuntimeEvent = RuntimeEvent;
1170	type RuntimeCall = RuntimeCall;
1171	type PalletsOrigin = OriginCaller;
1172	type WeightInfo = weights::pallet_utility::WeightInfo<Runtime>;
1173}
1174
1175parameter_types! {
1176	// One storage item; key size is 32; value is size 4+4+16+32 bytes = 56 bytes.
1177	pub const DepositBase: Balance = deposit(1, 88);
1178	// Additional storage item size of 32 bytes.
1179	pub const DepositFactor: Balance = deposit(0, 32);
1180	pub const MaxSignatories: u32 = 100;
1181}
1182
1183impl pallet_multisig::Config for Runtime {
1184	type RuntimeEvent = RuntimeEvent;
1185	type RuntimeCall = RuntimeCall;
1186	type Currency = Balances;
1187	type DepositBase = DepositBase;
1188	type DepositFactor = DepositFactor;
1189	type MaxSignatories = MaxSignatories;
1190	type WeightInfo = weights::pallet_multisig::WeightInfo<Runtime>;
1191	type BlockNumberProvider = frame_system::Pallet<Runtime>;
1192}
1193
1194parameter_types! {
1195	pub const ConfigDepositBase: Balance = 500 * CENTS;
1196	pub const FriendDepositFactor: Balance = 50 * CENTS;
1197	pub const MaxFriends: u16 = 9;
1198	pub const RecoveryDeposit: Balance = 500 * CENTS;
1199}
1200
1201impl pallet_recovery::Config for Runtime {
1202	type RuntimeEvent = RuntimeEvent;
1203	type WeightInfo = ();
1204	type RuntimeCall = RuntimeCall;
1205	type BlockNumberProvider = System;
1206	type Currency = Balances;
1207	type ConfigDepositBase = ConfigDepositBase;
1208	type FriendDepositFactor = FriendDepositFactor;
1209	type MaxFriends = MaxFriends;
1210	type RecoveryDeposit = RecoveryDeposit;
1211}
1212
1213parameter_types! {
1214	pub const MinVestedTransfer: Balance = 100 * CENTS;
1215	pub UnvestedFundsAllowedWithdrawReasons: WithdrawReasons =
1216		WithdrawReasons::except(WithdrawReasons::TRANSFER | WithdrawReasons::RESERVE);
1217}
1218
1219impl pallet_vesting::Config for Runtime {
1220	type RuntimeEvent = RuntimeEvent;
1221	type Currency = Balances;
1222	type BlockNumberToBalance = ConvertInto;
1223	type MinVestedTransfer = MinVestedTransfer;
1224	type WeightInfo = weights::pallet_vesting::WeightInfo<Runtime>;
1225	type UnvestedFundsAllowedWithdrawReasons = UnvestedFundsAllowedWithdrawReasons;
1226	type BlockNumberProvider = System;
1227	const MAX_VESTING_SCHEDULES: u32 = 28;
1228}
1229
1230impl pallet_sudo::Config for Runtime {
1231	type RuntimeEvent = RuntimeEvent;
1232	type RuntimeCall = RuntimeCall;
1233	type WeightInfo = weights::pallet_sudo::WeightInfo<Runtime>;
1234}
1235
1236parameter_types! {
1237	// One storage item; key size 32, value size 8; .
1238	pub const ProxyDepositBase: Balance = deposit(1, 8);
1239	// Additional storage item size of 33 bytes.
1240	pub const ProxyDepositFactor: Balance = deposit(0, 33);
1241	pub const MaxProxies: u16 = 32;
1242	pub const AnnouncementDepositBase: Balance = deposit(1, 8);
1243	pub const AnnouncementDepositFactor: Balance = deposit(0, 66);
1244	pub const MaxPending: u16 = 32;
1245}
1246
1247/// The type used to represent the kinds of proxying allowed.
1248#[derive(
1249	Copy,
1250	Clone,
1251	Eq,
1252	PartialEq,
1253	Ord,
1254	PartialOrd,
1255	Encode,
1256	Decode,
1257	DecodeWithMemTracking,
1258	Debug,
1259	MaxEncodedLen,
1260	TypeInfo,
1261)]
1262pub enum ProxyType {
1263	Any,
1264	NonTransfer,
1265	Governance,
1266	Staking,
1267	SudoBalances,
1268	IdentityJudgement,
1269	CancelProxy,
1270	Auction,
1271	NominationPools,
1272	ParaRegistration,
1273}
1274impl Default for ProxyType {
1275	fn default() -> Self {
1276		Self::Any
1277	}
1278}
1279impl InstanceFilter<RuntimeCall> for ProxyType {
1280	fn filter(&self, c: &RuntimeCall) -> bool {
1281		match self {
1282			ProxyType::Any => true,
1283			ProxyType::NonTransfer => matches!(
1284				c,
1285				RuntimeCall::System(..) |
1286				RuntimeCall::Babe(..) |
1287				RuntimeCall::Timestamp(..) |
1288				RuntimeCall::Indices(pallet_indices::Call::claim{..}) |
1289				RuntimeCall::Indices(pallet_indices::Call::free{..}) |
1290				RuntimeCall::Indices(pallet_indices::Call::freeze{..}) |
1291				// Specifically omitting Indices `transfer`, `force_transfer`
1292				// Specifically omitting the entire Balances pallet
1293				RuntimeCall::Staking(..) |
1294				RuntimeCall::Session(..) |
1295				RuntimeCall::Grandpa(..) |
1296				RuntimeCall::Utility(..) |
1297				RuntimeCall::Identity(..) |
1298				RuntimeCall::ConvictionVoting(..) |
1299				RuntimeCall::Referenda(..) |
1300				RuntimeCall::Whitelist(..) |
1301				RuntimeCall::Recovery(pallet_recovery::Call::as_recovered{..}) |
1302				RuntimeCall::Recovery(pallet_recovery::Call::vouch_recovery{..}) |
1303				RuntimeCall::Recovery(pallet_recovery::Call::claim_recovery{..}) |
1304				RuntimeCall::Recovery(pallet_recovery::Call::close_recovery{..}) |
1305				RuntimeCall::Recovery(pallet_recovery::Call::remove_recovery{..}) |
1306				RuntimeCall::Recovery(pallet_recovery::Call::cancel_recovered{..}) |
1307				// Specifically omitting Recovery `create_recovery`, `initiate_recovery`
1308				RuntimeCall::Vesting(pallet_vesting::Call::vest{..}) |
1309				RuntimeCall::Vesting(pallet_vesting::Call::vest_other{..}) |
1310				// Specifically omitting Vesting `vested_transfer`, and `force_vested_transfer`
1311				RuntimeCall::Scheduler(..) |
1312				// Specifically omitting Sudo pallet
1313				RuntimeCall::Proxy(..) |
1314				RuntimeCall::Multisig(..) |
1315				RuntimeCall::Registrar(paras_registrar::Call::register{..}) |
1316				RuntimeCall::Registrar(paras_registrar::Call::deregister{..}) |
1317				// Specifically omitting Registrar `swap`
1318				RuntimeCall::Registrar(paras_registrar::Call::reserve{..}) |
1319				RuntimeCall::Crowdloan(..) |
1320				RuntimeCall::Slots(..) |
1321				RuntimeCall::Auctions(..) | // Specifically omitting the entire XCM Pallet
1322				RuntimeCall::VoterList(..) |
1323				RuntimeCall::NominationPools(..) |
1324				RuntimeCall::FastUnstake(..)
1325			),
1326			ProxyType::Staking => {
1327				matches!(
1328					c,
1329					RuntimeCall::Staking(..) |
1330						RuntimeCall::Session(..) |
1331						RuntimeCall::Utility(..) |
1332						RuntimeCall::FastUnstake(..) |
1333						RuntimeCall::VoterList(..) |
1334						RuntimeCall::NominationPools(..)
1335				)
1336			},
1337			ProxyType::NominationPools => {
1338				matches!(c, RuntimeCall::NominationPools(..) | RuntimeCall::Utility(..))
1339			},
1340			ProxyType::SudoBalances => match c {
1341				RuntimeCall::Sudo(pallet_sudo::Call::sudo { call: ref x }) => {
1342					matches!(x.as_ref(), &RuntimeCall::Balances(..))
1343				},
1344				RuntimeCall::Utility(..) => true,
1345				_ => false,
1346			},
1347			ProxyType::Governance => matches!(
1348				c,
1349				// OpenGov calls
1350				RuntimeCall::ConvictionVoting(..) |
1351					RuntimeCall::Referenda(..) |
1352					RuntimeCall::Whitelist(..)
1353			),
1354			ProxyType::IdentityJudgement => matches!(
1355				c,
1356				RuntimeCall::Identity(pallet_identity::Call::provide_judgement { .. }) |
1357					RuntimeCall::Utility(..)
1358			),
1359			ProxyType::CancelProxy => {
1360				matches!(c, RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. }))
1361			},
1362			ProxyType::Auction => matches!(
1363				c,
1364				RuntimeCall::Auctions(..) |
1365					RuntimeCall::Crowdloan(..) |
1366					RuntimeCall::Registrar(..) |
1367					RuntimeCall::Slots(..)
1368			),
1369			ProxyType::ParaRegistration => matches!(
1370				c,
1371				RuntimeCall::Registrar(paras_registrar::Call::reserve { .. }) |
1372					RuntimeCall::Registrar(paras_registrar::Call::register { .. }) |
1373					RuntimeCall::Utility(pallet_utility::Call::batch { .. }) |
1374					RuntimeCall::Utility(pallet_utility::Call::batch_all { .. }) |
1375					RuntimeCall::Utility(pallet_utility::Call::force_batch { .. }) |
1376					RuntimeCall::Proxy(pallet_proxy::Call::remove_proxy { .. })
1377			),
1378		}
1379	}
1380	fn is_superset(&self, o: &Self) -> bool {
1381		match (self, o) {
1382			(x, y) if x == y => true,
1383			(ProxyType::Any, _) => true,
1384			(_, ProxyType::Any) => false,
1385			(ProxyType::NonTransfer, _) => true,
1386			_ => false,
1387		}
1388	}
1389}
1390
1391impl pallet_proxy::Config for Runtime {
1392	type RuntimeEvent = RuntimeEvent;
1393	type RuntimeCall = RuntimeCall;
1394	type Currency = Balances;
1395	type ProxyType = ProxyType;
1396	type ProxyDepositBase = ProxyDepositBase;
1397	type ProxyDepositFactor = ProxyDepositFactor;
1398	type MaxProxies = MaxProxies;
1399	type WeightInfo = weights::pallet_proxy::WeightInfo<Runtime>;
1400	type MaxPending = MaxPending;
1401	type CallHasher = BlakeTwo256;
1402	type AnnouncementDepositBase = AnnouncementDepositBase;
1403	type AnnouncementDepositFactor = AnnouncementDepositFactor;
1404	type BlockNumberProvider = frame_system::Pallet<Runtime>;
1405}
1406
1407impl parachains_origin::Config for Runtime {}
1408
1409impl parachains_configuration::Config for Runtime {
1410	type WeightInfo = weights::polkadot_runtime_parachains_configuration::WeightInfo<Runtime>;
1411}
1412
1413impl parachains_shared::Config for Runtime {
1414	type DisabledValidators = Session;
1415}
1416
1417impl parachains_session_info::Config for Runtime {
1418	type ValidatorSet = Historical;
1419}
1420
1421impl parachains_inclusion::Config for Runtime {
1422	type RuntimeEvent = RuntimeEvent;
1423	type DisputesHandler = ParasDisputes;
1424	type RewardValidators =
1425		parachains_reward_points::RewardValidatorsWithEraPoints<Runtime, StakingAhClient>;
1426	type MessageQueue = MessageQueue;
1427	type WeightInfo = weights::polkadot_runtime_parachains_inclusion::WeightInfo<Runtime>;
1428}
1429
1430parameter_types! {
1431	pub const ParasUnsignedPriority: TransactionPriority = TransactionPriority::max_value();
1432}
1433
1434impl parachains_paras::Config for Runtime {
1435	type RuntimeEvent = RuntimeEvent;
1436	type WeightInfo = weights::polkadot_runtime_parachains_paras::WeightInfo<Runtime>;
1437	type UnsignedPriority = ParasUnsignedPriority;
1438	type QueueFootprinter = ParaInclusion;
1439	type NextSessionRotation = Babe;
1440	type OnNewHead = ();
1441	type AssignCoretime = ParaScheduler;
1442	type Fungible = Balances;
1443	// Per day the cooldown is removed earlier, it should cost 1000.
1444	type CooldownRemovalMultiplier = ConstUint<{ 1000 * UNITS / DAYS as u128 }>;
1445	type AuthorizeCurrentCodeOrigin = EitherOfDiverse<
1446		EnsureRoot<AccountId>,
1447		// Collectives DDay plurality mapping.
1448		AsEnsureOriginWithArg<
1449			EnsureXcm<IsVoiceOfBody<xcm_config::Collectives, xcm_config::DDayBodyId>>,
1450		>,
1451	>;
1452}
1453
1454parameter_types! {
1455	/// Amount of weight that can be spent per block to service messages.
1456	///
1457	/// # WARNING
1458	///
1459	/// This is not a good value for para-chains since the `Scheduler` already uses up to 80% block weight.
1460	pub MessageQueueServiceWeight: Weight = Perbill::from_percent(20) * BlockWeights::get().max_block;
1461	pub const MessageQueueHeapSize: u32 = 128 * 1024;
1462	pub const MessageQueueMaxStale: u32 = 48;
1463}
1464
1465/// Message processor to handle any messages that were enqueued into the `MessageQueue` pallet.
1466pub struct MessageProcessor;
1467impl ProcessMessage for MessageProcessor {
1468	type Origin = AggregateMessageOrigin;
1469
1470	fn process_message(
1471		message: &[u8],
1472		origin: Self::Origin,
1473		meter: &mut WeightMeter,
1474		id: &mut [u8; 32],
1475	) -> Result<bool, ProcessMessageError> {
1476		let para = match origin {
1477			AggregateMessageOrigin::Ump(UmpQueueId::Para(para)) => para,
1478		};
1479		xcm_builder::ProcessXcmMessage::<
1480			Junction,
1481			xcm_executor::XcmExecutor<xcm_config::XcmConfig>,
1482			RuntimeCall,
1483		>::process_message(message, Junction::Parachain(para.into()), meter, id)
1484	}
1485}
1486
1487impl pallet_message_queue::Config for Runtime {
1488	type RuntimeEvent = RuntimeEvent;
1489	type Size = u32;
1490	type HeapSize = MessageQueueHeapSize;
1491	type MaxStale = MessageQueueMaxStale;
1492	type ServiceWeight = MessageQueueServiceWeight;
1493	type IdleMaxServiceWeight = MessageQueueServiceWeight;
1494	#[cfg(not(feature = "runtime-benchmarks"))]
1495	type MessageProcessor = MessageProcessor;
1496	#[cfg(feature = "runtime-benchmarks")]
1497	type MessageProcessor =
1498		pallet_message_queue::mock_helpers::NoopMessageProcessor<AggregateMessageOrigin>;
1499	type QueueChangeHandler = ParaInclusion;
1500	type QueuePausedQuery = ();
1501	type WeightInfo = weights::pallet_message_queue::WeightInfo<Runtime>;
1502}
1503
1504impl parachains_dmp::Config for Runtime {}
1505
1506parameter_types! {
1507	pub const HrmpChannelSizeAndCapacityWithSystemRatio: Percent = Percent::from_percent(100);
1508}
1509
1510impl parachains_hrmp::Config for Runtime {
1511	type RuntimeOrigin = RuntimeOrigin;
1512	type RuntimeEvent = RuntimeEvent;
1513	type ChannelManager = EnsureRoot<AccountId>;
1514	type Currency = Balances;
1515	type DefaultChannelSizeAndCapacityWithSystem = ActiveConfigHrmpChannelSizeAndCapacityRatio<
1516		Runtime,
1517		HrmpChannelSizeAndCapacityWithSystemRatio,
1518	>;
1519	type VersionWrapper = crate::XcmPallet;
1520	type WeightInfo = weights::polkadot_runtime_parachains_hrmp::WeightInfo<Self>;
1521}
1522
1523impl parachains_paras_inherent::Config for Runtime {
1524	type WeightInfo = weights::polkadot_runtime_parachains_paras_inherent::WeightInfo<Runtime>;
1525}
1526
1527impl parachains_scheduler::Config for Runtime {}
1528
1529parameter_types! {
1530	pub const BrokerId: u32 = BROKER_ID;
1531	pub const BrokerPalletId: PalletId = PalletId(*b"py/broke");
1532	pub MaxXcmTransactWeight: Weight = Weight::from_parts(200_000_000, 20_000);
1533}
1534
1535pub struct BrokerPot;
1536impl Get<InteriorLocation> for BrokerPot {
1537	fn get() -> InteriorLocation {
1538		Junction::AccountId32 { network: None, id: BrokerPalletId::get().into_account_truncating() }
1539			.into()
1540	}
1541}
1542
1543impl coretime::Config for Runtime {
1544	type RuntimeOrigin = RuntimeOrigin;
1545	type RuntimeEvent = RuntimeEvent;
1546	type BrokerId = BrokerId;
1547	type BrokerPotLocation = BrokerPot;
1548	type WeightInfo = weights::polkadot_runtime_parachains_coretime::WeightInfo<Runtime>;
1549	type SendXcm = crate::xcm_config::XcmRouter;
1550	type AssetTransactor = crate::xcm_config::LocalAssetTransactor;
1551	type AccountToLocation = xcm_builder::AliasesIntoAccountId32<
1552		xcm_config::ThisNetwork,
1553		<Runtime as frame_system::Config>::AccountId,
1554	>;
1555	type MaxXcmTransactWeight = MaxXcmTransactWeight;
1556}
1557
1558parameter_types! {
1559	pub const OnDemandTrafficDefaultValue: FixedU128 = FixedU128::from_u32(1);
1560	// Keep 2 timeslices worth of revenue information.
1561	pub const MaxHistoricalRevenue: BlockNumber = 2 * TIMESLICE_PERIOD;
1562	pub const OnDemandPalletId: PalletId = PalletId(*b"py/ondmd");
1563}
1564
1565impl parachains_on_demand::Config for Runtime {
1566	type RuntimeEvent = RuntimeEvent;
1567	type Currency = Balances;
1568	type TrafficDefaultValue = OnDemandTrafficDefaultValue;
1569	type WeightInfo = weights::polkadot_runtime_parachains_on_demand::WeightInfo<Runtime>;
1570	type MaxHistoricalRevenue = MaxHistoricalRevenue;
1571	type PalletId = OnDemandPalletId;
1572}
1573
1574impl parachains_initializer::Config for Runtime {
1575	type Randomness = pallet_babe::RandomnessFromOneEpochAgo<Runtime>;
1576	type ForceOrigin = EnsureRoot<AccountId>;
1577	type WeightInfo = weights::polkadot_runtime_parachains_initializer::WeightInfo<Runtime>;
1578	type CoretimeOnNewSession = Coretime;
1579}
1580
1581impl paras_sudo_wrapper::Config for Runtime {}
1582
1583parameter_types! {
1584	pub const PermanentSlotLeasePeriodLength: u32 = 26;
1585	pub const TemporarySlotLeasePeriodLength: u32 = 1;
1586	pub const MaxTemporarySlotPerLeasePeriod: u32 = 5;
1587}
1588
1589impl assigned_slots::Config for Runtime {
1590	type RuntimeEvent = RuntimeEvent;
1591	type AssignSlotOrigin = EnsureRoot<AccountId>;
1592	type Leaser = Slots;
1593	type PermanentSlotLeasePeriodLength = PermanentSlotLeasePeriodLength;
1594	type TemporarySlotLeasePeriodLength = TemporarySlotLeasePeriodLength;
1595	type MaxTemporarySlotPerLeasePeriod = MaxTemporarySlotPerLeasePeriod;
1596	type WeightInfo = weights::polkadot_runtime_common_assigned_slots::WeightInfo<Runtime>;
1597}
1598
1599impl parachains_disputes::Config for Runtime {
1600	type RuntimeEvent = RuntimeEvent;
1601	type RewardValidators =
1602		parachains_reward_points::RewardValidatorsWithEraPoints<Runtime, StakingAhClient>;
1603	type SlashingHandler = parachains_slashing::SlashValidatorsForDisputes<ParasSlashing>;
1604	type WeightInfo = weights::polkadot_runtime_parachains_disputes::WeightInfo<Runtime>;
1605}
1606
1607impl parachains_slashing::Config for Runtime {
1608	type KeyOwnerProofSystem = Historical;
1609	type KeyOwnerProof =
1610		<Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, ValidatorId)>>::Proof;
1611	type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
1612		KeyTypeId,
1613		ValidatorId,
1614	)>>::IdentificationTuple;
1615	type HandleReports = parachains_slashing::SlashingReportHandler<
1616		Self::KeyOwnerIdentification,
1617		Offences,
1618		ReportLongevity,
1619	>;
1620	type WeightInfo = weights::polkadot_runtime_parachains_disputes_slashing::WeightInfo<Runtime>;
1621	type BenchmarkingConfig = parachains_slashing::BenchConfig<300>;
1622}
1623
1624parameter_types! {
1625	pub const ParaDeposit: Balance = 2000 * CENTS;
1626	pub const RegistrarDataDepositPerByte: Balance = deposit(0, 1);
1627}
1628
1629impl paras_registrar::Config for Runtime {
1630	type RuntimeOrigin = RuntimeOrigin;
1631	type RuntimeEvent = RuntimeEvent;
1632	type Currency = Balances;
1633	type OnSwap = (Crowdloan, Slots, SwapLeases);
1634	type ParaDeposit = ParaDeposit;
1635	type DataDepositPerByte = RegistrarDataDepositPerByte;
1636	type WeightInfo = weights::polkadot_runtime_common_paras_registrar::WeightInfo<Runtime>;
1637}
1638
1639parameter_types! {
1640	pub const LeasePeriod: BlockNumber = 28 * DAYS;
1641}
1642
1643impl slots::Config for Runtime {
1644	type RuntimeEvent = RuntimeEvent;
1645	type Currency = Balances;
1646	type Registrar = Registrar;
1647	type LeasePeriod = LeasePeriod;
1648	type LeaseOffset = ();
1649	type ForceOrigin = EitherOf<EnsureRoot<Self::AccountId>, LeaseAdmin>;
1650	type WeightInfo = weights::polkadot_runtime_common_slots::WeightInfo<Runtime>;
1651}
1652
1653parameter_types! {
1654	pub const CrowdloanId: PalletId = PalletId(*b"py/cfund");
1655	pub const SubmissionDeposit: Balance = 100 * 100 * CENTS;
1656	pub const MinContribution: Balance = 100 * CENTS;
1657	pub const RemoveKeysLimit: u32 = 500;
1658	// Allow 32 bytes for an additional memo to a crowdloan.
1659	pub const MaxMemoLength: u8 = 32;
1660}
1661
1662impl crowdloan::Config for Runtime {
1663	type RuntimeEvent = RuntimeEvent;
1664	type PalletId = CrowdloanId;
1665	type SubmissionDeposit = SubmissionDeposit;
1666	type MinContribution = MinContribution;
1667	type RemoveKeysLimit = RemoveKeysLimit;
1668	type Registrar = Registrar;
1669	type Auctioneer = Auctions;
1670	type MaxMemoLength = MaxMemoLength;
1671	type WeightInfo = weights::polkadot_runtime_common_crowdloan::WeightInfo<Runtime>;
1672}
1673
1674parameter_types! {
1675	// The average auction is 7 days long, so this will be 70% for ending period.
1676	// 5 Days = 72000 Blocks @ 6 sec per block
1677	pub const EndingPeriod: BlockNumber = 5 * DAYS;
1678	// ~ 1000 samples per day -> ~ 20 blocks per sample -> 2 minute samples
1679	pub const SampleLength: BlockNumber = 2 * MINUTES;
1680}
1681
1682impl auctions::Config for Runtime {
1683	type RuntimeEvent = RuntimeEvent;
1684	type Leaser = Slots;
1685	type Registrar = Registrar;
1686	type EndingPeriod = EndingPeriod;
1687	type SampleLength = SampleLength;
1688	type Randomness = pallet_babe::RandomnessFromOneEpochAgo<Runtime>;
1689	type InitiateOrigin = EitherOf<EnsureRoot<Self::AccountId>, AuctionAdmin>;
1690	type WeightInfo = weights::polkadot_runtime_common_auctions::WeightInfo<Runtime>;
1691}
1692
1693impl identity_migrator::Config for Runtime {
1694	type RuntimeEvent = RuntimeEvent;
1695	type Reaper = EnsureSigned<AccountId>;
1696	type ReapIdentityHandler = ToParachainIdentityReaper<Runtime, Self::AccountId>;
1697	type WeightInfo = weights::polkadot_runtime_common_identity_migrator::WeightInfo<Runtime>;
1698}
1699
1700parameter_types! {
1701	pub const PoolsPalletId: PalletId = PalletId(*b"py/nopls");
1702	pub const MaxPointsToBalance: u8 = 10;
1703}
1704
1705impl pallet_nomination_pools::Config for Runtime {
1706	type RuntimeEvent = RuntimeEvent;
1707	type WeightInfo = weights::pallet_nomination_pools::WeightInfo<Self>;
1708	type Currency = Balances;
1709	type RuntimeFreezeReason = RuntimeFreezeReason;
1710	type RewardCounter = FixedU128;
1711	type BalanceToU256 = BalanceToU256;
1712	type U256ToBalance = U256ToBalance;
1713	type StakeAdapter =
1714		pallet_nomination_pools::adapter::DelegateStake<Self, Staking, DelegatedStaking>;
1715	type PostUnbondingPoolsWindow = ConstU32<4>;
1716	type MaxMetadataLen = ConstU32<256>;
1717	// we use the same number of allowed unlocking chunks as with staking.
1718	type MaxUnbonding = <Self as pallet_staking::Config>::MaxUnlockingChunks;
1719	type PalletId = PoolsPalletId;
1720	type MaxPointsToBalance = MaxPointsToBalance;
1721	type AdminOrigin = EitherOf<EnsureRoot<AccountId>, StakingAdmin>;
1722	type BlockNumberProvider = System;
1723	type Filter = Nothing;
1724}
1725
1726parameter_types! {
1727	pub const DelegatedStakingPalletId: PalletId = PalletId(*b"py/dlstk");
1728	pub const SlashRewardFraction: Perbill = Perbill::from_percent(1);
1729}
1730
1731impl pallet_delegated_staking::Config for Runtime {
1732	type RuntimeEvent = RuntimeEvent;
1733	type PalletId = DelegatedStakingPalletId;
1734	type Currency = Balances;
1735	type OnSlash = ();
1736	type SlashRewardFraction = SlashRewardFraction;
1737	type RuntimeHoldReason = RuntimeHoldReason;
1738	type CoreStaking = Staking;
1739}
1740
1741impl pallet_root_testing::Config for Runtime {
1742	type RuntimeEvent = RuntimeEvent;
1743}
1744
1745impl pallet_root_offences::Config for Runtime {
1746	type RuntimeEvent = RuntimeEvent;
1747	type OffenceHandler = StakingAhClient;
1748	type ReportOffence = Offences;
1749}
1750
1751parameter_types! {
1752	pub const DapSatellitePalletId: PalletId = PalletId(*b"dap/satl");
1753}
1754
1755impl pallet_dap_satellite::Config for Runtime {
1756	type Currency = Balances;
1757	type PalletId = DapSatellitePalletId;
1758}
1759
1760parameter_types! {
1761	pub MbmServiceWeight: Weight = Perbill::from_percent(80) * BlockWeights::get().max_block;
1762}
1763
1764impl pallet_migrations::Config for Runtime {
1765	type RuntimeEvent = RuntimeEvent;
1766	#[cfg(not(feature = "runtime-benchmarks"))]
1767	type Migrations = pallet_identity::migration::v2::LazyMigrationV1ToV2<Runtime>;
1768	// Benchmarks need mocked migrations to guarantee that they succeed.
1769	#[cfg(feature = "runtime-benchmarks")]
1770	type Migrations = pallet_migrations::mock_helpers::MockedMigrations;
1771	type CursorMaxLen = ConstU32<65_536>;
1772	type IdentifierMaxLen = ConstU32<256>;
1773	type MigrationStatusHandler = ();
1774	type FailedMigrationHandler = frame_support::migrations::FreezeChainOnFailedMigration;
1775	type MaxServiceWeight = MbmServiceWeight;
1776	type WeightInfo = weights::pallet_migrations::WeightInfo<Runtime>;
1777}
1778
1779parameter_types! {
1780	// The deposit configuration for the singed migration. Specially if you want to allow any signed account to do the migration (see `SignedFilter`, these deposits should be high)
1781	pub const MigrationSignedDepositPerItem: Balance = 1 * CENTS;
1782	pub const MigrationSignedDepositBase: Balance = 20 * CENTS * 100;
1783	pub const MigrationMaxKeyLen: u32 = 512;
1784}
1785
1786impl pallet_asset_rate::Config for Runtime {
1787	type WeightInfo = weights::pallet_asset_rate::WeightInfo<Runtime>;
1788	type RuntimeEvent = RuntimeEvent;
1789	type CreateOrigin = EnsureRoot<AccountId>;
1790	type RemoveOrigin = EnsureRoot<AccountId>;
1791	type UpdateOrigin = EnsureRoot<AccountId>;
1792	type Currency = Balances;
1793	type AssetKind = <Runtime as pallet_treasury::Config>::AssetKind;
1794	#[cfg(feature = "runtime-benchmarks")]
1795	type BenchmarkHelper = polkadot_runtime_common::impls::benchmarks::AssetRateArguments;
1796}
1797
1798// Notify `coretime` pallet when a lease swap occurs
1799pub struct SwapLeases;
1800impl OnSwap for SwapLeases {
1801	fn on_swap(one: ParaId, other: ParaId) {
1802		coretime::Pallet::<Runtime>::on_legacy_lease_swap(one, other);
1803	}
1804}
1805
1806pub type MetaTxExtension = (
1807	pallet_verify_signature::VerifySignature<Runtime>,
1808	pallet_meta_tx::MetaTxMarker<Runtime>,
1809	frame_system::CheckNonZeroSender<Runtime>,
1810	frame_system::CheckSpecVersion<Runtime>,
1811	frame_system::CheckTxVersion<Runtime>,
1812	frame_system::CheckGenesis<Runtime>,
1813	frame_system::CheckMortality<Runtime>,
1814	frame_system::CheckNonce<Runtime>,
1815	frame_metadata_hash_extension::CheckMetadataHash<Runtime>,
1816);
1817
1818impl pallet_meta_tx::Config for Runtime {
1819	type WeightInfo = weights::pallet_meta_tx::WeightInfo<Runtime>;
1820	type RuntimeEvent = RuntimeEvent;
1821	#[cfg(not(feature = "runtime-benchmarks"))]
1822	type Extension = MetaTxExtension;
1823	#[cfg(feature = "runtime-benchmarks")]
1824	type Extension = pallet_meta_tx::WeightlessExtension<Runtime>;
1825}
1826
1827impl pallet_verify_signature::Config for Runtime {
1828	type Signature = MultiSignature;
1829	type AccountIdentifier = MultiSigner;
1830	type WeightInfo = weights::pallet_verify_signature::WeightInfo<Runtime>;
1831	#[cfg(feature = "runtime-benchmarks")]
1832	type BenchmarkHelper = ();
1833}
1834
1835#[frame_support::runtime(legacy_ordering)]
1836mod runtime {
1837	#[runtime::runtime]
1838	#[runtime::derive(
1839		RuntimeCall,
1840		RuntimeEvent,
1841		RuntimeError,
1842		RuntimeOrigin,
1843		RuntimeFreezeReason,
1844		RuntimeHoldReason,
1845		RuntimeSlashReason,
1846		RuntimeLockId,
1847		RuntimeTask,
1848		RuntimeViewFunction
1849	)]
1850	pub struct Runtime;
1851
1852	// Basic stuff; balances is uncallable initially.
1853	#[runtime::pallet_index(0)]
1854	pub type System = frame_system;
1855
1856	// Babe must be before session.
1857	#[runtime::pallet_index(1)]
1858	pub type Babe = pallet_babe;
1859
1860	#[runtime::pallet_index(2)]
1861	pub type Timestamp = pallet_timestamp;
1862	#[runtime::pallet_index(3)]
1863	pub type Indices = pallet_indices;
1864	#[runtime::pallet_index(4)]
1865	pub type Balances = pallet_balances;
1866	#[runtime::pallet_index(26)]
1867	pub type TransactionPayment = pallet_transaction_payment;
1868	// DAP Satellite - collects funds for transfer to DAP on AssetHub
1869	#[runtime::pallet_index(106)]
1870	pub type DapSatellite = pallet_dap_satellite;
1871
1872	// Consensus support.
1873	// Authorship must be before session in order to note author in the correct session and era.
1874	#[runtime::pallet_index(5)]
1875	pub type Authorship = pallet_authorship;
1876	#[runtime::pallet_index(6)]
1877	pub type Staking = pallet_staking;
1878	#[runtime::pallet_index(7)]
1879	pub type Offences = pallet_offences;
1880	#[runtime::pallet_index(27)]
1881	pub type Historical = session_historical;
1882	#[runtime::pallet_index(70)]
1883	pub type Parameters = pallet_parameters;
1884
1885	#[runtime::pallet_index(8)]
1886	pub type Session = pallet_session;
1887	#[runtime::pallet_index(10)]
1888	pub type Grandpa = pallet_grandpa;
1889	#[runtime::pallet_index(12)]
1890	pub type AuthorityDiscovery = pallet_authority_discovery;
1891
1892	// Utility module.
1893	#[runtime::pallet_index(16)]
1894	pub type Utility = pallet_utility;
1895
1896	// Less simple identity module.
1897	#[runtime::pallet_index(17)]
1898	pub type Identity = pallet_identity;
1899
1900	// Social recovery module.
1901	#[runtime::pallet_index(18)]
1902	pub type Recovery = pallet_recovery;
1903
1904	// Vesting. Usable initially, but removed once all vesting is finished.
1905	#[runtime::pallet_index(19)]
1906	pub type Vesting = pallet_vesting;
1907
1908	// System scheduler.
1909	#[runtime::pallet_index(20)]
1910	pub type Scheduler = pallet_scheduler;
1911
1912	// Preimage registrar.
1913	#[runtime::pallet_index(28)]
1914	pub type Preimage = pallet_preimage;
1915
1916	// Sudo.
1917	#[runtime::pallet_index(21)]
1918	pub type Sudo = pallet_sudo;
1919
1920	// Proxy module. Late addition.
1921	#[runtime::pallet_index(22)]
1922	pub type Proxy = pallet_proxy;
1923
1924	// Multisig module. Late addition.
1925	#[runtime::pallet_index(23)]
1926	pub type Multisig = pallet_multisig;
1927
1928	// Election pallet. Only works with staking, but placed here to maintain indices.
1929	#[runtime::pallet_index(24)]
1930	pub type ElectionProviderMultiPhase = pallet_election_provider_multi_phase;
1931
1932	// Provides a semi-sorted list of nominators for staking.
1933	#[runtime::pallet_index(25)]
1934	pub type VoterList = pallet_bags_list<Instance1>;
1935
1936	// Nomination pools for staking.
1937	#[runtime::pallet_index(29)]
1938	pub type NominationPools = pallet_nomination_pools;
1939
1940	// Fast unstake pallet = extension to staking.
1941	#[runtime::pallet_index(30)]
1942	pub type FastUnstake = pallet_fast_unstake;
1943
1944	// OpenGov
1945	#[runtime::pallet_index(31)]
1946	pub type ConvictionVoting = pallet_conviction_voting;
1947	#[runtime::pallet_index(32)]
1948	pub type Referenda = pallet_referenda;
1949	#[runtime::pallet_index(35)]
1950	pub type Origins = pallet_custom_origins;
1951	#[runtime::pallet_index(36)]
1952	pub type Whitelist = pallet_whitelist;
1953
1954	// Treasury
1955	#[runtime::pallet_index(37)]
1956	pub type Treasury = pallet_treasury;
1957
1958	// Staking extension for delegation
1959	#[runtime::pallet_index(38)]
1960	pub type DelegatedStaking = pallet_delegated_staking;
1961
1962	// Parachains pallets. Start indices at 40 to leave room.
1963	#[runtime::pallet_index(41)]
1964	pub type ParachainsOrigin = parachains_origin;
1965	#[runtime::pallet_index(42)]
1966	pub type Configuration = parachains_configuration;
1967	#[runtime::pallet_index(43)]
1968	pub type ParasShared = parachains_shared;
1969	#[runtime::pallet_index(44)]
1970	pub type ParaInclusion = parachains_inclusion;
1971	#[runtime::pallet_index(45)]
1972	pub type ParaInherent = parachains_paras_inherent;
1973	#[runtime::pallet_index(46)]
1974	pub type ParaScheduler = parachains_scheduler;
1975	#[runtime::pallet_index(47)]
1976	pub type Paras = parachains_paras;
1977	#[runtime::pallet_index(48)]
1978	pub type Initializer = parachains_initializer;
1979	#[runtime::pallet_index(49)]
1980	pub type Dmp = parachains_dmp;
1981	// RIP Ump 50
1982	#[runtime::pallet_index(51)]
1983	pub type Hrmp = parachains_hrmp;
1984	#[runtime::pallet_index(52)]
1985	pub type ParaSessionInfo = parachains_session_info;
1986	#[runtime::pallet_index(53)]
1987	pub type ParasDisputes = parachains_disputes;
1988	#[runtime::pallet_index(54)]
1989	pub type ParasSlashing = parachains_slashing;
1990	#[runtime::pallet_index(56)]
1991	pub type OnDemandAssignmentProvider = parachains_on_demand;
1992	// RIP CoretimeAssignmentProvider 57 - Moved to scheduler::assigner_coretime submodule in PR
1993	// #10184 (Had no extrinsics nor events exposed)
1994
1995	// Parachain Onboarding Pallets. Start indices at 60 to leave room.
1996	#[runtime::pallet_index(60)]
1997	pub type Registrar = paras_registrar;
1998	#[runtime::pallet_index(61)]
1999	pub type Slots = slots;
2000	#[runtime::pallet_index(62)]
2001	pub type ParasSudoWrapper = paras_sudo_wrapper;
2002	#[runtime::pallet_index(63)]
2003	pub type Auctions = auctions;
2004	#[runtime::pallet_index(64)]
2005	pub type Crowdloan = crowdloan;
2006	#[runtime::pallet_index(65)]
2007	pub type AssignedSlots = assigned_slots;
2008	#[runtime::pallet_index(66)]
2009	pub type Coretime = coretime;
2010	#[runtime::pallet_index(67)]
2011	pub type StakingAhClient = pallet_staking_async_ah_client;
2012
2013	// Migrations pallet
2014	#[runtime::pallet_index(98)]
2015	pub type MultiBlockMigrations = pallet_migrations;
2016
2017	// Pallet for sending XCM.
2018	#[runtime::pallet_index(99)]
2019	pub type XcmPallet = pallet_xcm;
2020
2021	// Generalized message queue
2022	#[runtime::pallet_index(100)]
2023	pub type MessageQueue = pallet_message_queue;
2024
2025	// Asset rate.
2026	#[runtime::pallet_index(101)]
2027	pub type AssetRate = pallet_asset_rate;
2028
2029	// Root testing pallet.
2030	#[runtime::pallet_index(102)]
2031	pub type RootTesting = pallet_root_testing;
2032
2033	#[runtime::pallet_index(103)]
2034	pub type MetaTx = pallet_meta_tx::Pallet<Runtime>;
2035
2036	#[runtime::pallet_index(104)]
2037	pub type VerifySignature = pallet_verify_signature::Pallet<Runtime>;
2038
2039	// Root offences pallet
2040	#[runtime::pallet_index(105)]
2041	pub type RootOffences = pallet_root_offences;
2042
2043	// BEEFY Bridges support.
2044	#[runtime::pallet_index(200)]
2045	pub type Beefy = pallet_beefy;
2046	// MMR leaf construction must be after session in order to have a leaf's next_auth_set
2047	// refer to block<N>. See issue polkadot-fellows/runtimes#160 for details.
2048	#[runtime::pallet_index(201)]
2049	pub type Mmr = pallet_mmr;
2050	#[runtime::pallet_index(202)]
2051	pub type BeefyMmrLeaf = pallet_beefy_mmr;
2052
2053	// Pallet for migrating Identity to a parachain. To be removed post-migration.
2054	#[runtime::pallet_index(248)]
2055	pub type IdentityMigrator = identity_migrator;
2056}
2057
2058/// The address format for describing accounts.
2059pub type Address = sp_runtime::MultiAddress<AccountId, ()>;
2060/// Block header type as expected by this runtime.
2061pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
2062/// Block type as expected by this runtime.
2063pub type Block = generic::Block<Header, UncheckedExtrinsic>;
2064/// A Block signed with a Justification
2065pub type SignedBlock = generic::SignedBlock<Block>;
2066/// `BlockId` type as expected by this runtime.
2067pub type BlockId = generic::BlockId<Block>;
2068/// The extension to the basic transaction logic.
2069pub type TxExtension = (
2070	frame_system::AuthorizeCall<Runtime>,
2071	frame_system::CheckNonZeroSender<Runtime>,
2072	frame_system::CheckSpecVersion<Runtime>,
2073	frame_system::CheckTxVersion<Runtime>,
2074	frame_system::CheckGenesis<Runtime>,
2075	frame_system::CheckMortality<Runtime>,
2076	frame_system::CheckNonce<Runtime>,
2077	frame_system::CheckWeight<Runtime>,
2078	pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
2079	frame_metadata_hash_extension::CheckMetadataHash<Runtime>,
2080	frame_system::WeightReclaim<Runtime>,
2081);
2082
2083parameter_types! {
2084	/// Bounding number of agent pot accounts to be migrated in a single block.
2085	pub const MaxAgentsToMigrate: u32 = 300;
2086}
2087
2088/// All migrations that will run on the next runtime upgrade.
2089///
2090/// This contains the combined migrations of the last 10 releases. It allows to skip runtime
2091/// upgrades in case governance decides to do so. THE ORDER IS IMPORTANT.
2092pub type Migrations = migrations::Unreleased;
2093
2094/// The runtime migrations per release.
2095#[allow(deprecated, missing_docs)]
2096pub mod migrations {
2097	use super::*;
2098
2099	/// Unreleased migrations. Add new ones here:
2100	pub type Unreleased = (
2101		// This is only needed for Westend.
2102		pallet_delegated_staking::migration::unversioned::ProxyDelegatorMigration<
2103			Runtime,
2104			MaxAgentsToMigrate,
2105		>,
2106		pallet_staking::migrations::v16::MigrateV15ToV16<Runtime>,
2107		pallet_session::migrations::v1::MigrateV0ToV1<
2108			Runtime,
2109			pallet_staking::migrations::v17::MigrateDisabledToSession<Runtime>,
2110		>,
2111		// Migrate scheduler v3 -> v4 and on-demand v1 -> v2
2112		parachains_on_demand::migration::MigrateV1ToV2<Runtime>,
2113		parachains_scheduler::migration::MigrateV3ToV4<Runtime>,
2114		parachains_configuration::migration::v13::MigrateToV13<Runtime>,
2115		parachains_shared::migration::MigrateToV2<Runtime>,
2116		// permanent
2117		pallet_xcm::migration::MigrateToLatestXcmVersion<Runtime>,
2118	);
2119}
2120
2121/// Unchecked extrinsic type as expected by this runtime.
2122pub type UncheckedExtrinsic =
2123	generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, TxExtension>;
2124/// Unchecked signature payload type as expected by this runtime.
2125pub type UncheckedSignaturePayload =
2126	generic::UncheckedSignaturePayload<Address, Signature, TxExtension>;
2127
2128/// Executive: handles dispatch to the various modules.
2129pub type Executive = frame_executive::Executive<
2130	Runtime,
2131	Block,
2132	frame_system::ChainContext<Runtime>,
2133	Runtime,
2134	AllPalletsWithSystem,
2135>;
2136/// The payload being signed in transactions.
2137pub type SignedPayload = generic::SignedPayload<RuntimeCall, TxExtension>;
2138
2139#[cfg(feature = "runtime-benchmarks")]
2140mod benches {
2141	frame_benchmarking::define_benchmarks!(
2142		// Polkadot
2143		// NOTE: Make sure to prefix these with `runtime_common::` so
2144		// the that path resolves correctly in the generated file.
2145		[polkadot_runtime_common::assigned_slots, AssignedSlots]
2146		[polkadot_runtime_common::auctions, Auctions]
2147		[polkadot_runtime_common::crowdloan, Crowdloan]
2148		[polkadot_runtime_common::identity_migrator, IdentityMigrator]
2149		[polkadot_runtime_common::paras_registrar, Registrar]
2150		[polkadot_runtime_common::slots, Slots]
2151		[polkadot_runtime_parachains::configuration, Configuration]
2152		[polkadot_runtime_parachains::disputes, ParasDisputes]
2153		[polkadot_runtime_parachains::disputes::slashing, ParasSlashing]
2154		[polkadot_runtime_parachains::hrmp, Hrmp]
2155		[polkadot_runtime_parachains::inclusion, ParaInclusion]
2156		[polkadot_runtime_parachains::initializer, Initializer]
2157		[polkadot_runtime_parachains::paras, Paras]
2158		[polkadot_runtime_parachains::paras_inherent, ParaInherent]
2159		[polkadot_runtime_parachains::on_demand, OnDemandAssignmentProvider]
2160		[polkadot_runtime_parachains::coretime, Coretime]
2161		// Substrate
2162		[pallet_bags_list, VoterList]
2163		[pallet_balances, Balances]
2164		[pallet_beefy_mmr, BeefyMmrLeaf]
2165		[pallet_conviction_voting, ConvictionVoting]
2166		[pallet_election_provider_multi_phase, ElectionProviderMultiPhase]
2167		[frame_election_provider_support, ElectionProviderBench::<Runtime>]
2168		[pallet_fast_unstake, FastUnstake]
2169		[pallet_identity, Identity]
2170		[pallet_indices, Indices]
2171		[pallet_message_queue, MessageQueue]
2172		[pallet_migrations, MultiBlockMigrations]
2173		[pallet_mmr, Mmr]
2174		[pallet_multisig, Multisig]
2175		[pallet_nomination_pools, NominationPoolsBench::<Runtime>]
2176		[pallet_offences, OffencesBench::<Runtime>]
2177		[pallet_parameters, Parameters]
2178		[pallet_preimage, Preimage]
2179		[pallet_proxy, Proxy]
2180		[pallet_recovery, Recovery]
2181		[pallet_referenda, Referenda]
2182		[pallet_scheduler, Scheduler]
2183		[pallet_session, SessionBench::<Runtime>]
2184		[pallet_staking, Staking]
2185		[pallet_sudo, Sudo]
2186		[frame_system, SystemBench::<Runtime>]
2187		[frame_system_extensions, SystemExtensionsBench::<Runtime>]
2188		[pallet_timestamp, Timestamp]
2189		[pallet_transaction_payment, TransactionPayment]
2190		[pallet_treasury, Treasury]
2191		[pallet_utility, Utility]
2192		[pallet_vesting, Vesting]
2193		[pallet_whitelist, Whitelist]
2194		[pallet_asset_rate, AssetRate]
2195		[pallet_meta_tx, MetaTx]
2196		[pallet_verify_signature, VerifySignature]
2197		// XCM
2198		[pallet_xcm, PalletXcmExtrinsicsBenchmark::<Runtime>]
2199		// NOTE: Make sure you point to the individual modules below.
2200		[pallet_xcm_benchmarks::fungible, XcmBalances]
2201		[pallet_xcm_benchmarks::generic, XcmGeneric]
2202	);
2203}
2204
2205sp_api::impl_runtime_apis! {
2206	impl sp_api::Core<Block> for Runtime {
2207		fn version() -> RuntimeVersion {
2208			VERSION
2209		}
2210
2211		fn execute_block(block: <Block as BlockT>::LazyBlock) {
2212			Executive::execute_block(block);
2213		}
2214
2215		fn initialize_block(header: &<Block as BlockT>::Header) -> sp_runtime::ExtrinsicInclusionMode {
2216			Executive::initialize_block(header)
2217		}
2218	}
2219
2220	impl sp_api::Metadata<Block> for Runtime {
2221		fn metadata() -> OpaqueMetadata {
2222			OpaqueMetadata::new(Runtime::metadata().into())
2223		}
2224
2225		fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
2226			Runtime::metadata_at_version(version)
2227		}
2228
2229		fn metadata_versions() -> alloc::vec::Vec<u32> {
2230			Runtime::metadata_versions()
2231		}
2232	}
2233
2234	impl frame_support::view_functions::runtime_api::RuntimeViewFunction<Block> for Runtime {
2235		fn execute_view_function(id: frame_support::view_functions::ViewFunctionId, input: Vec<u8>) -> Result<Vec<u8>, frame_support::view_functions::ViewFunctionDispatchError> {
2236			Runtime::execute_view_function(id, input)
2237		}
2238	}
2239
2240	impl sp_block_builder::BlockBuilder<Block> for Runtime {
2241		fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
2242			Executive::apply_extrinsic(extrinsic)
2243		}
2244
2245		fn finalize_block() -> <Block as BlockT>::Header {
2246			Executive::finalize_block()
2247		}
2248
2249		fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
2250			data.create_extrinsics()
2251		}
2252
2253		fn check_inherents(
2254			block: <Block as BlockT>::LazyBlock,
2255			data: sp_inherents::InherentData,
2256		) -> sp_inherents::CheckInherentsResult {
2257			data.check_extrinsics(&block)
2258		}
2259	}
2260
2261	impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
2262		fn validate_transaction(
2263			source: TransactionSource,
2264			tx: <Block as BlockT>::Extrinsic,
2265			block_hash: <Block as BlockT>::Hash,
2266		) -> TransactionValidity {
2267			Executive::validate_transaction(source, tx, block_hash)
2268		}
2269	}
2270
2271	impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
2272		fn offchain_worker(header: &<Block as BlockT>::Header) {
2273			Executive::offchain_worker(header)
2274		}
2275	}
2276
2277	#[api_version(16)]
2278	impl polkadot_primitives::runtime_api::ParachainHost<Block> for Runtime {
2279		fn validators() -> Vec<ValidatorId> {
2280			parachains_runtime_api_impl::validators::<Runtime>()
2281		}
2282
2283		fn validator_groups() -> (Vec<Vec<ValidatorIndex>>, GroupRotationInfo<BlockNumber>) {
2284			parachains_runtime_api_impl::validator_groups::<Runtime>()
2285		}
2286
2287		fn availability_cores() -> Vec<CoreState<Hash, BlockNumber>> {
2288			parachains_runtime_api_impl::availability_cores::<Runtime>()
2289		}
2290
2291		fn persisted_validation_data(para_id: ParaId, assumption: OccupiedCoreAssumption)
2292			-> Option<PersistedValidationData<Hash, BlockNumber>> {
2293			parachains_runtime_api_impl::persisted_validation_data::<Runtime>(para_id, assumption)
2294		}
2295
2296		fn assumed_validation_data(
2297			para_id: ParaId,
2298			expected_persisted_validation_data_hash: Hash,
2299		) -> Option<(PersistedValidationData<Hash, BlockNumber>, ValidationCodeHash)> {
2300			parachains_runtime_api_impl::assumed_validation_data::<Runtime>(
2301				para_id,
2302				expected_persisted_validation_data_hash,
2303			)
2304		}
2305
2306		fn check_validation_outputs(
2307			para_id: ParaId,
2308			outputs: polkadot_primitives::CandidateCommitments,
2309		) -> bool {
2310			parachains_runtime_api_impl::check_validation_outputs::<Runtime>(para_id, outputs)
2311		}
2312
2313		fn session_index_for_child() -> SessionIndex {
2314			parachains_runtime_api_impl::session_index_for_child::<Runtime>()
2315		}
2316
2317		fn validation_code(para_id: ParaId, assumption: OccupiedCoreAssumption)
2318			-> Option<ValidationCode> {
2319			parachains_runtime_api_impl::validation_code::<Runtime>(para_id, assumption)
2320		}
2321
2322		fn candidate_pending_availability(para_id: ParaId) -> Option<CommittedCandidateReceipt<Hash>> {
2323			#[allow(deprecated)]
2324			parachains_runtime_api_impl::candidate_pending_availability::<Runtime>(para_id)
2325		}
2326
2327		fn candidate_events() -> Vec<CandidateEvent<Hash>> {
2328			parachains_runtime_api_impl::candidate_events::<Runtime, _>(|ev| {
2329				match ev {
2330					RuntimeEvent::ParaInclusion(ev) => {
2331						Some(ev)
2332					}
2333					_ => None,
2334				}
2335			})
2336		}
2337
2338		fn session_info(index: SessionIndex) -> Option<SessionInfo> {
2339			parachains_runtime_api_impl::session_info::<Runtime>(index)
2340		}
2341
2342		fn session_executor_params(session_index: SessionIndex) -> Option<ExecutorParams> {
2343			parachains_runtime_api_impl::session_executor_params::<Runtime>(session_index)
2344		}
2345
2346		fn dmq_contents(recipient: ParaId) -> Vec<InboundDownwardMessage<BlockNumber>> {
2347			parachains_runtime_api_impl::dmq_contents::<Runtime>(recipient)
2348		}
2349
2350		fn inbound_hrmp_channels_contents(
2351			recipient: ParaId
2352		) -> BTreeMap<ParaId, Vec<InboundHrmpMessage<BlockNumber>>> {
2353			parachains_runtime_api_impl::inbound_hrmp_channels_contents::<Runtime>(recipient)
2354		}
2355
2356		fn validation_code_by_hash(hash: ValidationCodeHash) -> Option<ValidationCode> {
2357			parachains_runtime_api_impl::validation_code_by_hash::<Runtime>(hash)
2358		}
2359
2360		fn on_chain_votes() -> Option<ScrapedOnChainVotes<Hash>> {
2361			parachains_runtime_api_impl::on_chain_votes::<Runtime>()
2362		}
2363
2364		fn submit_pvf_check_statement(
2365			stmt: PvfCheckStatement,
2366			signature: ValidatorSignature,
2367		) {
2368			parachains_runtime_api_impl::submit_pvf_check_statement::<Runtime>(stmt, signature)
2369		}
2370
2371		fn pvfs_require_precheck() -> Vec<ValidationCodeHash> {
2372			parachains_runtime_api_impl::pvfs_require_precheck::<Runtime>()
2373		}
2374
2375		fn validation_code_hash(para_id: ParaId, assumption: OccupiedCoreAssumption)
2376			-> Option<ValidationCodeHash>
2377		{
2378			parachains_runtime_api_impl::validation_code_hash::<Runtime>(para_id, assumption)
2379		}
2380
2381		fn disputes() -> Vec<(SessionIndex, CandidateHash, DisputeState<BlockNumber>)> {
2382			parachains_runtime_api_impl::get_session_disputes::<Runtime>()
2383		}
2384
2385		fn unapplied_slashes(
2386		) -> Vec<(SessionIndex, CandidateHash, slashing::LegacyPendingSlashes)> {
2387			parachains_runtime_api_impl::unapplied_slashes::<Runtime>()
2388		}
2389
2390		fn unapplied_slashes_v2(
2391		) -> Vec<(SessionIndex, CandidateHash, slashing::PendingSlashes)> {
2392			parachains_runtime_api_impl::unapplied_slashes_v2::<Runtime>()
2393		}
2394
2395		fn key_ownership_proof(
2396			validator_id: ValidatorId,
2397		) -> Option<slashing::OpaqueKeyOwnershipProof> {
2398			use codec::Encode;
2399
2400			Historical::prove((PARACHAIN_KEY_TYPE_ID, validator_id))
2401				.map(|p| p.encode())
2402				.map(slashing::OpaqueKeyOwnershipProof::new)
2403		}
2404
2405		fn submit_report_dispute_lost(
2406			dispute_proof: slashing::DisputeProof,
2407			key_ownership_proof: slashing::OpaqueKeyOwnershipProof,
2408		) -> Option<()> {
2409			parachains_runtime_api_impl::submit_unsigned_slashing_report::<Runtime>(
2410				dispute_proof,
2411				key_ownership_proof,
2412			)
2413		}
2414
2415		fn minimum_backing_votes() -> u32 {
2416			parachains_runtime_api_impl::minimum_backing_votes::<Runtime>()
2417		}
2418
2419		fn para_backing_state(para_id: ParaId) -> Option<polkadot_primitives::async_backing::BackingState> {
2420			#[allow(deprecated)]
2421			parachains_runtime_api_impl::backing_state::<Runtime>(para_id)
2422		}
2423
2424		fn async_backing_params() -> polkadot_primitives::AsyncBackingParams {
2425			#[allow(deprecated)]
2426			parachains_runtime_api_impl::async_backing_params::<Runtime>()
2427		}
2428
2429		fn approval_voting_params() -> ApprovalVotingParams {
2430			parachains_runtime_api_impl::approval_voting_params::<Runtime>()
2431		}
2432
2433		fn disabled_validators() -> Vec<ValidatorIndex> {
2434			parachains_runtime_api_impl::disabled_validators::<Runtime>()
2435		}
2436
2437		fn node_features() -> NodeFeatures {
2438			parachains_runtime_api_impl::node_features::<Runtime>()
2439		}
2440
2441		fn claim_queue() -> BTreeMap<CoreIndex, VecDeque<ParaId>> {
2442			parachains_runtime_api_impl::claim_queue::<Runtime>()
2443		}
2444
2445		fn candidates_pending_availability(para_id: ParaId) -> Vec<CommittedCandidateReceipt<Hash>> {
2446			parachains_runtime_api_impl::candidates_pending_availability::<Runtime>(para_id)
2447		}
2448
2449		fn backing_constraints(para_id: ParaId) -> Option<Constraints> {
2450			parachains_runtime_api_impl::backing_constraints::<Runtime>(para_id)
2451		}
2452
2453		fn scheduling_lookahead() -> u32 {
2454			parachains_runtime_api_impl::scheduling_lookahead::<Runtime>()
2455		}
2456
2457		fn validation_code_bomb_limit() -> u32 {
2458			parachains_runtime_api_impl::validation_code_bomb_limit::<Runtime>()
2459		}
2460
2461		fn para_ids() -> Vec<ParaId> {
2462			parachains_staging_runtime_api_impl::para_ids::<Runtime>()
2463		}
2464
2465		fn max_relay_parent_session_age() -> u32 {
2466			parachains_staging_runtime_api_impl::max_relay_parent_session_age::<Runtime>()
2467		}
2468
2469		fn ancestor_relay_parent_info(
2470			session_index: SessionIndex,
2471			relay_parent: Hash,
2472		) -> Option<polkadot_primitives::vstaging::RelayParentInfo<Hash, BlockNumber>> {
2473			parachains_staging_runtime_api_impl::ancestor_relay_parent_info::<Runtime>(session_index, relay_parent)
2474		}
2475	}
2476
2477	#[api_version(6)]
2478	impl sp_consensus_beefy::BeefyApi<Block, BeefyId> for Runtime {
2479		fn beefy_genesis() -> Option<BlockNumber> {
2480			pallet_beefy::GenesisBlock::<Runtime>::get()
2481		}
2482
2483		fn validator_set() -> Option<sp_consensus_beefy::ValidatorSet<BeefyId>> {
2484			Beefy::validator_set()
2485		}
2486
2487		fn submit_report_double_voting_unsigned_extrinsic(
2488			equivocation_proof: sp_consensus_beefy::DoubleVotingProof<
2489				BlockNumber,
2490				BeefyId,
2491				BeefySignature,
2492			>,
2493			key_owner_proof: sp_consensus_beefy::OpaqueKeyOwnershipProof,
2494		) -> Option<()> {
2495			let key_owner_proof = key_owner_proof.decode()?;
2496
2497			Beefy::submit_unsigned_double_voting_report(
2498				equivocation_proof,
2499				key_owner_proof,
2500			)
2501		}
2502
2503		fn submit_report_fork_voting_unsigned_extrinsic(
2504			equivocation_proof:
2505				sp_consensus_beefy::ForkVotingProof<
2506					<Block as BlockT>::Header,
2507					BeefyId,
2508					sp_runtime::OpaqueValue
2509				>,
2510			key_owner_proof: sp_consensus_beefy::OpaqueKeyOwnershipProof,
2511		) -> Option<()> {
2512			Beefy::submit_unsigned_fork_voting_report(
2513				equivocation_proof.try_into()?,
2514				key_owner_proof.decode()?,
2515			)
2516		}
2517
2518		fn submit_report_future_block_voting_unsigned_extrinsic(
2519			equivocation_proof: sp_consensus_beefy::FutureBlockVotingProof<BlockNumber, BeefyId>,
2520			key_owner_proof: sp_consensus_beefy::OpaqueKeyOwnershipProof,
2521		) -> Option<()> {
2522			Beefy::submit_unsigned_future_block_voting_report(
2523				equivocation_proof,
2524				key_owner_proof.decode()?,
2525			)
2526		}
2527
2528		fn generate_key_ownership_proof(
2529			_set_id: sp_consensus_beefy::ValidatorSetId,
2530			authority_id: BeefyId,
2531		) -> Option<sp_consensus_beefy::OpaqueKeyOwnershipProof> {
2532			use codec::Encode;
2533
2534			Historical::prove((sp_consensus_beefy::KEY_TYPE, authority_id))
2535				.map(|p| p.encode())
2536				.map(sp_consensus_beefy::OpaqueKeyOwnershipProof::new)
2537		}
2538	}
2539
2540	#[api_version(3)]
2541	impl mmr::MmrApi<Block, Hash, BlockNumber> for Runtime {
2542		fn mmr_root() -> Result<mmr::Hash, mmr::Error> {
2543			Ok(pallet_mmr::RootHash::<Runtime>::get())
2544		}
2545
2546		fn mmr_leaf_count() -> Result<mmr::LeafIndex, mmr::Error> {
2547			Ok(pallet_mmr::NumberOfLeaves::<Runtime>::get())
2548		}
2549
2550		fn generate_proof(
2551			block_numbers: Vec<BlockNumber>,
2552			best_known_block_number: Option<BlockNumber>,
2553		) -> Result<(Vec<mmr::EncodableOpaqueLeaf>, mmr::LeafProof<mmr::Hash>), mmr::Error> {
2554			Mmr::generate_proof(block_numbers, best_known_block_number).map(
2555				|(leaves, proof)| {
2556					(
2557						leaves
2558							.into_iter()
2559							.map(|leaf| mmr::EncodableOpaqueLeaf::from_leaf(&leaf))
2560							.collect(),
2561						proof,
2562					)
2563				},
2564			)
2565		}
2566
2567		fn generate_ancestry_proof(
2568			prev_block_number: BlockNumber,
2569			best_known_block_number: Option<BlockNumber>,
2570		) -> Result<mmr::AncestryProof<mmr::Hash>, mmr::Error> {
2571			Mmr::generate_ancestry_proof(prev_block_number, best_known_block_number)
2572		}
2573
2574		fn verify_proof(leaves: Vec<mmr::EncodableOpaqueLeaf>, proof: mmr::LeafProof<mmr::Hash>)
2575			-> Result<(), mmr::Error>
2576		{
2577			let leaves = leaves.into_iter().map(|leaf|
2578				leaf.into_opaque_leaf()
2579				.try_decode()
2580				.ok_or(mmr::Error::Verify)).collect::<Result<Vec<mmr::Leaf>, mmr::Error>>()?;
2581			Mmr::verify_leaves(leaves, proof)
2582		}
2583
2584		fn verify_proof_stateless(
2585			root: mmr::Hash,
2586			leaves: Vec<mmr::EncodableOpaqueLeaf>,
2587			proof: mmr::LeafProof<mmr::Hash>
2588		) -> Result<(), mmr::Error> {
2589			let nodes = leaves.into_iter().map(|leaf|mmr::DataOrHash::Data(leaf.into_opaque_leaf())).collect();
2590			pallet_mmr::verify_leaves_proof::<mmr::Hashing, _>(root, nodes, proof)
2591		}
2592	}
2593
2594	impl pallet_beefy_mmr::BeefyMmrApi<Block, Hash> for RuntimeApi {
2595		fn authority_set_proof() -> sp_consensus_beefy::mmr::BeefyAuthoritySet<Hash> {
2596			BeefyMmrLeaf::authority_set_proof()
2597		}
2598
2599		fn next_authority_set_proof() -> sp_consensus_beefy::mmr::BeefyNextAuthoritySet<Hash> {
2600			BeefyMmrLeaf::next_authority_set_proof()
2601		}
2602	}
2603
2604	impl fg_primitives::GrandpaApi<Block> for Runtime {
2605		fn grandpa_authorities() -> Vec<(GrandpaId, u64)> {
2606			Grandpa::grandpa_authorities()
2607		}
2608
2609		fn current_set_id() -> fg_primitives::SetId {
2610			pallet_grandpa::CurrentSetId::<Runtime>::get()
2611		}
2612
2613		fn submit_report_equivocation_unsigned_extrinsic(
2614			equivocation_proof: fg_primitives::EquivocationProof<
2615				<Block as BlockT>::Hash,
2616				sp_runtime::traits::NumberFor<Block>,
2617			>,
2618			key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof,
2619		) -> Option<()> {
2620			let key_owner_proof = key_owner_proof.decode()?;
2621
2622			Grandpa::submit_unsigned_equivocation_report(
2623				equivocation_proof,
2624				key_owner_proof,
2625			)
2626		}
2627
2628		fn generate_key_ownership_proof(
2629			_set_id: fg_primitives::SetId,
2630			authority_id: fg_primitives::AuthorityId,
2631		) -> Option<fg_primitives::OpaqueKeyOwnershipProof> {
2632			use codec::Encode;
2633
2634			Historical::prove((fg_primitives::KEY_TYPE, authority_id))
2635				.map(|p| p.encode())
2636				.map(fg_primitives::OpaqueKeyOwnershipProof::new)
2637		}
2638	}
2639
2640	impl sp_consensus_babe::BabeApi<Block> for Runtime {
2641		fn configuration() -> sp_consensus_babe::BabeConfiguration {
2642			let epoch_config = Babe::epoch_config().unwrap_or(BABE_GENESIS_EPOCH_CONFIG);
2643			sp_consensus_babe::BabeConfiguration {
2644				slot_duration: Babe::slot_duration(),
2645				epoch_length: EpochDuration::get(),
2646				c: epoch_config.c,
2647				authorities: Babe::authorities().to_vec(),
2648				randomness: Babe::randomness(),
2649				allowed_slots: epoch_config.allowed_slots,
2650			}
2651		}
2652
2653		fn current_epoch_start() -> sp_consensus_babe::Slot {
2654			Babe::current_epoch_start()
2655		}
2656
2657		fn current_epoch() -> sp_consensus_babe::Epoch {
2658			Babe::current_epoch()
2659		}
2660
2661		fn next_epoch() -> sp_consensus_babe::Epoch {
2662			Babe::next_epoch()
2663		}
2664
2665		fn generate_key_ownership_proof(
2666			_slot: sp_consensus_babe::Slot,
2667			authority_id: sp_consensus_babe::AuthorityId,
2668		) -> Option<sp_consensus_babe::OpaqueKeyOwnershipProof> {
2669			use codec::Encode;
2670
2671			Historical::prove((sp_consensus_babe::KEY_TYPE, authority_id))
2672				.map(|p| p.encode())
2673				.map(sp_consensus_babe::OpaqueKeyOwnershipProof::new)
2674		}
2675
2676		fn submit_report_equivocation_unsigned_extrinsic(
2677			equivocation_proof: sp_consensus_babe::EquivocationProof<<Block as BlockT>::Header>,
2678			key_owner_proof: sp_consensus_babe::OpaqueKeyOwnershipProof,
2679		) -> Option<()> {
2680			let key_owner_proof = key_owner_proof.decode()?;
2681
2682			Babe::submit_unsigned_equivocation_report(
2683				equivocation_proof,
2684				key_owner_proof,
2685			)
2686		}
2687	}
2688
2689	impl sp_authority_discovery::AuthorityDiscoveryApi<Block> for Runtime {
2690		fn authorities() -> Vec<AuthorityDiscoveryId> {
2691			parachains_runtime_api_impl::relevant_authority_ids::<Runtime>()
2692		}
2693	}
2694
2695	impl sp_session::SessionKeys<Block> for Runtime {
2696		fn generate_session_keys(owner: Vec<u8>, seed: Option<Vec<u8>>) -> sp_session::OpaqueGeneratedSessionKeys {
2697			SessionKeys::generate(&owner, seed).into()
2698		}
2699
2700		fn decode_session_keys(
2701			encoded: Vec<u8>,
2702		) -> Option<Vec<(Vec<u8>, sp_core::crypto::KeyTypeId)>> {
2703			SessionKeys::decode_into_raw_public_keys(&encoded)
2704		}
2705	}
2706
2707	impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
2708		fn account_nonce(account: AccountId) -> Nonce {
2709			System::account_nonce(account)
2710		}
2711	}
2712
2713	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<
2714		Block,
2715		Balance,
2716	> for Runtime {
2717		fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {
2718			TransactionPayment::query_info(uxt, len)
2719		}
2720		fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {
2721			TransactionPayment::query_fee_details(uxt, len)
2722		}
2723		fn query_weight_to_fee(weight: Weight) -> Balance {
2724			TransactionPayment::weight_to_fee(weight)
2725		}
2726		fn query_length_to_fee(length: u32) -> Balance {
2727			TransactionPayment::length_to_fee(length)
2728		}
2729	}
2730
2731	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi<Block, Balance, RuntimeCall>
2732		for Runtime
2733	{
2734		fn query_call_info(call: RuntimeCall, len: u32) -> RuntimeDispatchInfo<Balance> {
2735			TransactionPayment::query_call_info(call, len)
2736		}
2737		fn query_call_fee_details(call: RuntimeCall, len: u32) -> FeeDetails<Balance> {
2738			TransactionPayment::query_call_fee_details(call, len)
2739		}
2740		fn query_weight_to_fee(weight: Weight) -> Balance {
2741			TransactionPayment::weight_to_fee(weight)
2742		}
2743		fn query_length_to_fee(length: u32) -> Balance {
2744			TransactionPayment::length_to_fee(length)
2745		}
2746	}
2747
2748	impl xcm_runtime_apis::fees::XcmPaymentApi<Block> for Runtime {
2749		fn query_acceptable_payment_assets(xcm_version: xcm::Version) -> Result<Vec<VersionedAssetId>, XcmPaymentApiError> {
2750			let acceptable_assets = vec![AssetId(xcm_config::TokenLocation::get())];
2751			XcmPallet::query_acceptable_payment_assets(xcm_version, acceptable_assets)
2752		}
2753
2754		fn query_weight_to_asset_fee(weight: Weight, asset: VersionedAssetId) -> Result<u128, XcmPaymentApiError> {
2755			type Trader = <XcmConfig as xcm_executor::Config>::Trader;
2756			XcmPallet::query_weight_to_asset_fee::<Trader>(weight, asset)
2757		}
2758
2759		fn query_xcm_weight(message: VersionedXcm<()>) -> Result<Weight, XcmPaymentApiError> {
2760			XcmPallet::query_xcm_weight(message)
2761		}
2762
2763		fn query_delivery_fees(destination: VersionedLocation, message: VersionedXcm<()>, asset_id: VersionedAssetId) -> Result<VersionedAssets, XcmPaymentApiError> {
2764			type AssetExchanger = <XcmConfig as xcm_executor::Config>::AssetExchanger;
2765			XcmPallet::query_delivery_fees::<AssetExchanger>(destination, message, asset_id)
2766		}
2767	}
2768
2769	impl xcm_runtime_apis::dry_run::DryRunApi<Block, RuntimeCall, RuntimeEvent, OriginCaller> for Runtime {
2770		fn dry_run_call(origin: OriginCaller, call: RuntimeCall, result_xcms_version: XcmVersion) -> Result<CallDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
2771			XcmPallet::dry_run_call::<Runtime, xcm_config::XcmRouter, OriginCaller, RuntimeCall>(origin, call, result_xcms_version)
2772		}
2773
2774		fn dry_run_xcm(origin_location: VersionedLocation, xcm: VersionedXcm<RuntimeCall>) -> Result<XcmDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
2775			XcmPallet::dry_run_xcm::<xcm_config::XcmRouter>(origin_location, xcm)
2776		}
2777	}
2778
2779	impl xcm_runtime_apis::conversions::LocationToAccountApi<Block, AccountId> for Runtime {
2780		fn convert_location(location: VersionedLocation) -> Result<
2781			AccountId,
2782			xcm_runtime_apis::conversions::Error
2783		> {
2784			xcm_runtime_apis::conversions::LocationToAccountHelper::<
2785				AccountId,
2786				xcm_config::LocationConverter,
2787			>::convert_location(location)
2788		}
2789	}
2790
2791	impl pallet_nomination_pools_runtime_api::NominationPoolsApi<
2792		Block,
2793		AccountId,
2794		Balance,
2795	> for Runtime {
2796		fn pending_rewards(member: AccountId) -> Balance {
2797			NominationPools::api_pending_rewards(member).unwrap_or_default()
2798		}
2799
2800		fn points_to_balance(pool_id: PoolId, points: Balance) -> Balance {
2801			NominationPools::api_points_to_balance(pool_id, points)
2802		}
2803
2804		fn balance_to_points(pool_id: PoolId, new_funds: Balance) -> Balance {
2805			NominationPools::api_balance_to_points(pool_id, new_funds)
2806		}
2807
2808		fn pool_pending_slash(pool_id: PoolId) -> Balance {
2809			NominationPools::api_pool_pending_slash(pool_id)
2810		}
2811
2812		fn member_pending_slash(member: AccountId) -> Balance {
2813			NominationPools::api_member_pending_slash(member)
2814		}
2815
2816		fn pool_needs_delegate_migration(pool_id: PoolId) -> bool {
2817			NominationPools::api_pool_needs_delegate_migration(pool_id)
2818		}
2819
2820		fn member_needs_delegate_migration(member: AccountId) -> bool {
2821			NominationPools::api_member_needs_delegate_migration(member)
2822		}
2823
2824		fn member_total_balance(member: AccountId) -> Balance {
2825			NominationPools::api_member_total_balance(member)
2826		}
2827
2828		fn pool_balance(pool_id: PoolId) -> Balance {
2829			NominationPools::api_pool_balance(pool_id)
2830		}
2831
2832		fn pool_accounts(pool_id: PoolId) -> (AccountId, AccountId) {
2833			NominationPools::api_pool_accounts(pool_id)
2834		}
2835	}
2836
2837	impl pallet_staking_runtime_api::StakingApi<Block, Balance, AccountId> for Runtime {
2838		fn nominations_quota(balance: Balance) -> u32 {
2839			Staking::api_nominations_quota(balance)
2840		}
2841
2842		fn eras_stakers_page_count(era: sp_staking::EraIndex, account: AccountId) -> sp_staking::Page {
2843			Staking::api_eras_stakers_page_count(era, account)
2844		}
2845
2846		fn pending_rewards(era: sp_staking::EraIndex, account: AccountId) -> bool {
2847			Staking::api_pending_rewards(era, account)
2848		}
2849	}
2850
2851	#[cfg(feature = "try-runtime")]
2852	impl frame_try_runtime::TryRuntime<Block> for Runtime {
2853		fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) {
2854			log::info!("try-runtime::on_runtime_upgrade westend.");
2855		  // TODO:: remove once https://github.com/paritytech/polkadot-sdk/issues/9442 is resolved.
2856			let excluded_pallets = vec![
2857				b"Staking".to_vec(),          // replaced by staking-async
2858				b"NominationPools".to_vec(),  // moved to AH
2859				b"FastUnstake".to_vec(),      // deprecated
2860				b"DelegatedStaking".to_vec(), // moved to AH
2861			];
2862			let config = frame_executive::TryRuntimeUpgradeConfig::new(checks)
2863				.with_try_state_select(frame_try_runtime::TryStateSelect::AllExcept(
2864					excluded_pallets,
2865				));
2866			let weight = Executive::try_runtime_upgrade_with_config(config).unwrap();
2867			(weight, BlockWeights::get().max_block)
2868		}
2869
2870		fn execute_block(
2871			block: <Block as BlockT>::LazyBlock,
2872			state_root_check: bool,
2873			signature_check: bool,
2874			select: frame_try_runtime::TryStateSelect,
2875		) -> Weight {
2876			// NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to
2877			// have a backtrace here.
2878			Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap()
2879		}
2880	}
2881
2882	#[cfg(feature = "runtime-benchmarks")]
2883	impl frame_benchmarking::Benchmark<Block> for Runtime {
2884		fn benchmark_metadata(extra: bool) -> (
2885			Vec<frame_benchmarking::BenchmarkList>,
2886			Vec<frame_support::traits::StorageInfo>,
2887		) {
2888			use frame_benchmarking::BenchmarkList;
2889			use frame_support::traits::StorageInfoTrait;
2890
2891			use pallet_session_benchmarking::Pallet as SessionBench;
2892			use pallet_offences_benchmarking::Pallet as OffencesBench;
2893			use pallet_election_provider_support_benchmarking::Pallet as ElectionProviderBench;
2894			use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
2895			use frame_system_benchmarking::Pallet as SystemBench;
2896			use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
2897			use pallet_nomination_pools_benchmarking::Pallet as NominationPoolsBench;
2898
2899			type XcmBalances = pallet_xcm_benchmarks::fungible::Pallet::<Runtime>;
2900			type XcmGeneric = pallet_xcm_benchmarks::generic::Pallet::<Runtime>;
2901
2902			let mut list = Vec::<BenchmarkList>::new();
2903			list_benchmarks!(list, extra);
2904
2905			let storage_info = AllPalletsWithSystem::storage_info();
2906			return (list, storage_info)
2907		}
2908
2909		#[allow(non_local_definitions)]
2910		fn dispatch_benchmark(
2911			config: frame_benchmarking::BenchmarkConfig,
2912		) -> Result<
2913			Vec<frame_benchmarking::BenchmarkBatch>,
2914			alloc::string::String,
2915		> {
2916			use frame_support::traits::WhitelistedStorageKeys;
2917			use frame_benchmarking::{BenchmarkBatch, BenchmarkError};
2918			use sp_storage::TrackedStorageKey;
2919			// Trying to add benchmarks directly to some pallets caused cyclic dependency issues.
2920			// To get around that, we separated the benchmarks into its own crate.
2921			use pallet_session_benchmarking::Pallet as SessionBench;
2922			use pallet_offences_benchmarking::Pallet as OffencesBench;
2923			use pallet_election_provider_support_benchmarking::Pallet as ElectionProviderBench;
2924			use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
2925			use frame_system_benchmarking::Pallet as SystemBench;
2926			use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
2927			use pallet_nomination_pools_benchmarking::Pallet as NominationPoolsBench;
2928
2929			impl pallet_session_benchmarking::Config for Runtime {
2930				fn generate_session_keys_and_proof(owner: Self::AccountId) -> (Self::Keys, Vec<u8>) {
2931					let keys = SessionKeys::generate(&owner.encode(), None);
2932					(keys.keys, keys.proof.encode())
2933				}
2934			}
2935
2936			impl pallet_offences_benchmarking::Config for Runtime {}
2937			impl pallet_election_provider_support_benchmarking::Config for Runtime {}
2938
2939			use xcm_config::{AssetHub, TokenLocation};
2940
2941			use alloc::boxed::Box;
2942
2943			parameter_types! {
2944				pub ExistentialDepositAsset: Option<Asset> = Some((
2945					TokenLocation::get(),
2946					ExistentialDeposit::get()
2947				).into());
2948				pub AssetHubParaId: ParaId = westend_runtime_constants::system_parachain::ASSET_HUB_ID.into();
2949				pub const RandomParaId: ParaId = ParaId::new(43211234);
2950			}
2951
2952			impl pallet_xcm::benchmarking::Config for Runtime {
2953				type DeliveryHelper = (
2954					polkadot_runtime_common::xcm_sender::ToParachainDeliveryHelper<
2955						xcm_config::XcmConfig,
2956						ExistentialDepositAsset,
2957						xcm_config::PriceForChildParachainDelivery,
2958						AssetHubParaId,
2959						Dmp,
2960					>,
2961					polkadot_runtime_common::xcm_sender::ToParachainDeliveryHelper<
2962						xcm_config::XcmConfig,
2963						ExistentialDepositAsset,
2964						xcm_config::PriceForChildParachainDelivery,
2965						RandomParaId,
2966						Dmp,
2967					>
2968				);
2969
2970				fn reachable_dest() -> Option<Location> {
2971					Some(crate::xcm_config::AssetHub::get())
2972				}
2973
2974				fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
2975					// Relay/native token can be teleported to/from AH.
2976					Some((
2977						Asset { fun: Fungible(ExistentialDeposit::get()), id: AssetId(Here.into()) },
2978						crate::xcm_config::AssetHub::get(),
2979					))
2980				}
2981
2982				fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
2983					None
2984				}
2985
2986				fn set_up_complex_asset_transfer(
2987				) -> Option<(Assets, u32, Location, Box<dyn FnOnce()>)> {
2988					// Relay supports only native token, either reserve transfer it to non-system parachains,
2989					// or teleport it to system parachain. Use the teleport case for benchmarking as it's
2990					// slightly heavier.
2991
2992					// Relay/native token can be teleported to/from AH.
2993					let native_location = Here.into();
2994					let dest = crate::xcm_config::AssetHub::get();
2995					pallet_xcm::benchmarking::helpers::native_teleport_as_asset_transfer::<Runtime>(
2996						native_location,
2997						dest
2998					)
2999				}
3000
3001				fn get_asset() -> Asset {
3002					Asset {
3003						id: AssetId(Location::here()),
3004						fun: Fungible(ExistentialDeposit::get()),
3005					}
3006				}
3007			}
3008			impl frame_system_benchmarking::Config for Runtime {}
3009			impl pallet_transaction_payment::BenchmarkConfig for Runtime {}
3010			impl pallet_nomination_pools_benchmarking::Config for Runtime {}
3011			impl polkadot_runtime_parachains::disputes::slashing::benchmarking::Config for Runtime {}
3012
3013			use xcm::latest::{
3014				AssetId, Fungibility::*, InteriorLocation, Junction, Junctions::*,
3015				Asset, Assets, Location, NetworkId, Response,
3016			};
3017
3018			impl pallet_xcm_benchmarks::Config for Runtime {
3019				type XcmConfig = xcm_config::XcmConfig;
3020				type AccountIdConverter = xcm_config::LocationConverter;
3021				type DeliveryHelper = polkadot_runtime_common::xcm_sender::ToParachainDeliveryHelper<
3022					xcm_config::XcmConfig,
3023					ExistentialDepositAsset,
3024					xcm_config::PriceForChildParachainDelivery,
3025					AssetHubParaId,
3026					Dmp,
3027				>;
3028				fn valid_destination() -> Result<Location, BenchmarkError> {
3029					Ok(AssetHub::get())
3030				}
3031				fn worst_case_holding(_depositable_count: u32) -> xcm_executor::AssetsInHolding {
3032					use pallet_xcm_benchmarks::MockCredit;
3033					// Westend only knows about WND.
3034					let mut holding = xcm_executor::AssetsInHolding::new();
3035					holding.fungible.insert(
3036						AssetId(TokenLocation::get()),
3037						alloc::boxed::Box::new(MockCredit(1_000_000 * UNITS)),
3038					);
3039					holding
3040				}
3041			}
3042
3043			parameter_types! {
3044				pub TrustedTeleporter: Option<(Location, Asset)> = Some((
3045					AssetHub::get(),
3046					Asset { fun: Fungible(1 * UNITS), id: AssetId(TokenLocation::get()) },
3047				));
3048				pub const TrustedReserve: Option<(Location, Asset)> = None;
3049				pub const CheckedAccount: Option<(AccountId, xcm_builder::MintLocation)> = None;
3050			}
3051
3052			impl pallet_xcm_benchmarks::fungible::Config for Runtime {
3053				type TransactAsset = Balances;
3054
3055				type CheckedAccount = CheckedAccount;
3056				type TrustedTeleporter = TrustedTeleporter;
3057				type TrustedReserve = TrustedReserve;
3058
3059				fn get_asset() -> Asset {
3060					Asset {
3061						id: AssetId(TokenLocation::get()),
3062						fun: Fungible(1 * UNITS),
3063					}
3064				}
3065			}
3066
3067			impl pallet_xcm_benchmarks::generic::Config for Runtime {
3068				type TransactAsset = Balances;
3069				type RuntimeCall = RuntimeCall;
3070
3071				fn worst_case_response() -> (u64, Response) {
3072					(0u64, Response::Version(Default::default()))
3073				}
3074
3075				fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> {
3076					// Westend doesn't support asset exchanges
3077					Err(BenchmarkError::Skip)
3078				}
3079
3080				fn universal_alias() -> Result<(Location, Junction), BenchmarkError> {
3081					// The XCM executor of Westend doesn't have a configured `UniversalAliases`
3082					Err(BenchmarkError::Skip)
3083				}
3084
3085				fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> {
3086					Ok((AssetHub::get(), frame_system::Call::remark_with_event { remark: vec![] }.into()))
3087				}
3088
3089				fn subscribe_origin() -> Result<Location, BenchmarkError> {
3090					Ok(AssetHub::get())
3091				}
3092
3093				fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> {
3094					let origin = AssetHub::get();
3095					let assets: Assets = (AssetId(TokenLocation::get()), 1_000 * UNITS).into();
3096					let ticket = Location { parents: 0, interior: Here };
3097					Ok((origin, ticket, assets))
3098				}
3099
3100				fn worst_case_for_trader() -> Result<(Asset, WeightLimit), BenchmarkError> {
3101					Ok((Asset {
3102						id: AssetId(TokenLocation::get()),
3103						fun: Fungible(1_000_000 * UNITS),
3104					}, WeightLimit::Limited(Weight::from_parts(5000, 5000))))
3105				}
3106
3107				fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> {
3108					// Westend doesn't support asset locking
3109					Err(BenchmarkError::Skip)
3110				}
3111
3112				fn export_message_origin_and_destination(
3113				) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> {
3114					// Westend doesn't support exporting messages
3115					Err(BenchmarkError::Skip)
3116				}
3117
3118				fn alias_origin() -> Result<(Location, Location), BenchmarkError> {
3119					let origin = Location::new(0, [Parachain(1000)]);
3120					let target = Location::new(0, [Parachain(1000), AccountId32 { id: [128u8; 32], network: None }]);
3121					Ok((origin, target))
3122				}
3123			}
3124
3125			type XcmBalances = pallet_xcm_benchmarks::fungible::Pallet::<Runtime>;
3126			type XcmGeneric = pallet_xcm_benchmarks::generic::Pallet::<Runtime>;
3127
3128			let whitelist: Vec<TrackedStorageKey> = AllPalletsWithSystem::whitelisted_storage_keys();
3129
3130			let mut batches = Vec::<BenchmarkBatch>::new();
3131			let params = (&config, &whitelist);
3132
3133			add_benchmarks!(params, batches);
3134
3135			Ok(batches)
3136		}
3137	}
3138
3139	impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
3140		fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
3141			build_state::<RuntimeGenesisConfig>(config)
3142		}
3143
3144		fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
3145			get_preset::<RuntimeGenesisConfig>(id, &genesis_config_presets::get_preset)
3146		}
3147
3148		fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
3149			genesis_config_presets::preset_names()
3150		}
3151	}
3152
3153	impl xcm_runtime_apis::trusted_query::TrustedQueryApi<Block> for Runtime {
3154		fn is_trusted_reserve(asset: VersionedAsset, location: VersionedLocation) -> Result<bool, xcm_runtime_apis::trusted_query::Error> {
3155			XcmPallet::is_trusted_reserve(asset, location)
3156		}
3157		fn is_trusted_teleporter(asset: VersionedAsset, location: VersionedLocation) -> Result<bool, xcm_runtime_apis::trusted_query::Error> {
3158			XcmPallet::is_trusted_teleporter(asset, location)
3159		}
3160	}
3161}