Skip to main content

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