1#![cfg_attr(not(feature = "std"), no_std)]
25#![recursion_limit = "256"]
27
28#[cfg(feature = "std")]
30include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
31
32mod weights;
33pub mod xcm_config;
34
35extern crate alloc;
36
37use alloc::{vec, vec::Vec};
38use assets_common::{
39 foreign_creators::ForeignCreators,
40 local_and_foreign_assets::{LocalFromLeft, TargetFromLeft},
41 AssetIdForTrustBackedAssetsConvert,
42};
43use codec::Encode;
44use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases;
45use cumulus_primitives_core::{AggregateMessageOrigin, ClaimQueueOffset, CoreSelector, ParaId};
46use frame_support::{
47 construct_runtime, derive_impl,
48 dispatch::DispatchClass,
49 genesis_builder_helper::{build_state, get_preset},
50 ord_parameter_types,
51 pallet_prelude::Weight,
52 parameter_types,
53 traits::{
54 tokens::{fungible, fungibles, imbalance::ResolveAssetTo},
55 AsEnsureOriginWithArg, ConstBool, ConstU128, ConstU32, ConstU64, ConstU8, Everything,
56 TransformOrigin,
57 },
58 weights::{
59 constants::WEIGHT_REF_TIME_PER_SECOND, ConstantMultiplier, FeePolynomial, WeightToFee as _,
60 WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial,
61 },
62 PalletId,
63};
64use frame_system::{
65 limits::{BlockLength, BlockWeights},
66 EnsureRoot, EnsureSigned, EnsureSignedBy,
67};
68use parachains_common::{
69 impls::{AssetsToBlockAuthor, NonZeroIssuance},
70 message_queue::{NarrowOriginToSibling, ParaIdToSibling},
71};
72use smallvec::smallvec;
73use sp_api::impl_runtime_apis;
74pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;
75use sp_core::{crypto::KeyTypeId, OpaqueMetadata};
76use sp_runtime::{
77 generic, impl_opaque_keys,
78 traits::{AccountIdConversion, AccountIdLookup, BlakeTwo256, Block as BlockT, Dispatchable},
79 transaction_validity::{TransactionSource, TransactionValidity},
80 ApplyExtrinsicResult,
81};
82pub use sp_runtime::{traits::ConvertInto, MultiAddress, Perbill, Permill};
83#[cfg(feature = "std")]
84use sp_version::NativeVersion;
85use sp_version::RuntimeVersion;
86use xcm_config::{ForeignAssetsAssetId, LocationToAccountId, XcmOriginToTransactDispatchOrigin};
87
88#[cfg(any(feature = "std", test))]
89pub use sp_runtime::BuildStorage;
90
91use parachains_common::{AccountId, Signature};
92use polkadot_runtime_common::{BlockHashCount, SlowAdjustingFeeUpdate};
93use weights::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight};
94use xcm::{
95 latest::prelude::{AssetId as AssetLocationId, BodyId},
96 VersionedAsset, VersionedAssetId, VersionedAssets, VersionedLocation, VersionedXcm,
97};
98use xcm_runtime_apis::{
99 dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects},
100 fees::Error as XcmPaymentApiError,
101};
102
103pub type Balance = u128;
105
106pub type Nonce = u32;
108
109pub type Hash = sp_core::H256;
111
112pub type BlockNumber = u32;
114
115pub type Address = MultiAddress<AccountId, ()>;
117
118pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
120
121pub type Block = generic::Block<Header, UncheckedExtrinsic>;
123
124pub type SignedBlock = generic::SignedBlock<Block>;
126
127pub type BlockId = generic::BlockId<Block>;
129
130pub type AssetId = u32;
132
133pub type TxExtension = (
135 frame_system::CheckNonZeroSender<Runtime>,
136 frame_system::CheckSpecVersion<Runtime>,
137 frame_system::CheckTxVersion<Runtime>,
138 frame_system::CheckGenesis<Runtime>,
139 frame_system::CheckEra<Runtime>,
140 frame_system::CheckNonce<Runtime>,
141 frame_system::CheckWeight<Runtime>,
142 pallet_asset_tx_payment::ChargeAssetTxPayment<Runtime>,
143);
144
145pub type UncheckedExtrinsic =
147 generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, TxExtension>;
148
149pub type Migrations = (
150 pallet_balances::migration::MigrateToTrackInactive<Runtime, xcm_config::CheckingAccount>,
151 pallet_collator_selection::migration::v1::MigrateToV1<Runtime>,
152);
153
154pub type Executive = frame_executive::Executive<
156 Runtime,
157 Block,
158 frame_system::ChainContext<Runtime>,
159 Runtime,
160 AllPalletsWithSystem,
161 Migrations,
162>;
163
164pub struct WeightToFee;
175impl frame_support::weights::WeightToFee for WeightToFee {
176 type Balance = Balance;
177
178 fn weight_to_fee(weight: &Weight) -> Self::Balance {
179 let time_poly: FeePolynomial<Balance> = RefTimeToFee::polynomial().into();
180 let proof_poly: FeePolynomial<Balance> = ProofSizeToFee::polynomial().into();
181
182 time_poly.eval(weight.ref_time()).max(proof_poly.eval(weight.proof_size()))
184 }
185}
186
187pub struct RefTimeToFee;
189impl WeightToFeePolynomial for RefTimeToFee {
190 type Balance = Balance;
191 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {
192 let p = MILLIUNIT / 10;
193 let q = 100 * Balance::from(ExtrinsicBaseWeight::get().ref_time());
194
195 smallvec![WeightToFeeCoefficient {
196 degree: 1,
197 negative: false,
198 coeff_frac: Perbill::from_rational(p % q, q),
199 coeff_integer: p / q,
200 }]
201 }
202}
203
204pub struct ProofSizeToFee;
206impl WeightToFeePolynomial for ProofSizeToFee {
207 type Balance = Balance;
208 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {
209 let p = MILLIUNIT / 10;
211 let q = 10_000;
212
213 smallvec![WeightToFeeCoefficient {
214 degree: 1,
215 negative: false,
216 coeff_frac: Perbill::from_rational(p % q, q),
217 coeff_integer: p / q,
218 }]
219 }
220}
221pub mod opaque {
226 use super::*;
227 use sp_runtime::{generic, traits::BlakeTwo256};
228
229 pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;
230 pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
232 pub type Block = generic::Block<Header, UncheckedExtrinsic>;
234 pub type BlockId = generic::BlockId<Block>;
236}
237
238impl_opaque_keys! {
239 pub struct SessionKeys {
240 pub aura: Aura,
241 }
242}
243
244#[sp_version::runtime_version]
245pub const VERSION: RuntimeVersion = RuntimeVersion {
246 spec_name: alloc::borrow::Cow::Borrowed("penpal-parachain"),
247 impl_name: alloc::borrow::Cow::Borrowed("penpal-parachain"),
248 authoring_version: 1,
249 spec_version: 1,
250 impl_version: 0,
251 apis: RUNTIME_API_VERSIONS,
252 transaction_version: 1,
253 system_version: 1,
254};
255
256pub const MILLISECS_PER_BLOCK: u64 = 12000;
263
264pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;
267
268pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);
270pub const HOURS: BlockNumber = MINUTES * 60;
271pub const DAYS: BlockNumber = HOURS * 24;
272
273pub const UNIT: Balance = 1_000_000_000_000;
275pub const MILLIUNIT: Balance = 1_000_000_000;
276pub const MICROUNIT: Balance = 1_000_000;
277
278pub const EXISTENTIAL_DEPOSIT: Balance = MILLIUNIT;
280
281const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(5);
284
285const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
288
289const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(
291 WEIGHT_REF_TIME_PER_SECOND.saturating_div(2),
292 cumulus_primitives_core::relay_chain::MAX_POV_SIZE as u64,
293);
294
295const UNINCLUDED_SEGMENT_CAPACITY: u32 = 1;
298const BLOCK_PROCESSING_VELOCITY: u32 = 1;
301const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6000;
303
304#[cfg(feature = "std")]
306pub fn native_version() -> NativeVersion {
307 NativeVersion { runtime_version: VERSION, can_author_with: Default::default() }
308}
309
310parameter_types! {
311 pub const Version: RuntimeVersion = VERSION;
312
313 pub RuntimeBlockLength: BlockLength =
318 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
319 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()
320 .base_block(BlockExecutionWeight::get())
321 .for_class(DispatchClass::all(), |weights| {
322 weights.base_extrinsic = ExtrinsicBaseWeight::get();
323 })
324 .for_class(DispatchClass::Normal, |weights| {
325 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
326 })
327 .for_class(DispatchClass::Operational, |weights| {
328 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
329 weights.reserved = Some(
332 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT
333 );
334 })
335 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
336 .build_or_panic();
337 pub const SS58Prefix: u16 = 42;
338}
339
340#[derive_impl(frame_system::config_preludes::TestDefaultConfig)]
343impl frame_system::Config for Runtime {
344 type AccountId = AccountId;
346 type RuntimeCall = RuntimeCall;
348 type Lookup = AccountIdLookup<AccountId, ()>;
350 type Nonce = Nonce;
352 type Hash = Hash;
354 type Hashing = BlakeTwo256;
356 type Block = Block;
358 type RuntimeEvent = RuntimeEvent;
360 type RuntimeOrigin = RuntimeOrigin;
362 type BlockHashCount = BlockHashCount;
364 type Version = Version;
366 type PalletInfo = PalletInfo;
368 type AccountData = pallet_balances::AccountData<Balance>;
370 type OnNewAccount = ();
372 type OnKilledAccount = ();
374 type DbWeight = RocksDbWeight;
376 type BaseCallFilter = Everything;
378 type SystemWeightInfo = ();
380 type BlockWeights = RuntimeBlockWeights;
382 type BlockLength = RuntimeBlockLength;
384 type SS58Prefix = SS58Prefix;
386 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;
388 type MaxConsumers = frame_support::traits::ConstU32<16>;
389}
390
391impl pallet_timestamp::Config for Runtime {
392 type Moment = u64;
394 type OnTimestampSet = Aura;
395 type MinimumPeriod = ConstU64<{ SLOT_DURATION / 2 }>;
396 type WeightInfo = ();
397}
398
399impl pallet_authorship::Config for Runtime {
400 type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Aura>;
401 type EventHandler = (CollatorSelection,);
402}
403
404parameter_types! {
405 pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
406}
407
408impl pallet_balances::Config for Runtime {
409 type MaxLocks = ConstU32<50>;
410 type Balance = Balance;
412 type RuntimeEvent = RuntimeEvent;
414 type DustRemoval = ();
415 type ExistentialDeposit = ExistentialDeposit;
416 type AccountStore = System;
417 type WeightInfo = pallet_balances::weights::SubstrateWeight<Runtime>;
418 type MaxReserves = ConstU32<50>;
419 type ReserveIdentifier = [u8; 8];
420 type RuntimeHoldReason = RuntimeHoldReason;
421 type RuntimeFreezeReason = RuntimeFreezeReason;
422 type FreezeIdentifier = ();
423 type MaxFreezes = ConstU32<0>;
424 type DoneSlashHandler = ();
425}
426
427parameter_types! {
428 pub const TransactionByteFee: Balance = 10 * MICROUNIT;
430}
431
432impl pallet_transaction_payment::Config for Runtime {
433 type RuntimeEvent = RuntimeEvent;
434 type OnChargeTransaction = pallet_transaction_payment::FungibleAdapter<Balances, ()>;
435 type WeightToFee = WeightToFee;
436 type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
437 type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
438 type OperationalFeeMultiplier = ConstU8<5>;
439 type WeightInfo = ();
440}
441
442parameter_types! {
443 pub const AssetDeposit: Balance = 0;
444 pub const AssetAccountDeposit: Balance = 0;
445 pub const ApprovalDeposit: Balance = 0;
446 pub const AssetsStringLimit: u32 = 50;
447 pub const MetadataDepositBase: Balance = 0;
448 pub const MetadataDepositPerByte: Balance = 0;
449}
450
451pub type TrustBackedAssetsInstance = pallet_assets::Instance1;
456
457impl pallet_assets::Config<TrustBackedAssetsInstance> for Runtime {
458 type RuntimeEvent = RuntimeEvent;
459 type Balance = Balance;
460 type AssetId = AssetId;
461 type AssetIdParameter = codec::Compact<AssetId>;
462 type Currency = Balances;
463 type CreateOrigin = AsEnsureOriginWithArg<EnsureSigned<AccountId>>;
464 type ForceOrigin = EnsureRoot<AccountId>;
465 type AssetDeposit = AssetDeposit;
466 type MetadataDepositBase = MetadataDepositBase;
467 type MetadataDepositPerByte = MetadataDepositPerByte;
468 type ApprovalDeposit = ApprovalDeposit;
469 type StringLimit = AssetsStringLimit;
470 type Freezer = ();
471 type Extra = ();
472 type WeightInfo = pallet_assets::weights::SubstrateWeight<Runtime>;
473 type CallbackHandle = ();
474 type AssetAccountDeposit = AssetAccountDeposit;
475 type RemoveItemsLimit = frame_support::traits::ConstU32<1000>;
476 #[cfg(feature = "runtime-benchmarks")]
477 type BenchmarkHelper = ();
478}
479
480parameter_types! {
481 pub const ForeignAssetsAssetDeposit: Balance = AssetDeposit::get();
483 pub const ForeignAssetsAssetAccountDeposit: Balance = AssetAccountDeposit::get();
484 pub const ForeignAssetsApprovalDeposit: Balance = ApprovalDeposit::get();
485 pub const ForeignAssetsAssetsStringLimit: u32 = AssetsStringLimit::get();
486 pub const ForeignAssetsMetadataDepositBase: Balance = MetadataDepositBase::get();
487 pub const ForeignAssetsMetadataDepositPerByte: Balance = MetadataDepositPerByte::get();
488}
489
490pub type ForeignAssetsInstance = pallet_assets::Instance2;
492impl pallet_assets::Config<ForeignAssetsInstance> for Runtime {
493 type RuntimeEvent = RuntimeEvent;
494 type Balance = Balance;
495 type AssetId = ForeignAssetsAssetId;
496 type AssetIdParameter = ForeignAssetsAssetId;
497 type Currency = Balances;
498 type CreateOrigin =
501 ForeignCreators<Everything, LocationToAccountId, AccountId, xcm::latest::Location>;
502 type ForceOrigin = EnsureRoot<AccountId>;
503 type AssetDeposit = ForeignAssetsAssetDeposit;
504 type MetadataDepositBase = ForeignAssetsMetadataDepositBase;
505 type MetadataDepositPerByte = ForeignAssetsMetadataDepositPerByte;
506 type ApprovalDeposit = ForeignAssetsApprovalDeposit;
507 type StringLimit = ForeignAssetsAssetsStringLimit;
508 type Freezer = ();
509 type Extra = ();
510 type WeightInfo = pallet_assets::weights::SubstrateWeight<Runtime>;
511 type CallbackHandle = ();
512 type AssetAccountDeposit = ForeignAssetsAssetAccountDeposit;
513 type RemoveItemsLimit = frame_support::traits::ConstU32<1000>;
514 #[cfg(feature = "runtime-benchmarks")]
515 type BenchmarkHelper = xcm_config::XcmBenchmarkHelper;
516}
517
518parameter_types! {
519 pub const AssetConversionPalletId: PalletId = PalletId(*b"py/ascon");
520 pub const LiquidityWithdrawalFee: Permill = Permill::from_percent(0);
521}
522
523ord_parameter_types! {
524 pub const AssetConversionOrigin: sp_runtime::AccountId32 =
525 AccountIdConversion::<sp_runtime::AccountId32>::into_account_truncating(&AssetConversionPalletId::get());
526}
527
528pub type AssetsForceOrigin = EnsureRoot<AccountId>;
529
530pub type PoolAssetsInstance = pallet_assets::Instance3;
531impl pallet_assets::Config<PoolAssetsInstance> for Runtime {
532 type RuntimeEvent = RuntimeEvent;
533 type Balance = Balance;
534 type RemoveItemsLimit = ConstU32<1000>;
535 type AssetId = u32;
536 type AssetIdParameter = u32;
537 type Currency = Balances;
538 type CreateOrigin =
539 AsEnsureOriginWithArg<EnsureSignedBy<AssetConversionOrigin, sp_runtime::AccountId32>>;
540 type ForceOrigin = AssetsForceOrigin;
541 type AssetDeposit = ConstU128<0>;
542 type AssetAccountDeposit = ConstU128<0>;
543 type MetadataDepositBase = ConstU128<0>;
544 type MetadataDepositPerByte = ConstU128<0>;
545 type ApprovalDeposit = ConstU128<0>;
546 type StringLimit = ConstU32<50>;
547 type Freezer = ();
548 type Extra = ();
549 type WeightInfo = pallet_assets::weights::SubstrateWeight<Runtime>;
550 type CallbackHandle = ();
551 #[cfg(feature = "runtime-benchmarks")]
552 type BenchmarkHelper = ();
553}
554
555pub type LocalAndForeignAssets = fungibles::UnionOf<
557 Assets,
558 ForeignAssets,
559 LocalFromLeft<
560 AssetIdForTrustBackedAssetsConvert<
561 xcm_config::TrustBackedAssetsPalletLocation,
562 xcm::latest::Location,
563 >,
564 parachains_common::AssetIdForTrustBackedAssets,
565 xcm::latest::Location,
566 >,
567 xcm::latest::Location,
568 AccountId,
569>;
570
571pub type NativeAndAssets = fungible::UnionOf<
573 Balances,
574 LocalAndForeignAssets,
575 TargetFromLeft<xcm_config::RelayLocation, xcm::latest::Location>,
576 xcm::latest::Location,
577 AccountId,
578>;
579
580pub type PoolIdToAccountId = pallet_asset_conversion::AccountIdConverter<
581 AssetConversionPalletId,
582 (xcm::latest::Location, xcm::latest::Location),
583>;
584
585impl pallet_asset_conversion::Config for Runtime {
586 type RuntimeEvent = RuntimeEvent;
587 type Balance = Balance;
588 type HigherPrecisionBalance = sp_core::U256;
589 type AssetKind = xcm::latest::Location;
590 type Assets = NativeAndAssets;
591 type PoolId = (Self::AssetKind, Self::AssetKind);
592 type PoolLocator = pallet_asset_conversion::WithFirstAsset<
593 xcm_config::RelayLocation,
594 AccountId,
595 Self::AssetKind,
596 PoolIdToAccountId,
597 >;
598 type PoolAssetId = u32;
599 type PoolAssets = PoolAssets;
600 type PoolSetupFee = ConstU128<0>; type PoolSetupFeeAsset = xcm_config::RelayLocation;
602 type PoolSetupFeeTarget = ResolveAssetTo<AssetConversionOrigin, Self::Assets>;
603 type LiquidityWithdrawalFee = LiquidityWithdrawalFee;
604 type LPFee = ConstU32<3>;
605 type PalletId = AssetConversionPalletId;
606 type MaxSwapPathLength = ConstU32<3>;
607 type MintMinLiquidity = ConstU128<100>;
608 type WeightInfo = ();
609 #[cfg(feature = "runtime-benchmarks")]
610 type BenchmarkHelper = assets_common::benchmarks::AssetPairFactory<
611 xcm_config::RelayLocation,
612 parachain_info::Pallet<Runtime>,
613 xcm_config::TrustBackedAssetsPalletIndex,
614 xcm::latest::Location,
615 >;
616}
617
618parameter_types! {
619 pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
620 pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
621 pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
622}
623
624impl cumulus_pallet_parachain_system::Config for Runtime {
625 type WeightInfo = ();
626 type RuntimeEvent = RuntimeEvent;
627 type OnSystemEvent = ();
628 type SelfParaId = parachain_info::Pallet<Runtime>;
629 type DmpQueue = frame_support::traits::EnqueueWithOrigin<MessageQueue, RelayOrigin>;
630 type ReservedDmpWeight = ReservedDmpWeight;
631 type OutboundXcmpMessageSource = XcmpQueue;
632 type XcmpMessageHandler = XcmpQueue;
633 type ReservedXcmpWeight = ReservedXcmpWeight;
634 type CheckAssociatedRelayNumber = RelayNumberStrictlyIncreases;
635 type ConsensusHook = cumulus_pallet_aura_ext::FixedVelocityConsensusHook<
636 Runtime,
637 RELAY_CHAIN_SLOT_DURATION_MILLIS,
638 BLOCK_PROCESSING_VELOCITY,
639 UNINCLUDED_SEGMENT_CAPACITY,
640 >;
641 type SelectCore = cumulus_pallet_parachain_system::DefaultCoreSelector<Runtime>;
642}
643
644impl parachain_info::Config for Runtime {}
645
646parameter_types! {
647 pub MessageQueueServiceWeight: Weight = Perbill::from_percent(35) * RuntimeBlockWeights::get().max_block;
648}
649
650impl pallet_message_queue::Config for Runtime {
651 type RuntimeEvent = RuntimeEvent;
652 type WeightInfo = ();
653 type MessageProcessor = xcm_builder::ProcessXcmMessage<
654 AggregateMessageOrigin,
655 xcm_executor::XcmExecutor<xcm_config::XcmConfig>,
656 RuntimeCall,
657 >;
658 type Size = u32;
659 type QueueChangeHandler = NarrowOriginToSibling<XcmpQueue>;
661 type QueuePausedQuery = NarrowOriginToSibling<XcmpQueue>;
662 type HeapSize = sp_core::ConstU32<{ 103 * 1024 }>;
663 type MaxStale = sp_core::ConstU32<8>;
664 type ServiceWeight = MessageQueueServiceWeight;
665 type IdleMaxServiceWeight = MessageQueueServiceWeight;
666}
667
668impl cumulus_pallet_aura_ext::Config for Runtime {}
669
670parameter_types! {
671 pub FeeAssetId: AssetLocationId = AssetLocationId(xcm_config::RelayLocation::get());
673 pub const BaseDeliveryFee: u128 = (1_000_000_000_000u128 / 100).saturating_mul(3);
675}
676
677pub type PriceForSiblingParachainDelivery = polkadot_runtime_common::xcm_sender::ExponentialPrice<
678 FeeAssetId,
679 BaseDeliveryFee,
680 TransactionByteFee,
681 XcmpQueue,
682>;
683
684impl cumulus_pallet_xcmp_queue::Config for Runtime {
685 type RuntimeEvent = RuntimeEvent;
686 type ChannelInfo = ParachainSystem;
687 type VersionWrapper = PolkadotXcm;
688 type XcmpQueue = TransformOrigin<MessageQueue, AggregateMessageOrigin, ParaId, ParaIdToSibling>;
690 type MaxInboundSuspended = ConstU32<1_000>;
691 type MaxActiveOutboundChannels = ConstU32<128>;
692 type MaxPageSize = ConstU32<{ 103 * 1024 }>;
695 type ControllerOrigin = EnsureRoot<AccountId>;
696 type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;
697 type WeightInfo = ();
698 type PriceForSiblingDelivery = PriceForSiblingParachainDelivery;
699}
700
701parameter_types! {
702 pub const Period: u32 = 6 * HOURS;
703 pub const Offset: u32 = 0;
704}
705
706impl pallet_session::Config for Runtime {
707 type RuntimeEvent = RuntimeEvent;
708 type ValidatorId = <Self as frame_system::Config>::AccountId;
709 type ValidatorIdOf = pallet_collator_selection::IdentityCollator;
711 type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>;
712 type NextSessionRotation = pallet_session::PeriodicSessions<Period, Offset>;
713 type SessionManager = CollatorSelection;
714 type SessionHandler = <SessionKeys as sp_runtime::traits::OpaqueKeys>::KeyTypeIdProviders;
716 type Keys = SessionKeys;
717 type WeightInfo = ();
718}
719
720impl pallet_aura::Config for Runtime {
721 type AuthorityId = AuraId;
722 type DisabledValidators = ();
723 type MaxAuthorities = ConstU32<100_000>;
724 type AllowMultipleBlocksPerSlot = ConstBool<false>;
725 type SlotDuration = pallet_aura::MinimumPeriodTimesTwo<Self>;
726}
727
728parameter_types! {
729 pub const PotId: PalletId = PalletId(*b"PotStake");
730 pub const SessionLength: BlockNumber = 6 * HOURS;
731 pub const ExecutiveBody: BodyId = BodyId::Executive;
732}
733
734pub type CollatorSelectionUpdateOrigin = EnsureRoot<AccountId>;
736
737impl pallet_collator_selection::Config for Runtime {
738 type RuntimeEvent = RuntimeEvent;
739 type Currency = Balances;
740 type UpdateOrigin = CollatorSelectionUpdateOrigin;
741 type PotId = PotId;
742 type MaxCandidates = ConstU32<100>;
743 type MinEligibleCollators = ConstU32<4>;
744 type MaxInvulnerables = ConstU32<20>;
745 type KickThreshold = Period;
747 type ValidatorId = <Self as frame_system::Config>::AccountId;
748 type ValidatorIdOf = pallet_collator_selection::IdentityCollator;
749 type ValidatorRegistration = Session;
750 type WeightInfo = ();
751}
752
753#[cfg(feature = "runtime-benchmarks")]
754pub struct AssetTxHelper;
755
756#[cfg(feature = "runtime-benchmarks")]
757impl pallet_asset_tx_payment::BenchmarkHelperTrait<AccountId, u32, u32> for AssetTxHelper {
758 fn create_asset_id_parameter(_id: u32) -> (u32, u32) {
759 unimplemented!("Penpal uses default weights");
760 }
761 fn setup_balances_and_pool(_asset_id: u32, _account: AccountId) {
762 unimplemented!("Penpal uses default weights");
763 }
764}
765
766impl pallet_asset_tx_payment::Config for Runtime {
767 type RuntimeEvent = RuntimeEvent;
768 type Fungibles = Assets;
769 type OnChargeAssetTransaction = pallet_asset_tx_payment::FungiblesAdapter<
770 pallet_assets::BalanceToAssetBalance<
771 Balances,
772 Runtime,
773 ConvertInto,
774 TrustBackedAssetsInstance,
775 >,
776 AssetsToBlockAuthor<Runtime, TrustBackedAssetsInstance>,
777 >;
778 type WeightInfo = ();
779 #[cfg(feature = "runtime-benchmarks")]
780 type BenchmarkHelper = AssetTxHelper;
781}
782
783impl pallet_sudo::Config for Runtime {
784 type RuntimeEvent = RuntimeEvent;
785 type RuntimeCall = RuntimeCall;
786 type WeightInfo = pallet_sudo::weights::SubstrateWeight<Runtime>;
787}
788
789construct_runtime!(
791 pub enum Runtime
792 {
793 System: frame_system = 0,
795 ParachainSystem: cumulus_pallet_parachain_system = 1,
796 Timestamp: pallet_timestamp = 2,
797 ParachainInfo: parachain_info = 3,
798
799 Balances: pallet_balances = 10,
801 TransactionPayment: pallet_transaction_payment = 11,
802 AssetTxPayment: pallet_asset_tx_payment = 12,
803
804 Authorship: pallet_authorship = 20,
806 CollatorSelection: pallet_collator_selection = 21,
807 Session: pallet_session = 22,
808 Aura: pallet_aura = 23,
809 AuraExt: cumulus_pallet_aura_ext = 24,
810
811 XcmpQueue: cumulus_pallet_xcmp_queue = 30,
813 PolkadotXcm: pallet_xcm = 31,
814 CumulusXcm: cumulus_pallet_xcm = 32,
815 MessageQueue: pallet_message_queue = 34,
816
817 Assets: pallet_assets::<Instance1> = 50,
819 ForeignAssets: pallet_assets::<Instance2> = 51,
820 PoolAssets: pallet_assets::<Instance3> = 52,
821 AssetConversion: pallet_asset_conversion = 53,
822
823 Sudo: pallet_sudo = 255,
824 }
825);
826
827#[cfg(feature = "runtime-benchmarks")]
828mod benches {
829 frame_benchmarking::define_benchmarks!(
830 [frame_system, SystemBench::<Runtime>]
831 [frame_system_extensions, SystemExtensionsBench::<Runtime>]
832 [pallet_balances, Balances]
833 [pallet_message_queue, MessageQueue]
834 [pallet_session, SessionBench::<Runtime>]
835 [pallet_sudo, Sudo]
836 [pallet_timestamp, Timestamp]
837 [pallet_collator_selection, CollatorSelection]
838 [cumulus_pallet_parachain_system, ParachainSystem]
839 [cumulus_pallet_xcmp_queue, XcmpQueue]
840 );
841}
842
843impl_runtime_apis! {
844 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {
845 fn slot_duration() -> sp_consensus_aura::SlotDuration {
846 sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())
847 }
848
849 fn authorities() -> Vec<AuraId> {
850 pallet_aura::Authorities::<Runtime>::get().into_inner()
851 }
852 }
853
854 impl sp_api::Core<Block> for Runtime {
855 fn version() -> RuntimeVersion {
856 VERSION
857 }
858
859 fn execute_block(block: Block) {
860 Executive::execute_block(block)
861 }
862
863 fn initialize_block(header: &<Block as BlockT>::Header) -> sp_runtime::ExtrinsicInclusionMode {
864 Executive::initialize_block(header)
865 }
866 }
867
868 impl sp_api::Metadata<Block> for Runtime {
869 fn metadata() -> OpaqueMetadata {
870 OpaqueMetadata::new(Runtime::metadata().into())
871 }
872
873 fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
874 Runtime::metadata_at_version(version)
875 }
876
877 fn metadata_versions() -> alloc::vec::Vec<u32> {
878 Runtime::metadata_versions()
879 }
880 }
881
882 impl sp_block_builder::BlockBuilder<Block> for Runtime {
883 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
884 Executive::apply_extrinsic(extrinsic)
885 }
886
887 fn finalize_block() -> <Block as BlockT>::Header {
888 Executive::finalize_block()
889 }
890
891 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
892 data.create_extrinsics()
893 }
894
895 fn check_inherents(
896 block: Block,
897 data: sp_inherents::InherentData,
898 ) -> sp_inherents::CheckInherentsResult {
899 data.check_extrinsics(&block)
900 }
901 }
902
903 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
904 fn validate_transaction(
905 source: TransactionSource,
906 tx: <Block as BlockT>::Extrinsic,
907 block_hash: <Block as BlockT>::Hash,
908 ) -> TransactionValidity {
909 Executive::validate_transaction(source, tx, block_hash)
910 }
911 }
912
913 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
914 fn offchain_worker(header: &<Block as BlockT>::Header) {
915 Executive::offchain_worker(header)
916 }
917 }
918
919 impl sp_session::SessionKeys<Block> for Runtime {
920 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
921 SessionKeys::generate(seed)
922 }
923
924 fn decode_session_keys(
925 encoded: Vec<u8>,
926 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
927 SessionKeys::decode_into_raw_public_keys(&encoded)
928 }
929 }
930
931 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
932 fn account_nonce(account: AccountId) -> Nonce {
933 System::account_nonce(account)
934 }
935 }
936
937 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {
938 fn query_info(
939 uxt: <Block as BlockT>::Extrinsic,
940 len: u32,
941 ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
942 TransactionPayment::query_info(uxt, len)
943 }
944 fn query_fee_details(
945 uxt: <Block as BlockT>::Extrinsic,
946 len: u32,
947 ) -> pallet_transaction_payment::FeeDetails<Balance> {
948 TransactionPayment::query_fee_details(uxt, len)
949 }
950 fn query_weight_to_fee(weight: Weight) -> Balance {
951 TransactionPayment::weight_to_fee(weight)
952 }
953 fn query_length_to_fee(length: u32) -> Balance {
954 TransactionPayment::length_to_fee(length)
955 }
956 }
957
958 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi<Block, Balance, RuntimeCall>
959 for Runtime
960 {
961 fn query_call_info(
962 call: RuntimeCall,
963 len: u32,
964 ) -> pallet_transaction_payment::RuntimeDispatchInfo<Balance> {
965 TransactionPayment::query_call_info(call, len)
966 }
967 fn query_call_fee_details(
968 call: RuntimeCall,
969 len: u32,
970 ) -> pallet_transaction_payment::FeeDetails<Balance> {
971 TransactionPayment::query_call_fee_details(call, len)
972 }
973 fn query_weight_to_fee(weight: Weight) -> Balance {
974 TransactionPayment::weight_to_fee(weight)
975 }
976 fn query_length_to_fee(length: u32) -> Balance {
977 TransactionPayment::length_to_fee(length)
978 }
979 }
980
981 impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {
982 fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {
983 ParachainSystem::collect_collation_info(header)
984 }
985 }
986
987 impl cumulus_primitives_core::GetCoreSelectorApi<Block> for Runtime {
988 fn core_selector() -> (CoreSelector, ClaimQueueOffset) {
989 ParachainSystem::core_selector()
990 }
991 }
992
993 impl xcm_runtime_apis::fees::XcmPaymentApi<Block> for Runtime {
994 fn query_acceptable_payment_assets(xcm_version: xcm::Version) -> Result<Vec<VersionedAssetId>, XcmPaymentApiError> {
995 let acceptable_assets = vec![AssetLocationId(xcm_config::RelayLocation::get())];
996 PolkadotXcm::query_acceptable_payment_assets(xcm_version, acceptable_assets)
997 }
998
999 fn query_weight_to_asset_fee(weight: Weight, asset: VersionedAssetId) -> Result<u128, XcmPaymentApiError> {
1000 match asset.try_as::<AssetLocationId>() {
1001 Ok(asset_id) if asset_id.0 == xcm_config::RelayLocation::get() => {
1002 Ok(WeightToFee::weight_to_fee(&weight))
1004 },
1005 Ok(asset_id) => {
1006 log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - unhandled asset_id: {asset_id:?}!");
1007 Err(XcmPaymentApiError::AssetNotFound)
1008 },
1009 Err(_) => {
1010 log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - failed to convert asset: {asset:?}!");
1011 Err(XcmPaymentApiError::VersionedConversionFailed)
1012 }
1013 }
1014 }
1015
1016 fn query_xcm_weight(message: VersionedXcm<()>) -> Result<Weight, XcmPaymentApiError> {
1017 PolkadotXcm::query_xcm_weight(message)
1018 }
1019
1020 fn query_delivery_fees(destination: VersionedLocation, message: VersionedXcm<()>) -> Result<VersionedAssets, XcmPaymentApiError> {
1021 PolkadotXcm::query_delivery_fees(destination, message)
1022 }
1023 }
1024
1025 impl xcm_runtime_apis::dry_run::DryRunApi<Block, RuntimeCall, RuntimeEvent, OriginCaller> for Runtime {
1026 fn dry_run_call(origin: OriginCaller, call: RuntimeCall) -> Result<CallDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
1027 use xcm_builder::InspectMessageQueues;
1028 use xcm_executor::RecordXcm;
1029 use xcm::prelude::*;
1030 pallet_xcm::Pallet::<Runtime>::set_record_xcm(true);
1031 frame_system::Pallet::<Runtime>::reset_events(); let result = call.dispatch(origin.into());
1033 pallet_xcm::Pallet::<Runtime>::set_record_xcm(false);
1034 let local_xcm = pallet_xcm::Pallet::<Runtime>::recorded_xcm();
1035 let forwarded_xcms = xcm_config::XcmRouter::get_messages();
1036 let events: Vec<RuntimeEvent> = System::read_events_no_consensus().map(|record| record.event.clone()).collect();
1037 Ok(CallDryRunEffects {
1038 local_xcm: local_xcm.map(VersionedXcm::<()>::from),
1039 forwarded_xcms,
1040 emitted_events: events,
1041 execution_result: result,
1042 })
1043 }
1044
1045 fn dry_run_xcm(origin_location: VersionedLocation, program: VersionedXcm<RuntimeCall>) -> Result<XcmDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
1046 use xcm_builder::InspectMessageQueues;
1047 use xcm::prelude::*;
1048
1049 let origin_location: Location = origin_location.try_into().map_err(|error| {
1050 log::error!(
1051 target: "xcm::DryRunApi::dry_run_xcm",
1052 "Location version conversion failed with error: {:?}",
1053 error,
1054 );
1055 XcmDryRunApiError::VersionedConversionFailed
1056 })?;
1057 let program: Xcm<RuntimeCall> = program.try_into().map_err(|error| {
1058 log::error!(
1059 target: "xcm::DryRunApi::dry_run_xcm",
1060 "Xcm version conversion failed with error {:?}",
1061 error,
1062 );
1063 XcmDryRunApiError::VersionedConversionFailed
1064 })?;
1065 let mut hash = program.using_encoded(sp_core::hashing::blake2_256);
1066 frame_system::Pallet::<Runtime>::reset_events(); let result = xcm_executor::XcmExecutor::<xcm_config::XcmConfig>::prepare_and_execute(
1068 origin_location,
1069 program,
1070 &mut hash,
1071 Weight::MAX, Weight::zero(),
1073 );
1074 let forwarded_xcms = xcm_config::XcmRouter::get_messages();
1075 let events: Vec<RuntimeEvent> = System::read_events_no_consensus().map(|record| record.event.clone()).collect();
1076 Ok(XcmDryRunEffects {
1077 forwarded_xcms,
1078 emitted_events: events,
1079 execution_result: result,
1080 })
1081 }
1082 }
1083
1084 #[cfg(feature = "try-runtime")]
1085 impl frame_try_runtime::TryRuntime<Block> for Runtime {
1086 fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) {
1087 let weight = Executive::try_runtime_upgrade(checks).unwrap();
1088 (weight, RuntimeBlockWeights::get().max_block)
1089 }
1090
1091 fn execute_block(
1092 block: Block,
1093 state_root_check: bool,
1094 signature_check: bool,
1095 select: frame_try_runtime::TryStateSelect,
1096 ) -> Weight {
1097 Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap()
1100 }
1101 }
1102
1103 #[cfg(feature = "runtime-benchmarks")]
1104 impl frame_benchmarking::Benchmark<Block> for Runtime {
1105 fn benchmark_metadata(extra: bool) -> (
1106 Vec<frame_benchmarking::BenchmarkList>,
1107 Vec<frame_support::traits::StorageInfo>,
1108 ) {
1109 use frame_benchmarking::{Benchmarking, BenchmarkList};
1110 use frame_support::traits::StorageInfoTrait;
1111 use frame_system_benchmarking::Pallet as SystemBench;
1112 use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
1113 use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
1114
1115 let mut list = Vec::<BenchmarkList>::new();
1116 list_benchmarks!(list, extra);
1117
1118 let storage_info = AllPalletsWithSystem::storage_info();
1119 (list, storage_info)
1120 }
1121
1122 fn dispatch_benchmark(
1123 config: frame_benchmarking::BenchmarkConfig
1124 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, alloc::string::String> {
1125 use frame_benchmarking::{Benchmarking, BenchmarkBatch};
1126 use sp_storage::TrackedStorageKey;
1127
1128 use frame_system_benchmarking::Pallet as SystemBench;
1129 use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
1130 impl frame_system_benchmarking::Config for Runtime {}
1131
1132 use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
1133 impl cumulus_pallet_session_benchmarking::Config for Runtime {}
1134
1135 let whitelist: Vec<TrackedStorageKey> = vec![
1136 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),
1138 hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),
1140 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),
1142 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),
1144 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),
1146 ];
1147
1148 let mut batches = Vec::<BenchmarkBatch>::new();
1149 let params = (&config, &whitelist);
1150 add_benchmarks!(params, batches);
1151
1152 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }
1153 Ok(batches)
1154 }
1155 }
1156
1157 impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
1158 fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
1159 build_state::<RuntimeGenesisConfig>(config)
1160 }
1161
1162 fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
1163 get_preset::<RuntimeGenesisConfig>(id, |_| None)
1164 }
1165
1166 fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
1167 vec![]
1168 }
1169 }
1170
1171 impl xcm_runtime_apis::trusted_query::TrustedQueryApi<Block> for Runtime {
1172 fn is_trusted_reserve(asset: VersionedAsset, location: VersionedLocation) -> xcm_runtime_apis::trusted_query::XcmTrustedQueryResult {
1173 PolkadotXcm::is_trusted_reserve(asset, location)
1174 }
1175 fn is_trusted_teleporter(asset: VersionedAsset, location: VersionedLocation) -> xcm_runtime_apis::trusted_query::XcmTrustedQueryResult {
1176 PolkadotXcm::is_trusted_teleporter(asset, location)
1177 }
1178 }
1179}
1180
1181cumulus_pallet_parachain_system::register_validate_block! {
1182 Runtime = Runtime,
1183 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,
1184}