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::{Leaser, OnSwap},
66	BlockHashCount, BlockLength, SlowAdjustingFeeUpdate,
67};
68use polkadot_runtime_parachains::{
69	assigner_coretime as parachains_assigner_coretime, 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, FixedU128, KeyTypeId, Perbill, Percent, Permill, RuntimeDebug,
120};
121use sp_staking::SessionIndex;
122#[cfg(any(feature = "std", test))]
123use sp_version::NativeVersion;
124use sp_version::RuntimeVersion;
125use xcm::{
126	latest::prelude::*, Version as XcmVersion, VersionedAsset, VersionedAssetId, VersionedAssets,
127	VersionedLocation, VersionedXcm,
128};
129use xcm_builder::PayOverXcm;
130
131pub use frame_system::Call as SystemCall;
132pub use pallet_balances::Call as BalancesCall;
133
134/// Constant values used within the runtime.
135use rococo_runtime_constants::{currency::*, fee::*, time::*};
136
137// Weights used in the runtime.
138mod weights;
139
140// XCM configurations.
141pub mod xcm_config;
142
143// Implemented types.
144mod impls;
145use impls::ToParachainIdentityReaper;
146
147// Governance and configurations.
148pub mod governance;
149use governance::{
150	pallet_custom_origins, AuctionAdmin, Fellows, GeneralAdmin, LeaseAdmin, Treasurer,
151	TreasurySpender,
152};
153use xcm_config::XcmConfig;
154use xcm_runtime_apis::{
155	dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects},
156	fees::Error as XcmPaymentApiError,
157};
158
159#[cfg(test)]
160mod tests;
161
162mod genesis_config_presets;
163mod validator_manager;
164
165impl_runtime_weights!(rococo_runtime_constants);
166
167// Make the WASM binary available.
168#[cfg(feature = "std")]
169include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
170
171/// Provides the `WASM_BINARY` build with `fast-runtime` feature enabled.
172///
173/// This is for example useful for local test chains.
174#[cfg(feature = "std")]
175pub mod fast_runtime_binary {
176	include!(concat!(env!("OUT_DIR"), "/fast_runtime_binary.rs"));
177}
178
179/// Runtime version (Rococo).
180#[sp_version::runtime_version]
181pub const VERSION: RuntimeVersion = RuntimeVersion {
182	spec_name: alloc::borrow::Cow::Borrowed("rococo"),
183	impl_name: alloc::borrow::Cow::Borrowed("parity-rococo-v2.0"),
184	authoring_version: 0,
185	spec_version: 1_021_000,
186	impl_version: 0,
187	apis: RUNTIME_API_VERSIONS,
188	transaction_version: 26,
189	system_version: 1,
190};
191
192/// The BABE epoch configuration at genesis.
193pub const BABE_GENESIS_EPOCH_CONFIG: sp_consensus_babe::BabeEpochConfiguration =
194	sp_consensus_babe::BabeEpochConfiguration {
195		c: PRIMARY_PROBABILITY,
196		allowed_slots: sp_consensus_babe::AllowedSlots::PrimaryAndSecondaryVRFSlots,
197	};
198
199/// Native version.
200#[cfg(any(feature = "std", test))]
201pub fn native_version() -> NativeVersion {
202	NativeVersion { runtime_version: VERSION, can_author_with: Default::default() }
203}
204
205/// A type to identify calls to the Identity pallet. These will be filtered to prevent invocation,
206/// locking the state of the pallet and preventing further updates to identities and sub-identities.
207/// The locked state will be the genesis state of a new system chain and then removed from the Relay
208/// Chain.
209pub struct IsIdentityCall;
210impl Contains<RuntimeCall> for IsIdentityCall {
211	fn contains(c: &RuntimeCall) -> bool {
212		matches!(c, RuntimeCall::Identity(_))
213	}
214}
215
216parameter_types! {
217	pub const Version: RuntimeVersion = VERSION;
218	pub const SS58Prefix: u8 = 42;
219}
220
221#[derive_impl(frame_system::config_preludes::RelayChainDefaultConfig)]
222impl frame_system::Config for Runtime {
223	type BaseCallFilter = EverythingBut<IsIdentityCall>;
224	type BlockWeights = BlockWeights;
225	type BlockLength = BlockLength;
226	type DbWeight = RocksDbWeight;
227	type Nonce = Nonce;
228	type Hash = Hash;
229	type AccountId = AccountId;
230	type Block = Block;
231	type BlockHashCount = BlockHashCount;
232	type Version = Version;
233	type AccountData = pallet_balances::AccountData<Balance>;
234	type SystemWeightInfo = weights::frame_system::WeightInfo<Runtime>;
235	type ExtensionsWeightInfo = weights::frame_system_extensions::WeightInfo<Runtime>;
236	type SS58Prefix = SS58Prefix;
237	type MaxConsumers = frame_support::traits::ConstU32<16>;
238	type MultiBlockMigrator = MultiBlockMigrations;
239	type SingleBlockMigrations = Migrations;
240}
241
242parameter_types! {
243	pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) *
244		BlockWeights::get().max_block;
245	pub const MaxScheduledPerBlock: u32 = 50;
246	pub const NoPreimagePostponement: Option<u32> = Some(10);
247}
248
249/// Used the compare the privilege of an origin inside the scheduler.
250pub struct OriginPrivilegeCmp;
251
252impl PrivilegeCmp<OriginCaller> for OriginPrivilegeCmp {
253	fn cmp_privilege(left: &OriginCaller, right: &OriginCaller) -> Option<Ordering> {
254		if left == right {
255			return Some(Ordering::Equal);
256		}
257
258		match (left, right) {
259			// Root is greater than anything.
260			(OriginCaller::system(frame_system::RawOrigin::Root), _) => Some(Ordering::Greater),
261			// For every other origin we don't care, as they are not used for `ScheduleOrigin`.
262			_ => None,
263		}
264	}
265}
266
267/// Dynamic params that can be adjusted at runtime.
268#[dynamic_params(RuntimeParameters, pallet_parameters::Parameters::<Runtime>)]
269pub mod dynamic_params {
270	use super::*;
271
272	#[dynamic_pallet_params]
273	#[codec(index = 0)]
274	pub mod nis {
275		use super::*;
276
277		#[codec(index = 0)]
278		pub static Target: Perquintill = Perquintill::zero();
279
280		#[codec(index = 1)]
281		pub static MinBid: Balance = 100 * UNITS;
282	}
283
284	#[dynamic_pallet_params]
285	#[codec(index = 1)]
286	pub mod preimage {
287		use super::*;
288
289		#[codec(index = 0)]
290		pub static BaseDeposit: Balance = deposit(2, 64);
291
292		#[codec(index = 1)]
293		pub static ByteDeposit: Balance = deposit(0, 1);
294	}
295}
296
297#[cfg(feature = "runtime-benchmarks")]
298impl Default for RuntimeParameters {
299	fn default() -> Self {
300		RuntimeParameters::Preimage(dynamic_params::preimage::Parameters::BaseDeposit(
301			dynamic_params::preimage::BaseDeposit,
302			Some(1u32.into()),
303		))
304	}
305}
306
307/// Defines what origin can modify which dynamic parameters.
308pub struct DynamicParameterOrigin;
309impl EnsureOriginWithArg<RuntimeOrigin, RuntimeParametersKey> for DynamicParameterOrigin {
310	type Success = ();
311
312	fn try_origin(
313		origin: RuntimeOrigin,
314		key: &RuntimeParametersKey,
315	) -> Result<Self::Success, RuntimeOrigin> {
316		use crate::{dynamic_params::*, governance::*, RuntimeParametersKey::*};
317
318		match key {
319			Nis(nis::ParametersKey::MinBid(_)) => StakingAdmin::ensure_origin(origin.clone()),
320			Nis(nis::ParametersKey::Target(_)) => GeneralAdmin::ensure_origin(origin.clone()),
321			Preimage(_) => frame_system::ensure_root(origin.clone()),
322		}
323		.map_err(|_| origin)
324	}
325
326	#[cfg(feature = "runtime-benchmarks")]
327	fn try_successful_origin(_key: &RuntimeParametersKey) -> Result<RuntimeOrigin, ()> {
328		// Provide the origin for the parameter returned by `Default`:
329		Ok(RuntimeOrigin::root())
330	}
331}
332
333impl pallet_scheduler::Config for Runtime {
334	type RuntimeOrigin = RuntimeOrigin;
335	type RuntimeEvent = RuntimeEvent;
336	type PalletsOrigin = OriginCaller;
337	type RuntimeCall = RuntimeCall;
338	type MaximumWeight = MaximumSchedulerWeight;
339	// The goal of having ScheduleOrigin include AuctionAdmin is to allow the auctions track of
340	// OpenGov to schedule periodic auctions.
341	type ScheduleOrigin = EitherOf<EnsureRoot<AccountId>, AuctionAdmin>;
342	type MaxScheduledPerBlock = MaxScheduledPerBlock;
343	type WeightInfo = weights::pallet_scheduler::WeightInfo<Runtime>;
344	type OriginPrivilegeCmp = OriginPrivilegeCmp;
345	type Preimages = Preimage;
346	type BlockNumberProvider = frame_system::Pallet<Runtime>;
347}
348
349parameter_types! {
350	pub const PreimageHoldReason: RuntimeHoldReason = RuntimeHoldReason::Preimage(pallet_preimage::HoldReason::Preimage);
351}
352
353impl pallet_preimage::Config for Runtime {
354	type WeightInfo = weights::pallet_preimage::WeightInfo<Runtime>;
355	type RuntimeEvent = RuntimeEvent;
356	type Currency = Balances;
357	type ManagerOrigin = EnsureRoot<AccountId>;
358	type Consideration = HoldConsideration<
359		AccountId,
360		Balances,
361		PreimageHoldReason,
362		LinearStoragePrice<
363			dynamic_params::preimage::BaseDeposit,
364			dynamic_params::preimage::ByteDeposit,
365			Balance,
366		>,
367	>;
368}
369
370parameter_types! {
371	pub const ExpectedBlockTime: Moment = MILLISECS_PER_BLOCK;
372	pub ReportLongevity: u64 = EpochDurationInBlocks::get() as u64 * 10;
373}
374
375impl pallet_babe::Config for Runtime {
376	type EpochDuration = EpochDurationInBlocks;
377	type ExpectedBlockTime = ExpectedBlockTime;
378	// session module is the trigger
379	type EpochChangeTrigger = pallet_babe::ExternalTrigger;
380	type DisabledValidators = Session;
381	type WeightInfo = ();
382	type MaxAuthorities = MaxAuthorities;
383	type MaxNominators = ConstU32<0>;
384	type KeyOwnerProof = sp_session::MembershipProof;
385	type EquivocationReportSystem =
386		pallet_babe::EquivocationReportSystem<Self, Offences, Historical, ReportLongevity>;
387}
388
389parameter_types! {
390	pub const IndexDeposit: Balance = 100 * CENTS;
391}
392
393impl pallet_indices::Config for Runtime {
394	type AccountIndex = AccountIndex;
395	type Currency = Balances;
396	type Deposit = IndexDeposit;
397	type RuntimeEvent = RuntimeEvent;
398	type WeightInfo = weights::pallet_indices::WeightInfo<Runtime>;
399}
400
401parameter_types! {
402	pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
403	pub const MaxLocks: u32 = 50;
404	pub const MaxReserves: u32 = 50;
405}
406
407impl pallet_balances::Config for Runtime {
408	type Balance = Balance;
409	type DustRemoval = ();
410	type RuntimeEvent = RuntimeEvent;
411	type ExistentialDeposit = ExistentialDeposit;
412	type AccountStore = System;
413	type MaxLocks = MaxLocks;
414	type MaxReserves = MaxReserves;
415	type ReserveIdentifier = [u8; 8];
416	type WeightInfo = weights::pallet_balances_balances::WeightInfo<Runtime>;
417	type FreezeIdentifier = ();
418	type RuntimeHoldReason = RuntimeHoldReason;
419	type RuntimeFreezeReason = RuntimeFreezeReason;
420	type MaxFreezes = ConstU32<1>;
421	type DoneSlashHandler = ();
422}
423
424parameter_types! {
425	pub const TransactionByteFee: Balance = 10 * MILLICENTS;
426	/// This value increases the priority of `Operational` transactions by adding
427	/// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.
428	pub const OperationalFeeMultiplier: u8 = 5;
429}
430
431impl pallet_transaction_payment::Config for Runtime {
432	type RuntimeEvent = RuntimeEvent;
433	type OnChargeTransaction = FungibleAdapter<Balances, ToAuthor<Runtime>>;
434	type OperationalFeeMultiplier = OperationalFeeMultiplier;
435	type WeightToFee = WeightToFee;
436	type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
437	type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
438	type WeightInfo = weights::pallet_transaction_payment::WeightInfo<Runtime>;
439}
440
441parameter_types! {
442	pub const MinimumPeriod: u64 = SLOT_DURATION / 2;
443}
444impl pallet_timestamp::Config for Runtime {
445	type Moment = u64;
446	type OnTimestampSet = Babe;
447	type MinimumPeriod = MinimumPeriod;
448	type WeightInfo = weights::pallet_timestamp::WeightInfo<Runtime>;
449}
450
451impl pallet_authorship::Config for Runtime {
452	type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Babe>;
453	type EventHandler = ();
454}
455
456impl_opaque_keys! {
457	pub struct SessionKeys {
458		pub grandpa: Grandpa,
459		pub babe: Babe,
460		pub para_validator: Initializer,
461		pub para_assignment: ParaSessionInfo,
462		pub authority_discovery: AuthorityDiscovery,
463		pub beefy: Beefy,
464	}
465}
466
467/// Special `ValidatorIdOf` implementation that is just returning the input as result.
468pub struct ValidatorIdOf;
469impl sp_runtime::traits::Convert<AccountId, Option<AccountId>> for ValidatorIdOf {
470	fn convert(a: AccountId) -> Option<AccountId> {
471		Some(a)
472	}
473}
474
475impl pallet_session::Config for Runtime {
476	type RuntimeEvent = RuntimeEvent;
477	type ValidatorId = AccountId;
478	type ValidatorIdOf = ValidatorIdOf;
479	type ShouldEndSession = Babe;
480	type NextSessionRotation = Babe;
481	type SessionManager = pallet_session::historical::NoteHistoricalRoot<Self, ValidatorManager>;
482	type SessionHandler = <SessionKeys as OpaqueKeys>::KeyTypeIdProviders;
483	type Keys = SessionKeys;
484	type DisablingStrategy = ();
485	type WeightInfo = weights::pallet_session::WeightInfo<Runtime>;
486	type Currency = Balances;
487	type KeyDeposit = ();
488}
489
490pub struct FullIdentificationOf;
491impl sp_runtime::traits::Convert<AccountId, Option<()>> for FullIdentificationOf {
492	fn convert(_: AccountId) -> Option<()> {
493		Some(Default::default())
494	}
495}
496
497impl pallet_session::historical::Config for Runtime {
498	type RuntimeEvent = RuntimeEvent;
499	type FullIdentification = ();
500	type FullIdentificationOf = FullIdentificationOf;
501}
502
503parameter_types! {
504	pub const SessionsPerEra: SessionIndex = 6;
505	pub const BondingDuration: sp_staking::EraIndex = 28;
506}
507
508parameter_types! {
509	pub const SpendPeriod: BlockNumber = 6 * DAYS;
510	pub const Burn: Permill = Permill::from_perthousand(2);
511	pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry");
512	pub const PayoutSpendPeriod: BlockNumber = 30 * DAYS;
513	// The asset's interior location for the paying account. This is the Treasury
514	// pallet instance (which sits at index 18).
515	pub TreasuryInteriorLocation: InteriorLocation = PalletInstance(18).into();
516
517	pub const TipCountdown: BlockNumber = 1 * DAYS;
518	pub const TipFindersFee: Percent = Percent::from_percent(20);
519	pub const TipReportDepositBase: Balance = 100 * CENTS;
520	pub const DataDepositPerByte: Balance = 1 * CENTS;
521	pub const MaxApprovals: u32 = 100;
522	pub const MaxAuthorities: u32 = 100_000;
523	pub const MaxKeys: u32 = 10_000;
524	pub const MaxPeerInHeartbeats: u32 = 10_000;
525	pub const MaxBalance: Balance = Balance::max_value();
526}
527
528impl pallet_treasury::Config for Runtime {
529	type PalletId = TreasuryPalletId;
530	type Currency = Balances;
531	type RejectOrigin = EitherOfDiverse<EnsureRoot<AccountId>, Treasurer>;
532	type RuntimeEvent = RuntimeEvent;
533	type SpendPeriod = SpendPeriod;
534	type Burn = Burn;
535	type BurnDestination = Society;
536	type MaxApprovals = MaxApprovals;
537	type WeightInfo = weights::pallet_treasury::WeightInfo<Runtime>;
538	type SpendFunds = Bounties;
539	type SpendOrigin = TreasurySpender;
540	type AssetKind = VersionedLocatableAsset;
541	type Beneficiary = VersionedLocation;
542	type BeneficiaryLookup = IdentityLookup<Self::Beneficiary>;
543	type Paymaster = PayOverXcm<
544		TreasuryInteriorLocation,
545		crate::xcm_config::XcmRouter,
546		crate::XcmPallet,
547		ConstU32<{ 6 * HOURS }>,
548		Self::Beneficiary,
549		Self::AssetKind,
550		LocatableAssetConverter,
551		VersionedLocationConverter,
552	>;
553	type BalanceConverter = UnityOrOuterConversion<
554		ContainsParts<
555			FromContains<
556				xcm_builder::IsChildSystemParachain<ParaId>,
557				xcm_builder::IsParentsOnly<ConstU8<1>>,
558			>,
559		>,
560		AssetRate,
561	>;
562	type PayoutPeriod = PayoutSpendPeriod;
563	type BlockNumberProvider = System;
564	#[cfg(feature = "runtime-benchmarks")]
565	type BenchmarkHelper = polkadot_runtime_common::impls::benchmarks::TreasuryArguments;
566}
567
568parameter_types! {
569	pub const BountyDepositBase: Balance = 100 * CENTS;
570	pub const BountyDepositPayoutDelay: BlockNumber = 4 * DAYS;
571	pub const BountyUpdatePeriod: BlockNumber = 90 * DAYS;
572	pub const MaximumReasonLength: u32 = 16384;
573	pub const CuratorDepositMultiplier: Permill = Permill::from_percent(50);
574	pub const CuratorDepositMin: Balance = 10 * CENTS;
575	pub const CuratorDepositMax: Balance = 500 * CENTS;
576	pub const BountyValueMinimum: Balance = 200 * CENTS;
577}
578
579impl pallet_bounties::Config for Runtime {
580	type BountyDepositBase = BountyDepositBase;
581	type BountyDepositPayoutDelay = BountyDepositPayoutDelay;
582	type BountyUpdatePeriod = BountyUpdatePeriod;
583	type CuratorDepositMultiplier = CuratorDepositMultiplier;
584	type CuratorDepositMin = CuratorDepositMin;
585	type CuratorDepositMax = CuratorDepositMax;
586	type BountyValueMinimum = BountyValueMinimum;
587	type ChildBountyManager = ChildBounties;
588	type DataDepositPerByte = DataDepositPerByte;
589	type RuntimeEvent = RuntimeEvent;
590	type MaximumReasonLength = MaximumReasonLength;
591	type WeightInfo = weights::pallet_bounties::WeightInfo<Runtime>;
592	type OnSlash = Treasury;
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 RuntimeEvent = RuntimeEvent;
824	type WeightInfo = ();
825	type RuntimeCall = RuntimeCall;
826	type BlockNumberProvider = System;
827	type Currency = Balances;
828	type ConfigDepositBase = ConfigDepositBase;
829	type FriendDepositFactor = FriendDepositFactor;
830	type MaxFriends = MaxFriends;
831	type RecoveryDeposit = RecoveryDeposit;
832}
833
834parameter_types! {
835	pub const SocietyPalletId: PalletId = PalletId(*b"py/socie");
836}
837
838impl pallet_society::Config for Runtime {
839	type RuntimeEvent = RuntimeEvent;
840	type Currency = Balances;
841	type Randomness = pallet_babe::RandomnessFromOneEpochAgo<Runtime>;
842	type GraceStrikes = ConstU32<1>;
843	type PeriodSpend = ConstU128<{ 50_000 * CENTS }>;
844	type VotingPeriod = ConstU32<{ 5 * DAYS }>;
845	type ClaimPeriod = ConstU32<{ 2 * DAYS }>;
846	type MaxLockDuration = ConstU32<{ 36 * 30 * DAYS }>;
847	type FounderSetOrigin = EnsureRoot<AccountId>;
848	type ChallengePeriod = ConstU32<{ 7 * DAYS }>;
849	type MaxPayouts = ConstU32<8>;
850	type MaxBids = ConstU32<512>;
851	type PalletId = SocietyPalletId;
852	type BlockNumberProvider = System;
853	type WeightInfo = ();
854}
855
856parameter_types! {
857	pub const MinVestedTransfer: Balance = 100 * CENTS;
858	pub UnvestedFundsAllowedWithdrawReasons: WithdrawReasons =
859		WithdrawReasons::except(WithdrawReasons::TRANSFER | WithdrawReasons::RESERVE);
860}
861
862impl pallet_vesting::Config for Runtime {
863	type RuntimeEvent = RuntimeEvent;
864	type Currency = Balances;
865	type BlockNumberToBalance = ConvertInto;
866	type MinVestedTransfer = MinVestedTransfer;
867	type WeightInfo = weights::pallet_vesting::WeightInfo<Runtime>;
868	type UnvestedFundsAllowedWithdrawReasons = UnvestedFundsAllowedWithdrawReasons;
869	type BlockNumberProvider = System;
870	const MAX_VESTING_SCHEDULES: u32 = 28;
871}
872
873parameter_types! {
874	// One storage item; key size 32, value size 8; .
875	pub const ProxyDepositBase: Balance = deposit(1, 8);
876	// Additional storage item size of 33 bytes.
877	pub const ProxyDepositFactor: Balance = deposit(0, 33);
878	pub const MaxProxies: u16 = 32;
879	pub const AnnouncementDepositBase: Balance = deposit(1, 8);
880	pub const AnnouncementDepositFactor: Balance = deposit(0, 66);
881	pub const MaxPending: u16 = 32;
882}
883
884/// The type used to represent the kinds of proxying allowed.
885#[derive(
886	Copy,
887	Clone,
888	Eq,
889	PartialEq,
890	Ord,
891	PartialOrd,
892	Encode,
893	Decode,
894	DecodeWithMemTracking,
895	RuntimeDebug,
896	MaxEncodedLen,
897	TypeInfo,
898)]
899pub enum ProxyType {
900	Any,
901	NonTransfer,
902	Governance,
903	IdentityJudgement,
904	CancelProxy,
905	Auction,
906	Society,
907	OnDemandOrdering,
908}
909impl Default for ProxyType {
910	fn default() -> Self {
911		Self::Any
912	}
913}
914impl InstanceFilter<RuntimeCall> for ProxyType {
915	fn filter(&self, c: &RuntimeCall) -> bool {
916		match self {
917			ProxyType::Any => true,
918			ProxyType::NonTransfer => matches!(
919				c,
920				RuntimeCall::System(..) |
921				RuntimeCall::Babe(..) |
922				RuntimeCall::Timestamp(..) |
923				RuntimeCall::Indices(pallet_indices::Call::claim {..}) |
924				RuntimeCall::Indices(pallet_indices::Call::free {..}) |
925				RuntimeCall::Indices(pallet_indices::Call::freeze {..}) |
926				// Specifically omitting Indices `transfer`, `force_transfer`
927				// Specifically omitting the entire Balances pallet
928				RuntimeCall::Session(..) |
929				RuntimeCall::Grandpa(..) |
930				RuntimeCall::Treasury(..) |
931				RuntimeCall::Bounties(..) |
932				RuntimeCall::ChildBounties(..) |
933				RuntimeCall::ConvictionVoting(..) |
934				RuntimeCall::Referenda(..) |
935				RuntimeCall::FellowshipCollective(..) |
936				RuntimeCall::FellowshipReferenda(..) |
937				RuntimeCall::Whitelist(..) |
938				RuntimeCall::Claims(..) |
939				RuntimeCall::Utility(..) |
940				RuntimeCall::Identity(..) |
941				RuntimeCall::Society(..) |
942				RuntimeCall::Recovery(pallet_recovery::Call::as_recovered {..}) |
943				RuntimeCall::Recovery(pallet_recovery::Call::vouch_recovery {..}) |
944				RuntimeCall::Recovery(pallet_recovery::Call::claim_recovery {..}) |
945				RuntimeCall::Recovery(pallet_recovery::Call::close_recovery {..}) |
946				RuntimeCall::Recovery(pallet_recovery::Call::remove_recovery {..}) |
947				RuntimeCall::Recovery(pallet_recovery::Call::cancel_recovered {..}) |
948				// Specifically omitting Recovery `create_recovery`, `initiate_recovery`
949				RuntimeCall::Vesting(pallet_vesting::Call::vest {..}) |
950				RuntimeCall::Vesting(pallet_vesting::Call::vest_other {..}) |
951				// Specifically omitting Vesting `vested_transfer`, and `force_vested_transfer`
952				RuntimeCall::Scheduler(..) |
953				RuntimeCall::Proxy(..) |
954				RuntimeCall::Multisig(..) |
955				RuntimeCall::Nis(..) |
956				RuntimeCall::Registrar(paras_registrar::Call::register {..}) |
957				RuntimeCall::Registrar(paras_registrar::Call::deregister {..}) |
958				// Specifically omitting Registrar `swap`
959				RuntimeCall::Registrar(paras_registrar::Call::reserve {..}) |
960				RuntimeCall::Crowdloan(..) |
961				RuntimeCall::Slots(..) |
962				RuntimeCall::Auctions(..) // Specifically omitting the entire XCM Pallet
963			),
964			ProxyType::Governance => matches!(
965				c,
966				RuntimeCall::Bounties(..) |
967					RuntimeCall::Utility(..) |
968					RuntimeCall::ChildBounties(..) |
969					// OpenGov calls
970					RuntimeCall::ConvictionVoting(..) |
971					RuntimeCall::Referenda(..) |
972					RuntimeCall::FellowshipCollective(..) |
973					RuntimeCall::FellowshipReferenda(..) |
974					RuntimeCall::Whitelist(..)
975			),
976			ProxyType::IdentityJudgement => matches!(
977				c,
978				RuntimeCall::Identity(pallet_identity::Call::provide_judgement { .. }) |
979					RuntimeCall::Utility(..)
980			),
981			ProxyType::CancelProxy => {
982				matches!(c, RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. }))
983			},
984			ProxyType::Auction => matches!(
985				c,
986				RuntimeCall::Auctions { .. } |
987					RuntimeCall::Crowdloan { .. } |
988					RuntimeCall::Registrar { .. } |
989					RuntimeCall::Multisig(..) |
990					RuntimeCall::Slots { .. }
991			),
992			ProxyType::Society => matches!(c, RuntimeCall::Society(..)),
993			ProxyType::OnDemandOrdering => matches!(c, RuntimeCall::OnDemandAssignmentProvider(..)),
994		}
995	}
996	fn is_superset(&self, o: &Self) -> bool {
997		match (self, o) {
998			(x, y) if x == y => true,
999			(ProxyType::Any, _) => true,
1000			(_, ProxyType::Any) => false,
1001			(ProxyType::NonTransfer, _) => true,
1002			_ => false,
1003		}
1004	}
1005}
1006
1007impl pallet_proxy::Config for Runtime {
1008	type RuntimeEvent = RuntimeEvent;
1009	type RuntimeCall = RuntimeCall;
1010	type Currency = Balances;
1011	type ProxyType = ProxyType;
1012	type ProxyDepositBase = ProxyDepositBase;
1013	type ProxyDepositFactor = ProxyDepositFactor;
1014	type MaxProxies = MaxProxies;
1015	type WeightInfo = weights::pallet_proxy::WeightInfo<Runtime>;
1016	type MaxPending = MaxPending;
1017	type CallHasher = BlakeTwo256;
1018	type AnnouncementDepositBase = AnnouncementDepositBase;
1019	type AnnouncementDepositFactor = AnnouncementDepositFactor;
1020	type BlockNumberProvider = frame_system::Pallet<Runtime>;
1021}
1022
1023impl parachains_origin::Config for Runtime {}
1024
1025impl parachains_configuration::Config for Runtime {
1026	type WeightInfo = weights::polkadot_runtime_parachains_configuration::WeightInfo<Runtime>;
1027}
1028
1029impl parachains_shared::Config for Runtime {
1030	type DisabledValidators = Session;
1031}
1032
1033impl parachains_session_info::Config for Runtime {
1034	type ValidatorSet = Historical;
1035}
1036
1037/// Special `RewardValidators` that does nothing ;)
1038pub struct RewardValidators;
1039impl polkadot_runtime_parachains::inclusion::RewardValidators for RewardValidators {
1040	fn reward_backing(_: impl IntoIterator<Item = ValidatorIndex>) {}
1041	fn reward_bitfields(_: impl IntoIterator<Item = ValidatorIndex>) {}
1042}
1043
1044impl parachains_inclusion::Config for Runtime {
1045	type RuntimeEvent = RuntimeEvent;
1046	type DisputesHandler = ParasDisputes;
1047	type RewardValidators = RewardValidators;
1048	type MessageQueue = MessageQueue;
1049	type WeightInfo = weights::polkadot_runtime_parachains_inclusion::WeightInfo<Runtime>;
1050}
1051
1052parameter_types! {
1053	pub const ParasUnsignedPriority: TransactionPriority = TransactionPriority::max_value();
1054}
1055
1056impl parachains_paras::Config for Runtime {
1057	type RuntimeEvent = RuntimeEvent;
1058	type WeightInfo = weights::polkadot_runtime_parachains_paras::WeightInfo<Runtime>;
1059	type UnsignedPriority = ParasUnsignedPriority;
1060	type QueueFootprinter = ParaInclusion;
1061	type NextSessionRotation = Babe;
1062	type OnNewHead = Registrar;
1063	type AssignCoretime = CoretimeAssignmentProvider;
1064	type Fungible = Balances;
1065	// Per day the cooldown is removed earlier, it should cost 1000.
1066	type CooldownRemovalMultiplier = ConstUint<{ 1000 * UNITS / DAYS as u128 }>;
1067	type AuthorizeCurrentCodeOrigin = EnsureRoot<AccountId>;
1068}
1069
1070parameter_types! {
1071	/// Amount of weight that can be spent per block to service messages.
1072	///
1073	/// # WARNING
1074	///
1075	/// This is not a good value for para-chains since the `Scheduler` already uses up to 80% block weight.
1076	pub MessageQueueServiceWeight: Weight = Perbill::from_percent(20) * BlockWeights::get().max_block;
1077	pub const MessageQueueHeapSize: u32 = 32 * 1024;
1078	pub const MessageQueueMaxStale: u32 = 96;
1079}
1080
1081/// Message processor to handle any messages that were enqueued into the `MessageQueue` pallet.
1082pub struct MessageProcessor;
1083impl ProcessMessage for MessageProcessor {
1084	type Origin = AggregateMessageOrigin;
1085
1086	fn process_message(
1087		message: &[u8],
1088		origin: Self::Origin,
1089		meter: &mut WeightMeter,
1090		id: &mut [u8; 32],
1091	) -> Result<bool, ProcessMessageError> {
1092		let para = match origin {
1093			AggregateMessageOrigin::Ump(UmpQueueId::Para(para)) => para,
1094		};
1095		xcm_builder::ProcessXcmMessage::<
1096			Junction,
1097			xcm_executor::XcmExecutor<xcm_config::XcmConfig>,
1098			RuntimeCall,
1099		>::process_message(message, Junction::Parachain(para.into()), meter, id)
1100	}
1101}
1102
1103impl pallet_message_queue::Config for Runtime {
1104	type RuntimeEvent = RuntimeEvent;
1105	type Size = u32;
1106	type HeapSize = MessageQueueHeapSize;
1107	type MaxStale = MessageQueueMaxStale;
1108	type ServiceWeight = MessageQueueServiceWeight;
1109	type IdleMaxServiceWeight = MessageQueueServiceWeight;
1110	#[cfg(not(feature = "runtime-benchmarks"))]
1111	type MessageProcessor = MessageProcessor;
1112	#[cfg(feature = "runtime-benchmarks")]
1113	type MessageProcessor =
1114		pallet_message_queue::mock_helpers::NoopMessageProcessor<AggregateMessageOrigin>;
1115	type QueueChangeHandler = ParaInclusion;
1116	type QueuePausedQuery = ();
1117	type WeightInfo = weights::pallet_message_queue::WeightInfo<Runtime>;
1118}
1119
1120impl parachains_dmp::Config for Runtime {}
1121
1122parameter_types! {
1123	pub const HrmpChannelSizeAndCapacityWithSystemRatio: Percent = Percent::from_percent(100);
1124}
1125
1126impl parachains_hrmp::Config for Runtime {
1127	type RuntimeOrigin = RuntimeOrigin;
1128	type RuntimeEvent = RuntimeEvent;
1129	type ChannelManager = EnsureRoot<AccountId>;
1130	type Currency = Balances;
1131	type DefaultChannelSizeAndCapacityWithSystem = ActiveConfigHrmpChannelSizeAndCapacityRatio<
1132		Runtime,
1133		HrmpChannelSizeAndCapacityWithSystemRatio,
1134	>;
1135	type VersionWrapper = crate::XcmPallet;
1136	type WeightInfo = weights::polkadot_runtime_parachains_hrmp::WeightInfo<Runtime>;
1137}
1138
1139impl parachains_paras_inherent::Config for Runtime {
1140	type WeightInfo = weights::polkadot_runtime_parachains_paras_inherent::WeightInfo<Runtime>;
1141}
1142
1143impl parachains_scheduler::Config for Runtime {
1144	// If you change this, make sure the `Assignment` type of the new provider is binary compatible,
1145	// otherwise provide a migration.
1146	type AssignmentProvider = CoretimeAssignmentProvider;
1147}
1148
1149parameter_types! {
1150	pub const BrokerId: u32 = BROKER_ID;
1151	pub const BrokerPalletId: PalletId = PalletId(*b"py/broke");
1152	pub MaxXcmTransactWeight: Weight = Weight::from_parts(200_000_000, 20_000);
1153}
1154
1155pub struct BrokerPot;
1156impl Get<InteriorLocation> for BrokerPot {
1157	fn get() -> InteriorLocation {
1158		Junction::AccountId32 { network: None, id: BrokerPalletId::get().into_account_truncating() }
1159			.into()
1160	}
1161}
1162
1163impl coretime::Config for Runtime {
1164	type RuntimeOrigin = RuntimeOrigin;
1165	type RuntimeEvent = RuntimeEvent;
1166	type BrokerId = BrokerId;
1167	type BrokerPotLocation = BrokerPot;
1168	type WeightInfo = weights::polkadot_runtime_parachains_coretime::WeightInfo<Runtime>;
1169	type SendXcm = crate::xcm_config::XcmRouter;
1170	type AssetTransactor = crate::xcm_config::LocalAssetTransactor;
1171	type AccountToLocation = xcm_builder::AliasesIntoAccountId32<
1172		xcm_config::ThisNetwork,
1173		<Runtime as frame_system::Config>::AccountId,
1174	>;
1175	type MaxXcmTransactWeight = MaxXcmTransactWeight;
1176}
1177
1178parameter_types! {
1179	pub const OnDemandTrafficDefaultValue: FixedU128 = FixedU128::from_u32(1);
1180	// Keep 2 timeslices worth of revenue information.
1181	pub const MaxHistoricalRevenue: BlockNumber = 2 * TIMESLICE_PERIOD;
1182	pub const OnDemandPalletId: PalletId = PalletId(*b"py/ondmd");
1183}
1184
1185impl parachains_on_demand::Config for Runtime {
1186	type RuntimeEvent = RuntimeEvent;
1187	type Currency = Balances;
1188	type TrafficDefaultValue = OnDemandTrafficDefaultValue;
1189	type WeightInfo = weights::polkadot_runtime_parachains_on_demand::WeightInfo<Runtime>;
1190	type MaxHistoricalRevenue = MaxHistoricalRevenue;
1191	type PalletId = OnDemandPalletId;
1192}
1193
1194impl parachains_assigner_coretime::Config for Runtime {}
1195
1196impl parachains_initializer::Config for Runtime {
1197	type Randomness = pallet_babe::RandomnessFromOneEpochAgo<Runtime>;
1198	type ForceOrigin = EnsureRoot<AccountId>;
1199	type WeightInfo = weights::polkadot_runtime_parachains_initializer::WeightInfo<Runtime>;
1200	type CoretimeOnNewSession = Coretime;
1201}
1202
1203impl parachains_disputes::Config for Runtime {
1204	type RuntimeEvent = RuntimeEvent;
1205	type RewardValidators = ();
1206	type SlashingHandler = parachains_slashing::SlashValidatorsForDisputes<ParasSlashing>;
1207	type WeightInfo = weights::polkadot_runtime_parachains_disputes::WeightInfo<Runtime>;
1208}
1209
1210impl parachains_slashing::Config for Runtime {
1211	type KeyOwnerProofSystem = Historical;
1212	type KeyOwnerProof =
1213		<Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, ValidatorId)>>::Proof;
1214	type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
1215		KeyTypeId,
1216		ValidatorId,
1217	)>>::IdentificationTuple;
1218	type HandleReports = parachains_slashing::SlashingReportHandler<
1219		Self::KeyOwnerIdentification,
1220		Offences,
1221		ReportLongevity,
1222	>;
1223	type WeightInfo = parachains_slashing::TestWeightInfo;
1224	type BenchmarkingConfig = parachains_slashing::BenchConfig<200>;
1225}
1226
1227parameter_types! {
1228	pub const ParaDeposit: Balance = 40 * UNITS;
1229}
1230
1231impl paras_registrar::Config for Runtime {
1232	type RuntimeOrigin = RuntimeOrigin;
1233	type RuntimeEvent = RuntimeEvent;
1234	type Currency = Balances;
1235	type OnSwap = (Crowdloan, Slots, SwapLeases);
1236	type ParaDeposit = ParaDeposit;
1237	type DataDepositPerByte = DataDepositPerByte;
1238	type WeightInfo = weights::polkadot_runtime_common_paras_registrar::WeightInfo<Runtime>;
1239}
1240
1241parameter_types! {
1242	pub LeasePeriod: BlockNumber = prod_or_fast!(1 * DAYS, 1 * DAYS, "ROC_LEASE_PERIOD");
1243}
1244
1245impl slots::Config for Runtime {
1246	type RuntimeEvent = RuntimeEvent;
1247	type Currency = Balances;
1248	type Registrar = Registrar;
1249	type LeasePeriod = LeasePeriod;
1250	type LeaseOffset = ();
1251	type ForceOrigin = EitherOf<EnsureRoot<Self::AccountId>, LeaseAdmin>;
1252	type WeightInfo = weights::polkadot_runtime_common_slots::WeightInfo<Runtime>;
1253}
1254
1255parameter_types! {
1256	pub const CrowdloanId: PalletId = PalletId(*b"py/cfund");
1257	pub const SubmissionDeposit: Balance = 3 * GRAND;
1258	pub const MinContribution: Balance = 3_000 * CENTS;
1259	pub const RemoveKeysLimit: u32 = 1000;
1260	// Allow 32 bytes for an additional memo to a crowdloan.
1261	pub const MaxMemoLength: u8 = 32;
1262}
1263
1264impl crowdloan::Config for Runtime {
1265	type RuntimeEvent = RuntimeEvent;
1266	type PalletId = CrowdloanId;
1267	type SubmissionDeposit = SubmissionDeposit;
1268	type MinContribution = MinContribution;
1269	type RemoveKeysLimit = RemoveKeysLimit;
1270	type Registrar = Registrar;
1271	type Auctioneer = Auctions;
1272	type MaxMemoLength = MaxMemoLength;
1273	type WeightInfo = weights::polkadot_runtime_common_crowdloan::WeightInfo<Runtime>;
1274}
1275
1276parameter_types! {
1277	// The average auction is 7 days long, so this will be 70% for ending period.
1278	// 5 Days = 72000 Blocks @ 6 sec per block
1279	pub const EndingPeriod: BlockNumber = 5 * DAYS;
1280	// ~ 1000 samples per day -> ~ 20 blocks per sample -> 2 minute samples
1281	pub const SampleLength: BlockNumber = 2 * MINUTES;
1282}
1283
1284impl auctions::Config for Runtime {
1285	type RuntimeEvent = RuntimeEvent;
1286	type Leaser = Slots;
1287	type Registrar = Registrar;
1288	type EndingPeriod = EndingPeriod;
1289	type SampleLength = SampleLength;
1290	type Randomness = pallet_babe::RandomnessFromOneEpochAgo<Runtime>;
1291	type InitiateOrigin = EitherOf<EnsureRoot<Self::AccountId>, AuctionAdmin>;
1292	type WeightInfo = weights::polkadot_runtime_common_auctions::WeightInfo<Runtime>;
1293}
1294
1295impl identity_migrator::Config for Runtime {
1296	type RuntimeEvent = RuntimeEvent;
1297	type Reaper = EnsureSigned<AccountId>;
1298	type ReapIdentityHandler = ToParachainIdentityReaper<Runtime, Self::AccountId>;
1299	type WeightInfo = weights::polkadot_runtime_common_identity_migrator::WeightInfo<Runtime>;
1300}
1301
1302type NisCounterpartInstance = pallet_balances::Instance2;
1303impl pallet_balances::Config<NisCounterpartInstance> for Runtime {
1304	type Balance = Balance;
1305	type DustRemoval = ();
1306	type RuntimeEvent = RuntimeEvent;
1307	type ExistentialDeposit = ConstU128<10_000_000_000>; // One RTC cent
1308	type AccountStore = StorageMapShim<
1309		pallet_balances::Account<Runtime, NisCounterpartInstance>,
1310		AccountId,
1311		pallet_balances::AccountData<u128>,
1312	>;
1313	type MaxLocks = ConstU32<4>;
1314	type MaxReserves = ConstU32<4>;
1315	type ReserveIdentifier = [u8; 8];
1316	type WeightInfo = weights::pallet_balances_nis_counterpart_balances::WeightInfo<Runtime>;
1317	type RuntimeHoldReason = RuntimeHoldReason;
1318	type RuntimeFreezeReason = RuntimeFreezeReason;
1319	type FreezeIdentifier = ();
1320	type MaxFreezes = ConstU32<1>;
1321	type DoneSlashHandler = ();
1322}
1323
1324parameter_types! {
1325	pub const NisBasePeriod: BlockNumber = 30 * DAYS;
1326	pub MinReceipt: Perquintill = Perquintill::from_rational(1u64, 10_000_000u64);
1327	pub const IntakePeriod: BlockNumber = 5 * MINUTES;
1328	pub MaxIntakeWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;
1329	pub const ThawThrottle: (Perquintill, BlockNumber) = (Perquintill::from_percent(25), 5);
1330	pub const NisPalletId: PalletId = PalletId(*b"py/nis  ");
1331}
1332
1333impl pallet_nis::Config for Runtime {
1334	type WeightInfo = weights::pallet_nis::WeightInfo<Runtime>;
1335	type RuntimeEvent = RuntimeEvent;
1336	type Currency = Balances;
1337	type CurrencyBalance = Balance;
1338	type FundOrigin = frame_system::EnsureSigned<AccountId>;
1339	type Counterpart = NisCounterpartBalances;
1340	type CounterpartAmount = WithMaximumOf<ConstU128<21_000_000_000_000_000_000u128>>;
1341	type Deficit = (); // Mint
1342	type IgnoredIssuance = ();
1343	type Target = dynamic_params::nis::Target;
1344	type PalletId = NisPalletId;
1345	type QueueCount = ConstU32<300>;
1346	type MaxQueueLen = ConstU32<1000>;
1347	type FifoQueueLen = ConstU32<250>;
1348	type BasePeriod = NisBasePeriod;
1349	type MinBid = dynamic_params::nis::MinBid;
1350	type MinReceipt = MinReceipt;
1351	type IntakePeriod = IntakePeriod;
1352	type MaxIntakeWeight = MaxIntakeWeight;
1353	type ThawThrottle = ThawThrottle;
1354	type RuntimeHoldReason = RuntimeHoldReason;
1355	#[cfg(feature = "runtime-benchmarks")]
1356	type BenchmarkSetup = ();
1357}
1358
1359impl pallet_parameters::Config for Runtime {
1360	type RuntimeEvent = RuntimeEvent;
1361	type RuntimeParameters = RuntimeParameters;
1362	type AdminOrigin = DynamicParameterOrigin;
1363	type WeightInfo = weights::pallet_parameters::WeightInfo<Runtime>;
1364}
1365
1366parameter_types! {
1367	pub BeefySetIdSessionEntries: u32 = BondingDuration::get() * SessionsPerEra::get();
1368}
1369
1370impl pallet_beefy::Config for Runtime {
1371	type BeefyId = BeefyId;
1372	type MaxAuthorities = MaxAuthorities;
1373	type MaxNominators = ConstU32<0>;
1374	type MaxSetIdSessionEntries = BeefySetIdSessionEntries;
1375	type OnNewValidatorSet = MmrLeaf;
1376	type AncestryHelper = MmrLeaf;
1377	type WeightInfo = ();
1378	type KeyOwnerProof = <Historical as KeyOwnerProofSystem<(KeyTypeId, BeefyId)>>::Proof;
1379	type EquivocationReportSystem =
1380		pallet_beefy::EquivocationReportSystem<Self, Offences, Historical, ReportLongevity>;
1381}
1382
1383/// MMR helper types.
1384mod mmr {
1385	use super::Runtime;
1386	pub use pallet_mmr::primitives::*;
1387
1388	pub type Leaf = <<Runtime as pallet_mmr::Config>::LeafData as LeafDataProvider>::LeafData;
1389	pub type Hashing = <Runtime as pallet_mmr::Config>::Hashing;
1390	pub type Hash = <Hashing as sp_runtime::traits::Hash>::Output;
1391}
1392
1393impl pallet_mmr::Config for Runtime {
1394	const INDEXING_PREFIX: &'static [u8] = mmr::INDEXING_PREFIX;
1395	type Hashing = Keccak256;
1396	type OnNewRoot = pallet_beefy_mmr::DepositBeefyDigest<Runtime>;
1397	type LeafData = pallet_beefy_mmr::Pallet<Runtime>;
1398	type BlockHashProvider = pallet_mmr::DefaultBlockHashProvider<Runtime>;
1399	type WeightInfo = weights::pallet_mmr::WeightInfo<Runtime>;
1400	#[cfg(feature = "runtime-benchmarks")]
1401	type BenchmarkHelper = parachains_paras::benchmarking::mmr_setup::MmrSetup<Runtime>;
1402}
1403
1404parameter_types! {
1405	pub LeafVersion: MmrLeafVersion = MmrLeafVersion::new(0, 0);
1406}
1407
1408pub struct ParaHeadsRootProvider;
1409impl BeefyDataProvider<H256> for ParaHeadsRootProvider {
1410	fn extra_data() -> H256 {
1411		let para_heads: Vec<(u32, Vec<u8>)> =
1412			parachains_paras::Pallet::<Runtime>::sorted_para_heads();
1413		binary_merkle_tree::merkle_root::<mmr::Hashing, _>(
1414			para_heads.into_iter().map(|pair| pair.encode()),
1415		)
1416		.into()
1417	}
1418}
1419
1420impl pallet_beefy_mmr::Config for Runtime {
1421	type LeafVersion = LeafVersion;
1422	type BeefyAuthorityToMerkleLeaf = pallet_beefy_mmr::BeefyEcdsaToEthereum;
1423	type LeafExtra = H256;
1424	type BeefyDataProvider = ParaHeadsRootProvider;
1425	type WeightInfo = weights::pallet_beefy_mmr::WeightInfo<Runtime>;
1426}
1427
1428impl paras_sudo_wrapper::Config for Runtime {}
1429
1430parameter_types! {
1431	pub const PermanentSlotLeasePeriodLength: u32 = 365;
1432	pub const TemporarySlotLeasePeriodLength: u32 = 5;
1433	pub const MaxTemporarySlotPerLeasePeriod: u32 = 5;
1434}
1435
1436impl assigned_slots::Config for Runtime {
1437	type RuntimeEvent = RuntimeEvent;
1438	type AssignSlotOrigin = EnsureRoot<AccountId>;
1439	type Leaser = Slots;
1440	type PermanentSlotLeasePeriodLength = PermanentSlotLeasePeriodLength;
1441	type TemporarySlotLeasePeriodLength = TemporarySlotLeasePeriodLength;
1442	type MaxTemporarySlotPerLeasePeriod = MaxTemporarySlotPerLeasePeriod;
1443	type WeightInfo = weights::polkadot_runtime_common_assigned_slots::WeightInfo<Runtime>;
1444}
1445
1446impl validator_manager::Config for Runtime {
1447	type RuntimeEvent = RuntimeEvent;
1448	type PrivilegedOrigin = EnsureRoot<AccountId>;
1449}
1450
1451parameter_types! {
1452	pub MbmServiceWeight: Weight = Perbill::from_percent(80) * BlockWeights::get().max_block;
1453}
1454
1455impl pallet_migrations::Config for Runtime {
1456	type RuntimeEvent = RuntimeEvent;
1457	#[cfg(not(feature = "runtime-benchmarks"))]
1458	type Migrations = pallet_identity::migration::v2::LazyMigrationV1ToV2<Runtime>;
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		CoretimeAssignmentProvider: parachains_assigner_coretime = 68,
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	pub struct GetLegacyLeaseImpl;
1682	impl coretime::migration::GetLegacyLease<BlockNumber> for GetLegacyLeaseImpl {
1683		fn get_parachain_lease_in_blocks(para: ParaId) -> Option<BlockNumber> {
1684			let now = frame_system::Pallet::<Runtime>::block_number();
1685			let lease = slots::Leases::<Runtime>::get(para);
1686			if lease.is_empty() {
1687				return None;
1688			}
1689			// Lease not yet started, ignore:
1690			if lease.iter().any(Option::is_none) {
1691				return None;
1692			}
1693			let (index, _) =
1694				<slots::Pallet<Runtime> as Leaser<BlockNumber>>::lease_period_index(now)?;
1695			Some(index.saturating_add(lease.len() as u32).saturating_mul(LeasePeriod::get()))
1696		}
1697
1698		fn get_all_parachains_with_leases() -> Vec<ParaId> {
1699			slots::Leases::<Runtime>::iter()
1700				.filter(|(_, lease)| !lease.is_empty())
1701				.map(|(para, _)| para)
1702				.collect::<Vec<_>>()
1703		}
1704	}
1705
1706	parameter_types! {
1707		pub const DemocracyPalletName: &'static str = "Democracy";
1708		pub const CouncilPalletName: &'static str = "Council";
1709		pub const TechnicalCommitteePalletName: &'static str = "TechnicalCommittee";
1710		pub const PhragmenElectionPalletName: &'static str = "PhragmenElection";
1711		pub const TechnicalMembershipPalletName: &'static str = "TechnicalMembership";
1712		pub const TipsPalletName: &'static str = "Tips";
1713		pub const PhragmenElectionPalletId: LockIdentifier = *b"phrelect";
1714		/// Weight for balance unreservations
1715		pub BalanceUnreserveWeight: Weight = weights::pallet_balances_balances::WeightInfo::<Runtime>::force_unreserve();
1716		pub BalanceTransferAllowDeath: Weight = weights::pallet_balances_balances::WeightInfo::<Runtime>::transfer_allow_death();
1717	}
1718
1719	// Special Config for Gov V1 pallets, allowing us to run migrations for them without
1720	// implementing their configs on [`Runtime`].
1721	pub struct UnlockConfig;
1722	impl pallet_democracy::migrations::unlock_and_unreserve_all_funds::UnlockConfig for UnlockConfig {
1723		type Currency = Balances;
1724		type MaxVotes = ConstU32<100>;
1725		type MaxDeposits = ConstU32<100>;
1726		type AccountId = AccountId;
1727		type BlockNumber = BlockNumberFor<Runtime>;
1728		type DbWeight = <Runtime as frame_system::Config>::DbWeight;
1729		type PalletName = DemocracyPalletName;
1730	}
1731	impl pallet_elections_phragmen::migrations::unlock_and_unreserve_all_funds::UnlockConfig
1732		for UnlockConfig
1733	{
1734		type Currency = Balances;
1735		type MaxVotesPerVoter = ConstU32<16>;
1736		type PalletId = PhragmenElectionPalletId;
1737		type AccountId = AccountId;
1738		type DbWeight = <Runtime as frame_system::Config>::DbWeight;
1739		type PalletName = PhragmenElectionPalletName;
1740	}
1741	impl pallet_tips::migrations::unreserve_deposits::UnlockConfig<()> for UnlockConfig {
1742		type Currency = Balances;
1743		type Hash = Hash;
1744		type DataDepositPerByte = DataDepositPerByte;
1745		type TipReportDepositBase = TipReportDepositBase;
1746		type AccountId = AccountId;
1747		type BlockNumber = BlockNumberFor<Runtime>;
1748		type DbWeight = <Runtime as frame_system::Config>::DbWeight;
1749		type PalletName = TipsPalletName;
1750	}
1751
1752	// We don't have a limit in the Relay Chain.
1753	const IDENTITY_MIGRATION_KEY_LIMIT: u64 = u64::MAX;
1754
1755	/// Unreleased migrations. Add new ones here:
1756	pub type Unreleased = (
1757        pallet_society::migrations::MigrateToV2<Runtime, (), ()>,
1758        parachains_configuration::migration::v7::MigrateToV7<Runtime>,
1759        assigned_slots::migration::v1::MigrateToV1<Runtime>,
1760        parachains_scheduler::migration::MigrateV1ToV2<Runtime>,
1761        parachains_configuration::migration::v8::MigrateToV8<Runtime>,
1762        parachains_configuration::migration::v9::MigrateToV9<Runtime>,
1763        paras_registrar::migration::MigrateToV1<Runtime, ()>,
1764        pallet_referenda::migration::v1::MigrateV0ToV1<Runtime, ()>,
1765        pallet_referenda::migration::v1::MigrateV0ToV1<Runtime, pallet_referenda::Instance2>,
1766        pallet_child_bounties::migration::MigrateV0ToV1<Runtime, BalanceTransferAllowDeath>,
1767
1768        // Unlock & unreserve Gov1 funds
1769
1770        pallet_elections_phragmen::migrations::unlock_and_unreserve_all_funds::UnlockAndUnreserveAllFunds<UnlockConfig>,
1771        pallet_democracy::migrations::unlock_and_unreserve_all_funds::UnlockAndUnreserveAllFunds<UnlockConfig>,
1772        pallet_tips::migrations::unreserve_deposits::UnreserveDeposits<UnlockConfig, ()>,
1773        pallet_treasury::migration::cleanup_proposals::Migration<Runtime, (), BalanceUnreserveWeight>,
1774
1775        // Delete all Gov v1 pallet storage key/values.
1776
1777        frame_support::migrations::RemovePallet<DemocracyPalletName, <Runtime as frame_system::Config>::DbWeight>,
1778        frame_support::migrations::RemovePallet<CouncilPalletName, <Runtime as frame_system::Config>::DbWeight>,
1779        frame_support::migrations::RemovePallet<TechnicalCommitteePalletName, <Runtime as frame_system::Config>::DbWeight>,
1780        frame_support::migrations::RemovePallet<PhragmenElectionPalletName, <Runtime as frame_system::Config>::DbWeight>,
1781        frame_support::migrations::RemovePallet<TechnicalMembershipPalletName, <Runtime as frame_system::Config>::DbWeight>,
1782        frame_support::migrations::RemovePallet<TipsPalletName, <Runtime as frame_system::Config>::DbWeight>,
1783        pallet_grandpa::migrations::MigrateV4ToV5<Runtime>,
1784        parachains_configuration::migration::v10::MigrateToV10<Runtime>,
1785
1786        // Migrate Identity pallet for Usernames
1787        pallet_identity::migration::versioned::V0ToV1<Runtime, IDENTITY_MIGRATION_KEY_LIMIT>,
1788        parachains_configuration::migration::v11::MigrateToV11<Runtime>,
1789        // This needs to come after the `parachains_configuration` above as we are reading the configuration.
1790        coretime::migration::MigrateToCoretime<Runtime, crate::xcm_config::XcmRouter, GetLegacyLeaseImpl, TIMESLICE_PERIOD>,
1791        parachains_configuration::migration::v12::MigrateToV12<Runtime>,
1792        parachains_on_demand::migration::MigrateV0ToV1<Runtime>,
1793
1794		// migrates session storage item
1795		pallet_session::migrations::v1::MigrateV0ToV1<Runtime, pallet_session::migrations::v1::InitOffenceSeverity<Runtime>>,
1796
1797        // permanent
1798        pallet_xcm::migration::MigrateToLatestXcmVersion<Runtime>,
1799        parachains_inclusion::migration::MigrateToV1<Runtime>,
1800		parachains_shared::migration::MigrateToV1<Runtime>,
1801        parachains_scheduler::migration::MigrateV2ToV3<Runtime>,
1802    );
1803}
1804
1805/// Executive: handles dispatch to the various modules.
1806pub type Executive = frame_executive::Executive<
1807	Runtime,
1808	Block,
1809	frame_system::ChainContext<Runtime>,
1810	Runtime,
1811	AllPalletsWithSystem,
1812>;
1813/// The payload being signed in transactions.
1814pub type SignedPayload = generic::SignedPayload<RuntimeCall, TxExtension>;
1815
1816parameter_types! {
1817	// 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)
1818	pub const MigrationSignedDepositPerItem: Balance = 1 * CENTS;
1819	pub const MigrationSignedDepositBase: Balance = 20 * CENTS * 100;
1820	pub const MigrationMaxKeyLen: u32 = 512;
1821}
1822
1823impl pallet_state_trie_migration::Config for Runtime {
1824	type RuntimeEvent = RuntimeEvent;
1825	type Currency = Balances;
1826	type RuntimeHoldReason = RuntimeHoldReason;
1827	type SignedDepositPerItem = MigrationSignedDepositPerItem;
1828	type SignedDepositBase = MigrationSignedDepositBase;
1829	type ControlOrigin = EnsureRoot<AccountId>;
1830	// specific account for the migration, can trigger the signed migrations.
1831	type SignedFilter = frame_system::EnsureSignedBy<MigController, AccountId>;
1832
1833	// Use same weights as substrate ones.
1834	type WeightInfo = pallet_state_trie_migration::weights::SubstrateWeight<Runtime>;
1835	type MaxKeyLen = MigrationMaxKeyLen;
1836}
1837
1838frame_support::ord_parameter_types! {
1839	pub const MigController: AccountId = AccountId::from(hex_literal::hex!("52bc71c1eca5353749542dfdf0af97bf764f9c2f44e860cd485f1cd86400f649"));
1840}
1841
1842#[cfg(feature = "runtime-benchmarks")]
1843mod benches {
1844	frame_benchmarking::define_benchmarks!(
1845		// Polkadot
1846		// NOTE: Make sure to prefix these with `runtime_common::` so
1847		// the that path resolves correctly in the generated file.
1848		[polkadot_runtime_common::assigned_slots, AssignedSlots]
1849		[polkadot_runtime_common::auctions, Auctions]
1850		[polkadot_runtime_common::crowdloan, Crowdloan]
1851		[polkadot_runtime_common::claims, Claims]
1852		[polkadot_runtime_common::identity_migrator, IdentityMigrator]
1853		[polkadot_runtime_common::slots, Slots]
1854		[polkadot_runtime_common::paras_registrar, Registrar]
1855		[polkadot_runtime_parachains::configuration, Configuration]
1856		[polkadot_runtime_parachains::coretime, Coretime]
1857		[polkadot_runtime_parachains::hrmp, Hrmp]
1858		[polkadot_runtime_parachains::disputes, ParasDisputes]
1859		[polkadot_runtime_parachains::inclusion, ParaInclusion]
1860		[polkadot_runtime_parachains::initializer, Initializer]
1861		[polkadot_runtime_parachains::paras_inherent, ParaInherent]
1862		[polkadot_runtime_parachains::paras, Paras]
1863		[polkadot_runtime_parachains::on_demand, OnDemandAssignmentProvider]
1864		// Substrate
1865		[pallet_balances, Balances]
1866		[pallet_balances, NisCounterpartBalances]
1867		[pallet_beefy_mmr, MmrLeaf]
1868		[frame_benchmarking::baseline, Baseline::<Runtime>]
1869		[pallet_bounties, Bounties]
1870		[pallet_child_bounties, ChildBounties]
1871		[pallet_conviction_voting, ConvictionVoting]
1872		[pallet_nis, Nis]
1873		[pallet_identity, Identity]
1874		[pallet_indices, Indices]
1875		[pallet_message_queue, MessageQueue]
1876		[pallet_migrations, MultiBlockMigrations]
1877		[pallet_mmr, Mmr]
1878		[pallet_multisig, Multisig]
1879		[pallet_parameters, Parameters]
1880		[pallet_preimage, Preimage]
1881		[pallet_proxy, Proxy]
1882		[pallet_ranked_collective, FellowshipCollective]
1883		[pallet_recovery, Recovery]
1884		[pallet_referenda, Referenda]
1885		[pallet_referenda, FellowshipReferenda]
1886		[pallet_scheduler, Scheduler]
1887		[pallet_sudo, Sudo]
1888		[frame_system, SystemBench::<Runtime>]
1889		[frame_system_extensions, SystemExtensionsBench::<Runtime>]
1890		[pallet_timestamp, Timestamp]
1891		[pallet_transaction_payment, TransactionPayment]
1892		[pallet_treasury, Treasury]
1893		[pallet_utility, Utility]
1894		[pallet_vesting, Vesting]
1895		[pallet_asset_rate, AssetRate]
1896		[pallet_whitelist, Whitelist]
1897		// XCM
1898		[pallet_xcm, PalletXcmExtrinsicsBenchmark::<Runtime>]
1899		[pallet_xcm_benchmarks::fungible, pallet_xcm_benchmarks::fungible::Pallet::<Runtime>]
1900		[pallet_xcm_benchmarks::generic, pallet_xcm_benchmarks::generic::Pallet::<Runtime>]
1901	);
1902}
1903
1904sp_api::impl_runtime_apis! {
1905	impl sp_api::Core<Block> for Runtime {
1906		fn version() -> RuntimeVersion {
1907			VERSION
1908		}
1909
1910		fn execute_block(block: <Block as BlockT>::LazyBlock) {
1911			Executive::execute_block(block);
1912		}
1913
1914		fn initialize_block(header: &<Block as BlockT>::Header) -> sp_runtime::ExtrinsicInclusionMode {
1915			Executive::initialize_block(header)
1916		}
1917	}
1918
1919	impl xcm_runtime_apis::fees::XcmPaymentApi<Block> for Runtime {
1920		fn query_acceptable_payment_assets(xcm_version: xcm::Version) -> Result<Vec<VersionedAssetId>, XcmPaymentApiError> {
1921			let acceptable_assets = vec![AssetId(xcm_config::TokenLocation::get())];
1922			XcmPallet::query_acceptable_payment_assets(xcm_version, acceptable_assets)
1923		}
1924
1925		fn query_weight_to_asset_fee(weight: Weight, asset: VersionedAssetId) -> Result<u128, XcmPaymentApiError> {
1926			type Trader = <XcmConfig as xcm_executor::Config>::Trader;
1927			XcmPallet::query_weight_to_asset_fee::<Trader>(weight, asset)
1928		}
1929
1930		fn query_xcm_weight(message: VersionedXcm<()>) -> Result<Weight, XcmPaymentApiError> {
1931			XcmPallet::query_xcm_weight(message)
1932		}
1933
1934		fn query_delivery_fees(destination: VersionedLocation, message: VersionedXcm<()>, asset_id: VersionedAssetId) -> Result<VersionedAssets, XcmPaymentApiError> {
1935			type AssetExchanger = <XcmConfig as xcm_executor::Config>::AssetExchanger;
1936			XcmPallet::query_delivery_fees::<AssetExchanger>(destination, message, asset_id)
1937		}
1938	}
1939
1940	impl xcm_runtime_apis::dry_run::DryRunApi<Block, RuntimeCall, RuntimeEvent, OriginCaller> for Runtime {
1941		fn dry_run_call(origin: OriginCaller, call: RuntimeCall, result_xcms_version: XcmVersion) -> Result<CallDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
1942			XcmPallet::dry_run_call::<Runtime, xcm_config::XcmRouter, OriginCaller, RuntimeCall>(origin, call, result_xcms_version)
1943		}
1944
1945		fn dry_run_xcm(origin_location: VersionedLocation, xcm: VersionedXcm<RuntimeCall>) -> Result<XcmDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
1946			XcmPallet::dry_run_xcm::<xcm_config::XcmRouter>(origin_location, xcm)
1947		}
1948	}
1949
1950	impl xcm_runtime_apis::conversions::LocationToAccountApi<Block, AccountId> for Runtime {
1951		fn convert_location(location: VersionedLocation) -> Result<
1952			AccountId,
1953			xcm_runtime_apis::conversions::Error
1954		> {
1955			xcm_runtime_apis::conversions::LocationToAccountHelper::<
1956				AccountId,
1957				xcm_config::LocationConverter,
1958			>::convert_location(location)
1959		}
1960	}
1961
1962	impl sp_api::Metadata<Block> for Runtime {
1963		fn metadata() -> OpaqueMetadata {
1964			OpaqueMetadata::new(Runtime::metadata().into())
1965		}
1966
1967		fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
1968			Runtime::metadata_at_version(version)
1969		}
1970
1971		fn metadata_versions() -> alloc::vec::Vec<u32> {
1972			Runtime::metadata_versions()
1973		}
1974	}
1975
1976	impl sp_block_builder::BlockBuilder<Block> for Runtime {
1977		fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
1978			Executive::apply_extrinsic(extrinsic)
1979		}
1980
1981		fn finalize_block() -> <Block as BlockT>::Header {
1982			Executive::finalize_block()
1983		}
1984
1985		fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
1986			data.create_extrinsics()
1987		}
1988
1989		fn check_inherents(
1990			block: <Block as BlockT>::LazyBlock,
1991			data: sp_inherents::InherentData,
1992		) -> sp_inherents::CheckInherentsResult {
1993			data.check_extrinsics(&block)
1994		}
1995	}
1996
1997	impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
1998		fn validate_transaction(
1999			source: TransactionSource,
2000			tx: <Block as BlockT>::Extrinsic,
2001			block_hash: <Block as BlockT>::Hash,
2002		) -> TransactionValidity {
2003			Executive::validate_transaction(source, tx, block_hash)
2004		}
2005	}
2006
2007	impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
2008		fn offchain_worker(header: &<Block as BlockT>::Header) {
2009			Executive::offchain_worker(header)
2010		}
2011	}
2012
2013	#[api_version(15)]
2014	impl polkadot_primitives::runtime_api::ParachainHost<Block> for Runtime {
2015		fn validators() -> Vec<ValidatorId> {
2016			parachains_runtime_api_impl::validators::<Runtime>()
2017		}
2018
2019		fn validator_groups() -> (Vec<Vec<ValidatorIndex>>, GroupRotationInfo<BlockNumber>) {
2020			parachains_runtime_api_impl::validator_groups::<Runtime>()
2021		}
2022
2023		fn availability_cores() -> Vec<CoreState<Hash, BlockNumber>> {
2024			parachains_runtime_api_impl::availability_cores::<Runtime>()
2025		}
2026
2027		fn persisted_validation_data(para_id: ParaId, assumption: OccupiedCoreAssumption)
2028			-> Option<PersistedValidationData<Hash, BlockNumber>> {
2029			parachains_runtime_api_impl::persisted_validation_data::<Runtime>(para_id, assumption)
2030		}
2031
2032		fn assumed_validation_data(
2033			para_id: ParaId,
2034			expected_persisted_validation_data_hash: Hash,
2035		) -> Option<(PersistedValidationData<Hash, BlockNumber>, ValidationCodeHash)> {
2036			parachains_runtime_api_impl::assumed_validation_data::<Runtime>(
2037				para_id,
2038				expected_persisted_validation_data_hash,
2039			)
2040		}
2041
2042		fn check_validation_outputs(
2043			para_id: ParaId,
2044			outputs: polkadot_primitives::CandidateCommitments,
2045		) -> bool {
2046			parachains_runtime_api_impl::check_validation_outputs::<Runtime>(para_id, outputs)
2047		}
2048
2049		fn session_index_for_child() -> SessionIndex {
2050			parachains_runtime_api_impl::session_index_for_child::<Runtime>()
2051		}
2052
2053		fn validation_code(para_id: ParaId, assumption: OccupiedCoreAssumption)
2054			-> Option<ValidationCode> {
2055			parachains_runtime_api_impl::validation_code::<Runtime>(para_id, assumption)
2056		}
2057
2058		fn candidate_pending_availability(para_id: ParaId) -> Option<CommittedCandidateReceipt<Hash>> {
2059			#[allow(deprecated)]
2060			parachains_runtime_api_impl::candidate_pending_availability::<Runtime>(para_id)
2061		}
2062
2063		fn candidate_events() -> Vec<CandidateEvent<Hash>> {
2064			parachains_runtime_api_impl::candidate_events::<Runtime, _>(|ev| {
2065				match ev {
2066					RuntimeEvent::ParaInclusion(ev) => {
2067						Some(ev)
2068					}
2069					_ => None,
2070				}
2071			})
2072		}
2073
2074		fn session_info(index: SessionIndex) -> Option<SessionInfo> {
2075			parachains_runtime_api_impl::session_info::<Runtime>(index)
2076		}
2077
2078		fn session_executor_params(session_index: SessionIndex) -> Option<ExecutorParams> {
2079			parachains_runtime_api_impl::session_executor_params::<Runtime>(session_index)
2080		}
2081
2082		fn dmq_contents(recipient: ParaId) -> Vec<InboundDownwardMessage<BlockNumber>> {
2083			parachains_runtime_api_impl::dmq_contents::<Runtime>(recipient)
2084		}
2085
2086		fn inbound_hrmp_channels_contents(
2087			recipient: ParaId
2088		) -> BTreeMap<ParaId, Vec<InboundHrmpMessage<BlockNumber>>> {
2089			parachains_runtime_api_impl::inbound_hrmp_channels_contents::<Runtime>(recipient)
2090		}
2091
2092		fn validation_code_by_hash(hash: ValidationCodeHash) -> Option<ValidationCode> {
2093			parachains_runtime_api_impl::validation_code_by_hash::<Runtime>(hash)
2094		}
2095
2096		fn on_chain_votes() -> Option<ScrapedOnChainVotes<Hash>> {
2097			parachains_runtime_api_impl::on_chain_votes::<Runtime>()
2098		}
2099
2100		fn submit_pvf_check_statement(
2101			stmt: polkadot_primitives::PvfCheckStatement,
2102			signature: polkadot_primitives::ValidatorSignature
2103		) {
2104			parachains_runtime_api_impl::submit_pvf_check_statement::<Runtime>(stmt, signature)
2105		}
2106
2107		fn pvfs_require_precheck() -> Vec<ValidationCodeHash> {
2108			parachains_runtime_api_impl::pvfs_require_precheck::<Runtime>()
2109		}
2110
2111		fn validation_code_hash(para_id: ParaId, assumption: OccupiedCoreAssumption)
2112			-> Option<ValidationCodeHash>
2113		{
2114			parachains_runtime_api_impl::validation_code_hash::<Runtime>(para_id, assumption)
2115		}
2116
2117		fn disputes() -> Vec<(SessionIndex, CandidateHash, DisputeState<BlockNumber>)> {
2118			parachains_runtime_api_impl::get_session_disputes::<Runtime>()
2119		}
2120
2121		fn unapplied_slashes(
2122		) -> Vec<(SessionIndex, CandidateHash, slashing::LegacyPendingSlashes)> {
2123			parachains_runtime_api_impl::unapplied_slashes::<Runtime>()
2124		}
2125
2126		fn unapplied_slashes_v2(
2127		) -> Vec<(SessionIndex, CandidateHash, slashing::PendingSlashes)> {
2128			parachains_runtime_api_impl::unapplied_slashes_v2::<Runtime>()
2129		}
2130
2131		fn key_ownership_proof(
2132			validator_id: ValidatorId,
2133		) -> Option<slashing::OpaqueKeyOwnershipProof> {
2134			use codec::Encode;
2135
2136			Historical::prove((PARACHAIN_KEY_TYPE_ID, validator_id))
2137				.map(|p| p.encode())
2138				.map(slashing::OpaqueKeyOwnershipProof::new)
2139		}
2140
2141		fn submit_report_dispute_lost(
2142			dispute_proof: slashing::DisputeProof,
2143			key_ownership_proof: slashing::OpaqueKeyOwnershipProof,
2144		) -> Option<()> {
2145			parachains_runtime_api_impl::submit_unsigned_slashing_report::<Runtime>(
2146				dispute_proof,
2147				key_ownership_proof,
2148			)
2149		}
2150
2151		fn minimum_backing_votes() -> u32 {
2152			parachains_runtime_api_impl::minimum_backing_votes::<Runtime>()
2153		}
2154
2155		fn para_backing_state(para_id: ParaId) -> Option<polkadot_primitives::async_backing::BackingState> {
2156			#[allow(deprecated)]
2157			parachains_runtime_api_impl::backing_state::<Runtime>(para_id)
2158		}
2159
2160		fn async_backing_params() -> polkadot_primitives::AsyncBackingParams {
2161			#[allow(deprecated)]
2162			parachains_runtime_api_impl::async_backing_params::<Runtime>()
2163		}
2164
2165		fn approval_voting_params() -> ApprovalVotingParams {
2166			parachains_runtime_api_impl::approval_voting_params::<Runtime>()
2167		}
2168
2169		fn disabled_validators() -> Vec<ValidatorIndex> {
2170			parachains_runtime_api_impl::disabled_validators::<Runtime>()
2171		}
2172
2173		fn node_features() -> NodeFeatures {
2174			parachains_runtime_api_impl::node_features::<Runtime>()
2175		}
2176
2177		fn claim_queue() -> BTreeMap<CoreIndex, VecDeque<ParaId>> {
2178			parachains_runtime_api_impl::claim_queue::<Runtime>()
2179		}
2180
2181		fn candidates_pending_availability(para_id: ParaId) -> Vec<CommittedCandidateReceipt<Hash>> {
2182			parachains_runtime_api_impl::candidates_pending_availability::<Runtime>(para_id)
2183		}
2184
2185		fn backing_constraints(para_id: ParaId) -> Option<Constraints> {
2186			parachains_runtime_api_impl::backing_constraints::<Runtime>(para_id)
2187		}
2188
2189		fn scheduling_lookahead() -> u32 {
2190			parachains_runtime_api_impl::scheduling_lookahead::<Runtime>()
2191		}
2192
2193		fn validation_code_bomb_limit() -> u32 {
2194			parachains_runtime_api_impl::validation_code_bomb_limit::<Runtime>()
2195		}
2196
2197		fn para_ids() -> Vec<ParaId> {
2198			parachains_staging_runtime_api_impl::para_ids::<Runtime>()
2199		}
2200	}
2201
2202	#[api_version(6)]
2203	impl sp_consensus_beefy::BeefyApi<Block, BeefyId> for Runtime {
2204		fn beefy_genesis() -> Option<BlockNumber> {
2205			pallet_beefy::GenesisBlock::<Runtime>::get()
2206		}
2207
2208		fn validator_set() -> Option<sp_consensus_beefy::ValidatorSet<BeefyId>> {
2209			Beefy::validator_set()
2210		}
2211
2212		fn submit_report_double_voting_unsigned_extrinsic(
2213			equivocation_proof: sp_consensus_beefy::DoubleVotingProof<
2214				BlockNumber,
2215				BeefyId,
2216				BeefySignature,
2217			>,
2218			key_owner_proof: sp_consensus_beefy::OpaqueKeyOwnershipProof,
2219		) -> Option<()> {
2220			let key_owner_proof = key_owner_proof.decode()?;
2221
2222			Beefy::submit_unsigned_double_voting_report(
2223				equivocation_proof,
2224				key_owner_proof,
2225			)
2226		}
2227
2228		fn submit_report_fork_voting_unsigned_extrinsic(
2229			equivocation_proof:
2230				sp_consensus_beefy::ForkVotingProof<
2231					<Block as BlockT>::Header,
2232					BeefyId,
2233					sp_runtime::OpaqueValue
2234				>,
2235			key_owner_proof: sp_consensus_beefy::OpaqueKeyOwnershipProof,
2236		) -> Option<()> {
2237			Beefy::submit_unsigned_fork_voting_report(
2238				equivocation_proof.try_into()?,
2239				key_owner_proof.decode()?,
2240			)
2241		}
2242
2243		fn submit_report_future_block_voting_unsigned_extrinsic(
2244			equivocation_proof: sp_consensus_beefy::FutureBlockVotingProof<BlockNumber, BeefyId>,
2245			key_owner_proof: sp_consensus_beefy::OpaqueKeyOwnershipProof,
2246		) -> Option<()> {
2247			Beefy::submit_unsigned_future_block_voting_report(
2248				equivocation_proof,
2249				key_owner_proof.decode()?,
2250			)
2251		}
2252
2253		fn generate_key_ownership_proof(
2254			_set_id: sp_consensus_beefy::ValidatorSetId,
2255			authority_id: BeefyId,
2256		) -> Option<sp_consensus_beefy::OpaqueKeyOwnershipProof> {
2257			use codec::Encode;
2258
2259			Historical::prove((sp_consensus_beefy::KEY_TYPE, authority_id))
2260				.map(|p| p.encode())
2261				.map(sp_consensus_beefy::OpaqueKeyOwnershipProof::new)
2262		}
2263	}
2264
2265	#[api_version(3)]
2266	impl mmr::MmrApi<Block, mmr::Hash, BlockNumber> for Runtime {
2267		fn mmr_root() -> Result<mmr::Hash, mmr::Error> {
2268			Ok(pallet_mmr::RootHash::<Runtime>::get())
2269		}
2270
2271		fn mmr_leaf_count() -> Result<mmr::LeafIndex, mmr::Error> {
2272			Ok(pallet_mmr::NumberOfLeaves::<Runtime>::get())
2273		}
2274
2275		fn generate_proof(
2276			block_numbers: Vec<BlockNumber>,
2277			best_known_block_number: Option<BlockNumber>,
2278		) -> Result<(Vec<mmr::EncodableOpaqueLeaf>, mmr::LeafProof<mmr::Hash>), mmr::Error> {
2279			Mmr::generate_proof(block_numbers, best_known_block_number).map(
2280				|(leaves, proof)| {
2281					(
2282						leaves
2283							.into_iter()
2284							.map(|leaf| mmr::EncodableOpaqueLeaf::from_leaf(&leaf))
2285							.collect(),
2286						proof,
2287					)
2288				},
2289			)
2290		}
2291
2292		fn generate_ancestry_proof(
2293			prev_block_number: BlockNumber,
2294			best_known_block_number: Option<BlockNumber>,
2295		) -> Result<mmr::AncestryProof<mmr::Hash>, mmr::Error> {
2296			Mmr::generate_ancestry_proof(prev_block_number, best_known_block_number)
2297		}
2298
2299		fn verify_proof(leaves: Vec<mmr::EncodableOpaqueLeaf>, proof: mmr::LeafProof<mmr::Hash>)
2300			-> Result<(), mmr::Error>
2301		{
2302			let leaves = leaves.into_iter().map(|leaf|
2303				leaf.into_opaque_leaf()
2304				.try_decode()
2305				.ok_or(mmr::Error::Verify)).collect::<Result<Vec<mmr::Leaf>, mmr::Error>>()?;
2306			Mmr::verify_leaves(leaves, proof)
2307		}
2308
2309		fn verify_proof_stateless(
2310			root: mmr::Hash,
2311			leaves: Vec<mmr::EncodableOpaqueLeaf>,
2312			proof: mmr::LeafProof<mmr::Hash>
2313		) -> Result<(), mmr::Error> {
2314			let nodes = leaves.into_iter().map(|leaf|mmr::DataOrHash::Data(leaf.into_opaque_leaf())).collect();
2315			pallet_mmr::verify_leaves_proof::<mmr::Hashing, _>(root, nodes, proof)
2316		}
2317	}
2318
2319	impl fg_primitives::GrandpaApi<Block> for Runtime {
2320		fn grandpa_authorities() -> Vec<(GrandpaId, u64)> {
2321			Grandpa::grandpa_authorities()
2322		}
2323
2324		fn current_set_id() -> fg_primitives::SetId {
2325			pallet_grandpa::CurrentSetId::<Runtime>::get()
2326		}
2327
2328		fn submit_report_equivocation_unsigned_extrinsic(
2329			equivocation_proof: fg_primitives::EquivocationProof<
2330				<Block as BlockT>::Hash,
2331				sp_runtime::traits::NumberFor<Block>,
2332			>,
2333			key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof,
2334		) -> Option<()> {
2335			let key_owner_proof = key_owner_proof.decode()?;
2336
2337			Grandpa::submit_unsigned_equivocation_report(
2338				equivocation_proof,
2339				key_owner_proof,
2340			)
2341		}
2342
2343		fn generate_key_ownership_proof(
2344			_set_id: fg_primitives::SetId,
2345			authority_id: fg_primitives::AuthorityId,
2346		) -> Option<fg_primitives::OpaqueKeyOwnershipProof> {
2347			use codec::Encode;
2348
2349			Historical::prove((fg_primitives::KEY_TYPE, authority_id))
2350				.map(|p| p.encode())
2351				.map(fg_primitives::OpaqueKeyOwnershipProof::new)
2352		}
2353	}
2354
2355	impl sp_consensus_babe::BabeApi<Block> for Runtime {
2356		fn configuration() -> sp_consensus_babe::BabeConfiguration {
2357			let epoch_config = Babe::epoch_config().unwrap_or(BABE_GENESIS_EPOCH_CONFIG);
2358			sp_consensus_babe::BabeConfiguration {
2359				slot_duration: Babe::slot_duration(),
2360				epoch_length: EpochDurationInBlocks::get().into(),
2361				c: epoch_config.c,
2362				authorities: Babe::authorities().to_vec(),
2363				randomness: Babe::randomness(),
2364				allowed_slots: epoch_config.allowed_slots,
2365			}
2366		}
2367
2368		fn current_epoch_start() -> sp_consensus_babe::Slot {
2369			Babe::current_epoch_start()
2370		}
2371
2372		fn current_epoch() -> sp_consensus_babe::Epoch {
2373			Babe::current_epoch()
2374		}
2375
2376		fn next_epoch() -> sp_consensus_babe::Epoch {
2377			Babe::next_epoch()
2378		}
2379
2380		fn generate_key_ownership_proof(
2381			_slot: sp_consensus_babe::Slot,
2382			authority_id: sp_consensus_babe::AuthorityId,
2383		) -> Option<sp_consensus_babe::OpaqueKeyOwnershipProof> {
2384			use codec::Encode;
2385
2386			Historical::prove((sp_consensus_babe::KEY_TYPE, authority_id))
2387				.map(|p| p.encode())
2388				.map(sp_consensus_babe::OpaqueKeyOwnershipProof::new)
2389		}
2390
2391		fn submit_report_equivocation_unsigned_extrinsic(
2392			equivocation_proof: sp_consensus_babe::EquivocationProof<<Block as BlockT>::Header>,
2393			key_owner_proof: sp_consensus_babe::OpaqueKeyOwnershipProof,
2394		) -> Option<()> {
2395			let key_owner_proof = key_owner_proof.decode()?;
2396
2397			Babe::submit_unsigned_equivocation_report(
2398				equivocation_proof,
2399				key_owner_proof,
2400			)
2401		}
2402	}
2403
2404	impl sp_authority_discovery::AuthorityDiscoveryApi<Block> for Runtime {
2405		fn authorities() -> Vec<AuthorityDiscoveryId> {
2406			parachains_runtime_api_impl::relevant_authority_ids::<Runtime>()
2407		}
2408	}
2409
2410	impl sp_session::SessionKeys<Block> for Runtime {
2411		fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
2412			SessionKeys::generate(seed)
2413		}
2414
2415		fn decode_session_keys(
2416			encoded: Vec<u8>,
2417		) -> Option<Vec<(Vec<u8>, sp_core::crypto::KeyTypeId)>> {
2418			SessionKeys::decode_into_raw_public_keys(&encoded)
2419		}
2420	}
2421
2422	impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
2423		fn account_nonce(account: AccountId) -> Nonce {
2424			System::account_nonce(account)
2425		}
2426	}
2427
2428	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<
2429		Block,
2430		Balance,
2431	> for Runtime {
2432		fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {
2433			TransactionPayment::query_info(uxt, len)
2434		}
2435		fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {
2436			TransactionPayment::query_fee_details(uxt, len)
2437		}
2438		fn query_weight_to_fee(weight: Weight) -> Balance {
2439			TransactionPayment::weight_to_fee(weight)
2440		}
2441		fn query_length_to_fee(length: u32) -> Balance {
2442			TransactionPayment::length_to_fee(length)
2443		}
2444	}
2445
2446	impl pallet_beefy_mmr::BeefyMmrApi<Block, Hash> for RuntimeApi {
2447		fn authority_set_proof() -> sp_consensus_beefy::mmr::BeefyAuthoritySet<Hash> {
2448			MmrLeaf::authority_set_proof()
2449		}
2450
2451		fn next_authority_set_proof() -> sp_consensus_beefy::mmr::BeefyNextAuthoritySet<Hash> {
2452			MmrLeaf::next_authority_set_proof()
2453		}
2454	}
2455
2456	#[cfg(feature = "try-runtime")]
2457	impl frame_try_runtime::TryRuntime<Block> for Runtime {
2458		fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) {
2459			log::info!("try-runtime::on_runtime_upgrade rococo.");
2460			let weight = Executive::try_runtime_upgrade(checks).unwrap();
2461			(weight, BlockWeights::get().max_block)
2462		}
2463
2464		fn execute_block(
2465			block: <Block as BlockT>::LazyBlock,
2466			state_root_check: bool,
2467			signature_check: bool,
2468			select: frame_try_runtime::TryStateSelect,
2469		) -> Weight {
2470			// NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to
2471			// have a backtrace here.
2472			Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap()
2473		}
2474	}
2475
2476	#[cfg(feature = "runtime-benchmarks")]
2477	impl frame_benchmarking::Benchmark<Block> for Runtime {
2478		fn benchmark_metadata(extra: bool) -> (
2479			Vec<frame_benchmarking::BenchmarkList>,
2480			Vec<frame_support::traits::StorageInfo>,
2481		) {
2482			use frame_benchmarking::BenchmarkList;
2483			use frame_support::traits::StorageInfoTrait;
2484
2485			use frame_system_benchmarking::Pallet as SystemBench;
2486			use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
2487			use frame_benchmarking::baseline::Pallet as Baseline;
2488
2489			use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
2490
2491			let mut list = Vec::<BenchmarkList>::new();
2492			list_benchmarks!(list, extra);
2493
2494			let storage_info = AllPalletsWithSystem::storage_info();
2495			return (list, storage_info)
2496		}
2497
2498		#[allow(non_local_definitions)]
2499		fn dispatch_benchmark(
2500			config: frame_benchmarking::BenchmarkConfig,
2501		) -> Result<
2502			Vec<frame_benchmarking::BenchmarkBatch>,
2503			alloc::string::String,
2504		> {
2505			use frame_support::traits::WhitelistedStorageKeys;
2506			use frame_benchmarking::{BenchmarkBatch, BenchmarkError};
2507			use frame_system_benchmarking::Pallet as SystemBench;
2508			use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
2509			use frame_benchmarking::baseline::Pallet as Baseline;
2510			use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
2511			use sp_storage::TrackedStorageKey;
2512			use xcm::latest::prelude::*;
2513			use xcm_config::{
2514				AssetHub, LocalCheckAccount, LocationConverter, TokenLocation, XcmConfig,
2515			};
2516
2517			parameter_types! {
2518				pub ExistentialDepositAsset: Option<Asset> = Some((
2519					TokenLocation::get(),
2520					ExistentialDeposit::get()
2521				).into());
2522				pub AssetHubParaId: ParaId = rococo_runtime_constants::system_parachain::ASSET_HUB_ID.into();
2523				pub const RandomParaId: ParaId = ParaId::new(43211234);
2524			}
2525
2526			impl frame_system_benchmarking::Config for Runtime {}
2527			impl frame_benchmarking::baseline::Config for Runtime {}
2528			impl pallet_xcm::benchmarking::Config for Runtime {
2529				type DeliveryHelper = (
2530					polkadot_runtime_common::xcm_sender::ToParachainDeliveryHelper<
2531						XcmConfig,
2532						ExistentialDepositAsset,
2533						xcm_config::PriceForChildParachainDelivery,
2534						AssetHubParaId,
2535						Dmp,
2536					>,
2537					polkadot_runtime_common::xcm_sender::ToParachainDeliveryHelper<
2538						XcmConfig,
2539						ExistentialDepositAsset,
2540						xcm_config::PriceForChildParachainDelivery,
2541						RandomParaId,
2542						Dmp,
2543					>
2544				);
2545
2546				fn reachable_dest() -> Option<Location> {
2547					Some(crate::xcm_config::AssetHub::get())
2548				}
2549
2550				fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
2551					// Relay/native token can be teleported to/from AH.
2552					Some((
2553						Asset {
2554							fun: Fungible(ExistentialDeposit::get()),
2555							id: AssetId(Here.into())
2556						},
2557						crate::xcm_config::AssetHub::get(),
2558					))
2559				}
2560
2561				fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
2562					None
2563				}
2564
2565				fn set_up_complex_asset_transfer(
2566				) -> Option<(Assets, u32, Location, alloc::boxed::Box<dyn FnOnce()>)> {
2567					// Relay supports only native token, either reserve transfer it to non-system parachains,
2568					// or teleport it to system parachain. Use the teleport case for benchmarking as it's
2569					// slightly heavier.
2570					// Relay/native token can be teleported to/from AH.
2571					let native_location = Here.into();
2572					let dest = crate::xcm_config::AssetHub::get();
2573					pallet_xcm::benchmarking::helpers::native_teleport_as_asset_transfer::<Runtime>(
2574						native_location,
2575						dest
2576					)
2577				}
2578
2579				fn get_asset() -> Asset {
2580					Asset {
2581						id: AssetId(Location::here()),
2582						fun: Fungible(ExistentialDeposit::get()),
2583					}
2584				}
2585			}
2586			impl pallet_xcm_benchmarks::Config for Runtime {
2587				type XcmConfig = XcmConfig;
2588				type AccountIdConverter = LocationConverter;
2589				type DeliveryHelper = polkadot_runtime_common::xcm_sender::ToParachainDeliveryHelper<
2590					XcmConfig,
2591					ExistentialDepositAsset,
2592					xcm_config::PriceForChildParachainDelivery,
2593					AssetHubParaId,
2594					Dmp,
2595				>;
2596				fn valid_destination() -> Result<Location, BenchmarkError> {
2597					Ok(AssetHub::get())
2598				}
2599				fn worst_case_holding(_depositable_count: u32) -> Assets {
2600					// Rococo only knows about ROC
2601					vec![Asset{
2602						id: AssetId(TokenLocation::get()),
2603						fun: Fungible(1_000_000 * UNITS),
2604					}].into()
2605				}
2606			}
2607
2608			parameter_types! {
2609				pub TrustedTeleporter: Option<(Location, Asset)> = Some((
2610					AssetHub::get(),
2611					Asset { fun: Fungible(1 * UNITS), id: AssetId(TokenLocation::get()) },
2612				));
2613				pub TrustedReserve: Option<(Location, Asset)> = None;
2614			}
2615
2616			impl pallet_xcm_benchmarks::fungible::Config for Runtime {
2617				type TransactAsset = Balances;
2618
2619				type CheckedAccount = LocalCheckAccount;
2620				type TrustedTeleporter = TrustedTeleporter;
2621				type TrustedReserve = TrustedReserve;
2622
2623				fn get_asset() -> Asset {
2624					Asset {
2625						id: AssetId(TokenLocation::get()),
2626						fun: Fungible(1 * UNITS),
2627					}
2628				}
2629			}
2630
2631			impl pallet_xcm_benchmarks::generic::Config for Runtime {
2632				type TransactAsset = Balances;
2633				type RuntimeCall = RuntimeCall;
2634
2635				fn worst_case_response() -> (u64, Response) {
2636					(0u64, Response::Version(Default::default()))
2637				}
2638
2639				fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> {
2640					// Rococo doesn't support asset exchanges
2641					Err(BenchmarkError::Skip)
2642				}
2643
2644				fn universal_alias() -> Result<(Location, Junction), BenchmarkError> {
2645					// The XCM executor of Rococo doesn't have a configured `UniversalAliases`
2646					Err(BenchmarkError::Skip)
2647				}
2648
2649				fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> {
2650					Ok((AssetHub::get(), frame_system::Call::remark_with_event { remark: vec![] }.into()))
2651				}
2652
2653				fn subscribe_origin() -> Result<Location, BenchmarkError> {
2654					Ok(AssetHub::get())
2655				}
2656
2657				fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> {
2658					let origin = AssetHub::get();
2659					let assets: Assets = (AssetId(TokenLocation::get()), 1_000 * UNITS).into();
2660					let ticket = Location { parents: 0, interior: Here };
2661					Ok((origin, ticket, assets))
2662				}
2663
2664				fn worst_case_for_trader() -> Result<(Asset, WeightLimit), BenchmarkError> {
2665					Ok((Asset {
2666						id: AssetId(TokenLocation::get()),
2667						fun: Fungible(1_000_000 * UNITS),
2668					}, WeightLimit::Limited(Weight::from_parts(5000, 5000))))
2669				}
2670
2671				fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> {
2672					// Rococo doesn't support asset locking
2673					Err(BenchmarkError::Skip)
2674				}
2675
2676				fn export_message_origin_and_destination(
2677				) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> {
2678					// Rococo doesn't support exporting messages
2679					Err(BenchmarkError::Skip)
2680				}
2681
2682				fn alias_origin() -> Result<(Location, Location), BenchmarkError> {
2683					// The XCM executor of Rococo doesn't have a configured `Aliasers`
2684					Err(BenchmarkError::Skip)
2685				}
2686			}
2687
2688			let mut whitelist: Vec<TrackedStorageKey> = AllPalletsWithSystem::whitelisted_storage_keys();
2689			let treasury_key = frame_system::Account::<Runtime>::hashed_key_for(Treasury::account_id());
2690			whitelist.push(treasury_key.to_vec().into());
2691
2692			let mut batches = Vec::<BenchmarkBatch>::new();
2693			let params = (&config, &whitelist);
2694
2695			add_benchmarks!(params, batches);
2696
2697			Ok(batches)
2698		}
2699	}
2700
2701	impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
2702		fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
2703			build_state::<RuntimeGenesisConfig>(config)
2704		}
2705
2706		fn get_preset(id: &Option<PresetId>) -> Option<Vec<u8>> {
2707			get_preset::<RuntimeGenesisConfig>(id, &genesis_config_presets::get_preset)
2708		}
2709
2710		fn preset_names() -> Vec<PresetId> {
2711			genesis_config_presets::preset_names()
2712		}
2713	}
2714
2715	impl xcm_runtime_apis::trusted_query::TrustedQueryApi<Block> for Runtime {
2716		fn is_trusted_reserve(asset: VersionedAsset, location: VersionedLocation) -> Result<bool, xcm_runtime_apis::trusted_query::Error> {
2717			XcmPallet::is_trusted_reserve(asset, location)
2718		}
2719		fn is_trusted_teleporter(asset: VersionedAsset, location: VersionedLocation) -> Result<bool, xcm_runtime_apis::trusted_query::Error> {
2720			XcmPallet::is_trusted_teleporter(asset, location)
2721		}
2722	}
2723}
2724
2725#[cfg(all(test, feature = "try-runtime"))]
2726mod remote_tests {
2727	use super::*;
2728	use frame_try_runtime::{runtime_decl_for_try_runtime::TryRuntime, UpgradeCheckSelect};
2729	use remote_externalities::{
2730		Builder, Mode, OfflineConfig, OnlineConfig, SnapshotConfig, Transport,
2731	};
2732	use std::env::var;
2733
2734	#[tokio::test]
2735	async fn run_migrations() {
2736		if var("RUN_MIGRATION_TESTS").is_err() {
2737			return;
2738		}
2739
2740		sp_tracing::try_init_simple();
2741		let transport: Transport =
2742			var("WS").unwrap_or("wss://rococo-rpc.polkadot.io:443".to_string()).into();
2743		let maybe_state_snapshot: Option<SnapshotConfig> = var("SNAP").map(|s| s.into()).ok();
2744		let mut ext = Builder::<Block>::default()
2745			.mode(if let Some(state_snapshot) = maybe_state_snapshot {
2746				Mode::OfflineOrElseOnline(
2747					OfflineConfig { state_snapshot: state_snapshot.clone() },
2748					OnlineConfig {
2749						transport,
2750						state_snapshot: Some(state_snapshot),
2751						..Default::default()
2752					},
2753				)
2754			} else {
2755				Mode::Online(OnlineConfig { transport, ..Default::default() })
2756			})
2757			.build()
2758			.await
2759			.unwrap();
2760		ext.execute_with(|| Runtime::on_runtime_upgrade(UpgradeCheckSelect::PreAndPost));
2761	}
2762}