penpal_runtime/
lib.rs

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