referrerpolicy=no-referrer-when-downgrade

pallet_staking_async_rc_runtime/
lib.rs

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