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::{foreign_creators::ForeignCreators, local_and_foreign_assets::TargetFromLeft};
53use cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases;
54use cumulus_primitives_core::{AggregateMessageOrigin, ParaId};
55use frame_support::{
56	construct_runtime, derive_impl,
57	dispatch::DispatchClass,
58	genesis_builder_helper::{build_state, get_preset},
59	ord_parameter_types,
60	pallet_prelude::Weight,
61	parameter_types,
62	traits::{
63		tokens::{
64			fungible,
65			imbalance::{MaybeResolveAssetTo, ResolveAssetTo},
66		},
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::BlockAuthor,
83	message_queue::{NarrowOriginToSibling, ParaIdToSibling},
84	AccountId, Balance, BlockNumber, Hash, Header, Nonce, Signature,
85};
86use polkadot_runtime_common::{BlockHashCount, SlowAdjustingFeeUpdate};
87use smallvec::smallvec;
88use sp_api::impl_runtime_apis;
89pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;
90use sp_core::{crypto::KeyTypeId, OpaqueMetadata};
91use sp_runtime::{
92	generic, impl_opaque_keys,
93	traits::{AccountIdConversion, AccountIdLookup, BlakeTwo256, Block as BlockT},
94	transaction_validity::{TransactionSource, TransactionValidity},
95	ApplyExtrinsicResult, FixedU128,
96};
97pub use sp_runtime::{traits::ConvertInto, MultiAddress, Perbill, Permill};
98use testnet_parachains_constants::westend::{consensus::*, time::*};
99use weights::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight};
100use xcm::{
101	latest::prelude::{AssetId as AssetLocationId, BodyId, Location},
102	Version as XcmVersion, VersionedAsset, VersionedAssetId, VersionedAssets, VersionedLocation,
103	VersionedXcm,
104};
105use xcm_runtime_apis::{
106	dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects},
107	fees::Error as XcmPaymentApiError,
108};
109
110#[cfg(any(feature = "std", test))]
111pub use sp_runtime::BuildStorage;
112#[cfg(feature = "std")]
113use sp_version::NativeVersion;
114use sp_version::RuntimeVersion;
115use xcm_config::{
116	AssetsAssetId, LocationToAccountId, XcmConfig, XcmOriginToTransactDispatchOrigin,
117};
118
119/// The address format for describing accounts.
120pub type Address = MultiAddress<AccountId, ()>;
121
122/// Block type as expected by this runtime.
123pub type Block = generic::Block<Header, UncheckedExtrinsic>;
124
125/// A Block signed with a Justification
126pub type SignedBlock = generic::SignedBlock<Block>;
127
128/// BlockId type as expected by this runtime.
129pub type BlockId = generic::BlockId<Block>;
130
131// Id used for identifying assets.
132pub type AssetId = u32;
133
134/// The extension to the basic transaction logic.
135pub type TxExtension = (
136	frame_system::AuthorizeCall<Runtime>,
137	frame_system::CheckNonZeroSender<Runtime>,
138	frame_system::CheckSpecVersion<Runtime>,
139	frame_system::CheckTxVersion<Runtime>,
140	frame_system::CheckGenesis<Runtime>,
141	frame_system::CheckEra<Runtime>,
142	frame_system::CheckNonce<Runtime>,
143	frame_system::CheckWeight<Runtime>,
144	pallet_asset_conversion_tx_payment::ChargeAssetTxPayment<Runtime>,
145	frame_metadata_hash_extension::CheckMetadataHash<Runtime>,
146	pallet_revive::evm::tx_extension::SetOrigin<Runtime>,
147	frame_system::WeightReclaim<Runtime>,
148);
149
150/// Default extensions applied to Ethereum transactions.
151#[derive(Clone, PartialEq, Eq, Debug)]
152pub struct EthExtraImpl;
153
154impl EthExtra for EthExtraImpl {
155	type Config = Runtime;
156	type ExtensionV0 = TxExtension;
157	type ExtensionOtherVersions = sp_runtime::traits::InvalidVersion;
158
159	fn get_eth_extension(nonce: u32, tip: Balance) -> Self::ExtensionV0 {
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_conversion_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<0>;
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 = RuntimeFreezeReason;
438	type MaxFreezes = frame_support::traits::VariantCountOf<RuntimeFreezeReason>;
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/// Pallet Assets instance to store local and foreign assets, where:
467///
468/// * Local assets are identified by `assets_common::matching::LocalLocationPattern`.
469/// * Foreign assets are the rest
470pub type AssetsInstance = pallet_assets::Instance2;
471impl pallet_assets::Config<AssetsInstance> for Runtime {
472	type RuntimeEvent = RuntimeEvent;
473	type Balance = Balance;
474	type AssetId = AssetsAssetId;
475	type AssetIdParameter = AssetsAssetId;
476	type ReserveData = ForeignAssetReserveData;
477	type Currency = Balances;
478	// This is to allow any other location to create assets. Used in tests, not
479	// recommended on real chains.
480	type CreateOrigin =
481		ForeignCreators<Everything, LocationToAccountId, AccountId, xcm::latest::Location>;
482	type ForceOrigin = EnsureRoot<AccountId>;
483	type AssetDeposit = AssetDeposit;
484	type MetadataDepositBase = MetadataDepositBase;
485	type MetadataDepositPerByte = MetadataDepositPerByte;
486	type ApprovalDeposit = ApprovalDeposit;
487	type StringLimit = AssetsStringLimit;
488	type Holder = ();
489	type Freezer = ();
490	type Extra = ();
491	type WeightInfo = pallet_assets::weights::SubstrateWeight<Runtime>;
492	type CallbackHandle = ();
493	type AssetAccountDeposit = AssetAccountDeposit;
494	type RemoveItemsLimit = frame_support::traits::ConstU32<1000>;
495	#[cfg(feature = "runtime-benchmarks")]
496	type BenchmarkHelper = assets_common::benchmarks::LocationAssetsBenchmarkHelper;
497}
498
499parameter_types! {
500	pub const AssetConversionPalletId: PalletId = PalletId(*b"py/ascon");
501	pub const LpFee: Permill = Permill::zero(); // Makes account balance tracking in tests a bit easier
502	pub const LiquidityWithdrawalFee: Permill = Permill::from_percent(0);
503}
504
505ord_parameter_types! {
506	pub const AssetConversionOrigin: sp_runtime::AccountId32 =
507		AccountIdConversion::<sp_runtime::AccountId32>::into_account_truncating(&AssetConversionPalletId::get());
508}
509
510pub type AssetsForceOrigin = EnsureRoot<AccountId>;
511
512pub type PoolAssetsInstance = pallet_assets::Instance3;
513impl pallet_assets::Config<PoolAssetsInstance> for Runtime {
514	type RuntimeEvent = RuntimeEvent;
515	type Balance = Balance;
516	type RemoveItemsLimit = ConstU32<1000>;
517	type AssetId = u32;
518	type AssetIdParameter = u32;
519	type ReserveData = ();
520	type Currency = Balances;
521	type CreateOrigin =
522		AsEnsureOriginWithArg<EnsureSignedBy<AssetConversionOrigin, sp_runtime::AccountId32>>;
523	type ForceOrigin = AssetsForceOrigin;
524	type AssetDeposit = ConstU128<0>;
525	type AssetAccountDeposit = ConstU128<0>;
526	type MetadataDepositBase = ConstU128<0>;
527	type MetadataDepositPerByte = ConstU128<0>;
528	type ApprovalDeposit = ConstU128<0>;
529	type StringLimit = ConstU32<50>;
530	type Holder = ();
531	type Freezer = ();
532	type Extra = ();
533	type WeightInfo = pallet_assets::weights::SubstrateWeight<Runtime>;
534	type CallbackHandle = ();
535	#[cfg(feature = "runtime-benchmarks")]
536	type BenchmarkHelper = ();
537}
538
539/// Union fungibles implementation for [`Assets`] and `Balances`.
540pub type NativeAndAssets = fungible::UnionOf<
541	Balances,
542	Assets,
543	TargetFromLeft<xcm_config::PenpalNativeCurrency, xcm::latest::Location>,
544	xcm::latest::Location,
545	AccountId,
546>;
547
548pub type PoolIdToAccountId = pallet_asset_conversion::AccountIdConverter<
549	AssetConversionPalletId,
550	(xcm::latest::Location, xcm::latest::Location),
551>;
552
553impl pallet_asset_conversion::Config for Runtime {
554	type RuntimeEvent = RuntimeEvent;
555	type Balance = Balance;
556	type HigherPrecisionBalance = sp_core::U256;
557	type AssetKind = xcm::latest::Location;
558	type Assets = NativeAndAssets;
559	type PoolId = (Self::AssetKind, Self::AssetKind);
560	type PoolLocator = pallet_asset_conversion::WithFirstAsset<
561		xcm_config::PenpalNativeCurrency,
562		AccountId,
563		Self::AssetKind,
564		PoolIdToAccountId,
565	>;
566	type PoolAssetId = u32;
567	type PoolAssets = PoolAssets;
568	type PoolSetupFee = ConstU128<0>; // Asset class deposit fees are sufficient to prevent spam
569	type PoolSetupFeeAsset = xcm_config::PenpalNativeCurrency;
570	type PoolSetupFeeTarget = ResolveAssetTo<AssetConversionOrigin, Self::Assets>;
571	type LiquidityWithdrawalFee = LiquidityWithdrawalFee;
572	type LPFee = LpFee;
573	type PalletId = AssetConversionPalletId;
574	type MaxSwapPathLength = ConstU32<3>;
575	type MintMinLiquidity = ConstU128<100>;
576	type WeightInfo = ();
577	#[cfg(feature = "runtime-benchmarks")]
578	type BenchmarkHelper = assets_common::benchmarks::AssetPairFactory<
579		xcm_config::PenpalNativeCurrency,
580		parachain_info::Pallet<Runtime>,
581		xcm_config::AssetsPalletIndex,
582		xcm::latest::Location,
583	>;
584}
585
586parameter_types! {
587	pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
588	pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
589	pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
590}
591
592type ConsensusHook = cumulus_pallet_aura_ext::FixedVelocityConsensusHook<
593	Runtime,
594	RELAY_CHAIN_SLOT_DURATION_MILLIS,
595	BLOCK_PROCESSING_VELOCITY,
596	UNINCLUDED_SEGMENT_CAPACITY,
597>;
598
599impl cumulus_pallet_parachain_system::Config for Runtime {
600	type WeightInfo = ();
601	type RuntimeEvent = RuntimeEvent;
602	type OnSystemEvent = ();
603	type SelfParaId = parachain_info::Pallet<Runtime>;
604	type DmpQueue = frame_support::traits::EnqueueWithOrigin<MessageQueue, RelayOrigin>;
605	type ReservedDmpWeight = ReservedDmpWeight;
606	type OutboundXcmpMessageSource = XcmpQueue;
607	type XcmpMessageHandler = XcmpQueue;
608	type ReservedXcmpWeight = ReservedXcmpWeight;
609	type CheckAssociatedRelayNumber = RelayNumberMonotonicallyIncreases;
610	type ConsensusHook = cumulus_pallet_aura_ext::FixedVelocityConsensusHook<
611		Runtime,
612		RELAY_CHAIN_SLOT_DURATION_MILLIS,
613		BLOCK_PROCESSING_VELOCITY,
614		UNINCLUDED_SEGMENT_CAPACITY,
615	>;
616	type RelayParentOffset = ConstU32<0>;
617}
618
619impl parachain_info::Config for Runtime {}
620
621parameter_types! {
622	pub MessageQueueServiceWeight: Weight = Perbill::from_percent(35) * RuntimeBlockWeights::get().max_block;
623}
624
625impl pallet_message_queue::Config for Runtime {
626	type RuntimeEvent = RuntimeEvent;
627	type WeightInfo = ();
628	type MessageProcessor = xcm_builder::ProcessXcmMessage<
629		AggregateMessageOrigin,
630		xcm_executor::XcmExecutor<xcm_config::XcmConfig>,
631		RuntimeCall,
632	>;
633	type Size = u32;
634	// The XCMP queue pallet is only ever able to handle the `Sibling(ParaId)` origin:
635	type QueueChangeHandler = NarrowOriginToSibling<XcmpQueue>;
636	type QueuePausedQuery = NarrowOriginToSibling<XcmpQueue>;
637	type HeapSize = sp_core::ConstU32<{ 103 * 1024 }>;
638	type MaxStale = sp_core::ConstU32<8>;
639	type ServiceWeight = MessageQueueServiceWeight;
640	type IdleMaxServiceWeight = MessageQueueServiceWeight;
641}
642
643impl cumulus_pallet_aura_ext::Config for Runtime {}
644
645parameter_types! {
646	/// The asset ID for the asset that we use to pay for message delivery fees.
647	pub FeeAssetId: AssetLocationId = AssetLocationId(xcm_config::PenpalNativeCurrency::get());
648	/// The base fee for the message delivery fees (3 CENTS).
649	pub const BaseDeliveryFee: u128 = (1_000_000_000_000u128 / 100).saturating_mul(3);
650}
651
652pub type PriceForSiblingParachainDelivery = polkadot_runtime_common::xcm_sender::ExponentialPrice<
653	FeeAssetId,
654	BaseDeliveryFee,
655	TransactionByteFee,
656	XcmpQueue,
657>;
658
659impl cumulus_pallet_xcmp_queue::Config for Runtime {
660	type RuntimeEvent = RuntimeEvent;
661	type ChannelInfo = ParachainSystem;
662	type VersionWrapper = PolkadotXcm;
663	// Enqueue XCMP messages from siblings for later processing.
664	type XcmpQueue = TransformOrigin<MessageQueue, AggregateMessageOrigin, ParaId, ParaIdToSibling>;
665	type MaxInboundSuspended = ConstU32<1_000>;
666	type MaxActiveOutboundChannels = ConstU32<128>;
667	// Most on-chain HRMP channels are configured to use 102400 bytes of max message size, so we
668	// need to set the page size larger than that until we reduce the channel size on-chain.
669	type MaxPageSize = ConstU32<{ 103 * 1024 }>;
670	type ControllerOrigin = EnsureRoot<AccountId>;
671	type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;
672	type WeightInfo = ();
673	type PriceForSiblingDelivery = PriceForSiblingParachainDelivery;
674}
675
676parameter_types! {
677	pub const Period: u32 = 6 * HOURS;
678	pub const Offset: u32 = 0;
679}
680impl pallet_session::Config for Runtime {
681	type RuntimeEvent = RuntimeEvent;
682	type ValidatorId = <Self as frame_system::Config>::AccountId;
683	// we don't have stash and controller, thus we don't need the convert as well.
684	type ValidatorIdOf = pallet_collator_selection::IdentityCollator;
685	type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>;
686	type NextSessionRotation = pallet_session::PeriodicSessions<Period, Offset>;
687	type SessionManager = CollatorSelection;
688	// Essentially just Aura, but let's be pedantic.
689	type SessionHandler = <SessionKeys as sp_runtime::traits::OpaqueKeys>::KeyTypeIdProviders;
690	type Keys = SessionKeys;
691	type DisablingStrategy = ();
692	type WeightInfo = ();
693	type Currency = Balances;
694	type KeyDeposit = ();
695}
696
697impl pallet_aura::Config for Runtime {
698	type AuthorityId = AuraId;
699	type DisabledValidators = ();
700	type MaxAuthorities = ConstU32<100_000>;
701	type AllowMultipleBlocksPerSlot = ConstBool<true>;
702	type SlotDuration = ConstU64<SLOT_DURATION>;
703}
704
705parameter_types! {
706	pub const PotId: PalletId = PalletId(*b"PotStake");
707	pub const SessionLength: BlockNumber = 6 * HOURS;
708	pub const ExecutiveBody: BodyId = BodyId::Executive;
709}
710
711// We allow root only to execute privileged collator selection operations.
712pub type CollatorSelectionUpdateOrigin = EnsureRoot<AccountId>;
713
714impl pallet_collator_selection::Config for Runtime {
715	type RuntimeEvent = RuntimeEvent;
716	type Currency = Balances;
717	type UpdateOrigin = CollatorSelectionUpdateOrigin;
718	type PotId = PotId;
719	type MaxCandidates = ConstU32<100>;
720	type MinEligibleCollators = ConstU32<4>;
721	type MaxInvulnerables = ConstU32<20>;
722	// should be a multiple of session or things will get inconsistent
723	type KickThreshold = Period;
724	type ValidatorId = <Self as frame_system::Config>::AccountId;
725	type ValidatorIdOf = pallet_collator_selection::IdentityCollator;
726	type ValidatorRegistration = Session;
727	type WeightInfo = ();
728}
729
730#[cfg(feature = "runtime-benchmarks")]
731pub struct AssetTxConversionHelper;
732
733#[cfg(feature = "runtime-benchmarks")]
734impl pallet_asset_conversion_tx_payment::BenchmarkHelperTrait<AccountId, Location, Location>
735	for AssetTxConversionHelper
736{
737	fn create_asset_id_parameter(_id: u32) -> (Location, Location) {
738		unimplemented!("Penpal uses default weights");
739	}
740	fn setup_balances_and_pool(_asset_id: Location, _account: AccountId) {
741		unimplemented!("Penpal uses default weights");
742	}
743}
744
745impl pallet_asset_conversion_tx_payment::Config for Runtime {
746	type RuntimeEvent = RuntimeEvent;
747	type AssetId = Location;
748	type OnChargeAssetTransaction = pallet_asset_conversion_tx_payment::SwapAssetAdapter<
749		xcm_config::PenpalNativeCurrency,
750		NativeAndAssets,
751		AssetConversion,
752		MaybeResolveAssetTo<BlockAuthor<Runtime>, NativeAndAssets, AccountId>,
753	>;
754	type WeightInfo = ();
755
756	#[cfg(feature = "runtime-benchmarks")]
757	type BenchmarkHelper = AssetTxConversionHelper;
758}
759
760parameter_types! {
761	pub const DepositPerItem: Balance = 0;
762	pub const DepositPerChildTrieItem: Balance = 0;
763	pub const DepositPerByte: Balance = 0;
764	pub CodeHashLockupDepositPercent: Perbill = Perbill::from_percent(30);
765	pub const MaxEthExtrinsicWeight: FixedU128 = FixedU128::from_rational(9, 10);
766}
767
768impl pallet_revive::Config for Runtime {
769	type Time = Timestamp;
770	type Balance = Balance;
771	type Currency = Balances;
772	type RuntimeEvent = RuntimeEvent;
773	type RuntimeCall = RuntimeCall;
774	type RuntimeOrigin = RuntimeOrigin;
775	type DepositPerItem = DepositPerItem;
776	type DepositPerChildTrieItem = DepositPerChildTrieItem;
777	type DepositPerByte = DepositPerByte;
778	type WeightInfo = pallet_revive::weights::SubstrateWeight<Self>;
779	type Precompiles = ();
780	type AddressMapper = pallet_revive::AccountId32Mapper<Self>;
781	type RuntimeMemory = ConstU32<{ 128 * 1024 * 1024 }>;
782	type PVFMemory = ConstU32<{ 512 * 1024 * 1024 }>;
783	type AllowEVMBytecode = ConstBool<true>;
784	type UploadOrigin = EnsureSigned<Self::AccountId>;
785	type InstantiateOrigin = EnsureSigned<Self::AccountId>;
786	type RuntimeHoldReason = RuntimeHoldReason;
787	type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent;
788	type ChainId = ConstU64<420_420_999>;
789	type NativeToEthRatio = ConstU32<1_000_000>; // 10^(18 - 12) Eth is 10^18, Native is 10^12.
790	type FindAuthor = <Runtime as pallet_authorship::Config>::FindAuthor;
791	type FeeInfo = pallet_revive::evm::fees::Info<Address, Signature, EthExtraImpl>;
792	type MaxEthExtrinsicWeight = MaxEthExtrinsicWeight;
793	type DebugEnabled = ConstBool<false>;
794	type AutoMap = ConstBool<false>;
795	type GasScale = ConstU32<1000>;
796	type OnBurn = ();
797	type Deposit = ();
798}
799
800impl pallet_sudo::Config for Runtime {
801	type RuntimeEvent = RuntimeEvent;
802	type RuntimeCall = RuntimeCall;
803	type WeightInfo = pallet_sudo::weights::SubstrateWeight<Runtime>;
804}
805
806impl pallet_utility::Config for Runtime {
807	type RuntimeEvent = RuntimeEvent;
808	type RuntimeCall = RuntimeCall;
809	type PalletsOrigin = OriginCaller;
810	type WeightInfo = pallet_utility::weights::SubstrateWeight<Runtime>;
811}
812
813// Create the runtime by composing the FRAME pallets that were previously configured.
814construct_runtime!(
815	pub enum Runtime
816	{
817		// System support stuff.
818		System: frame_system = 0,
819		ParachainSystem: cumulus_pallet_parachain_system = 1,
820		Timestamp: pallet_timestamp = 2,
821		ParachainInfo: parachain_info = 3,
822
823		// Monetary stuff.
824		Balances: pallet_balances = 10,
825		TransactionPayment: pallet_transaction_payment = 11,
826		AssetTxPayment: pallet_asset_conversion_tx_payment = 12,
827
828		// Collator support. The order of these 4 are important and shall not change.
829		Authorship: pallet_authorship = 20,
830		CollatorSelection: pallet_collator_selection = 21,
831		Session: pallet_session = 22,
832		Aura: pallet_aura = 23,
833		AuraExt: cumulus_pallet_aura_ext = 24,
834
835		// XCM helpers.
836		XcmpQueue: cumulus_pallet_xcmp_queue = 30,
837		PolkadotXcm: pallet_xcm = 31,
838		CumulusXcm: cumulus_pallet_xcm = 32,
839		MessageQueue: pallet_message_queue = 34,
840
841		// Handy utilities.
842		Utility: pallet_utility = 40,
843
844		// The main stage.
845
846		// Removed, i.e. merged into the foreign assets pallet.
847		// Assets: pallet_assets::<Instance1> = 50,
848		Assets: pallet_assets::<Instance2> = 50,
849		PoolAssets: pallet_assets::<Instance3> = 52,
850		AssetConversion: pallet_asset_conversion = 53,
851
852		Revive: pallet_revive = 60,
853
854		Sudo: pallet_sudo = 255,
855	}
856);
857
858#[cfg(feature = "runtime-benchmarks")]
859mod benches {
860	frame_benchmarking::define_benchmarks!(
861		[frame_system, SystemBench::<Runtime>]
862		[frame_system_extensions, SystemExtensionsBench::<Runtime>]
863		[pallet_balances, Balances]
864		[pallet_message_queue, MessageQueue]
865		[pallet_session, SessionBench::<Runtime>]
866		[pallet_sudo, Sudo]
867		[pallet_timestamp, Timestamp]
868		[pallet_collator_selection, CollatorSelection]
869		[cumulus_pallet_parachain_system, ParachainSystem]
870		[cumulus_pallet_xcmp_queue, XcmpQueue]
871		[pallet_utility, Utility]
872	);
873}
874
875pallet_revive::impl_runtime_apis_plus_revive_traits!(
876	Runtime,
877	Revive,
878	Executive,
879	EthExtraImpl,
880
881	impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {
882		fn slot_duration() -> sp_consensus_aura::SlotDuration {
883			sp_consensus_aura::SlotDuration::from_millis(SLOT_DURATION)
884		}
885
886		fn authorities() -> Vec<AuraId> {
887			pallet_aura::Authorities::<Runtime>::get().into_inner()
888		}
889	}
890
891	impl sp_api::Core<Block> for Runtime {
892		fn version() -> RuntimeVersion {
893			VERSION
894		}
895
896		fn execute_block(block: <Block as BlockT>::LazyBlock) {
897			Executive::execute_block(block)
898		}
899
900		fn initialize_block(header: &<Block as BlockT>::Header) -> sp_runtime::ExtrinsicInclusionMode {
901			Executive::initialize_block(header)
902		}
903	}
904
905	impl sp_api::Metadata<Block> for Runtime {
906		fn metadata() -> OpaqueMetadata {
907			OpaqueMetadata::new(Runtime::metadata().into())
908		}
909
910		fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
911			Runtime::metadata_at_version(version)
912		}
913
914		fn metadata_versions() -> alloc::vec::Vec<u32> {
915			Runtime::metadata_versions()
916		}
917	}
918
919	impl sp_block_builder::BlockBuilder<Block> for Runtime {
920		fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
921			Executive::apply_extrinsic(extrinsic)
922		}
923
924		fn finalize_block() -> <Block as BlockT>::Header {
925			Executive::finalize_block()
926		}
927
928		fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
929			data.create_extrinsics()
930		}
931
932		fn check_inherents(
933			block: <Block as BlockT>::LazyBlock,
934			data: sp_inherents::InherentData,
935		) -> sp_inherents::CheckInherentsResult {
936			data.check_extrinsics(&block)
937		}
938	}
939
940	impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
941		fn validate_transaction(
942			source: TransactionSource,
943			tx: <Block as BlockT>::Extrinsic,
944			block_hash: <Block as BlockT>::Hash,
945		) -> TransactionValidity {
946			Executive::validate_transaction(source, tx, block_hash)
947		}
948	}
949
950	impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
951		fn offchain_worker(header: &<Block as BlockT>::Header) {
952			Executive::offchain_worker(header)
953		}
954	}
955
956	impl sp_session::SessionKeys<Block> for Runtime {
957		fn generate_session_keys(owner: Vec<u8>, seed: Option<Vec<u8>>) -> sp_session::OpaqueGeneratedSessionKeys {
958			SessionKeys::generate(&owner, seed).into()
959		}
960
961		fn decode_session_keys(
962			encoded: Vec<u8>,
963		) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
964			SessionKeys::decode_into_raw_public_keys(&encoded)
965		}
966	}
967
968	impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
969		fn account_nonce(account: AccountId) -> Nonce {
970			System::account_nonce(account)
971		}
972	}
973
974	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {
975		fn query_info(
976			uxt: <Block as BlockT>::Extrinsic,
977			len: u32,
978		) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
979			TransactionPayment::query_info(uxt, len)
980		}
981		fn query_fee_details(
982			uxt: <Block as BlockT>::Extrinsic,
983			len: u32,
984		) -> pallet_transaction_payment::FeeDetails<Balance> {
985			TransactionPayment::query_fee_details(uxt, len)
986		}
987		fn query_weight_to_fee(weight: Weight) -> Balance {
988			TransactionPayment::weight_to_fee(weight)
989		}
990		fn query_length_to_fee(length: u32) -> Balance {
991			TransactionPayment::length_to_fee(length)
992		}
993	}
994
995	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi<Block, Balance, RuntimeCall>
996		for Runtime
997	{
998		fn query_call_info(
999			call: RuntimeCall,
1000			len: u32,
1001		) -> pallet_transaction_payment::RuntimeDispatchInfo<Balance> {
1002			TransactionPayment::query_call_info(call, len)
1003		}
1004		fn query_call_fee_details(
1005			call: RuntimeCall,
1006			len: u32,
1007		) -> pallet_transaction_payment::FeeDetails<Balance> {
1008			TransactionPayment::query_call_fee_details(call, len)
1009		}
1010		fn query_weight_to_fee(weight: Weight) -> Balance {
1011			TransactionPayment::weight_to_fee(weight)
1012		}
1013		fn query_length_to_fee(length: u32) -> Balance {
1014			TransactionPayment::length_to_fee(length)
1015		}
1016	}
1017
1018	impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {
1019		fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {
1020			ParachainSystem::collect_collation_info(header)
1021		}
1022	}
1023
1024	impl xcm_runtime_apis::fees::XcmPaymentApi<Block> for Runtime {
1025		fn query_acceptable_payment_assets(xcm_version: xcm::Version) -> Result<Vec<VersionedAssetId>, XcmPaymentApiError> {
1026			let acceptable_assets = vec![AssetLocationId(xcm_config::PenpalNativeCurrency::get())];
1027			PolkadotXcm::query_acceptable_payment_assets(xcm_version, acceptable_assets)
1028		}
1029
1030		fn query_weight_to_asset_fee(weight: Weight, asset: VersionedAssetId) -> Result<u128, XcmPaymentApiError> {
1031			type Trader = <XcmConfig as xcm_executor::Config>::Trader;
1032			PolkadotXcm::query_weight_to_asset_fee::<Trader>(weight, asset)
1033		}
1034
1035		fn query_xcm_weight(message: VersionedXcm<()>) -> Result<Weight, XcmPaymentApiError> {
1036			PolkadotXcm::query_xcm_weight(message)
1037		}
1038
1039		fn query_delivery_fees(destination: VersionedLocation, message: VersionedXcm<()>, asset_id: VersionedAssetId) -> Result<VersionedAssets, XcmPaymentApiError> {
1040			type AssetExchanger = <XcmConfig as xcm_executor::Config>::AssetExchanger;
1041			PolkadotXcm::query_delivery_fees::<AssetExchanger>(destination, message, asset_id)
1042		}
1043	}
1044
1045	impl xcm_runtime_apis::dry_run::DryRunApi<Block, RuntimeCall, RuntimeEvent, OriginCaller> for Runtime {
1046		fn dry_run_call(origin: OriginCaller, call: RuntimeCall, result_xcms_version: XcmVersion) -> Result<CallDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
1047			PolkadotXcm::dry_run_call::<Runtime, xcm_config::XcmRouter, OriginCaller, RuntimeCall>(origin, call, result_xcms_version)
1048		}
1049
1050		fn dry_run_xcm(origin_location: VersionedLocation, xcm: VersionedXcm<RuntimeCall>) -> Result<XcmDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
1051			PolkadotXcm::dry_run_xcm::<xcm_config::XcmRouter>(origin_location, xcm)
1052		}
1053	}
1054
1055	impl xcm_runtime_apis::conversions::LocationToAccountApi<Block, AccountId> for Runtime {
1056		fn convert_location(location: VersionedLocation) -> Result<
1057			AccountId,
1058			xcm_runtime_apis::conversions::Error
1059		> {
1060			xcm_runtime_apis::conversions::LocationToAccountHelper::<
1061				AccountId,
1062				xcm_config::LocationToAccountId,
1063			>::convert_location(location)
1064		}
1065	}
1066
1067	impl xcm_runtime_apis::trusted_query::TrustedQueryApi<Block> for Runtime {
1068		fn is_trusted_reserve(asset: VersionedAsset, location: VersionedLocation) -> xcm_runtime_apis::trusted_query::XcmTrustedQueryResult {
1069			PolkadotXcm::is_trusted_reserve(asset, location)
1070		}
1071		fn is_trusted_teleporter(asset: VersionedAsset, location: VersionedLocation) -> xcm_runtime_apis::trusted_query::XcmTrustedQueryResult {
1072			PolkadotXcm::is_trusted_teleporter(asset, location)
1073		}
1074	}
1075
1076	impl xcm_runtime_apis::authorized_aliases::AuthorizedAliasersApi<Block> for Runtime {
1077		fn authorized_aliasers(target: VersionedLocation) -> Result<
1078			Vec<xcm_runtime_apis::authorized_aliases::OriginAliaser>,
1079			xcm_runtime_apis::authorized_aliases::Error
1080		> {
1081			PolkadotXcm::authorized_aliasers(target)
1082		}
1083		fn is_authorized_alias(origin: VersionedLocation, target: VersionedLocation) -> Result<
1084			bool,
1085			xcm_runtime_apis::authorized_aliases::Error
1086		> {
1087			PolkadotXcm::is_authorized_alias(origin, target)
1088		}
1089	}
1090
1091	#[cfg(feature = "try-runtime")]
1092	impl frame_try_runtime::TryRuntime<Block> for Runtime {
1093		fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) {
1094			let weight = Executive::try_runtime_upgrade(checks).unwrap();
1095			(weight, RuntimeBlockWeights::get().max_block)
1096		}
1097
1098		fn execute_block(
1099			block: <Block as BlockT>::LazyBlock,
1100			state_root_check: bool,
1101			signature_check: bool,
1102			select: frame_try_runtime::TryStateSelect,
1103		) -> Weight {
1104			// NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to
1105			// have a backtrace here.
1106			Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap()
1107		}
1108	}
1109
1110	#[cfg(feature = "runtime-benchmarks")]
1111	impl frame_benchmarking::Benchmark<Block> for Runtime {
1112		fn benchmark_metadata(extra: bool) -> (
1113			Vec<frame_benchmarking::BenchmarkList>,
1114			Vec<frame_support::traits::StorageInfo>,
1115		) {
1116			use frame_benchmarking::BenchmarkList;
1117			use frame_support::traits::StorageInfoTrait;
1118			use frame_system_benchmarking::Pallet as SystemBench;
1119			use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
1120			use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
1121
1122			let mut list = Vec::<BenchmarkList>::new();
1123			list_benchmarks!(list, extra);
1124
1125			let storage_info = AllPalletsWithSystem::storage_info();
1126			(list, storage_info)
1127		}
1128
1129		#[allow(non_local_definitions)]
1130		fn dispatch_benchmark(
1131			config: frame_benchmarking::BenchmarkConfig
1132		) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, alloc::string::String> {
1133			use frame_benchmarking::BenchmarkBatch;
1134			use sp_storage::TrackedStorageKey;
1135			use codec::Encode;
1136
1137			use frame_system_benchmarking::Pallet as SystemBench;
1138			use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
1139			impl frame_system_benchmarking::Config for Runtime {}
1140
1141			use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
1142			impl cumulus_pallet_session_benchmarking::Config for Runtime {
1143				fn generate_session_keys_and_proof(owner: Self::AccountId) -> (Self::Keys, Vec<u8>) {
1144					let keys = SessionKeys::generate(&owner.encode(), None);
1145					(keys.keys, keys.proof.encode())
1146				}
1147			}
1148
1149			use frame_support::traits::WhitelistedStorageKeys;
1150			let whitelist: Vec<TrackedStorageKey> = AllPalletsWithSystem::whitelisted_storage_keys();
1151
1152			let mut batches = Vec::<BenchmarkBatch>::new();
1153			let params = (&config, &whitelist);
1154			add_benchmarks!(params, batches);
1155
1156			if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }
1157			Ok(batches)
1158		}
1159	}
1160
1161	impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
1162		fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
1163			build_state::<RuntimeGenesisConfig>(config)
1164		}
1165
1166		fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
1167			get_preset::<RuntimeGenesisConfig>(id, &genesis_config_presets::get_preset)
1168		}
1169
1170		fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
1171			genesis_config_presets::preset_names()
1172		}
1173	}
1174
1175	impl cumulus_primitives_core::GetParachainInfo<Block> for Runtime {
1176		fn parachain_id() -> ParaId {
1177			ParachainInfo::parachain_id()
1178		}
1179	}
1180
1181	impl cumulus_primitives_aura::AuraUnincludedSegmentApi<Block> for Runtime {
1182		fn can_build_upon(
1183			included_hash: <Block as BlockT>::Hash,
1184			slot: cumulus_primitives_aura::Slot,
1185		) -> bool {
1186			ConsensusHook::can_build_upon(included_hash, slot)
1187		}
1188	}
1189);
1190
1191cumulus_pallet_parachain_system::register_validate_block! {
1192	Runtime = Runtime,
1193	BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,
1194}