westend_runtime/
lib.rs

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