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_025_002,
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 DepositProvider = Hrmp;
1136	type DefaultChannelSizeAndCapacityWithSystem = ActiveConfigHrmpChannelSizeAndCapacityRatio<
1137		Runtime,
1138		HrmpChannelSizeAndCapacityWithSystemRatio,
1139	>;
1140	type VersionWrapper = crate::XcmPallet;
1141	type WeightInfo = weights::polkadot_runtime_parachains_hrmp::WeightInfo<Runtime>;
1142}
1143
1144impl parachains_paras_inherent::Config for Runtime {
1145	type WeightInfo = weights::polkadot_runtime_parachains_paras_inherent::WeightInfo<Runtime>;
1146}
1147
1148impl parachains_scheduler::Config for Runtime {}
1149
1150parameter_types! {
1151	pub const BrokerId: u32 = BROKER_ID;
1152	pub const BrokerPalletId: PalletId = PalletId(*b"py/broke");
1153	pub MaxXcmTransactWeight: Weight = Weight::from_parts(200_000_000, 20_000);
1154}
1155
1156pub struct BrokerPot;
1157impl Get<InteriorLocation> for BrokerPot {
1158	fn get() -> InteriorLocation {
1159		Junction::AccountId32 { network: None, id: BrokerPalletId::get().into_account_truncating() }
1160			.into()
1161	}
1162}
1163
1164impl coretime::Config for Runtime {
1165	type RuntimeOrigin = RuntimeOrigin;
1166	type RuntimeEvent = RuntimeEvent;
1167	type BrokerId = BrokerId;
1168	type BrokerPotLocation = BrokerPot;
1169	type WeightInfo = weights::polkadot_runtime_parachains_coretime::WeightInfo<Runtime>;
1170	type SendXcm = crate::xcm_config::XcmRouter;
1171	type AssetTransactor = crate::xcm_config::LocalAssetTransactor;
1172	type AccountToLocation = xcm_builder::AliasesIntoAccountId32<
1173		xcm_config::ThisNetwork,
1174		<Runtime as frame_system::Config>::AccountId,
1175	>;
1176	type MaxXcmTransactWeight = MaxXcmTransactWeight;
1177}
1178
1179parameter_types! {
1180	pub const OnDemandTrafficDefaultValue: FixedU128 = FixedU128::from_u32(1);
1181	// Keep 2 timeslices worth of revenue information.
1182	pub const MaxHistoricalRevenue: BlockNumber = 2 * TIMESLICE_PERIOD;
1183	pub const OnDemandPalletId: PalletId = PalletId(*b"py/ondmd");
1184}
1185
1186impl parachains_on_demand::Config for Runtime {
1187	type RuntimeEvent = RuntimeEvent;
1188	type Currency = Balances;
1189	type TrafficDefaultValue = OnDemandTrafficDefaultValue;
1190	type WeightInfo = weights::polkadot_runtime_parachains_on_demand::WeightInfo<Runtime>;
1191	type MaxHistoricalRevenue = MaxHistoricalRevenue;
1192	type PalletId = OnDemandPalletId;
1193}
1194
1195impl parachains_initializer::Config for Runtime {
1196	type Randomness = pallet_babe::RandomnessFromOneEpochAgo<Runtime>;
1197	type ForceOrigin = EnsureRoot<AccountId>;
1198	type WeightInfo = weights::polkadot_runtime_parachains_initializer::WeightInfo<Runtime>;
1199	type CoretimeOnNewSession = Coretime;
1200}
1201
1202impl parachains_disputes::Config for Runtime {
1203	type RuntimeEvent = RuntimeEvent;
1204	type RewardValidators = ();
1205	type SlashingHandler = parachains_slashing::SlashValidatorsForDisputes<ParasSlashing>;
1206	type WeightInfo = weights::polkadot_runtime_parachains_disputes::WeightInfo<Runtime>;
1207}
1208
1209impl parachains_slashing::Config for Runtime {
1210	type KeyOwnerProofSystem = Historical;
1211	type KeyOwnerProof =
1212		<Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, ValidatorId)>>::Proof;
1213	type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
1214		KeyTypeId,
1215		ValidatorId,
1216	)>>::IdentificationTuple;
1217	type HandleReports = parachains_slashing::SlashingReportHandler<
1218		Self::KeyOwnerIdentification,
1219		Offences,
1220		ReportLongevity,
1221	>;
1222	type WeightInfo = parachains_slashing::TestWeightInfo;
1223	type BenchmarkingConfig = parachains_slashing::BenchConfig<200>;
1224}
1225
1226parameter_types! {
1227	pub const ParaDeposit: Balance = 40 * UNITS;
1228}
1229
1230impl paras_registrar::Config for Runtime {
1231	type RuntimeOrigin = RuntimeOrigin;
1232	type RuntimeEvent = RuntimeEvent;
1233	type Currency = Balances;
1234	type OnSwap = (Crowdloan, Slots, SwapLeases);
1235	type ParaDeposit = ParaDeposit;
1236	type DataDepositPerByte = DataDepositPerByte;
1237	type WeightInfo = weights::polkadot_runtime_common_paras_registrar::WeightInfo<Runtime>;
1238}
1239
1240parameter_types! {
1241	pub LeasePeriod: BlockNumber = prod_or_fast!(1 * DAYS, 1 * DAYS, "ROC_LEASE_PERIOD");
1242}
1243
1244impl slots::Config for Runtime {
1245	type RuntimeEvent = RuntimeEvent;
1246	type Currency = Balances;
1247	type Registrar = Registrar;
1248	type LeasePeriod = LeasePeriod;
1249	type LeaseOffset = ();
1250	type ForceOrigin = EitherOf<EnsureRoot<Self::AccountId>, LeaseAdmin>;
1251	type WeightInfo = weights::polkadot_runtime_common_slots::WeightInfo<Runtime>;
1252}
1253
1254parameter_types! {
1255	pub const CrowdloanId: PalletId = PalletId(*b"py/cfund");
1256	pub const SubmissionDeposit: Balance = 3 * GRAND;
1257	pub const MinContribution: Balance = 3_000 * CENTS;
1258	pub const RemoveKeysLimit: u32 = 1000;
1259	// Allow 32 bytes for an additional memo to a crowdloan.
1260	pub const MaxMemoLength: u8 = 32;
1261}
1262
1263impl crowdloan::Config for Runtime {
1264	type RuntimeEvent = RuntimeEvent;
1265	type PalletId = CrowdloanId;
1266	type SubmissionDeposit = SubmissionDeposit;
1267	type MinContribution = MinContribution;
1268	type RemoveKeysLimit = RemoveKeysLimit;
1269	type Registrar = Registrar;
1270	type Auctioneer = Auctions;
1271	type MaxMemoLength = MaxMemoLength;
1272	type WeightInfo = weights::polkadot_runtime_common_crowdloan::WeightInfo<Runtime>;
1273}
1274
1275parameter_types! {
1276	// The average auction is 7 days long, so this will be 70% for ending period.
1277	// 5 Days = 72000 Blocks @ 6 sec per block
1278	pub const EndingPeriod: BlockNumber = 5 * DAYS;
1279	// ~ 1000 samples per day -> ~ 20 blocks per sample -> 2 minute samples
1280	pub const SampleLength: BlockNumber = 2 * MINUTES;
1281}
1282
1283impl auctions::Config for Runtime {
1284	type RuntimeEvent = RuntimeEvent;
1285	type Leaser = Slots;
1286	type Registrar = Registrar;
1287	type EndingPeriod = EndingPeriod;
1288	type SampleLength = SampleLength;
1289	type Randomness = pallet_babe::RandomnessFromOneEpochAgo<Runtime>;
1290	type InitiateOrigin = EitherOf<EnsureRoot<Self::AccountId>, AuctionAdmin>;
1291	type WeightInfo = weights::polkadot_runtime_common_auctions::WeightInfo<Runtime>;
1292}
1293
1294impl identity_migrator::Config for Runtime {
1295	type RuntimeEvent = RuntimeEvent;
1296	type Reaper = EnsureSigned<AccountId>;
1297	type ReapIdentityHandler = ToParachainIdentityReaper<Runtime, Self::AccountId>;
1298	type WeightInfo = weights::polkadot_runtime_common_identity_migrator::WeightInfo<Runtime>;
1299}
1300
1301type NisCounterpartInstance = pallet_balances::Instance2;
1302impl pallet_balances::Config<NisCounterpartInstance> for Runtime {
1303	type Balance = Balance;
1304	type DustRemoval = ();
1305	type RuntimeEvent = RuntimeEvent;
1306	type ExistentialDeposit = ConstU128<10_000_000_000>; // One RTC cent
1307	type AccountStore = StorageMapShim<
1308		pallet_balances::Account<Runtime, NisCounterpartInstance>,
1309		AccountId,
1310		pallet_balances::AccountData<u128>,
1311	>;
1312	type MaxLocks = ConstU32<4>;
1313	type MaxReserves = ConstU32<4>;
1314	type ReserveIdentifier = [u8; 8];
1315	type WeightInfo = weights::pallet_balances_nis_counterpart_balances::WeightInfo<Runtime>;
1316	type RuntimeHoldReason = RuntimeHoldReason;
1317	type RuntimeFreezeReason = RuntimeFreezeReason;
1318	type DoneSlashHandler = ();
1319}
1320
1321parameter_types! {
1322	pub const NisBasePeriod: BlockNumber = 30 * DAYS;
1323	pub MinReceipt: Perquintill = Perquintill::from_rational(1u64, 10_000_000u64);
1324	pub const IntakePeriod: BlockNumber = 5 * MINUTES;
1325	pub MaxIntakeWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;
1326	pub const ThawThrottle: (Perquintill, BlockNumber) = (Perquintill::from_percent(25), 5);
1327	pub const NisPalletId: PalletId = PalletId(*b"py/nis  ");
1328}
1329
1330impl pallet_nis::Config for Runtime {
1331	type WeightInfo = weights::pallet_nis::WeightInfo<Runtime>;
1332	type RuntimeEvent = RuntimeEvent;
1333	type Currency = Balances;
1334	type CurrencyBalance = Balance;
1335	type FundOrigin = frame_system::EnsureSigned<AccountId>;
1336	type Counterpart = NisCounterpartBalances;
1337	type CounterpartAmount = WithMaximumOf<ConstU128<21_000_000_000_000_000_000u128>>;
1338	type Deficit = (); // Mint
1339	type IgnoredIssuance = ();
1340	type Target = dynamic_params::nis::Target;
1341	type PalletId = NisPalletId;
1342	type QueueCount = ConstU32<300>;
1343	type MaxQueueLen = ConstU32<1000>;
1344	type FifoQueueLen = ConstU32<250>;
1345	type BasePeriod = NisBasePeriod;
1346	type MinBid = dynamic_params::nis::MinBid;
1347	type MinReceipt = MinReceipt;
1348	type IntakePeriod = IntakePeriod;
1349	type MaxIntakeWeight = MaxIntakeWeight;
1350	type ThawThrottle = ThawThrottle;
1351	type RuntimeHoldReason = RuntimeHoldReason;
1352	#[cfg(feature = "runtime-benchmarks")]
1353	type BenchmarkSetup = ();
1354}
1355
1356impl pallet_parameters::Config for Runtime {
1357	type RuntimeEvent = RuntimeEvent;
1358	type RuntimeParameters = RuntimeParameters;
1359	type AdminOrigin = DynamicParameterOrigin;
1360	type WeightInfo = weights::pallet_parameters::WeightInfo<Runtime>;
1361}
1362
1363parameter_types! {
1364	pub BeefySetIdSessionEntries: u32 = BondingDuration::get() * SessionsPerEra::get();
1365}
1366
1367impl pallet_beefy::Config for Runtime {
1368	type BeefyId = BeefyId;
1369	type MaxAuthorities = MaxAuthorities;
1370	type MaxNominators = ConstU32<0>;
1371	type MaxSetIdSessionEntries = BeefySetIdSessionEntries;
1372	type OnNewValidatorSet = MmrLeaf;
1373	type AncestryHelper = MmrLeaf;
1374	type WeightInfo = ();
1375	type KeyOwnerProof = <Historical as KeyOwnerProofSystem<(KeyTypeId, BeefyId)>>::Proof;
1376	type EquivocationReportSystem =
1377		pallet_beefy::EquivocationReportSystem<Self, Offences, Historical, ReportLongevity>;
1378}
1379
1380/// MMR helper types.
1381mod mmr {
1382	use super::Runtime;
1383	pub use pallet_mmr::primitives::*;
1384
1385	pub type Leaf = <<Runtime as pallet_mmr::Config>::LeafData as LeafDataProvider>::LeafData;
1386	pub type Hashing = <Runtime as pallet_mmr::Config>::Hashing;
1387	pub type Hash = <Hashing as sp_runtime::traits::Hash>::Output;
1388}
1389
1390impl pallet_mmr::Config for Runtime {
1391	const INDEXING_PREFIX: &'static [u8] = mmr::INDEXING_PREFIX;
1392	type Hashing = Keccak256;
1393	type OnNewRoot = pallet_beefy_mmr::DepositBeefyDigest<Runtime>;
1394	type LeafData = pallet_beefy_mmr::Pallet<Runtime>;
1395	type BlockHashProvider = pallet_mmr::DefaultBlockHashProvider<Runtime>;
1396	type WeightInfo = weights::pallet_mmr::WeightInfo<Runtime>;
1397	#[cfg(feature = "runtime-benchmarks")]
1398	type BenchmarkHelper = parachains_paras::benchmarking::mmr_setup::MmrSetup<Runtime>;
1399}
1400
1401parameter_types! {
1402	pub LeafVersion: MmrLeafVersion = MmrLeafVersion::new(0, 0);
1403}
1404
1405pub struct ParaHeadsRootProvider;
1406impl BeefyDataProvider<H256> for ParaHeadsRootProvider {
1407	fn extra_data() -> H256 {
1408		let para_heads: Vec<(u32, Vec<u8>)> =
1409			parachains_paras::Pallet::<Runtime>::sorted_para_heads();
1410		binary_merkle_tree::merkle_root::<mmr::Hashing, _>(
1411			para_heads.into_iter().map(|pair| pair.encode()),
1412		)
1413		.into()
1414	}
1415}
1416
1417impl pallet_beefy_mmr::Config for Runtime {
1418	type LeafVersion = LeafVersion;
1419	type BeefyAuthorityToMerkleLeaf = pallet_beefy_mmr::BeefyEcdsaToEthereum;
1420	type LeafExtra = H256;
1421	type BeefyDataProvider = ParaHeadsRootProvider;
1422	type WeightInfo = weights::pallet_beefy_mmr::WeightInfo<Runtime>;
1423}
1424
1425impl paras_sudo_wrapper::Config for Runtime {}
1426
1427parameter_types! {
1428	pub const PermanentSlotLeasePeriodLength: u32 = 365;
1429	pub const TemporarySlotLeasePeriodLength: u32 = 5;
1430	pub const MaxTemporarySlotPerLeasePeriod: u32 = 5;
1431}
1432
1433impl assigned_slots::Config for Runtime {
1434	type RuntimeEvent = RuntimeEvent;
1435	type AssignSlotOrigin = EnsureRoot<AccountId>;
1436	type Leaser = Slots;
1437	type PermanentSlotLeasePeriodLength = PermanentSlotLeasePeriodLength;
1438	type TemporarySlotLeasePeriodLength = TemporarySlotLeasePeriodLength;
1439	type MaxTemporarySlotPerLeasePeriod = MaxTemporarySlotPerLeasePeriod;
1440	type WeightInfo = weights::polkadot_runtime_common_assigned_slots::WeightInfo<Runtime>;
1441}
1442
1443impl validator_manager::Config for Runtime {
1444	type RuntimeEvent = RuntimeEvent;
1445	type PrivilegedOrigin = EnsureRoot<AccountId>;
1446}
1447
1448parameter_types! {
1449	pub MbmServiceWeight: Weight = Perbill::from_percent(80) * BlockWeights::get().max_block;
1450}
1451
1452impl pallet_migrations::Config for Runtime {
1453	type RuntimeEvent = RuntimeEvent;
1454	#[cfg(not(feature = "runtime-benchmarks"))]
1455	type Migrations = (
1456		pallet_identity::migration::v2::LazyMigrationV1ToV2<Runtime>,
1457		parachains_dmp::migration::MigrateV0ToV1<Runtime>,
1458	);
1459	// Benchmarks need mocked migrations to guarantee that they succeed.
1460	#[cfg(feature = "runtime-benchmarks")]
1461	type Migrations = pallet_migrations::mock_helpers::MockedMigrations;
1462	type CursorMaxLen = ConstU32<65_536>;
1463	type IdentifierMaxLen = ConstU32<256>;
1464	type MigrationStatusHandler = ();
1465	type FailedMigrationHandler = frame_support::migrations::FreezeChainOnFailedMigration;
1466	type MaxServiceWeight = MbmServiceWeight;
1467	type WeightInfo = weights::pallet_migrations::WeightInfo<Runtime>;
1468}
1469
1470impl pallet_sudo::Config for Runtime {
1471	type RuntimeEvent = RuntimeEvent;
1472	type RuntimeCall = RuntimeCall;
1473	type WeightInfo = weights::pallet_sudo::WeightInfo<Runtime>;
1474}
1475
1476impl pallet_root_testing::Config for Runtime {
1477	type RuntimeEvent = RuntimeEvent;
1478}
1479
1480impl pallet_asset_rate::Config for Runtime {
1481	type WeightInfo = weights::pallet_asset_rate::WeightInfo<Runtime>;
1482	type RuntimeEvent = RuntimeEvent;
1483	type CreateOrigin = EnsureRoot<AccountId>;
1484	type RemoveOrigin = EnsureRoot<AccountId>;
1485	type UpdateOrigin = EnsureRoot<AccountId>;
1486	type Currency = Balances;
1487	type AssetKind = <Runtime as pallet_treasury::Config>::AssetKind;
1488	#[cfg(feature = "runtime-benchmarks")]
1489	type BenchmarkHelper = polkadot_runtime_common::impls::benchmarks::AssetRateArguments;
1490}
1491
1492// Notify `coretime` pallet when a lease swap occurs
1493pub struct SwapLeases;
1494impl OnSwap for SwapLeases {
1495	fn on_swap(one: ParaId, other: ParaId) {
1496		coretime::Pallet::<Runtime>::on_legacy_lease_swap(one, other);
1497	}
1498}
1499
1500construct_runtime! {
1501	pub enum Runtime
1502	{
1503		// Basic stuff; balances is uncallable initially.
1504		System: frame_system = 0,
1505
1506		// Babe must be before session.
1507		Babe: pallet_babe = 1,
1508
1509		Timestamp: pallet_timestamp = 2,
1510		Indices: pallet_indices = 3,
1511		Balances: pallet_balances = 4,
1512		Parameters: pallet_parameters = 6,
1513		TransactionPayment: pallet_transaction_payment = 33,
1514
1515		// Consensus support.
1516		// Authorship must be before session in order to note author in the correct session and era.
1517		Authorship: pallet_authorship = 5,
1518		Offences: pallet_offences = 7,
1519		Historical: session_historical = 34,
1520
1521		Session: pallet_session = 8,
1522		Grandpa: pallet_grandpa = 10,
1523		AuthorityDiscovery: pallet_authority_discovery = 12,
1524
1525		// Governance stuff; uncallable initially.
1526		Treasury: pallet_treasury = 18,
1527		ConvictionVoting: pallet_conviction_voting = 20,
1528		Referenda: pallet_referenda = 21,
1529		//	pub type FellowshipCollectiveInstance = pallet_ranked_collective::Instance1;
1530		FellowshipCollective: pallet_ranked_collective::<Instance1> = 22,
1531		// pub type FellowshipReferendaInstance = pallet_referenda::Instance2;
1532		FellowshipReferenda: pallet_referenda::<Instance2> = 23,
1533		Origins: pallet_custom_origins = 43,
1534		Whitelist: pallet_whitelist = 44,
1535		// Claims. Usable initially.
1536		Claims: claims = 19,
1537
1538		// Utility module.
1539		Utility: pallet_utility = 24,
1540
1541		// Less simple identity module.
1542		Identity: pallet_identity = 25,
1543
1544		// Society module.
1545		Society: pallet_society = 26,
1546
1547		// Social recovery module.
1548		Recovery: pallet_recovery = 27,
1549
1550		// Vesting. Usable initially, but removed once all vesting is finished.
1551		Vesting: pallet_vesting = 28,
1552
1553		// System scheduler.
1554		Scheduler: pallet_scheduler = 29,
1555
1556		// Proxy module. Late addition.
1557		Proxy: pallet_proxy = 30,
1558
1559		// Multisig module. Late addition.
1560		Multisig: pallet_multisig = 31,
1561
1562		// Preimage registrar.
1563		Preimage: pallet_preimage = 32,
1564
1565		// Asset rate.
1566		AssetRate: pallet_asset_rate = 39,
1567
1568		// Bounties modules.
1569		Bounties: pallet_bounties = 35,
1570		ChildBounties: pallet_child_bounties = 40,
1571
1572		// NIS pallet.
1573		Nis: pallet_nis = 38,
1574		// pub type NisCounterpartInstance = pallet_balances::Instance2;
1575		NisCounterpartBalances: pallet_balances::<Instance2> = 45,
1576
1577		// Parachains pallets. Start indices at 50 to leave room.
1578		ParachainsOrigin: parachains_origin = 50,
1579		Configuration: parachains_configuration = 51,
1580		ParasShared: parachains_shared = 52,
1581		ParaInclusion: parachains_inclusion = 53,
1582		ParaInherent: parachains_paras_inherent = 54,
1583		ParaScheduler: parachains_scheduler = 55,
1584		Paras: parachains_paras = 56,
1585		Initializer: parachains_initializer = 57,
1586		Dmp: parachains_dmp = 58,
1587		Hrmp: parachains_hrmp = 60,
1588		ParaSessionInfo: parachains_session_info = 61,
1589		ParasDisputes: parachains_disputes = 62,
1590		ParasSlashing: parachains_slashing = 63,
1591		MessageQueue: pallet_message_queue = 64,
1592		OnDemandAssignmentProvider: parachains_on_demand = 66,
1593		// RIP CoretimeAssignmentProvider 68 - Moved to scheduler::assigner_coretime submodule in PR #10184
1594
1595		// Parachain Onboarding Pallets. Start indices at 70 to leave room.
1596		Registrar: paras_registrar = 70,
1597		Slots: slots = 71,
1598		Auctions: auctions = 72,
1599		Crowdloan: crowdloan = 73,
1600		Coretime: coretime = 74,
1601
1602		// Migrations pallet
1603		MultiBlockMigrations: pallet_migrations = 98,
1604
1605		// Pallet for sending XCM.
1606		XcmPallet: pallet_xcm = 99,
1607
1608		// BEEFY Bridges support.
1609		Beefy: pallet_beefy = 240,
1610		// MMR leaf construction must be after session in order to have a leaf's next_auth_set
1611		// refer to block<N>. See issue polkadot-fellows/runtimes#160 for details.
1612		Mmr: pallet_mmr = 241,
1613		MmrLeaf: pallet_beefy_mmr = 242,
1614
1615		// Pallet for migrating Identity to a parachain. To be removed post-migration.
1616		IdentityMigrator: identity_migrator = 248,
1617
1618		ParasSudoWrapper: paras_sudo_wrapper = 250,
1619		AssignedSlots: assigned_slots = 251,
1620
1621		// Validator Manager pallet.
1622		ValidatorManager: validator_manager = 252,
1623
1624		// State trie migration pallet, only temporary.
1625		StateTrieMigration: pallet_state_trie_migration = 254,
1626
1627		// Root testing pallet.
1628		RootTesting: pallet_root_testing = 249,
1629
1630		// Sudo.
1631		Sudo: pallet_sudo = 255,
1632	}
1633}
1634
1635/// The address format for describing accounts.
1636pub type Address = sp_runtime::MultiAddress<AccountId, ()>;
1637/// Block header type as expected by this runtime.
1638pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
1639/// Block type as expected by this runtime.
1640pub type Block = generic::Block<Header, UncheckedExtrinsic>;
1641/// A Block signed with a Justification
1642pub type SignedBlock = generic::SignedBlock<Block>;
1643/// `BlockId` type as expected by this runtime.
1644pub type BlockId = generic::BlockId<Block>;
1645/// The extension to the basic transaction logic.
1646pub type TxExtension = (
1647	frame_system::AuthorizeCall<Runtime>,
1648	frame_system::CheckNonZeroSender<Runtime>,
1649	frame_system::CheckSpecVersion<Runtime>,
1650	frame_system::CheckTxVersion<Runtime>,
1651	frame_system::CheckGenesis<Runtime>,
1652	frame_system::CheckMortality<Runtime>,
1653	frame_system::CheckNonce<Runtime>,
1654	frame_system::CheckWeight<Runtime>,
1655	pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
1656	frame_metadata_hash_extension::CheckMetadataHash<Runtime>,
1657	frame_system::WeightReclaim<Runtime>,
1658);
1659
1660/// Unchecked extrinsic type as expected by this runtime.
1661pub type UncheckedExtrinsic =
1662	generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, TxExtension>;
1663/// Unchecked signature payload type as expected by this runtime.
1664pub type UncheckedSignaturePayload =
1665	generic::UncheckedSignaturePayload<Address, Signature, TxExtension>;
1666
1667/// All migrations that will run on the next runtime upgrade.
1668///
1669/// This contains the combined migrations of the last 10 releases. It allows to skip runtime
1670/// upgrades in case governance decides to do so. THE ORDER IS IMPORTANT.
1671pub type Migrations = migrations::Unreleased;
1672
1673/// The runtime migrations per release.
1674#[allow(deprecated, missing_docs)]
1675pub mod migrations {
1676	use super::*;
1677
1678	use frame_support::traits::LockIdentifier;
1679	use frame_system::pallet_prelude::BlockNumberFor;
1680
1681	parameter_types! {
1682		pub const DemocracyPalletName: &'static str = "Democracy";
1683		pub const CouncilPalletName: &'static str = "Council";
1684		pub const TechnicalCommitteePalletName: &'static str = "TechnicalCommittee";
1685		pub const PhragmenElectionPalletName: &'static str = "PhragmenElection";
1686		pub const TechnicalMembershipPalletName: &'static str = "TechnicalMembership";
1687		pub const TipsPalletName: &'static str = "Tips";
1688		pub const PhragmenElectionPalletId: LockIdentifier = *b"phrelect";
1689		/// Weight for balance unreservations
1690		pub BalanceUnreserveWeight: Weight = weights::pallet_balances_balances::WeightInfo::<Runtime>::force_unreserve();
1691		pub BalanceTransferAllowDeath: Weight = weights::pallet_balances_balances::WeightInfo::<Runtime>::transfer_allow_death();
1692	}
1693
1694	// Special Config for Gov V1 pallets, allowing us to run migrations for them without
1695	// implementing their configs on [`Runtime`].
1696	pub struct UnlockConfig;
1697	impl pallet_democracy::migrations::unlock_and_unreserve_all_funds::UnlockConfig for UnlockConfig {
1698		type Currency = Balances;
1699		type MaxVotes = ConstU32<100>;
1700		type MaxDeposits = ConstU32<100>;
1701		type AccountId = AccountId;
1702		type BlockNumber = BlockNumberFor<Runtime>;
1703		type DbWeight = <Runtime as frame_system::Config>::DbWeight;
1704		type PalletName = DemocracyPalletName;
1705	}
1706	impl pallet_elections_phragmen::migrations::unlock_and_unreserve_all_funds::UnlockConfig
1707		for UnlockConfig
1708	{
1709		type Currency = Balances;
1710		type MaxVotesPerVoter = ConstU32<16>;
1711		type PalletId = PhragmenElectionPalletId;
1712		type AccountId = AccountId;
1713		type DbWeight = <Runtime as frame_system::Config>::DbWeight;
1714		type PalletName = PhragmenElectionPalletName;
1715	}
1716	impl pallet_tips::migrations::unreserve_deposits::UnlockConfig<()> for UnlockConfig {
1717		type Currency = Balances;
1718		type Hash = Hash;
1719		type DataDepositPerByte = DataDepositPerByte;
1720		type TipReportDepositBase = TipReportDepositBase;
1721		type AccountId = AccountId;
1722		type BlockNumber = BlockNumberFor<Runtime>;
1723		type DbWeight = <Runtime as frame_system::Config>::DbWeight;
1724		type PalletName = TipsPalletName;
1725	}
1726
1727	// We don't have a limit in the Relay Chain.
1728	const IDENTITY_MIGRATION_KEY_LIMIT: u64 = u64::MAX;
1729
1730	/// Unreleased migrations. Add new ones here:
1731	pub type Unreleased = (
1732        pallet_society::migrations::MigrateToV2<Runtime, (), ()>,
1733        parachains_configuration::migration::v7::MigrateToV7<Runtime>,
1734        assigned_slots::migration::v1::MigrateToV1<Runtime>,
1735        parachains_configuration::migration::v8::MigrateToV8<Runtime>,
1736        parachains_configuration::migration::v9::MigrateToV9<Runtime>,
1737        paras_registrar::migration::MigrateToV1<Runtime, ()>,
1738        pallet_referenda::migration::v1::MigrateV0ToV1<Runtime, ()>,
1739        pallet_referenda::migration::v1::MigrateV0ToV1<Runtime, pallet_referenda::Instance2>,
1740        pallet_child_bounties::migration::MigrateV0ToV1<Runtime, BalanceTransferAllowDeath>,
1741
1742        // Unlock & unreserve Gov1 funds
1743
1744        pallet_elections_phragmen::migrations::unlock_and_unreserve_all_funds::UnlockAndUnreserveAllFunds<UnlockConfig>,
1745        pallet_democracy::migrations::unlock_and_unreserve_all_funds::UnlockAndUnreserveAllFunds<UnlockConfig>,
1746        pallet_tips::migrations::unreserve_deposits::UnreserveDeposits<UnlockConfig, ()>,
1747        pallet_treasury::migration::cleanup_proposals::Migration<Runtime, (), BalanceUnreserveWeight>,
1748
1749        // Delete all Gov v1 pallet storage key/values.
1750
1751        frame_support::migrations::RemovePallet<DemocracyPalletName, <Runtime as frame_system::Config>::DbWeight>,
1752        frame_support::migrations::RemovePallet<CouncilPalletName, <Runtime as frame_system::Config>::DbWeight>,
1753        frame_support::migrations::RemovePallet<TechnicalCommitteePalletName, <Runtime as frame_system::Config>::DbWeight>,
1754        frame_support::migrations::RemovePallet<PhragmenElectionPalletName, <Runtime as frame_system::Config>::DbWeight>,
1755        frame_support::migrations::RemovePallet<TechnicalMembershipPalletName, <Runtime as frame_system::Config>::DbWeight>,
1756        frame_support::migrations::RemovePallet<TipsPalletName, <Runtime as frame_system::Config>::DbWeight>,
1757        pallet_grandpa::migrations::MigrateV4ToV5<Runtime>,
1758        parachains_configuration::migration::v10::MigrateToV10<Runtime>,
1759
1760        // Migrate Identity pallet for Usernames
1761        pallet_identity::migration::versioned::V0ToV1<Runtime, IDENTITY_MIGRATION_KEY_LIMIT>,
1762
1763		// migrates session storage item
1764		pallet_session::migrations::v1::MigrateV0ToV1<Runtime, pallet_session::migrations::v1::InitOffenceSeverity<Runtime>>,
1765
1766		// Migrate scheduler v3 -> v4 and on-demand v1 -> v2
1767		parachains_on_demand::migration::MigrateV1ToV2<Runtime>,
1768		parachains_scheduler::migration::MigrateV3ToV4<Runtime>,
1769
1770		parachains_configuration::migration::v13::MigrateToV13<Runtime>,
1771		parachains_shared::migration::MigrateToV2<Runtime>,
1772
1773        // permanent
1774        pallet_xcm::migration::MigrateToLatestXcmVersion<Runtime>,
1775        parachains_inclusion::migration::MigrateToV1<Runtime>,
1776    );
1777}
1778
1779/// Executive: handles dispatch to the various modules.
1780pub type Executive = frame_executive::Executive<
1781	Runtime,
1782	Block,
1783	frame_system::ChainContext<Runtime>,
1784	Runtime,
1785	AllPalletsWithSystem,
1786>;
1787/// The payload being signed in transactions.
1788pub type SignedPayload = generic::SignedPayload<RuntimeCall, TxExtension>;
1789
1790parameter_types! {
1791	// 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)
1792	pub const MigrationSignedDepositPerItem: Balance = 1 * CENTS;
1793	pub const MigrationSignedDepositBase: Balance = 20 * CENTS * 100;
1794	pub const MigrationMaxKeyLen: u32 = 512;
1795}
1796
1797impl pallet_state_trie_migration::Config for Runtime {
1798	type RuntimeEvent = RuntimeEvent;
1799	type Currency = Balances;
1800	type RuntimeHoldReason = RuntimeHoldReason;
1801	type SignedDepositPerItem = MigrationSignedDepositPerItem;
1802	type SignedDepositBase = MigrationSignedDepositBase;
1803	type ControlOrigin = EnsureRoot<AccountId>;
1804	// specific account for the migration, can trigger the signed migrations.
1805	type SignedFilter = frame_system::EnsureSignedBy<MigController, AccountId>;
1806
1807	// Use same weights as substrate ones.
1808	type WeightInfo = pallet_state_trie_migration::weights::SubstrateWeight<Runtime>;
1809	type MaxKeyLen = MigrationMaxKeyLen;
1810}
1811
1812frame_support::ord_parameter_types! {
1813	pub const MigController: AccountId = AccountId::from(hex_literal::hex!("52bc71c1eca5353749542dfdf0af97bf764f9c2f44e860cd485f1cd86400f649"));
1814}
1815
1816#[cfg(feature = "runtime-benchmarks")]
1817mod benches {
1818	frame_benchmarking::define_benchmarks!(
1819		// Polkadot
1820		// NOTE: Make sure to prefix these with `runtime_common::` so
1821		// the that path resolves correctly in the generated file.
1822		[polkadot_runtime_common::assigned_slots, AssignedSlots]
1823		[polkadot_runtime_common::auctions, Auctions]
1824		[polkadot_runtime_common::crowdloan, Crowdloan]
1825		[polkadot_runtime_common::claims, Claims]
1826		[polkadot_runtime_common::identity_migrator, IdentityMigrator]
1827		[polkadot_runtime_common::slots, Slots]
1828		[polkadot_runtime_common::paras_registrar, Registrar]
1829		[polkadot_runtime_parachains::configuration, Configuration]
1830		[polkadot_runtime_parachains::coretime, Coretime]
1831		[polkadot_runtime_parachains::dmp, Dmp]
1832		[polkadot_runtime_parachains::hrmp, Hrmp]
1833		[polkadot_runtime_parachains::disputes, ParasDisputes]
1834		[polkadot_runtime_parachains::inclusion, ParaInclusion]
1835		[polkadot_runtime_parachains::initializer, Initializer]
1836		[polkadot_runtime_parachains::paras_inherent, ParaInherent]
1837		[polkadot_runtime_parachains::paras, Paras]
1838		[polkadot_runtime_parachains::on_demand, OnDemandAssignmentProvider]
1839		// Substrate
1840		[pallet_balances, Balances]
1841		[pallet_balances, NisCounterpartBalances]
1842		[pallet_beefy_mmr, MmrLeaf]
1843		[frame_benchmarking::baseline, Baseline::<Runtime>]
1844		[pallet_bounties, Bounties]
1845		[pallet_child_bounties, ChildBounties]
1846		[pallet_conviction_voting, ConvictionVoting]
1847		[pallet_nis, Nis]
1848		[pallet_identity, Identity]
1849		[pallet_indices, Indices]
1850		[pallet_message_queue, MessageQueue]
1851		[pallet_migrations, MultiBlockMigrations]
1852		[pallet_mmr, Mmr]
1853		[pallet_multisig, Multisig]
1854		[pallet_parameters, Parameters]
1855		[pallet_preimage, Preimage]
1856		[pallet_proxy, Proxy]
1857		[pallet_ranked_collective, FellowshipCollective]
1858		[pallet_recovery, Recovery]
1859		[pallet_referenda, Referenda]
1860		[pallet_referenda, FellowshipReferenda]
1861		[pallet_scheduler, Scheduler]
1862		[pallet_sudo, Sudo]
1863		[frame_system, SystemBench::<Runtime>]
1864		[frame_system_extensions, SystemExtensionsBench::<Runtime>]
1865		[pallet_timestamp, Timestamp]
1866		[pallet_transaction_payment, TransactionPayment]
1867		[pallet_treasury, Treasury]
1868		[pallet_utility, Utility]
1869		[pallet_vesting, Vesting]
1870		[pallet_asset_rate, AssetRate]
1871		[pallet_whitelist, Whitelist]
1872		// XCM
1873		[pallet_xcm, PalletXcmExtrinsicsBenchmark::<Runtime>]
1874		[pallet_xcm_benchmarks::fungible, pallet_xcm_benchmarks::fungible::Pallet::<Runtime>]
1875		[pallet_xcm_benchmarks::generic, pallet_xcm_benchmarks::generic::Pallet::<Runtime>]
1876	);
1877}
1878
1879sp_api::impl_runtime_apis! {
1880	impl sp_api::Core<Block> for Runtime {
1881		fn version() -> RuntimeVersion {
1882			VERSION
1883		}
1884
1885		fn execute_block(block: <Block as BlockT>::LazyBlock) {
1886			Executive::execute_block(block);
1887		}
1888
1889		fn initialize_block(header: &<Block as BlockT>::Header) -> sp_runtime::ExtrinsicInclusionMode {
1890			Executive::initialize_block(header)
1891		}
1892	}
1893
1894	impl xcm_runtime_apis::fees::XcmPaymentApi<Block> for Runtime {
1895		fn query_acceptable_payment_assets(xcm_version: xcm::Version) -> Result<Vec<VersionedAssetId>, XcmPaymentApiError> {
1896			let acceptable_assets = vec![AssetId(xcm_config::TokenLocation::get())];
1897			XcmPallet::query_acceptable_payment_assets(xcm_version, acceptable_assets)
1898		}
1899
1900		fn query_weight_to_asset_fee(weight: Weight, asset: VersionedAssetId) -> Result<u128, XcmPaymentApiError> {
1901			type Trader = <XcmConfig as xcm_executor::Config>::Trader;
1902			XcmPallet::query_weight_to_asset_fee::<Trader>(weight, asset)
1903		}
1904
1905		fn query_xcm_weight(message: VersionedXcm<()>) -> Result<Weight, XcmPaymentApiError> {
1906			XcmPallet::query_xcm_weight(message)
1907		}
1908
1909		fn query_delivery_fees(destination: VersionedLocation, message: VersionedXcm<()>, asset_id: VersionedAssetId) -> Result<VersionedAssets, XcmPaymentApiError> {
1910			type AssetExchanger = <XcmConfig as xcm_executor::Config>::AssetExchanger;
1911			XcmPallet::query_delivery_fees::<AssetExchanger>(destination, message, asset_id)
1912		}
1913	}
1914
1915	impl xcm_runtime_apis::dry_run::DryRunApi<Block, RuntimeCall, RuntimeEvent, OriginCaller> for Runtime {
1916		fn dry_run_call(origin: OriginCaller, call: RuntimeCall, result_xcms_version: XcmVersion) -> Result<CallDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
1917			XcmPallet::dry_run_call::<Runtime, xcm_config::XcmRouter, OriginCaller, RuntimeCall>(origin, call, result_xcms_version)
1918		}
1919
1920		fn dry_run_xcm(origin_location: VersionedLocation, xcm: VersionedXcm<RuntimeCall>) -> Result<XcmDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
1921			XcmPallet::dry_run_xcm::<xcm_config::XcmRouter>(origin_location, xcm)
1922		}
1923	}
1924
1925	impl xcm_runtime_apis::conversions::LocationToAccountApi<Block, AccountId> for Runtime {
1926		fn convert_location(location: VersionedLocation) -> Result<
1927			AccountId,
1928			xcm_runtime_apis::conversions::Error
1929		> {
1930			xcm_runtime_apis::conversions::LocationToAccountHelper::<
1931				AccountId,
1932				xcm_config::LocationConverter,
1933			>::convert_location(location)
1934		}
1935	}
1936
1937	impl sp_api::Metadata<Block> for Runtime {
1938		fn metadata() -> OpaqueMetadata {
1939			OpaqueMetadata::new(Runtime::metadata().into())
1940		}
1941
1942		fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
1943			Runtime::metadata_at_version(version)
1944		}
1945
1946		fn metadata_versions() -> alloc::vec::Vec<u32> {
1947			Runtime::metadata_versions()
1948		}
1949	}
1950
1951	impl sp_block_builder::BlockBuilder<Block> for Runtime {
1952		fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
1953			Executive::apply_extrinsic(extrinsic)
1954		}
1955
1956		fn finalize_block() -> <Block as BlockT>::Header {
1957			Executive::finalize_block()
1958		}
1959
1960		fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
1961			data.create_extrinsics()
1962		}
1963
1964		fn check_inherents(
1965			block: <Block as BlockT>::LazyBlock,
1966			data: sp_inherents::InherentData,
1967		) -> sp_inherents::CheckInherentsResult {
1968			data.check_extrinsics(&block)
1969		}
1970	}
1971
1972	impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
1973		fn validate_transaction(
1974			source: TransactionSource,
1975			tx: <Block as BlockT>::Extrinsic,
1976			block_hash: <Block as BlockT>::Hash,
1977		) -> TransactionValidity {
1978			Executive::validate_transaction(source, tx, block_hash)
1979		}
1980	}
1981
1982	impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
1983		fn offchain_worker(header: &<Block as BlockT>::Header) {
1984			Executive::offchain_worker(header)
1985		}
1986	}
1987
1988	#[api_version(16)]
1989	impl polkadot_primitives::runtime_api::ParachainHost<Block> for Runtime {
1990		fn validators() -> Vec<ValidatorId> {
1991			parachains_runtime_api_impl::validators::<Runtime>()
1992		}
1993
1994		fn validator_groups() -> (Vec<Vec<ValidatorIndex>>, GroupRotationInfo<BlockNumber>) {
1995			parachains_runtime_api_impl::validator_groups::<Runtime>()
1996		}
1997
1998		fn availability_cores() -> Vec<CoreState<Hash, BlockNumber>> {
1999			parachains_runtime_api_impl::availability_cores::<Runtime>()
2000		}
2001
2002		fn persisted_validation_data(para_id: ParaId, assumption: OccupiedCoreAssumption)
2003			-> Option<PersistedValidationData<Hash, BlockNumber>> {
2004			parachains_runtime_api_impl::persisted_validation_data::<Runtime>(para_id, assumption)
2005		}
2006
2007		fn assumed_validation_data(
2008			para_id: ParaId,
2009			expected_persisted_validation_data_hash: Hash,
2010		) -> Option<(PersistedValidationData<Hash, BlockNumber>, ValidationCodeHash)> {
2011			parachains_runtime_api_impl::assumed_validation_data::<Runtime>(
2012				para_id,
2013				expected_persisted_validation_data_hash,
2014			)
2015		}
2016
2017		fn check_validation_outputs(
2018			para_id: ParaId,
2019			outputs: polkadot_primitives::CandidateCommitments,
2020		) -> bool {
2021			parachains_runtime_api_impl::check_validation_outputs::<Runtime>(para_id, outputs)
2022		}
2023
2024		fn session_index_for_child() -> SessionIndex {
2025			parachains_runtime_api_impl::session_index_for_child::<Runtime>()
2026		}
2027
2028		fn validation_code(para_id: ParaId, assumption: OccupiedCoreAssumption)
2029			-> Option<ValidationCode> {
2030			parachains_runtime_api_impl::validation_code::<Runtime>(para_id, assumption)
2031		}
2032
2033		fn candidate_pending_availability(para_id: ParaId) -> Option<CommittedCandidateReceipt<Hash>> {
2034			#[allow(deprecated)]
2035			parachains_runtime_api_impl::candidate_pending_availability::<Runtime>(para_id)
2036		}
2037
2038		fn candidate_events() -> Vec<CandidateEvent<Hash>> {
2039			parachains_runtime_api_impl::candidate_events::<Runtime, _>(|ev| {
2040				match ev {
2041					RuntimeEvent::ParaInclusion(ev) => {
2042						Some(ev)
2043					}
2044					_ => None,
2045				}
2046			})
2047		}
2048
2049		fn session_info(index: SessionIndex) -> Option<SessionInfo> {
2050			parachains_runtime_api_impl::session_info::<Runtime>(index)
2051		}
2052
2053		fn session_executor_params(session_index: SessionIndex) -> Option<ExecutorParams> {
2054			parachains_runtime_api_impl::session_executor_params::<Runtime>(session_index)
2055		}
2056
2057		fn dmq_contents(recipient: ParaId) -> Vec<InboundDownwardMessage<BlockNumber>> {
2058			parachains_runtime_api_impl::dmq_contents::<Runtime>(recipient)
2059		}
2060
2061		fn inbound_hrmp_channels_contents(
2062			recipient: ParaId
2063		) -> BTreeMap<ParaId, Vec<InboundHrmpMessage<BlockNumber>>> {
2064			parachains_runtime_api_impl::inbound_hrmp_channels_contents::<Runtime>(recipient)
2065		}
2066
2067		fn validation_code_by_hash(hash: ValidationCodeHash) -> Option<ValidationCode> {
2068			parachains_runtime_api_impl::validation_code_by_hash::<Runtime>(hash)
2069		}
2070
2071		fn on_chain_votes() -> Option<ScrapedOnChainVotes<Hash>> {
2072			parachains_runtime_api_impl::on_chain_votes::<Runtime>()
2073		}
2074
2075		fn submit_pvf_check_statement(
2076			stmt: polkadot_primitives::PvfCheckStatement,
2077			signature: polkadot_primitives::ValidatorSignature
2078		) {
2079			parachains_runtime_api_impl::submit_pvf_check_statement::<Runtime>(stmt, signature)
2080		}
2081
2082		fn pvfs_require_precheck() -> Vec<ValidationCodeHash> {
2083			parachains_runtime_api_impl::pvfs_require_precheck::<Runtime>()
2084		}
2085
2086		fn validation_code_hash(para_id: ParaId, assumption: OccupiedCoreAssumption)
2087			-> Option<ValidationCodeHash>
2088		{
2089			parachains_runtime_api_impl::validation_code_hash::<Runtime>(para_id, assumption)
2090		}
2091
2092		fn disputes() -> Vec<(SessionIndex, CandidateHash, DisputeState<BlockNumber>)> {
2093			parachains_runtime_api_impl::get_session_disputes::<Runtime>()
2094		}
2095
2096		fn unapplied_slashes(
2097		) -> Vec<(SessionIndex, CandidateHash, slashing::LegacyPendingSlashes)> {
2098			parachains_runtime_api_impl::unapplied_slashes::<Runtime>()
2099		}
2100
2101		fn unapplied_slashes_v2(
2102		) -> Vec<(SessionIndex, CandidateHash, slashing::PendingSlashes)> {
2103			parachains_runtime_api_impl::unapplied_slashes_v2::<Runtime>()
2104		}
2105
2106		fn key_ownership_proof(
2107			validator_id: ValidatorId,
2108		) -> Option<slashing::OpaqueKeyOwnershipProof> {
2109			use codec::Encode;
2110
2111			Historical::prove((PARACHAIN_KEY_TYPE_ID, validator_id))
2112				.map(|p| p.encode())
2113				.map(slashing::OpaqueKeyOwnershipProof::new)
2114		}
2115
2116		fn submit_report_dispute_lost(
2117			dispute_proof: slashing::DisputeProof,
2118			key_ownership_proof: slashing::OpaqueKeyOwnershipProof,
2119		) -> Option<()> {
2120			parachains_runtime_api_impl::submit_unsigned_slashing_report::<Runtime>(
2121				dispute_proof,
2122				key_ownership_proof,
2123			)
2124		}
2125
2126		fn minimum_backing_votes() -> u32 {
2127			parachains_runtime_api_impl::minimum_backing_votes::<Runtime>()
2128		}
2129
2130		fn para_backing_state(para_id: ParaId) -> Option<polkadot_primitives::async_backing::BackingState> {
2131			#[allow(deprecated)]
2132			parachains_runtime_api_impl::backing_state::<Runtime>(para_id)
2133		}
2134
2135		fn async_backing_params() -> polkadot_primitives::AsyncBackingParams {
2136			#[allow(deprecated)]
2137			parachains_runtime_api_impl::async_backing_params::<Runtime>()
2138		}
2139
2140		fn approval_voting_params() -> ApprovalVotingParams {
2141			parachains_runtime_api_impl::approval_voting_params::<Runtime>()
2142		}
2143
2144		fn disabled_validators() -> Vec<ValidatorIndex> {
2145			parachains_runtime_api_impl::disabled_validators::<Runtime>()
2146		}
2147
2148		fn node_features() -> NodeFeatures {
2149			parachains_runtime_api_impl::node_features::<Runtime>()
2150		}
2151
2152		fn claim_queue() -> BTreeMap<CoreIndex, VecDeque<ParaId>> {
2153			parachains_runtime_api_impl::claim_queue::<Runtime>()
2154		}
2155
2156		fn candidates_pending_availability(para_id: ParaId) -> Vec<CommittedCandidateReceipt<Hash>> {
2157			parachains_runtime_api_impl::candidates_pending_availability::<Runtime>(para_id)
2158		}
2159
2160		fn backing_constraints(para_id: ParaId) -> Option<Constraints> {
2161			parachains_runtime_api_impl::backing_constraints::<Runtime>(para_id)
2162		}
2163
2164		fn scheduling_lookahead() -> u32 {
2165			parachains_runtime_api_impl::scheduling_lookahead::<Runtime>()
2166		}
2167
2168		fn validation_code_bomb_limit() -> u32 {
2169			parachains_runtime_api_impl::validation_code_bomb_limit::<Runtime>()
2170		}
2171
2172		fn para_ids() -> Vec<ParaId> {
2173			parachains_staging_runtime_api_impl::para_ids::<Runtime>()
2174		}
2175
2176		fn max_relay_parent_session_age() -> u32 {
2177			parachains_staging_runtime_api_impl::max_relay_parent_session_age::<Runtime>()
2178		}
2179
2180		fn ancestor_relay_parent_info(
2181			session_index: SessionIndex,
2182			relay_parent: Hash,
2183		) -> Option<polkadot_primitives::vstaging::RelayParentInfo<Hash, BlockNumber>> {
2184			parachains_staging_runtime_api_impl::ancestor_relay_parent_info::<Runtime>(session_index, relay_parent)
2185		}
2186	}
2187
2188	#[api_version(6)]
2189	impl sp_consensus_beefy::BeefyApi<Block, BeefyId> for Runtime {
2190		fn beefy_genesis() -> Option<BlockNumber> {
2191			pallet_beefy::GenesisBlock::<Runtime>::get()
2192		}
2193
2194		fn validator_set() -> Option<sp_consensus_beefy::ValidatorSet<BeefyId>> {
2195			Beefy::validator_set()
2196		}
2197
2198		fn submit_report_double_voting_unsigned_extrinsic(
2199			equivocation_proof: sp_consensus_beefy::DoubleVotingProof<
2200				BlockNumber,
2201				BeefyId,
2202				BeefySignature,
2203			>,
2204			key_owner_proof: sp_consensus_beefy::OpaqueKeyOwnershipProof,
2205		) -> Option<()> {
2206			let key_owner_proof = key_owner_proof.decode()?;
2207
2208			Beefy::submit_unsigned_double_voting_report(
2209				equivocation_proof,
2210				key_owner_proof,
2211			)
2212		}
2213
2214		fn submit_report_fork_voting_unsigned_extrinsic(
2215			equivocation_proof:
2216				sp_consensus_beefy::ForkVotingProof<
2217					<Block as BlockT>::Header,
2218					BeefyId,
2219					sp_runtime::OpaqueValue
2220				>,
2221			key_owner_proof: sp_consensus_beefy::OpaqueKeyOwnershipProof,
2222		) -> Option<()> {
2223			Beefy::submit_unsigned_fork_voting_report(
2224				equivocation_proof.try_into()?,
2225				key_owner_proof.decode()?,
2226			)
2227		}
2228
2229		fn submit_report_future_block_voting_unsigned_extrinsic(
2230			equivocation_proof: sp_consensus_beefy::FutureBlockVotingProof<BlockNumber, BeefyId>,
2231			key_owner_proof: sp_consensus_beefy::OpaqueKeyOwnershipProof,
2232		) -> Option<()> {
2233			Beefy::submit_unsigned_future_block_voting_report(
2234				equivocation_proof,
2235				key_owner_proof.decode()?,
2236			)
2237		}
2238
2239		fn generate_key_ownership_proof(
2240			_set_id: sp_consensus_beefy::ValidatorSetId,
2241			authority_id: BeefyId,
2242		) -> Option<sp_consensus_beefy::OpaqueKeyOwnershipProof> {
2243			use codec::Encode;
2244
2245			Historical::prove((sp_consensus_beefy::KEY_TYPE, authority_id))
2246				.map(|p| p.encode())
2247				.map(sp_consensus_beefy::OpaqueKeyOwnershipProof::new)
2248		}
2249	}
2250
2251	#[api_version(3)]
2252	impl mmr::MmrApi<Block, mmr::Hash, BlockNumber> for Runtime {
2253		fn mmr_root() -> Result<mmr::Hash, mmr::Error> {
2254			Ok(pallet_mmr::RootHash::<Runtime>::get())
2255		}
2256
2257		fn mmr_leaf_count() -> Result<mmr::LeafIndex, mmr::Error> {
2258			Ok(pallet_mmr::NumberOfLeaves::<Runtime>::get())
2259		}
2260
2261		fn generate_proof(
2262			block_numbers: Vec<BlockNumber>,
2263			best_known_block_number: Option<BlockNumber>,
2264		) -> Result<(Vec<mmr::EncodableOpaqueLeaf>, mmr::LeafProof<mmr::Hash>), mmr::Error> {
2265			Mmr::generate_proof(block_numbers, best_known_block_number).map(
2266				|(leaves, proof)| {
2267					(
2268						leaves
2269							.into_iter()
2270							.map(|leaf| mmr::EncodableOpaqueLeaf::from_leaf(&leaf))
2271							.collect(),
2272						proof,
2273					)
2274				},
2275			)
2276		}
2277
2278		fn generate_ancestry_proof(
2279			prev_block_number: BlockNumber,
2280			best_known_block_number: Option<BlockNumber>,
2281		) -> Result<mmr::AncestryProof<mmr::Hash>, mmr::Error> {
2282			Mmr::generate_ancestry_proof(prev_block_number, best_known_block_number)
2283		}
2284
2285		fn verify_proof(leaves: Vec<mmr::EncodableOpaqueLeaf>, proof: mmr::LeafProof<mmr::Hash>)
2286			-> Result<(), mmr::Error>
2287		{
2288			let leaves = leaves.into_iter().map(|leaf|
2289				leaf.into_opaque_leaf()
2290				.try_decode()
2291				.ok_or(mmr::Error::Verify)).collect::<Result<Vec<mmr::Leaf>, mmr::Error>>()?;
2292			Mmr::verify_leaves(leaves, proof)
2293		}
2294
2295		fn verify_proof_stateless(
2296			root: mmr::Hash,
2297			leaves: Vec<mmr::EncodableOpaqueLeaf>,
2298			proof: mmr::LeafProof<mmr::Hash>
2299		) -> Result<(), mmr::Error> {
2300			let nodes = leaves.into_iter().map(|leaf|mmr::DataOrHash::Data(leaf.into_opaque_leaf())).collect();
2301			pallet_mmr::verify_leaves_proof::<mmr::Hashing, _>(root, nodes, proof)
2302		}
2303	}
2304
2305	impl fg_primitives::GrandpaApi<Block> for Runtime {
2306		fn grandpa_authorities() -> Vec<(GrandpaId, u64)> {
2307			Grandpa::grandpa_authorities()
2308		}
2309
2310		fn current_set_id() -> fg_primitives::SetId {
2311			pallet_grandpa::CurrentSetId::<Runtime>::get()
2312		}
2313
2314		fn submit_report_equivocation_unsigned_extrinsic(
2315			equivocation_proof: fg_primitives::EquivocationProof<
2316				<Block as BlockT>::Hash,
2317				sp_runtime::traits::NumberFor<Block>,
2318			>,
2319			key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof,
2320		) -> Option<()> {
2321			let key_owner_proof = key_owner_proof.decode()?;
2322
2323			Grandpa::submit_unsigned_equivocation_report(
2324				equivocation_proof,
2325				key_owner_proof,
2326			)
2327		}
2328
2329		fn generate_key_ownership_proof(
2330			_set_id: fg_primitives::SetId,
2331			authority_id: fg_primitives::AuthorityId,
2332		) -> Option<fg_primitives::OpaqueKeyOwnershipProof> {
2333			use codec::Encode;
2334
2335			Historical::prove((fg_primitives::KEY_TYPE, authority_id))
2336				.map(|p| p.encode())
2337				.map(fg_primitives::OpaqueKeyOwnershipProof::new)
2338		}
2339	}
2340
2341	impl sp_consensus_babe::BabeApi<Block> for Runtime {
2342		fn configuration() -> sp_consensus_babe::BabeConfiguration {
2343			let epoch_config = Babe::epoch_config().unwrap_or(BABE_GENESIS_EPOCH_CONFIG);
2344			sp_consensus_babe::BabeConfiguration {
2345				slot_duration: Babe::slot_duration(),
2346				epoch_length: EpochDurationInBlocks::get().into(),
2347				c: epoch_config.c,
2348				authorities: Babe::authorities().to_vec(),
2349				randomness: Babe::randomness(),
2350				allowed_slots: epoch_config.allowed_slots,
2351			}
2352		}
2353
2354		fn current_epoch_start() -> sp_consensus_babe::Slot {
2355			Babe::current_epoch_start()
2356		}
2357
2358		fn current_epoch() -> sp_consensus_babe::Epoch {
2359			Babe::current_epoch()
2360		}
2361
2362		fn next_epoch() -> sp_consensus_babe::Epoch {
2363			Babe::next_epoch()
2364		}
2365
2366		fn generate_key_ownership_proof(
2367			_slot: sp_consensus_babe::Slot,
2368			authority_id: sp_consensus_babe::AuthorityId,
2369		) -> Option<sp_consensus_babe::OpaqueKeyOwnershipProof> {
2370			use codec::Encode;
2371
2372			Historical::prove((sp_consensus_babe::KEY_TYPE, authority_id))
2373				.map(|p| p.encode())
2374				.map(sp_consensus_babe::OpaqueKeyOwnershipProof::new)
2375		}
2376
2377		fn submit_report_equivocation_unsigned_extrinsic(
2378			equivocation_proof: sp_consensus_babe::EquivocationProof<<Block as BlockT>::Header>,
2379			key_owner_proof: sp_consensus_babe::OpaqueKeyOwnershipProof,
2380		) -> Option<()> {
2381			let key_owner_proof = key_owner_proof.decode()?;
2382
2383			Babe::submit_unsigned_equivocation_report(
2384				equivocation_proof,
2385				key_owner_proof,
2386			)
2387		}
2388	}
2389
2390	impl sp_authority_discovery::AuthorityDiscoveryApi<Block> for Runtime {
2391		fn authorities() -> Vec<AuthorityDiscoveryId> {
2392			parachains_runtime_api_impl::relevant_authority_ids::<Runtime>()
2393		}
2394	}
2395
2396	impl sp_session::SessionKeys<Block> for Runtime {
2397		fn generate_session_keys(
2398			owner: Vec<u8>,
2399			seed: Option<Vec<u8>>,
2400		) -> sp_session::OpaqueGeneratedSessionKeys {
2401			SessionKeys::generate(&owner, seed).into()
2402		}
2403
2404		fn decode_session_keys(
2405			encoded: Vec<u8>,
2406		) -> Option<Vec<(Vec<u8>, sp_core::crypto::KeyTypeId)>> {
2407			SessionKeys::decode_into_raw_public_keys(&encoded)
2408		}
2409	}
2410
2411	impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
2412		fn account_nonce(account: AccountId) -> Nonce {
2413			System::account_nonce(account)
2414		}
2415	}
2416
2417	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<
2418		Block,
2419		Balance,
2420	> for Runtime {
2421		fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {
2422			TransactionPayment::query_info(uxt, len)
2423		}
2424		fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {
2425			TransactionPayment::query_fee_details(uxt, len)
2426		}
2427		fn query_weight_to_fee(weight: Weight) -> Balance {
2428			TransactionPayment::weight_to_fee(weight)
2429		}
2430		fn query_length_to_fee(length: u32) -> Balance {
2431			TransactionPayment::length_to_fee(length)
2432		}
2433	}
2434
2435	impl pallet_beefy_mmr::BeefyMmrApi<Block, Hash> for RuntimeApi {
2436		fn authority_set_proof() -> sp_consensus_beefy::mmr::BeefyAuthoritySet<Hash> {
2437			MmrLeaf::authority_set_proof()
2438		}
2439
2440		fn next_authority_set_proof() -> sp_consensus_beefy::mmr::BeefyNextAuthoritySet<Hash> {
2441			MmrLeaf::next_authority_set_proof()
2442		}
2443	}
2444
2445	#[cfg(feature = "try-runtime")]
2446	impl frame_try_runtime::TryRuntime<Block> for Runtime {
2447		fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) {
2448			log::info!("try-runtime::on_runtime_upgrade rococo.");
2449			let weight = Executive::try_runtime_upgrade(checks).unwrap();
2450			(weight, BlockWeights::get().max_block)
2451		}
2452
2453		fn execute_block(
2454			block: <Block as BlockT>::LazyBlock,
2455			state_root_check: bool,
2456			signature_check: bool,
2457			select: frame_try_runtime::TryStateSelect,
2458		) -> Weight {
2459			// NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to
2460			// have a backtrace here.
2461			Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap()
2462		}
2463	}
2464
2465	#[cfg(feature = "runtime-benchmarks")]
2466	impl frame_benchmarking::Benchmark<Block> for Runtime {
2467		fn benchmark_metadata(extra: bool) -> (
2468			Vec<frame_benchmarking::BenchmarkList>,
2469			Vec<frame_support::traits::StorageInfo>,
2470		) {
2471			use frame_benchmarking::BenchmarkList;
2472			use frame_support::traits::StorageInfoTrait;
2473
2474			use frame_system_benchmarking::Pallet as SystemBench;
2475			use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
2476			use frame_benchmarking::baseline::Pallet as Baseline;
2477
2478			use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
2479
2480			let mut list = Vec::<BenchmarkList>::new();
2481			list_benchmarks!(list, extra);
2482
2483			let storage_info = AllPalletsWithSystem::storage_info();
2484			return (list, storage_info)
2485		}
2486
2487		#[allow(non_local_definitions)]
2488		fn dispatch_benchmark(
2489			config: frame_benchmarking::BenchmarkConfig,
2490		) -> Result<
2491			Vec<frame_benchmarking::BenchmarkBatch>,
2492			alloc::string::String,
2493		> {
2494			use frame_support::traits::WhitelistedStorageKeys;
2495			use frame_benchmarking::{BenchmarkBatch, BenchmarkError};
2496			use frame_system_benchmarking::Pallet as SystemBench;
2497			use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
2498			use frame_benchmarking::baseline::Pallet as Baseline;
2499			use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
2500			use sp_storage::TrackedStorageKey;
2501			use xcm::latest::prelude::*;
2502			use xcm_config::{
2503				AssetHub, LocalCheckAccount, LocationConverter, TokenLocation, XcmConfig,
2504			};
2505
2506			parameter_types! {
2507				pub ExistentialDepositAsset: Option<Asset> = Some((
2508					TokenLocation::get(),
2509					ExistentialDeposit::get()
2510				).into());
2511				pub AssetHubParaId: ParaId = rococo_runtime_constants::system_parachain::ASSET_HUB_ID.into();
2512				pub const RandomParaId: ParaId = ParaId::new(43211234);
2513			}
2514
2515			impl frame_system_benchmarking::Config for Runtime {}
2516			impl frame_benchmarking::baseline::Config for Runtime {}
2517			impl pallet_transaction_payment::BenchmarkConfig for Runtime {}
2518			impl pallet_xcm::benchmarking::Config for Runtime {
2519				type DeliveryHelper = (
2520					polkadot_runtime_common::xcm_sender::ToParachainDeliveryHelper<
2521						XcmConfig,
2522						ExistentialDepositAsset,
2523						xcm_config::PriceForChildParachainDelivery,
2524						AssetHubParaId,
2525						Dmp,
2526					>,
2527					polkadot_runtime_common::xcm_sender::ToParachainDeliveryHelper<
2528						XcmConfig,
2529						ExistentialDepositAsset,
2530						xcm_config::PriceForChildParachainDelivery,
2531						RandomParaId,
2532						Dmp,
2533					>
2534				);
2535
2536				fn reachable_dest() -> Option<Location> {
2537					Some(crate::xcm_config::AssetHub::get())
2538				}
2539
2540				fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
2541					// Relay/native token can be teleported to/from AH.
2542					Some((
2543						Asset {
2544							fun: Fungible(ExistentialDeposit::get()),
2545							id: AssetId(Here.into())
2546						},
2547						crate::xcm_config::AssetHub::get(),
2548					))
2549				}
2550
2551				fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
2552					None
2553				}
2554
2555				fn set_up_complex_asset_transfer(
2556				) -> Option<(Assets, u32, Location, alloc::boxed::Box<dyn FnOnce()>)> {
2557					// Relay supports only native token, either reserve transfer it to non-system parachains,
2558					// or teleport it to system parachain. Use the teleport case for benchmarking as it's
2559					// slightly heavier.
2560					// Relay/native token can be teleported to/from AH.
2561					let native_location = Here.into();
2562					let dest = crate::xcm_config::AssetHub::get();
2563					pallet_xcm::benchmarking::helpers::native_teleport_as_asset_transfer::<Runtime>(
2564						native_location,
2565						dest
2566					)
2567				}
2568
2569				// `get_assets` stays at its default: the `AssetTransactor` only handles the
2570				// native token, so a multi-asset worst case is not constructible here.
2571				fn get_asset() -> Asset {
2572					Asset {
2573						id: AssetId(Location::here()),
2574						fun: Fungible(ExistentialDeposit::get()),
2575					}
2576				}
2577				fn batch_call(calls: Vec<RuntimeCall>) -> Option<RuntimeCall> {
2578					Some(RuntimeCall::Utility(pallet_utility::Call::batch { calls }))
2579				}
2580			}
2581			impl pallet_xcm_benchmarks::Config for Runtime {
2582				type XcmConfig = XcmConfig;
2583				type AccountIdConverter = LocationConverter;
2584				type DeliveryHelper = polkadot_runtime_common::xcm_sender::ToParachainDeliveryHelper<
2585					XcmConfig,
2586					ExistentialDepositAsset,
2587					xcm_config::PriceForChildParachainDelivery,
2588					AssetHubParaId,
2589					Dmp,
2590				>;
2591				fn valid_destination() -> Result<Location, BenchmarkError> {
2592					Ok(AssetHub::get())
2593				}
2594				fn worst_case_holding(_depositable_count: u32) -> xcm_executor::AssetsInHolding {
2595					use pallet_xcm_benchmarks::MockCredit;
2596					// Rococo only knows about ROC
2597					let mut holding = xcm_executor::AssetsInHolding::new();
2598					holding.fungible.insert(
2599						AssetId(TokenLocation::get()),
2600						alloc::boxed::Box::new(MockCredit(1_000_000 * UNITS)),
2601					);
2602					holding
2603				}
2604			}
2605
2606			parameter_types! {
2607				pub TrustedTeleporter: Option<(Location, Asset)> = Some((
2608					AssetHub::get(),
2609					Asset { fun: Fungible(1 * UNITS), id: AssetId(TokenLocation::get()) },
2610				));
2611				pub TrustedReserve: Option<(Location, Asset)> = None;
2612			}
2613
2614			impl pallet_xcm_benchmarks::fungible::Config for Runtime {
2615				type TransactAsset = Balances;
2616
2617				type CheckedAccount = LocalCheckAccount;
2618				type TrustedTeleporter = TrustedTeleporter;
2619				type TrustedReserve = TrustedReserve;
2620
2621				fn get_asset() -> Asset {
2622					Asset {
2623						id: AssetId(TokenLocation::get()),
2624						fun: Fungible(1 * UNITS),
2625					}
2626				}
2627			}
2628
2629			impl pallet_xcm_benchmarks::generic::Config for Runtime {
2630				type TransactAsset = Balances;
2631				type RuntimeCall = RuntimeCall;
2632
2633				fn worst_case_response() -> (u64, Response) {
2634					(0u64, Response::Version(Default::default()))
2635				}
2636
2637				fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> {
2638					// Rococo doesn't support asset exchanges
2639					Err(BenchmarkError::Skip)
2640				}
2641
2642				fn universal_alias() -> Result<(Location, Junction), BenchmarkError> {
2643					// The XCM executor of Rococo doesn't have a configured `UniversalAliases`
2644					Err(BenchmarkError::Skip)
2645				}
2646
2647				fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> {
2648					Ok((AssetHub::get(), frame_system::Call::remark_with_event { remark: vec![] }.into()))
2649				}
2650
2651				fn subscribe_origin() -> Result<Location, BenchmarkError> {
2652					Ok(AssetHub::get())
2653				}
2654
2655				fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> {
2656					let origin = AssetHub::get();
2657					let assets: Assets = (AssetId(TokenLocation::get()), 1_000 * UNITS).into();
2658					let ticket = Location { parents: 0, interior: Here };
2659					Ok((origin, ticket, assets))
2660				}
2661
2662				fn worst_case_for_trader() -> Result<(Asset, WeightLimit), BenchmarkError> {
2663					Ok((Asset {
2664						id: AssetId(TokenLocation::get()),
2665						fun: Fungible(1_000_000 * UNITS),
2666					}, WeightLimit::Limited(Weight::from_parts(5000, 5000))))
2667				}
2668
2669				fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> {
2670					// Rococo doesn't support asset locking
2671					Err(BenchmarkError::Skip)
2672				}
2673
2674				fn export_message_origin_and_destination(
2675				) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> {
2676					// Rococo doesn't support exporting messages
2677					Err(BenchmarkError::Skip)
2678				}
2679
2680				fn alias_origin() -> Result<(Location, Location), BenchmarkError> {
2681					// The XCM executor of Rococo doesn't have a configured `Aliasers`
2682					Err(BenchmarkError::Skip)
2683				}
2684			}
2685
2686			let mut whitelist: Vec<TrackedStorageKey> = AllPalletsWithSystem::whitelisted_storage_keys();
2687			let treasury_key = frame_system::Account::<Runtime>::hashed_key_for(Treasury::account_id());
2688			whitelist.push(treasury_key.to_vec().into());
2689
2690			let mut batches = Vec::<BenchmarkBatch>::new();
2691			let params = (&config, &whitelist);
2692
2693			add_benchmarks!(params, batches);
2694
2695			Ok(batches)
2696		}
2697	}
2698
2699	impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
2700		fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
2701			build_state::<RuntimeGenesisConfig>(config)
2702		}
2703
2704		fn get_preset(id: &Option<PresetId>) -> Option<Vec<u8>> {
2705			get_preset::<RuntimeGenesisConfig>(id, &genesis_config_presets::get_preset)
2706		}
2707
2708		fn preset_names() -> Vec<PresetId> {
2709			genesis_config_presets::preset_names()
2710		}
2711	}
2712
2713	impl xcm_runtime_apis::trusted_query::TrustedQueryApi<Block> for Runtime {
2714		fn is_trusted_reserve(asset: VersionedAsset, location: VersionedLocation) -> Result<bool, xcm_runtime_apis::trusted_query::Error> {
2715			XcmPallet::is_trusted_reserve(asset, location)
2716		}
2717		fn is_trusted_teleporter(asset: VersionedAsset, location: VersionedLocation) -> Result<bool, xcm_runtime_apis::trusted_query::Error> {
2718			XcmPallet::is_trusted_teleporter(asset, location)
2719		}
2720	}
2721}
2722
2723#[cfg(all(test, feature = "try-runtime"))]
2724mod remote_tests {
2725	use super::*;
2726	use frame_try_runtime::{runtime_decl_for_try_runtime::TryRuntime, UpgradeCheckSelect};
2727	use remote_externalities::{Builder, Mode, OfflineConfig, OnlineConfig, SnapshotConfig};
2728	use std::env::var;
2729
2730	#[tokio::test]
2731	async fn run_migrations() {
2732		if var("RUN_MIGRATION_TESTS").is_err() {
2733			return;
2734		}
2735
2736		sp_tracing::try_init_simple();
2737		let transport = var("WS").unwrap_or("wss://rococo-rpc.polkadot.io:443".to_string());
2738		let maybe_state_snapshot: Option<SnapshotConfig> = var("SNAP").map(|s| s.into()).ok();
2739
2740		let transport_uris = vec![transport];
2741		let mut ext = Builder::<Block>::default()
2742			.mode(if let Some(state_snapshot) = maybe_state_snapshot {
2743				Mode::OfflineOrElseOnline(
2744					OfflineConfig { state_snapshot: state_snapshot.clone() },
2745					OnlineConfig {
2746						transport_uris,
2747						state_snapshot: Some(state_snapshot),
2748						..Default::default()
2749					},
2750				)
2751			} else {
2752				Mode::Online(OnlineConfig { transport_uris, ..Default::default() })
2753			})
2754			.build()
2755			.await
2756			.unwrap();
2757		ext.execute_with(|| Runtime::on_runtime_upgrade(UpgradeCheckSelect::PreAndPost));
2758	}
2759}