referrerpolicy=no-referrer-when-downgrade

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