penpal_runtime/
lib.rs

1// Copyright (C) Parity Technologies (UK) Ltd.
2// This file is part of Cumulus.
3
4// Cumulus 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// Cumulus 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 Cumulus.  If not, see <http://www.gnu.org/licenses/>.
16
17//! The PenPal runtime is designed as a test runtime that can be created with an arbitrary `ParaId`,
18//! such that multiple instances of the parachain can be on the same parent relay. Ensure that you
19//! have enough nodes running to support this or you will get scheduling errors.
20//!
21//! The PenPal runtime's primary use is for testing interactions between System parachains and
22//! other chains that are not trusted teleporters.
23
24#![cfg_attr(not(feature = "std"), no_std)]
25// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.
26#![recursion_limit = "256"]
27
28// Make the WASM binary available.
29#[cfg(feature = "std")]
30include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
31
32mod weights;
33pub mod xcm_config;
34
35extern crate alloc;
36
37use alloc::{vec, vec::Vec};
38use assets_common::{
39	foreign_creators::ForeignCreators,
40	local_and_foreign_assets::{LocalFromLeft, TargetFromLeft},
41	AssetIdForTrustBackedAssetsConvert,
42};
43use codec::Encode;
44use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases;
45use cumulus_primitives_core::{AggregateMessageOrigin, ClaimQueueOffset, CoreSelector, ParaId};
46use frame_support::{
47	construct_runtime, derive_impl,
48	dispatch::DispatchClass,
49	genesis_builder_helper::{build_state, get_preset},
50	ord_parameter_types,
51	pallet_prelude::Weight,
52	parameter_types,
53	traits::{
54		tokens::{fungible, fungibles, imbalance::ResolveAssetTo},
55		AsEnsureOriginWithArg, ConstBool, ConstU128, ConstU32, ConstU64, ConstU8, Everything,
56		TransformOrigin,
57	},
58	weights::{
59		constants::WEIGHT_REF_TIME_PER_SECOND, ConstantMultiplier, FeePolynomial, WeightToFee as _,
60		WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial,
61	},
62	PalletId,
63};
64use frame_system::{
65	limits::{BlockLength, BlockWeights},
66	EnsureRoot, EnsureSigned, EnsureSignedBy,
67};
68use parachains_common::{
69	impls::{AssetsToBlockAuthor, NonZeroIssuance},
70	message_queue::{NarrowOriginToSibling, ParaIdToSibling},
71};
72use smallvec::smallvec;
73use sp_api::impl_runtime_apis;
74pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;
75use sp_core::{crypto::KeyTypeId, OpaqueMetadata};
76use sp_runtime::{
77	generic, impl_opaque_keys,
78	traits::{AccountIdConversion, AccountIdLookup, BlakeTwo256, Block as BlockT, Dispatchable},
79	transaction_validity::{TransactionSource, TransactionValidity},
80	ApplyExtrinsicResult,
81};
82pub use sp_runtime::{traits::ConvertInto, MultiAddress, Perbill, Permill};
83#[cfg(feature = "std")]
84use sp_version::NativeVersion;
85use sp_version::RuntimeVersion;
86use xcm_config::{ForeignAssetsAssetId, LocationToAccountId, XcmOriginToTransactDispatchOrigin};
87
88#[cfg(any(feature = "std", test))]
89pub use sp_runtime::BuildStorage;
90
91use parachains_common::{AccountId, Signature};
92use polkadot_runtime_common::{BlockHashCount, SlowAdjustingFeeUpdate};
93use weights::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight};
94use xcm::{
95	latest::prelude::{AssetId as AssetLocationId, BodyId},
96	VersionedAsset, VersionedAssetId, VersionedAssets, VersionedLocation, VersionedXcm,
97};
98use xcm_runtime_apis::{
99	dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects},
100	fees::Error as XcmPaymentApiError,
101};
102
103/// Balance of an account.
104pub type Balance = u128;
105
106/// Index of a transaction in the chain.
107pub type Nonce = u32;
108
109/// A hash of some data used by the chain.
110pub type Hash = sp_core::H256;
111
112/// An index to a block.
113pub type BlockNumber = u32;
114
115/// The address format for describing accounts.
116pub type Address = MultiAddress<AccountId, ()>;
117
118/// Block header type as expected by this runtime.
119pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
120
121/// Block type as expected by this runtime.
122pub type Block = generic::Block<Header, UncheckedExtrinsic>;
123
124/// A Block signed with a Justification
125pub type SignedBlock = generic::SignedBlock<Block>;
126
127/// BlockId type as expected by this runtime.
128pub type BlockId = generic::BlockId<Block>;
129
130// Id used for identifying assets.
131pub type AssetId = u32;
132
133/// The extension to the basic transaction logic.
134pub type TxExtension = (
135	frame_system::CheckNonZeroSender<Runtime>,
136	frame_system::CheckSpecVersion<Runtime>,
137	frame_system::CheckTxVersion<Runtime>,
138	frame_system::CheckGenesis<Runtime>,
139	frame_system::CheckEra<Runtime>,
140	frame_system::CheckNonce<Runtime>,
141	frame_system::CheckWeight<Runtime>,
142	pallet_asset_tx_payment::ChargeAssetTxPayment<Runtime>,
143);
144
145/// Unchecked extrinsic type as expected by this runtime.
146pub type UncheckedExtrinsic =
147	generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, TxExtension>;
148
149pub type Migrations = (
150	pallet_balances::migration::MigrateToTrackInactive<Runtime, xcm_config::CheckingAccount>,
151	pallet_collator_selection::migration::v1::MigrateToV1<Runtime>,
152);
153
154/// Executive: handles dispatch to the various modules.
155pub type Executive = frame_executive::Executive<
156	Runtime,
157	Block,
158	frame_system::ChainContext<Runtime>,
159	Runtime,
160	AllPalletsWithSystem,
161	Migrations,
162>;
163
164/// Handles converting a weight scalar to a fee value, based on the scale and granularity of the
165/// node's balance type.
166///
167/// This should typically create a mapping between the following ranges:
168///   - `[0, MAXIMUM_BLOCK_WEIGHT]`
169///   - `[Balance::min, Balance::max]`
170///
171/// Yet, it can be used for any other sort of change to weight-fee. Some examples being:
172///   - Setting it to `0` will essentially disable the weight fee.
173///   - Setting it to `1` will cause the literal `#[weight = x]` values to be charged.
174pub struct WeightToFee;
175impl frame_support::weights::WeightToFee for WeightToFee {
176	type Balance = Balance;
177
178	fn weight_to_fee(weight: &Weight) -> Self::Balance {
179		let time_poly: FeePolynomial<Balance> = RefTimeToFee::polynomial().into();
180		let proof_poly: FeePolynomial<Balance> = ProofSizeToFee::polynomial().into();
181
182		// Take the maximum instead of the sum to charge by the more scarce resource.
183		time_poly.eval(weight.ref_time()).max(proof_poly.eval(weight.proof_size()))
184	}
185}
186
187/// Maps the reference time component of `Weight` to a fee.
188pub struct RefTimeToFee;
189impl WeightToFeePolynomial for RefTimeToFee {
190	type Balance = Balance;
191	fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {
192		let p = MILLIUNIT / 10;
193		let q = 100 * Balance::from(ExtrinsicBaseWeight::get().ref_time());
194
195		smallvec![WeightToFeeCoefficient {
196			degree: 1,
197			negative: false,
198			coeff_frac: Perbill::from_rational(p % q, q),
199			coeff_integer: p / q,
200		}]
201	}
202}
203
204/// Maps the proof size component of `Weight` to a fee.
205pub struct ProofSizeToFee;
206impl WeightToFeePolynomial for ProofSizeToFee {
207	type Balance = Balance;
208	fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {
209		// Map 10kb proof to 1 CENT.
210		let p = MILLIUNIT / 10;
211		let q = 10_000;
212
213		smallvec![WeightToFeeCoefficient {
214			degree: 1,
215			negative: false,
216			coeff_frac: Perbill::from_rational(p % q, q),
217			coeff_integer: p / q,
218		}]
219	}
220}
221/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know
222/// the specifics of the runtime. They can then be made to be agnostic over specific formats
223/// of data like extrinsics, allowing for them to continue syncing the network through upgrades
224/// to even the core data structures.
225pub mod opaque {
226	use super::*;
227	use sp_runtime::{generic, traits::BlakeTwo256};
228
229	pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;
230	/// Opaque block header type.
231	pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
232	/// Opaque block type.
233	pub type Block = generic::Block<Header, UncheckedExtrinsic>;
234	/// Opaque block identifier type.
235	pub type BlockId = generic::BlockId<Block>;
236}
237
238impl_opaque_keys! {
239	pub struct SessionKeys {
240		pub aura: Aura,
241	}
242}
243
244#[sp_version::runtime_version]
245pub const VERSION: RuntimeVersion = RuntimeVersion {
246	spec_name: alloc::borrow::Cow::Borrowed("penpal-parachain"),
247	impl_name: alloc::borrow::Cow::Borrowed("penpal-parachain"),
248	authoring_version: 1,
249	spec_version: 1,
250	impl_version: 0,
251	apis: RUNTIME_API_VERSIONS,
252	transaction_version: 1,
253	system_version: 1,
254};
255
256/// This determines the average expected block time that we are targeting.
257/// Blocks will be produced at a minimum duration defined by `SLOT_DURATION`.
258/// `SLOT_DURATION` is picked up by `pallet_timestamp` which is in turn picked
259/// up by `pallet_aura` to implement `fn slot_duration()`.
260///
261/// Change this to adjust the block time.
262pub const MILLISECS_PER_BLOCK: u64 = 12000;
263
264// NOTE: Currently it is not possible to change the slot duration after the chain has started.
265//       Attempting to do so will brick block production.
266pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;
267
268// Time is measured by number of blocks.
269pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);
270pub const HOURS: BlockNumber = MINUTES * 60;
271pub const DAYS: BlockNumber = HOURS * 24;
272
273// Unit = the base number of indivisible units for balances
274pub const UNIT: Balance = 1_000_000_000_000;
275pub const MILLIUNIT: Balance = 1_000_000_000;
276pub const MICROUNIT: Balance = 1_000_000;
277
278/// The existential deposit. Set to 1/10 of the Connected Relay Chain.
279pub const EXISTENTIAL_DEPOSIT: Balance = MILLIUNIT;
280
281/// We assume that ~5% of the block weight is consumed by `on_initialize` handlers. This is
282/// used to limit the maximal weight of a single extrinsic.
283const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(5);
284
285/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used by
286/// `Operational` extrinsics.
287const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
288
289/// We allow for 0.5 of a second of compute with a 12 second average block time.
290const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(
291	WEIGHT_REF_TIME_PER_SECOND.saturating_div(2),
292	cumulus_primitives_core::relay_chain::MAX_POV_SIZE as u64,
293);
294
295/// Maximum number of blocks simultaneously accepted by the Runtime, not yet included
296/// into the relay chain.
297const UNINCLUDED_SEGMENT_CAPACITY: u32 = 1;
298/// How many parachain blocks are processed by the relay chain per parent. Limits the
299/// number of blocks authored per slot.
300const BLOCK_PROCESSING_VELOCITY: u32 = 1;
301/// Relay chain slot duration, in milliseconds.
302const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6000;
303
304/// The version information used to identify this runtime when compiled natively.
305#[cfg(feature = "std")]
306pub fn native_version() -> NativeVersion {
307	NativeVersion { runtime_version: VERSION, can_author_with: Default::default() }
308}
309
310parameter_types! {
311	pub const Version: RuntimeVersion = VERSION;
312
313	// This part is copied from Substrate's `bin/node/runtime/src/lib.rs`.
314	//  The `RuntimeBlockLength` and `RuntimeBlockWeights` exist here because the
315	// `DeletionWeightLimit` and `DeletionQueueDepth` depend on those to parameterize
316	// the lazy contract deletion.
317	pub RuntimeBlockLength: BlockLength =
318		BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
319	pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()
320		.base_block(BlockExecutionWeight::get())
321		.for_class(DispatchClass::all(), |weights| {
322			weights.base_extrinsic = ExtrinsicBaseWeight::get();
323		})
324		.for_class(DispatchClass::Normal, |weights| {
325			weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
326		})
327		.for_class(DispatchClass::Operational, |weights| {
328			weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
329			// Operational transactions have some extra reserved space, so that they
330			// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.
331			weights.reserved = Some(
332				MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT
333			);
334		})
335		.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
336		.build_or_panic();
337	pub const SS58Prefix: u16 = 42;
338}
339
340// Configure FRAME pallets to include in runtime.
341
342#[derive_impl(frame_system::config_preludes::TestDefaultConfig)]
343impl frame_system::Config for Runtime {
344	/// The identifier used to distinguish between accounts.
345	type AccountId = AccountId;
346	/// The aggregated dispatch type that is available for extrinsics.
347	type RuntimeCall = RuntimeCall;
348	/// The lookup mechanism to get account ID from whatever is passed in dispatchers.
349	type Lookup = AccountIdLookup<AccountId, ()>;
350	/// The index type for storing how many extrinsics an account has signed.
351	type Nonce = Nonce;
352	/// The type for hashing blocks and tries.
353	type Hash = Hash;
354	/// The hashing algorithm used.
355	type Hashing = BlakeTwo256;
356	/// The block type.
357	type Block = Block;
358	/// The ubiquitous event type.
359	type RuntimeEvent = RuntimeEvent;
360	/// The ubiquitous origin type.
361	type RuntimeOrigin = RuntimeOrigin;
362	/// Maximum number of block number to block hash mappings to keep (oldest pruned first).
363	type BlockHashCount = BlockHashCount;
364	/// Runtime version.
365	type Version = Version;
366	/// Converts a module to an index of this module in the runtime.
367	type PalletInfo = PalletInfo;
368	/// The data to be stored in an account.
369	type AccountData = pallet_balances::AccountData<Balance>;
370	/// What to do if a new account is created.
371	type OnNewAccount = ();
372	/// What to do if an account is fully reaped from the system.
373	type OnKilledAccount = ();
374	/// The weight of database operations that the runtime can invoke.
375	type DbWeight = RocksDbWeight;
376	/// The basic call filter to use in dispatchable.
377	type BaseCallFilter = Everything;
378	/// Weight information for the extrinsics of this pallet.
379	type SystemWeightInfo = ();
380	/// Block & extrinsics weights: base values and limits.
381	type BlockWeights = RuntimeBlockWeights;
382	/// The maximum length of a block (in bytes).
383	type BlockLength = RuntimeBlockLength;
384	/// This is used as an identifier of the chain. 42 is the generic substrate prefix.
385	type SS58Prefix = SS58Prefix;
386	/// The action to take on a Runtime Upgrade
387	type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;
388	type MaxConsumers = frame_support::traits::ConstU32<16>;
389}
390
391impl pallet_timestamp::Config for Runtime {
392	/// A timestamp: milliseconds since the unix epoch.
393	type Moment = u64;
394	type OnTimestampSet = Aura;
395	type MinimumPeriod = ConstU64<{ SLOT_DURATION / 2 }>;
396	type WeightInfo = ();
397}
398
399impl pallet_authorship::Config for Runtime {
400	type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Aura>;
401	type EventHandler = (CollatorSelection,);
402}
403
404parameter_types! {
405	pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
406}
407
408impl pallet_balances::Config for Runtime {
409	type MaxLocks = ConstU32<50>;
410	/// The type for recording an account's balance.
411	type Balance = Balance;
412	/// The ubiquitous event type.
413	type RuntimeEvent = RuntimeEvent;
414	type DustRemoval = ();
415	type ExistentialDeposit = ExistentialDeposit;
416	type AccountStore = System;
417	type WeightInfo = pallet_balances::weights::SubstrateWeight<Runtime>;
418	type MaxReserves = ConstU32<50>;
419	type ReserveIdentifier = [u8; 8];
420	type RuntimeHoldReason = RuntimeHoldReason;
421	type RuntimeFreezeReason = RuntimeFreezeReason;
422	type FreezeIdentifier = ();
423	type MaxFreezes = ConstU32<0>;
424	type DoneSlashHandler = ();
425}
426
427parameter_types! {
428	/// Relay Chain `TransactionByteFee` / 10
429	pub const TransactionByteFee: Balance = 10 * MICROUNIT;
430}
431
432impl pallet_transaction_payment::Config for Runtime {
433	type RuntimeEvent = RuntimeEvent;
434	type OnChargeTransaction = pallet_transaction_payment::FungibleAdapter<Balances, ()>;
435	type WeightToFee = WeightToFee;
436	type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
437	type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
438	type OperationalFeeMultiplier = ConstU8<5>;
439	type WeightInfo = ();
440}
441
442parameter_types! {
443	pub const AssetDeposit: Balance = 0;
444	pub const AssetAccountDeposit: Balance = 0;
445	pub const ApprovalDeposit: Balance = 0;
446	pub const AssetsStringLimit: u32 = 50;
447	pub const MetadataDepositBase: Balance = 0;
448	pub const MetadataDepositPerByte: Balance = 0;
449}
450
451// /// We allow root and the Relay Chain council to execute privileged asset operations.
452// pub type AssetsForceOrigin =
453// 	EnsureOneOf<EnsureRoot<AccountId>, EnsureXcm<IsMajorityOfBody<KsmLocation, ExecutiveBody>>>;
454
455pub type TrustBackedAssetsInstance = pallet_assets::Instance1;
456
457impl pallet_assets::Config<TrustBackedAssetsInstance> for Runtime {
458	type RuntimeEvent = RuntimeEvent;
459	type Balance = Balance;
460	type AssetId = AssetId;
461	type AssetIdParameter = codec::Compact<AssetId>;
462	type Currency = Balances;
463	type CreateOrigin = AsEnsureOriginWithArg<EnsureSigned<AccountId>>;
464	type ForceOrigin = EnsureRoot<AccountId>;
465	type AssetDeposit = AssetDeposit;
466	type MetadataDepositBase = MetadataDepositBase;
467	type MetadataDepositPerByte = MetadataDepositPerByte;
468	type ApprovalDeposit = ApprovalDeposit;
469	type StringLimit = AssetsStringLimit;
470	type Freezer = ();
471	type Extra = ();
472	type WeightInfo = pallet_assets::weights::SubstrateWeight<Runtime>;
473	type CallbackHandle = ();
474	type AssetAccountDeposit = AssetAccountDeposit;
475	type RemoveItemsLimit = frame_support::traits::ConstU32<1000>;
476	#[cfg(feature = "runtime-benchmarks")]
477	type BenchmarkHelper = ();
478}
479
480parameter_types! {
481	// we just reuse the same deposits
482	pub const ForeignAssetsAssetDeposit: Balance = AssetDeposit::get();
483	pub const ForeignAssetsAssetAccountDeposit: Balance = AssetAccountDeposit::get();
484	pub const ForeignAssetsApprovalDeposit: Balance = ApprovalDeposit::get();
485	pub const ForeignAssetsAssetsStringLimit: u32 = AssetsStringLimit::get();
486	pub const ForeignAssetsMetadataDepositBase: Balance = MetadataDepositBase::get();
487	pub const ForeignAssetsMetadataDepositPerByte: Balance = MetadataDepositPerByte::get();
488}
489
490/// Another pallet assets instance to store foreign assets from bridgehub.
491pub type ForeignAssetsInstance = pallet_assets::Instance2;
492impl pallet_assets::Config<ForeignAssetsInstance> for Runtime {
493	type RuntimeEvent = RuntimeEvent;
494	type Balance = Balance;
495	type AssetId = ForeignAssetsAssetId;
496	type AssetIdParameter = ForeignAssetsAssetId;
497	type Currency = Balances;
498	// This is to allow any other remote location to create foreign assets. Used in tests, not
499	// recommended on real chains.
500	type CreateOrigin =
501		ForeignCreators<Everything, LocationToAccountId, AccountId, xcm::latest::Location>;
502	type ForceOrigin = EnsureRoot<AccountId>;
503	type AssetDeposit = ForeignAssetsAssetDeposit;
504	type MetadataDepositBase = ForeignAssetsMetadataDepositBase;
505	type MetadataDepositPerByte = ForeignAssetsMetadataDepositPerByte;
506	type ApprovalDeposit = ForeignAssetsApprovalDeposit;
507	type StringLimit = ForeignAssetsAssetsStringLimit;
508	type Freezer = ();
509	type Extra = ();
510	type WeightInfo = pallet_assets::weights::SubstrateWeight<Runtime>;
511	type CallbackHandle = ();
512	type AssetAccountDeposit = ForeignAssetsAssetAccountDeposit;
513	type RemoveItemsLimit = frame_support::traits::ConstU32<1000>;
514	#[cfg(feature = "runtime-benchmarks")]
515	type BenchmarkHelper = xcm_config::XcmBenchmarkHelper;
516}
517
518parameter_types! {
519	pub const AssetConversionPalletId: PalletId = PalletId(*b"py/ascon");
520	pub const LiquidityWithdrawalFee: Permill = Permill::from_percent(0);
521}
522
523ord_parameter_types! {
524	pub const AssetConversionOrigin: sp_runtime::AccountId32 =
525		AccountIdConversion::<sp_runtime::AccountId32>::into_account_truncating(&AssetConversionPalletId::get());
526}
527
528pub type AssetsForceOrigin = EnsureRoot<AccountId>;
529
530pub type PoolAssetsInstance = pallet_assets::Instance3;
531impl pallet_assets::Config<PoolAssetsInstance> for Runtime {
532	type RuntimeEvent = RuntimeEvent;
533	type Balance = Balance;
534	type RemoveItemsLimit = ConstU32<1000>;
535	type AssetId = u32;
536	type AssetIdParameter = u32;
537	type Currency = Balances;
538	type CreateOrigin =
539		AsEnsureOriginWithArg<EnsureSignedBy<AssetConversionOrigin, sp_runtime::AccountId32>>;
540	type ForceOrigin = AssetsForceOrigin;
541	type AssetDeposit = ConstU128<0>;
542	type AssetAccountDeposit = ConstU128<0>;
543	type MetadataDepositBase = ConstU128<0>;
544	type MetadataDepositPerByte = ConstU128<0>;
545	type ApprovalDeposit = ConstU128<0>;
546	type StringLimit = ConstU32<50>;
547	type Freezer = ();
548	type Extra = ();
549	type WeightInfo = pallet_assets::weights::SubstrateWeight<Runtime>;
550	type CallbackHandle = ();
551	#[cfg(feature = "runtime-benchmarks")]
552	type BenchmarkHelper = ();
553}
554
555/// Union fungibles implementation for `Assets` and `ForeignAssets`.
556pub type LocalAndForeignAssets = fungibles::UnionOf<
557	Assets,
558	ForeignAssets,
559	LocalFromLeft<
560		AssetIdForTrustBackedAssetsConvert<
561			xcm_config::TrustBackedAssetsPalletLocation,
562			xcm::latest::Location,
563		>,
564		parachains_common::AssetIdForTrustBackedAssets,
565		xcm::latest::Location,
566	>,
567	xcm::latest::Location,
568	AccountId,
569>;
570
571/// Union fungibles implementation for [`LocalAndForeignAssets`] and `Balances`.
572pub type NativeAndAssets = fungible::UnionOf<
573	Balances,
574	LocalAndForeignAssets,
575	TargetFromLeft<xcm_config::RelayLocation, xcm::latest::Location>,
576	xcm::latest::Location,
577	AccountId,
578>;
579
580pub type PoolIdToAccountId = pallet_asset_conversion::AccountIdConverter<
581	AssetConversionPalletId,
582	(xcm::latest::Location, xcm::latest::Location),
583>;
584
585impl pallet_asset_conversion::Config for Runtime {
586	type RuntimeEvent = RuntimeEvent;
587	type Balance = Balance;
588	type HigherPrecisionBalance = sp_core::U256;
589	type AssetKind = xcm::latest::Location;
590	type Assets = NativeAndAssets;
591	type PoolId = (Self::AssetKind, Self::AssetKind);
592	type PoolLocator = pallet_asset_conversion::WithFirstAsset<
593		xcm_config::RelayLocation,
594		AccountId,
595		Self::AssetKind,
596		PoolIdToAccountId,
597	>;
598	type PoolAssetId = u32;
599	type PoolAssets = PoolAssets;
600	type PoolSetupFee = ConstU128<0>; // Asset class deposit fees are sufficient to prevent spam
601	type PoolSetupFeeAsset = xcm_config::RelayLocation;
602	type PoolSetupFeeTarget = ResolveAssetTo<AssetConversionOrigin, Self::Assets>;
603	type LiquidityWithdrawalFee = LiquidityWithdrawalFee;
604	type LPFee = ConstU32<3>;
605	type PalletId = AssetConversionPalletId;
606	type MaxSwapPathLength = ConstU32<3>;
607	type MintMinLiquidity = ConstU128<100>;
608	type WeightInfo = ();
609	#[cfg(feature = "runtime-benchmarks")]
610	type BenchmarkHelper = assets_common::benchmarks::AssetPairFactory<
611		xcm_config::RelayLocation,
612		parachain_info::Pallet<Runtime>,
613		xcm_config::TrustBackedAssetsPalletIndex,
614		xcm::latest::Location,
615	>;
616}
617
618parameter_types! {
619	pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
620	pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
621	pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
622}
623
624impl cumulus_pallet_parachain_system::Config for Runtime {
625	type WeightInfo = ();
626	type RuntimeEvent = RuntimeEvent;
627	type OnSystemEvent = ();
628	type SelfParaId = parachain_info::Pallet<Runtime>;
629	type DmpQueue = frame_support::traits::EnqueueWithOrigin<MessageQueue, RelayOrigin>;
630	type ReservedDmpWeight = ReservedDmpWeight;
631	type OutboundXcmpMessageSource = XcmpQueue;
632	type XcmpMessageHandler = XcmpQueue;
633	type ReservedXcmpWeight = ReservedXcmpWeight;
634	type CheckAssociatedRelayNumber = RelayNumberStrictlyIncreases;
635	type ConsensusHook = cumulus_pallet_aura_ext::FixedVelocityConsensusHook<
636		Runtime,
637		RELAY_CHAIN_SLOT_DURATION_MILLIS,
638		BLOCK_PROCESSING_VELOCITY,
639		UNINCLUDED_SEGMENT_CAPACITY,
640	>;
641	type SelectCore = cumulus_pallet_parachain_system::DefaultCoreSelector<Runtime>;
642}
643
644impl parachain_info::Config for Runtime {}
645
646parameter_types! {
647	pub MessageQueueServiceWeight: Weight = Perbill::from_percent(35) * RuntimeBlockWeights::get().max_block;
648}
649
650impl pallet_message_queue::Config for Runtime {
651	type RuntimeEvent = RuntimeEvent;
652	type WeightInfo = ();
653	type MessageProcessor = xcm_builder::ProcessXcmMessage<
654		AggregateMessageOrigin,
655		xcm_executor::XcmExecutor<xcm_config::XcmConfig>,
656		RuntimeCall,
657	>;
658	type Size = u32;
659	// The XCMP queue pallet is only ever able to handle the `Sibling(ParaId)` origin:
660	type QueueChangeHandler = NarrowOriginToSibling<XcmpQueue>;
661	type QueuePausedQuery = NarrowOriginToSibling<XcmpQueue>;
662	type HeapSize = sp_core::ConstU32<{ 103 * 1024 }>;
663	type MaxStale = sp_core::ConstU32<8>;
664	type ServiceWeight = MessageQueueServiceWeight;
665	type IdleMaxServiceWeight = MessageQueueServiceWeight;
666}
667
668impl cumulus_pallet_aura_ext::Config for Runtime {}
669
670parameter_types! {
671	/// The asset ID for the asset that we use to pay for message delivery fees.
672	pub FeeAssetId: AssetLocationId = AssetLocationId(xcm_config::RelayLocation::get());
673	/// The base fee for the message delivery fees (3 CENTS).
674	pub const BaseDeliveryFee: u128 = (1_000_000_000_000u128 / 100).saturating_mul(3);
675}
676
677pub type PriceForSiblingParachainDelivery = polkadot_runtime_common::xcm_sender::ExponentialPrice<
678	FeeAssetId,
679	BaseDeliveryFee,
680	TransactionByteFee,
681	XcmpQueue,
682>;
683
684impl cumulus_pallet_xcmp_queue::Config for Runtime {
685	type RuntimeEvent = RuntimeEvent;
686	type ChannelInfo = ParachainSystem;
687	type VersionWrapper = PolkadotXcm;
688	// Enqueue XCMP messages from siblings for later processing.
689	type XcmpQueue = TransformOrigin<MessageQueue, AggregateMessageOrigin, ParaId, ParaIdToSibling>;
690	type MaxInboundSuspended = ConstU32<1_000>;
691	type MaxActiveOutboundChannels = ConstU32<128>;
692	// Most on-chain HRMP channels are configured to use 102400 bytes of max message size, so we
693	// need to set the page size larger than that until we reduce the channel size on-chain.
694	type MaxPageSize = ConstU32<{ 103 * 1024 }>;
695	type ControllerOrigin = EnsureRoot<AccountId>;
696	type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;
697	type WeightInfo = ();
698	type PriceForSiblingDelivery = PriceForSiblingParachainDelivery;
699}
700
701parameter_types! {
702	pub const Period: u32 = 6 * HOURS;
703	pub const Offset: u32 = 0;
704}
705
706impl pallet_session::Config for Runtime {
707	type RuntimeEvent = RuntimeEvent;
708	type ValidatorId = <Self as frame_system::Config>::AccountId;
709	// we don't have stash and controller, thus we don't need the convert as well.
710	type ValidatorIdOf = pallet_collator_selection::IdentityCollator;
711	type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>;
712	type NextSessionRotation = pallet_session::PeriodicSessions<Period, Offset>;
713	type SessionManager = CollatorSelection;
714	// Essentially just Aura, but let's be pedantic.
715	type SessionHandler = <SessionKeys as sp_runtime::traits::OpaqueKeys>::KeyTypeIdProviders;
716	type Keys = SessionKeys;
717	type WeightInfo = ();
718}
719
720impl pallet_aura::Config for Runtime {
721	type AuthorityId = AuraId;
722	type DisabledValidators = ();
723	type MaxAuthorities = ConstU32<100_000>;
724	type AllowMultipleBlocksPerSlot = ConstBool<false>;
725	type SlotDuration = pallet_aura::MinimumPeriodTimesTwo<Self>;
726}
727
728parameter_types! {
729	pub const PotId: PalletId = PalletId(*b"PotStake");
730	pub const SessionLength: BlockNumber = 6 * HOURS;
731	pub const ExecutiveBody: BodyId = BodyId::Executive;
732}
733
734// We allow root only to execute privileged collator selection operations.
735pub type CollatorSelectionUpdateOrigin = EnsureRoot<AccountId>;
736
737impl pallet_collator_selection::Config for Runtime {
738	type RuntimeEvent = RuntimeEvent;
739	type Currency = Balances;
740	type UpdateOrigin = CollatorSelectionUpdateOrigin;
741	type PotId = PotId;
742	type MaxCandidates = ConstU32<100>;
743	type MinEligibleCollators = ConstU32<4>;
744	type MaxInvulnerables = ConstU32<20>;
745	// should be a multiple of session or things will get inconsistent
746	type KickThreshold = Period;
747	type ValidatorId = <Self as frame_system::Config>::AccountId;
748	type ValidatorIdOf = pallet_collator_selection::IdentityCollator;
749	type ValidatorRegistration = Session;
750	type WeightInfo = ();
751}
752
753#[cfg(feature = "runtime-benchmarks")]
754pub struct AssetTxHelper;
755
756#[cfg(feature = "runtime-benchmarks")]
757impl pallet_asset_tx_payment::BenchmarkHelperTrait<AccountId, u32, u32> for AssetTxHelper {
758	fn create_asset_id_parameter(_id: u32) -> (u32, u32) {
759		unimplemented!("Penpal uses default weights");
760	}
761	fn setup_balances_and_pool(_asset_id: u32, _account: AccountId) {
762		unimplemented!("Penpal uses default weights");
763	}
764}
765
766impl pallet_asset_tx_payment::Config for Runtime {
767	type RuntimeEvent = RuntimeEvent;
768	type Fungibles = Assets;
769	type OnChargeAssetTransaction = pallet_asset_tx_payment::FungiblesAdapter<
770		pallet_assets::BalanceToAssetBalance<
771			Balances,
772			Runtime,
773			ConvertInto,
774			TrustBackedAssetsInstance,
775		>,
776		AssetsToBlockAuthor<Runtime, TrustBackedAssetsInstance>,
777	>;
778	type WeightInfo = ();
779	#[cfg(feature = "runtime-benchmarks")]
780	type BenchmarkHelper = AssetTxHelper;
781}
782
783impl pallet_sudo::Config for Runtime {
784	type RuntimeEvent = RuntimeEvent;
785	type RuntimeCall = RuntimeCall;
786	type WeightInfo = pallet_sudo::weights::SubstrateWeight<Runtime>;
787}
788
789// Create the runtime by composing the FRAME pallets that were previously configured.
790construct_runtime!(
791	pub enum Runtime
792	{
793		// System support stuff.
794		System: frame_system = 0,
795		ParachainSystem: cumulus_pallet_parachain_system = 1,
796		Timestamp: pallet_timestamp = 2,
797		ParachainInfo: parachain_info = 3,
798
799		// Monetary stuff.
800		Balances: pallet_balances = 10,
801		TransactionPayment: pallet_transaction_payment = 11,
802		AssetTxPayment: pallet_asset_tx_payment = 12,
803
804		// Collator support. The order of these 4 are important and shall not change.
805		Authorship: pallet_authorship = 20,
806		CollatorSelection: pallet_collator_selection = 21,
807		Session: pallet_session = 22,
808		Aura: pallet_aura = 23,
809		AuraExt: cumulus_pallet_aura_ext = 24,
810
811		// XCM helpers.
812		XcmpQueue: cumulus_pallet_xcmp_queue = 30,
813		PolkadotXcm: pallet_xcm = 31,
814		CumulusXcm: cumulus_pallet_xcm = 32,
815		MessageQueue: pallet_message_queue = 34,
816
817		// The main stage.
818		Assets: pallet_assets::<Instance1> = 50,
819		ForeignAssets: pallet_assets::<Instance2> = 51,
820		PoolAssets: pallet_assets::<Instance3> = 52,
821		AssetConversion: pallet_asset_conversion = 53,
822
823		Sudo: pallet_sudo = 255,
824	}
825);
826
827#[cfg(feature = "runtime-benchmarks")]
828mod benches {
829	frame_benchmarking::define_benchmarks!(
830		[frame_system, SystemBench::<Runtime>]
831		[frame_system_extensions, SystemExtensionsBench::<Runtime>]
832		[pallet_balances, Balances]
833		[pallet_message_queue, MessageQueue]
834		[pallet_session, SessionBench::<Runtime>]
835		[pallet_sudo, Sudo]
836		[pallet_timestamp, Timestamp]
837		[pallet_collator_selection, CollatorSelection]
838		[cumulus_pallet_parachain_system, ParachainSystem]
839		[cumulus_pallet_xcmp_queue, XcmpQueue]
840	);
841}
842
843impl_runtime_apis! {
844	impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {
845		fn slot_duration() -> sp_consensus_aura::SlotDuration {
846			sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())
847		}
848
849		fn authorities() -> Vec<AuraId> {
850			pallet_aura::Authorities::<Runtime>::get().into_inner()
851		}
852	}
853
854	impl sp_api::Core<Block> for Runtime {
855		fn version() -> RuntimeVersion {
856			VERSION
857		}
858
859		fn execute_block(block: Block) {
860			Executive::execute_block(block)
861		}
862
863		fn initialize_block(header: &<Block as BlockT>::Header) -> sp_runtime::ExtrinsicInclusionMode {
864			Executive::initialize_block(header)
865		}
866	}
867
868	impl sp_api::Metadata<Block> for Runtime {
869		fn metadata() -> OpaqueMetadata {
870			OpaqueMetadata::new(Runtime::metadata().into())
871		}
872
873		fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
874			Runtime::metadata_at_version(version)
875		}
876
877		fn metadata_versions() -> alloc::vec::Vec<u32> {
878			Runtime::metadata_versions()
879		}
880	}
881
882	impl sp_block_builder::BlockBuilder<Block> for Runtime {
883		fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
884			Executive::apply_extrinsic(extrinsic)
885		}
886
887		fn finalize_block() -> <Block as BlockT>::Header {
888			Executive::finalize_block()
889		}
890
891		fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
892			data.create_extrinsics()
893		}
894
895		fn check_inherents(
896			block: Block,
897			data: sp_inherents::InherentData,
898		) -> sp_inherents::CheckInherentsResult {
899			data.check_extrinsics(&block)
900		}
901	}
902
903	impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
904		fn validate_transaction(
905			source: TransactionSource,
906			tx: <Block as BlockT>::Extrinsic,
907			block_hash: <Block as BlockT>::Hash,
908		) -> TransactionValidity {
909			Executive::validate_transaction(source, tx, block_hash)
910		}
911	}
912
913	impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
914		fn offchain_worker(header: &<Block as BlockT>::Header) {
915			Executive::offchain_worker(header)
916		}
917	}
918
919	impl sp_session::SessionKeys<Block> for Runtime {
920		fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
921			SessionKeys::generate(seed)
922		}
923
924		fn decode_session_keys(
925			encoded: Vec<u8>,
926		) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
927			SessionKeys::decode_into_raw_public_keys(&encoded)
928		}
929	}
930
931	impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
932		fn account_nonce(account: AccountId) -> Nonce {
933			System::account_nonce(account)
934		}
935	}
936
937	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {
938		fn query_info(
939			uxt: <Block as BlockT>::Extrinsic,
940			len: u32,
941		) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
942			TransactionPayment::query_info(uxt, len)
943		}
944		fn query_fee_details(
945			uxt: <Block as BlockT>::Extrinsic,
946			len: u32,
947		) -> pallet_transaction_payment::FeeDetails<Balance> {
948			TransactionPayment::query_fee_details(uxt, len)
949		}
950		fn query_weight_to_fee(weight: Weight) -> Balance {
951			TransactionPayment::weight_to_fee(weight)
952		}
953		fn query_length_to_fee(length: u32) -> Balance {
954			TransactionPayment::length_to_fee(length)
955		}
956	}
957
958	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi<Block, Balance, RuntimeCall>
959		for Runtime
960	{
961		fn query_call_info(
962			call: RuntimeCall,
963			len: u32,
964		) -> pallet_transaction_payment::RuntimeDispatchInfo<Balance> {
965			TransactionPayment::query_call_info(call, len)
966		}
967		fn query_call_fee_details(
968			call: RuntimeCall,
969			len: u32,
970		) -> pallet_transaction_payment::FeeDetails<Balance> {
971			TransactionPayment::query_call_fee_details(call, len)
972		}
973		fn query_weight_to_fee(weight: Weight) -> Balance {
974			TransactionPayment::weight_to_fee(weight)
975		}
976		fn query_length_to_fee(length: u32) -> Balance {
977			TransactionPayment::length_to_fee(length)
978		}
979	}
980
981	impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {
982		fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {
983			ParachainSystem::collect_collation_info(header)
984		}
985	}
986
987	impl cumulus_primitives_core::GetCoreSelectorApi<Block> for Runtime {
988		fn core_selector() -> (CoreSelector, ClaimQueueOffset) {
989			ParachainSystem::core_selector()
990		}
991	}
992
993	impl xcm_runtime_apis::fees::XcmPaymentApi<Block> for Runtime {
994		fn query_acceptable_payment_assets(xcm_version: xcm::Version) -> Result<Vec<VersionedAssetId>, XcmPaymentApiError> {
995			let acceptable_assets = vec![AssetLocationId(xcm_config::RelayLocation::get())];
996			PolkadotXcm::query_acceptable_payment_assets(xcm_version, acceptable_assets)
997		}
998
999		fn query_weight_to_asset_fee(weight: Weight, asset: VersionedAssetId) -> Result<u128, XcmPaymentApiError> {
1000			match asset.try_as::<AssetLocationId>() {
1001				Ok(asset_id) if asset_id.0 == xcm_config::RelayLocation::get() => {
1002					// for native token
1003					Ok(WeightToFee::weight_to_fee(&weight))
1004				},
1005				Ok(asset_id) => {
1006					log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - unhandled asset_id: {asset_id:?}!");
1007					Err(XcmPaymentApiError::AssetNotFound)
1008				},
1009				Err(_) => {
1010					log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - failed to convert asset: {asset:?}!");
1011					Err(XcmPaymentApiError::VersionedConversionFailed)
1012				}
1013			}
1014		}
1015
1016		fn query_xcm_weight(message: VersionedXcm<()>) -> Result<Weight, XcmPaymentApiError> {
1017			PolkadotXcm::query_xcm_weight(message)
1018		}
1019
1020		fn query_delivery_fees(destination: VersionedLocation, message: VersionedXcm<()>) -> Result<VersionedAssets, XcmPaymentApiError> {
1021			PolkadotXcm::query_delivery_fees(destination, message)
1022		}
1023	}
1024
1025	impl xcm_runtime_apis::dry_run::DryRunApi<Block, RuntimeCall, RuntimeEvent, OriginCaller> for Runtime {
1026		fn dry_run_call(origin: OriginCaller, call: RuntimeCall) -> Result<CallDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
1027			use xcm_builder::InspectMessageQueues;
1028			use xcm_executor::RecordXcm;
1029			use xcm::prelude::*;
1030			pallet_xcm::Pallet::<Runtime>::set_record_xcm(true);
1031			frame_system::Pallet::<Runtime>::reset_events(); // To make sure we only record events from current call.
1032			let result = call.dispatch(origin.into());
1033			pallet_xcm::Pallet::<Runtime>::set_record_xcm(false);
1034			let local_xcm = pallet_xcm::Pallet::<Runtime>::recorded_xcm();
1035			let forwarded_xcms = xcm_config::XcmRouter::get_messages();
1036			let events: Vec<RuntimeEvent> = System::read_events_no_consensus().map(|record| record.event.clone()).collect();
1037			Ok(CallDryRunEffects {
1038				local_xcm: local_xcm.map(VersionedXcm::<()>::from),
1039				forwarded_xcms,
1040				emitted_events: events,
1041				execution_result: result,
1042			})
1043		}
1044
1045		fn dry_run_xcm(origin_location: VersionedLocation, program: VersionedXcm<RuntimeCall>) -> Result<XcmDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
1046			use xcm_builder::InspectMessageQueues;
1047			use xcm::prelude::*;
1048
1049			let origin_location: Location = origin_location.try_into().map_err(|error| {
1050				log::error!(
1051					target: "xcm::DryRunApi::dry_run_xcm",
1052					"Location version conversion failed with error: {:?}",
1053					error,
1054				);
1055				XcmDryRunApiError::VersionedConversionFailed
1056			})?;
1057			let program: Xcm<RuntimeCall> = program.try_into().map_err(|error| {
1058				log::error!(
1059					target: "xcm::DryRunApi::dry_run_xcm",
1060					"Xcm version conversion failed with error {:?}",
1061					error,
1062				);
1063				XcmDryRunApiError::VersionedConversionFailed
1064			})?;
1065			let mut hash = program.using_encoded(sp_core::hashing::blake2_256);
1066			frame_system::Pallet::<Runtime>::reset_events(); // To make sure we only record events from current call.
1067			let result = xcm_executor::XcmExecutor::<xcm_config::XcmConfig>::prepare_and_execute(
1068				origin_location,
1069				program,
1070				&mut hash,
1071				Weight::MAX, // Max limit.
1072				Weight::zero(),
1073			);
1074			let forwarded_xcms = xcm_config::XcmRouter::get_messages();
1075			let events: Vec<RuntimeEvent> = System::read_events_no_consensus().map(|record| record.event.clone()).collect();
1076			Ok(XcmDryRunEffects {
1077				forwarded_xcms,
1078				emitted_events: events,
1079				execution_result: result,
1080			})
1081		}
1082	}
1083
1084	#[cfg(feature = "try-runtime")]
1085	impl frame_try_runtime::TryRuntime<Block> for Runtime {
1086		fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) {
1087			let weight = Executive::try_runtime_upgrade(checks).unwrap();
1088			(weight, RuntimeBlockWeights::get().max_block)
1089		}
1090
1091		fn execute_block(
1092			block: Block,
1093			state_root_check: bool,
1094			signature_check: bool,
1095			select: frame_try_runtime::TryStateSelect,
1096		) -> Weight {
1097			// NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to
1098			// have a backtrace here.
1099			Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap()
1100		}
1101	}
1102
1103	#[cfg(feature = "runtime-benchmarks")]
1104	impl frame_benchmarking::Benchmark<Block> for Runtime {
1105		fn benchmark_metadata(extra: bool) -> (
1106			Vec<frame_benchmarking::BenchmarkList>,
1107			Vec<frame_support::traits::StorageInfo>,
1108		) {
1109			use frame_benchmarking::{Benchmarking, BenchmarkList};
1110			use frame_support::traits::StorageInfoTrait;
1111			use frame_system_benchmarking::Pallet as SystemBench;
1112			use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
1113			use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
1114
1115			let mut list = Vec::<BenchmarkList>::new();
1116			list_benchmarks!(list, extra);
1117
1118			let storage_info = AllPalletsWithSystem::storage_info();
1119			(list, storage_info)
1120		}
1121
1122		fn dispatch_benchmark(
1123			config: frame_benchmarking::BenchmarkConfig
1124		) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, alloc::string::String> {
1125			use frame_benchmarking::{Benchmarking, BenchmarkBatch};
1126			use sp_storage::TrackedStorageKey;
1127
1128			use frame_system_benchmarking::Pallet as SystemBench;
1129			use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
1130			impl frame_system_benchmarking::Config for Runtime {}
1131
1132			use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
1133			impl cumulus_pallet_session_benchmarking::Config for Runtime {}
1134
1135			let whitelist: Vec<TrackedStorageKey> = vec![
1136				// Block Number
1137				hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),
1138				// Total Issuance
1139				hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),
1140				// Execution Phase
1141				hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),
1142				// Event Count
1143				hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),
1144				// System Events
1145				hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),
1146			];
1147
1148			let mut batches = Vec::<BenchmarkBatch>::new();
1149			let params = (&config, &whitelist);
1150			add_benchmarks!(params, batches);
1151
1152			if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }
1153			Ok(batches)
1154		}
1155	}
1156
1157	impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
1158		fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
1159			build_state::<RuntimeGenesisConfig>(config)
1160		}
1161
1162		fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
1163			get_preset::<RuntimeGenesisConfig>(id, |_| None)
1164		}
1165
1166		fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
1167			vec![]
1168		}
1169	}
1170
1171	impl xcm_runtime_apis::trusted_query::TrustedQueryApi<Block> for Runtime {
1172		fn is_trusted_reserve(asset: VersionedAsset, location: VersionedLocation) -> xcm_runtime_apis::trusted_query::XcmTrustedQueryResult {
1173			PolkadotXcm::is_trusted_reserve(asset, location)
1174		}
1175		fn is_trusted_teleporter(asset: VersionedAsset, location: VersionedLocation) -> xcm_runtime_apis::trusted_query::XcmTrustedQueryResult {
1176			PolkadotXcm::is_trusted_teleporter(asset, location)
1177		}
1178	}
1179}
1180
1181cumulus_pallet_parachain_system::register_validate_block! {
1182	Runtime = Runtime,
1183	BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,
1184}