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