Skip to main content

westend_runtime/
lib.rs

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