referrerpolicy=no-referrer-when-downgrade

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