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