westend_runtime/
lib.rs

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