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