Skip to main content

westend_runtime/
lib.rs

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