referrerpolicy=no-referrer-when-downgrade

rococo_runtime/
lib.rs

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