1#![feature(variant_count)]
2#![cfg_attr(not(feature = "std"), no_std)]
3#![recursion_limit = "256"]
5
6#[cfg(feature = "std")]
8include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
9
10extern crate alloc;
11
12use alloc::borrow::Cow;
13#[cfg(not(feature = "std"))]
14use alloc::format;
15use core::mem;
16use domain_runtime_primitives::opaque::Header;
17pub use domain_runtime_primitives::{
18 block_weights, maximum_block_length, opaque, AccountId, Address, Balance, BlockNumber, Hash,
19 Nonce, Signature, EXISTENTIAL_DEPOSIT, MAX_OUTGOING_MESSAGES,
20};
21use domain_runtime_primitives::{
22 CheckExtrinsicsValidityError, DecodeExtrinsicError, HoldIdentifier, TargetBlockFullness,
23 ERR_BALANCE_OVERFLOW, SLOT_DURATION,
24};
25use frame_support::dispatch::{DispatchClass, DispatchInfo, GetDispatchInfo};
26use frame_support::genesis_builder_helper::{build_state, get_preset};
27use frame_support::inherent::ProvideInherent;
28use frame_support::pallet_prelude::TypeInfo;
29use frame_support::traits::fungible::Credit;
30use frame_support::traits::{
31 ConstU16, ConstU32, ConstU64, Everything, Imbalance, OnUnbalanced, VariantCount,
32};
33use frame_support::weights::constants::ParityDbWeight;
34use frame_support::weights::{ConstantMultiplier, IdentityFee, Weight};
35use frame_support::{construct_runtime, parameter_types};
36use frame_system::limits::{BlockLength, BlockWeights};
37use pallet_block_fees::fees::OnChargeDomainTransaction;
38use pallet_transporter::EndpointHandler;
39use parity_scale_codec::{Decode, DecodeLimit, Encode, MaxEncodedLen};
40use sp_api::impl_runtime_apis;
41use sp_core::crypto::KeyTypeId;
42use sp_core::{Get, OpaqueMetadata};
43use sp_domains::{ChannelId, DomainAllowlistUpdates, DomainId, Transfers};
44use sp_messenger::endpoint::{Endpoint, EndpointHandler as EndpointHandlerT, EndpointId};
45use sp_messenger::messages::{
46 BlockMessagesWithStorageKey, ChainId, CrossDomainMessage, FeeModel, MessageId, MessageKey,
47};
48use sp_messenger::{ChannelNonce, XdmId};
49use sp_messenger_host_functions::{get_storage_key, StorageKeyRequest};
50use sp_mmr_primitives::EncodableOpaqueLeaf;
51use sp_runtime::generic::{Era, ExtrinsicFormat, Preamble};
52use sp_runtime::traits::{
53 AccountIdLookup, BlakeTwo256, Block as BlockT, Checkable, DispatchTransaction, Keccak256,
54 NumberFor, One, TransactionExtension, ValidateUnsigned, Zero,
55};
56use sp_runtime::transaction_validity::{
57 InvalidTransaction, TransactionSource, TransactionValidity, TransactionValidityError,
58};
59use sp_runtime::type_with_default::TypeWithDefault;
60use sp_runtime::{generic, impl_opaque_keys, ApplyExtrinsicResult, Digest, ExtrinsicInclusionMode};
61pub use sp_runtime::{MultiAddress, Perbill, Permill};
62use sp_std::collections::btree_set::BTreeSet;
63use sp_std::marker::PhantomData;
64use sp_std::prelude::*;
65use sp_subspace_mmr::domain_mmr_runtime_interface::{
66 is_consensus_block_finalized, verify_mmr_proof,
67};
68use sp_subspace_mmr::{ConsensusChainMmrLeafProof, MmrLeaf};
69use sp_version::RuntimeVersion;
70use static_assertions::const_assert;
71use subspace_runtime_primitives::utility::DefaultNonceProvider;
72use subspace_runtime_primitives::{
73 BlockNumber as ConsensusBlockNumber, DomainEventSegmentSize, Hash as ConsensusBlockHash,
74 Moment, SlowAdjustingFeeUpdate, XdmAdjustedWeightToFee, XdmFeeMultipler,
75 MAX_CALL_RECURSION_DEPTH, SSC,
76};
77
78pub type Block = generic::Block<Header, UncheckedExtrinsic>;
80
81pub type SignedBlock = generic::SignedBlock<Block>;
83
84pub type BlockId = generic::BlockId<Block>;
86
87pub type SignedExtra = (
89 frame_system::CheckNonZeroSender<Runtime>,
90 frame_system::CheckSpecVersion<Runtime>,
91 frame_system::CheckTxVersion<Runtime>,
92 frame_system::CheckGenesis<Runtime>,
93 frame_system::CheckMortality<Runtime>,
94 frame_system::CheckNonce<Runtime>,
95 domain_check_weight::CheckWeight<Runtime>,
96 pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
97 pallet_messenger::extensions::MessengerExtension<Runtime>,
98);
99
100pub type CustomSignedExtra = (
102 frame_system::CheckNonZeroSender<Runtime>,
103 frame_system::CheckSpecVersion<Runtime>,
104 frame_system::CheckTxVersion<Runtime>,
105 frame_system::CheckGenesis<Runtime>,
106 frame_system::CheckMortality<Runtime>,
107 frame_system::CheckNonce<Runtime>,
108 domain_check_weight::CheckWeight<Runtime>,
109 pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
110 pallet_messenger::extensions::MessengerTrustedMmrExtension<Runtime>,
111);
112
113pub type UncheckedExtrinsic =
115 generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
116
117pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, RuntimeCall, SignedExtra>;
119
120pub type Executive = domain_pallet_executive::Executive<
122 Runtime,
123 frame_system::ChainContext<Runtime>,
124 Runtime,
125 AllPalletsWithSystem,
126>;
127
128impl_opaque_keys! {
129 pub struct SessionKeys {
130 pub operator: sp_domains::OperatorKey,
132 }
133}
134
135#[sp_version::runtime_version]
136pub const VERSION: RuntimeVersion = RuntimeVersion {
137 spec_name: Cow::Borrowed("subspace-auto-id-domain"),
138 impl_name: Cow::Borrowed("subspace-auto-id-domain"),
139 authoring_version: 0,
140 spec_version: 1,
141 impl_version: 0,
142 apis: RUNTIME_API_VERSIONS,
143 transaction_version: 0,
144 system_version: 2,
145};
146
147parameter_types! {
148 pub const Version: RuntimeVersion = VERSION;
149 pub const BlockHashCount: BlockNumber = 2400;
150 pub RuntimeBlockLength: BlockLength = maximum_block_length();
151 pub RuntimeBlockWeights: BlockWeights = block_weights();
152}
153
154impl frame_system::Config for Runtime {
155 type AccountId = AccountId;
157 type RuntimeCall = RuntimeCall;
159 type RuntimeTask = RuntimeTask;
161 type Lookup = AccountIdLookup<AccountId, ()>;
163 type Nonce = TypeWithDefault<Nonce, DefaultNonceProvider<System, Nonce>>;
165 type Hash = Hash;
167 type Hashing = BlakeTwo256;
169 type Block = Block;
171 type RuntimeEvent = RuntimeEvent;
173 type RuntimeOrigin = RuntimeOrigin;
175 type BlockHashCount = BlockHashCount;
177 type Version = Version;
179 type PalletInfo = PalletInfo;
181 type AccountData = pallet_balances::AccountData<Balance>;
183 type OnNewAccount = ();
185 type OnKilledAccount = ();
187 type DbWeight = ParityDbWeight;
189 type BaseCallFilter = Everything;
191 type SystemWeightInfo = frame_system::weights::SubstrateWeight<Runtime>;
193 type BlockWeights = RuntimeBlockWeights;
195 type BlockLength = RuntimeBlockLength;
197 type SS58Prefix = ConstU16<6094>;
198 type OnSetCode = ();
200 type SingleBlockMigrations = ();
201 type MultiBlockMigrator = ();
202 type PreInherents = ();
203 type PostInherents = ();
204 type PostTransactions = ();
205 type MaxConsumers = ConstU32<16>;
206 type ExtensionsWeightInfo = frame_system::ExtensionsWeight<Runtime>;
207 type EventSegmentSize = DomainEventSegmentSize;
208}
209
210impl pallet_timestamp::Config for Runtime {
211 type Moment = Moment;
213 type OnTimestampSet = ();
214 type MinimumPeriod = ConstU64<{ SLOT_DURATION / 2 }>;
215 type WeightInfo = pallet_timestamp::weights::SubstrateWeight<Runtime>;
216}
217
218parameter_types! {
219 pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
220 pub const MaxLocks: u32 = 50;
221 pub const MaxReserves: u32 = 50;
222}
223
224pub struct DustRemovalHandler;
226
227impl OnUnbalanced<Credit<AccountId, Balances>> for DustRemovalHandler {
228 fn on_nonzero_unbalanced(dusted_amount: Credit<AccountId, Balances>) {
229 BlockFees::note_burned_balance(dusted_amount.peek());
230 }
231}
232
233impl pallet_balances::Config for Runtime {
234 type RuntimeFreezeReason = RuntimeFreezeReason;
235 type MaxLocks = MaxLocks;
236 type Balance = Balance;
238 type RuntimeEvent = RuntimeEvent;
240 type DustRemoval = DustRemovalHandler;
241 type ExistentialDeposit = ExistentialDeposit;
242 type AccountStore = System;
243 type WeightInfo = pallet_balances::weights::SubstrateWeight<Runtime>;
244 type MaxReserves = MaxReserves;
245 type ReserveIdentifier = [u8; 8];
246 type FreezeIdentifier = ();
247 type MaxFreezes = ();
248 type RuntimeHoldReason = HoldIdentifierWrapper;
249 type DoneSlashHandler = ();
250}
251
252parameter_types! {
253 pub const OperationalFeeMultiplier: u8 = 5;
254 pub const DomainChainByteFee: Balance = 1;
255}
256
257impl pallet_block_fees::Config for Runtime {
258 type Balance = Balance;
259 type DomainChainByteFee = DomainChainByteFee;
260}
261
262pub struct FinalDomainTransactionByteFee;
263
264impl Get<Balance> for FinalDomainTransactionByteFee {
265 fn get() -> Balance {
266 BlockFees::final_domain_transaction_byte_fee()
267 }
268}
269
270impl pallet_transaction_payment::Config for Runtime {
271 type RuntimeEvent = RuntimeEvent;
272 type OnChargeTransaction = OnChargeDomainTransaction<Balances>;
273 type WeightToFee = IdentityFee<Balance>;
274 type LengthToFee = ConstantMultiplier<Balance, FinalDomainTransactionByteFee>;
275 type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Runtime, TargetBlockFullness>;
276 type OperationalFeeMultiplier = OperationalFeeMultiplier;
277 type WeightInfo = pallet_transaction_payment::weights::SubstrateWeight<Runtime>;
278}
279
280impl pallet_auto_id::Config for Runtime {
281 type RuntimeEvent = RuntimeEvent;
282 type Time = Timestamp;
283 type Weights = pallet_auto_id::weights::SubstrateWeight<Self>;
284}
285
286pub struct ExtrinsicStorageFees;
287
288impl domain_pallet_executive::ExtrinsicStorageFees<Runtime> for ExtrinsicStorageFees {
289 fn extract_signer(xt: UncheckedExtrinsic) -> (Option<AccountId>, DispatchInfo) {
290 let dispatch_info = xt.get_dispatch_info();
291 let lookup = frame_system::ChainContext::<Runtime>::default();
292 let maybe_signer = extract_signer_inner(&xt, &lookup).and_then(|res| res.ok());
293 (maybe_signer, dispatch_info)
294 }
295
296 fn on_storage_fees_charged(
297 charged_fees: Balance,
298 tx_size: u32,
299 ) -> Result<(), TransactionValidityError> {
300 let consensus_storage_fee = BlockFees::consensus_chain_byte_fee()
301 .checked_mul(Balance::from(tx_size))
302 .ok_or(InvalidTransaction::Custom(ERR_BALANCE_OVERFLOW))?;
303
304 let (paid_consensus_storage_fee, paid_domain_fee) = if charged_fees <= consensus_storage_fee
305 {
306 (charged_fees, Zero::zero())
307 } else {
308 (consensus_storage_fee, charged_fees - consensus_storage_fee)
309 };
310
311 BlockFees::note_consensus_storage_fee(paid_consensus_storage_fee);
312 BlockFees::note_domain_execution_fee(paid_domain_fee);
313 Ok(())
314 }
315}
316
317impl domain_pallet_executive::Config for Runtime {
318 type RuntimeEvent = RuntimeEvent;
319 type WeightInfo = domain_pallet_executive::weights::SubstrateWeight<Runtime>;
320 type Currency = Balances;
321 type LengthToFee = <Runtime as pallet_transaction_payment::Config>::LengthToFee;
322 type ExtrinsicStorageFees = ExtrinsicStorageFees;
323}
324
325parameter_types! {
326 pub SelfChainId: ChainId = SelfDomainId::self_domain_id().into();
327}
328
329pub struct OnXDMRewards;
330
331impl sp_messenger::OnXDMRewards<Balance> for OnXDMRewards {
332 fn on_xdm_rewards(rewards: Balance) {
333 BlockFees::note_domain_execution_fee(rewards)
334 }
335 fn on_chain_protocol_fees(chain_id: ChainId, fees: Balance) {
336 BlockFees::note_chain_rewards(chain_id, fees);
338 }
339}
340
341type MmrHash = <Keccak256 as sp_runtime::traits::Hash>::Output;
342
343pub struct MmrProofVerifier;
344
345impl sp_subspace_mmr::MmrProofVerifier<MmrHash, NumberFor<Block>, Hash> for MmrProofVerifier {
346 fn verify_proof_and_extract_leaf(
347 mmr_leaf_proof: ConsensusChainMmrLeafProof<NumberFor<Block>, Hash, MmrHash>,
348 ) -> Option<MmrLeaf<ConsensusBlockNumber, ConsensusBlockHash>> {
349 let ConsensusChainMmrLeafProof {
350 consensus_block_number,
351 opaque_mmr_leaf: opaque_leaf,
352 proof,
353 ..
354 } = mmr_leaf_proof;
355
356 if !is_consensus_block_finalized(consensus_block_number) {
357 return None;
358 }
359
360 let leaf: MmrLeaf<ConsensusBlockNumber, ConsensusBlockHash> =
361 opaque_leaf.into_opaque_leaf().try_decode()?;
362
363 verify_mmr_proof(vec![EncodableOpaqueLeaf::from_leaf(&leaf)], proof.encode())
364 .then_some(leaf)
365 }
366}
367
368pub struct StorageKeys;
369
370impl sp_messenger::StorageKeys for StorageKeys {
371 fn confirmed_domain_block_storage_key(domain_id: DomainId) -> Option<Vec<u8>> {
372 get_storage_key(StorageKeyRequest::ConfirmedDomainBlockStorageKey(domain_id))
373 }
374
375 fn outbox_storage_key(chain_id: ChainId, message_key: MessageKey) -> Option<Vec<u8>> {
376 get_storage_key(StorageKeyRequest::OutboxStorageKey {
377 chain_id,
378 message_key,
379 })
380 }
381
382 fn inbox_responses_storage_key(chain_id: ChainId, message_key: MessageKey) -> Option<Vec<u8>> {
383 get_storage_key(StorageKeyRequest::InboxResponseStorageKey {
384 chain_id,
385 message_key,
386 })
387 }
388}
389
390#[derive(
392 PartialEq, Eq, Clone, Encode, Decode, TypeInfo, MaxEncodedLen, Ord, PartialOrd, Copy, Debug,
393)]
394pub struct HoldIdentifierWrapper(HoldIdentifier);
395
396impl VariantCount for HoldIdentifierWrapper {
397 const VARIANT_COUNT: u32 = mem::variant_count::<HoldIdentifier>() as u32;
398}
399
400impl pallet_messenger::HoldIdentifier<Runtime> for HoldIdentifierWrapper {
401 fn messenger_channel() -> Self {
402 Self(HoldIdentifier::MessengerChannel)
403 }
404}
405
406parameter_types! {
407 pub const ChannelReserveFee: Balance = 100 * SSC;
408 pub const ChannelInitReservePortion: Perbill = Perbill::from_percent(20);
409 pub const ChannelFeeModel: FeeModel<Balance> = FeeModel{relay_fee: SSC};
411 pub const MaxOutgoingMessages: u32 = MAX_OUTGOING_MESSAGES;
412 pub const MessageVersion: pallet_messenger::MessageVersion = pallet_messenger::MessageVersion::V1;
413}
414
415const_assert!(MaxOutgoingMessages::get() >= 1);
417
418impl pallet_messenger::Config for Runtime {
419 type RuntimeEvent = RuntimeEvent;
420 type SelfChainId = SelfChainId;
421
422 fn get_endpoint_handler(endpoint: &Endpoint) -> Option<Box<dyn EndpointHandlerT<MessageId>>> {
423 if endpoint == &Endpoint::Id(TransporterEndpointId::get()) {
424 Some(Box::new(EndpointHandler(PhantomData::<Runtime>)))
425 } else {
426 None
427 }
428 }
429
430 type Currency = Balances;
431 type WeightInfo = pallet_messenger::weights::SubstrateWeight<Runtime>;
432 type WeightToFee = IdentityFee<Balance>;
433 type AdjustedWeightToFee = XdmAdjustedWeightToFee<Runtime>;
434 type FeeMultiplier = XdmFeeMultipler;
435 type OnXDMRewards = OnXDMRewards;
436 type MmrHash = MmrHash;
437 type MmrProofVerifier = MmrProofVerifier;
438 type StorageKeys = StorageKeys;
439 type DomainOwner = ();
440 type HoldIdentifier = HoldIdentifierWrapper;
441 type ChannelReserveFee = ChannelReserveFee;
442 type ChannelInitReservePortion = ChannelInitReservePortion;
443 type DomainRegistration = ();
444 type ChannelFeeModel = ChannelFeeModel;
445 type MaxOutgoingMessages = MaxOutgoingMessages;
446 type MessengerOrigin = pallet_messenger::EnsureMessengerOrigin;
447 type MessageVersion = MessageVersion;
448 type NoteChainTransfer = Transporter;
449}
450
451impl<C> frame_system::offchain::CreateTransactionBase<C> for Runtime
452where
453 RuntimeCall: From<C>,
454{
455 type Extrinsic = UncheckedExtrinsic;
456 type RuntimeCall = RuntimeCall;
457}
458
459parameter_types! {
460 pub const TransporterEndpointId: EndpointId = 1;
461}
462
463impl pallet_transporter::Config for Runtime {
464 type RuntimeEvent = RuntimeEvent;
465 type SelfChainId = SelfChainId;
466 type SelfEndpointId = TransporterEndpointId;
467 type Currency = Balances;
468 type Sender = Messenger;
469 type AccountIdConverter = domain_runtime_primitives::AccountIdConverter;
470 type WeightInfo = pallet_transporter::weights::SubstrateWeight<Runtime>;
471 type SkipBalanceTransferChecks = ();
472}
473
474impl pallet_domain_id::Config for Runtime {}
475
476pub struct IntoRuntimeCall;
477
478impl sp_domain_sudo::IntoRuntimeCall<RuntimeCall> for IntoRuntimeCall {
479 fn runtime_call(call: Vec<u8>) -> RuntimeCall {
480 UncheckedExtrinsic::decode(&mut call.as_slice())
481 .expect("must always be a valid extrinsic as checked by consensus chain; qed")
482 .function
483 }
484}
485
486impl pallet_domain_sudo::Config for Runtime {
487 type RuntimeEvent = RuntimeEvent;
488 type RuntimeCall = RuntimeCall;
489 type IntoRuntimeCall = IntoRuntimeCall;
490}
491
492impl pallet_storage_overlay_checks::Config for Runtime {}
493
494construct_runtime!(
498 pub struct Runtime {
499 System: frame_system = 0,
501 Timestamp: pallet_timestamp = 1,
505 ExecutivePallet: domain_pallet_executive = 2,
506
507 Balances: pallet_balances = 20,
509 TransactionPayment: pallet_transaction_payment = 21,
510
511 AutoId: pallet_auto_id = 40,
513
514 Messenger: pallet_messenger = 60,
517 Transporter: pallet_transporter = 61,
518
519 SelfDomainId: pallet_domain_id = 90,
521 BlockFees: pallet_block_fees = 91,
522
523 Sudo: pallet_domain_sudo = 100,
525
526 StorageOverlayChecks: pallet_storage_overlay_checks = 200,
528 }
529);
530
531fn is_xdm_mmr_proof_valid(ext: &<Block as BlockT>::Extrinsic) -> Option<bool> {
532 match &ext.function {
533 RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })
534 | RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
535 let ConsensusChainMmrLeafProof {
536 consensus_block_number,
537 opaque_mmr_leaf,
538 proof,
539 ..
540 } = msg.proof.consensus_mmr_proof();
541
542 if !is_consensus_block_finalized(consensus_block_number) {
543 return Some(false);
544 }
545
546 Some(verify_mmr_proof(vec![opaque_mmr_leaf], proof.encode()))
547 }
548 _ => None,
549 }
550}
551
552fn is_valid_sudo_call(encoded_ext: Vec<u8>) -> bool {
554 UncheckedExtrinsic::decode_with_depth_limit(
555 MAX_CALL_RECURSION_DEPTH,
556 &mut encoded_ext.as_slice(),
557 )
558 .is_ok()
559}
560
561fn construct_sudo_call_extrinsic(encoded_ext: Vec<u8>) -> <Block as BlockT>::Extrinsic {
562 let ext = UncheckedExtrinsic::decode(&mut encoded_ext.as_slice()).expect(
563 "must always be a valid extrinsic due to the check above and storage proof check; qed",
564 );
565 UncheckedExtrinsic::new_bare(
566 pallet_domain_sudo::Call::sudo {
567 call: Box::new(ext.function),
568 }
569 .into(),
570 )
571}
572
573fn extract_signer_inner<Lookup>(
574 ext: &UncheckedExtrinsic,
575 lookup: &Lookup,
576) -> Option<Result<AccountId, TransactionValidityError>>
577where
578 Lookup: sp_runtime::traits::Lookup<Source = Address, Target = AccountId>,
579{
580 match &ext.preamble {
581 Preamble::Bare(_) | Preamble::General(_, _) => None,
582 Preamble::Signed(address, _, _) => {
583 Some(lookup.lookup(address.clone()).map_err(|e| e.into()))
584 }
585 }
586}
587
588pub fn extract_signer(
589 extrinsics: Vec<UncheckedExtrinsic>,
590) -> Vec<(Option<opaque::AccountId>, UncheckedExtrinsic)> {
591 let lookup = frame_system::ChainContext::<Runtime>::default();
592
593 extrinsics
594 .into_iter()
595 .map(|extrinsic| {
596 let maybe_signer =
597 extract_signer_inner(&extrinsic, &lookup).and_then(|account_result| {
598 account_result.ok().map(|account_id| account_id.encode())
599 });
600 (maybe_signer, extrinsic)
601 })
602 .collect()
603}
604
605fn extrinsic_era(extrinsic: &<Block as BlockT>::Extrinsic) -> Option<Era> {
606 match &extrinsic.preamble {
607 Preamble::Bare(_) | Preamble::General(_, _) => None,
608 Preamble::Signed(_, _, extra) => Some(extra.4 .0),
609 }
610}
611
612impl pallet_messenger::extensions::MaybeMessengerCall<Runtime> for RuntimeCall {
613 fn maybe_messenger_call(&self) -> Option<&pallet_messenger::Call<Runtime>> {
614 match self {
615 RuntimeCall::Messenger(call) => Some(call),
616 _ => None,
617 }
618 }
619}
620
621impl<C> subspace_runtime_primitives::CreateUnsigned<C> for Runtime
622where
623 RuntimeCall: From<C>,
624{
625 fn create_unsigned(call: Self::RuntimeCall) -> Self::Extrinsic {
626 create_unsigned_general_extrinsic(call)
627 }
628}
629
630fn create_unsigned_general_extrinsic(call: RuntimeCall) -> UncheckedExtrinsic {
631 let extra: SignedExtra = (
632 frame_system::CheckNonZeroSender::<Runtime>::new(),
633 frame_system::CheckSpecVersion::<Runtime>::new(),
634 frame_system::CheckTxVersion::<Runtime>::new(),
635 frame_system::CheckGenesis::<Runtime>::new(),
636 frame_system::CheckMortality::<Runtime>::from(generic::Era::Immortal),
637 frame_system::CheckNonce::<Runtime>::from(0u32.into()),
640 domain_check_weight::CheckWeight::<Runtime>::new(),
641 pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(0u128),
644 pallet_messenger::extensions::MessengerExtension::<Runtime>::new(),
645 );
646
647 UncheckedExtrinsic::new_transaction(call, extra)
648}
649
650#[cfg(feature = "runtime-benchmarks")]
651mod benches {
652 frame_benchmarking::define_benchmarks!(
653 [frame_benchmarking, BaselineBench::<Runtime>]
654 [frame_system, SystemBench::<Runtime>]
655 [domain_pallet_executive, ExecutivePallet]
656 [pallet_messenger, Messenger]
657 [pallet_auto_id, AutoId]
658 );
659}
660
661fn check_transaction_and_do_pre_dispatch_inner(
662 uxt: &<Block as BlockT>::Extrinsic,
663) -> Result<(), TransactionValidityError> {
664 let lookup = frame_system::ChainContext::<Runtime>::default();
665
666 let xt = uxt.clone().check(&lookup)?;
667
668 let dispatch_info = xt.get_dispatch_info();
669
670 if dispatch_info.class == DispatchClass::Mandatory {
671 return Err(InvalidTransaction::MandatoryValidation.into());
672 }
673
674 let encoded_len = uxt.encoded_size();
675
676 match xt.format {
681 ExtrinsicFormat::General(extension_version, extra) => {
682 let origin = RuntimeOrigin::none();
683 <SignedExtra as DispatchTransaction<RuntimeCall>>::validate_and_prepare(
684 extra,
685 origin,
686 &xt.function,
687 &dispatch_info,
688 encoded_len,
689 extension_version,
690 )
691 .map(|_| ())
692 }
693 ExtrinsicFormat::Signed(account_id, extra) => {
695 let custom_extra: CustomSignedExtra = (
696 extra.0,
697 extra.1,
698 extra.2,
699 extra.3,
700 extra.4,
701 extra.5,
702 extra.6.clone(),
703 extra.7,
704 pallet_messenger::extensions::MessengerTrustedMmrExtension::<Runtime>::new(),
705 );
706 let origin = RuntimeOrigin::signed(account_id);
707 <CustomSignedExtra as DispatchTransaction<RuntimeCall>>::validate_and_prepare(
708 custom_extra,
709 origin,
710 &xt.function,
711 &dispatch_info,
712 encoded_len,
713 0,
716 )
717 .map(|_| ())
718 }
719 ExtrinsicFormat::Bare => {
721 Runtime::pre_dispatch(&xt.function).map(|_| ())?;
722 <SignedExtra as TransactionExtension<RuntimeCall>>::bare_validate_and_prepare(
723 &xt.function,
724 &dispatch_info,
725 encoded_len,
726 )
727 .map(|_| ())
728 }
729 }
730}
731
732#[cfg(feature = "runtime-benchmarks")]
733impl frame_system_benchmarking::Config for Runtime {}
734
735#[cfg(feature = "runtime-benchmarks")]
736impl frame_benchmarking::baseline::Config for Runtime {}
737
738impl_runtime_apis! {
739 impl sp_api::Core<Block> for Runtime {
740 fn version() -> RuntimeVersion {
741 VERSION
742 }
743
744 fn execute_block(block: Block) {
745 Executive::execute_block(block)
746 }
747
748 fn initialize_block(header: &<Block as BlockT>::Header) -> ExtrinsicInclusionMode {
749 Executive::initialize_block(header)
750 }
751 }
752
753 impl sp_api::Metadata<Block> for Runtime {
754 fn metadata() -> OpaqueMetadata {
755 OpaqueMetadata::new(Runtime::metadata().into())
756 }
757
758 fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
759 Runtime::metadata_at_version(version)
760 }
761
762 fn metadata_versions() -> Vec<u32> {
763 Runtime::metadata_versions()
764 }
765 }
766
767 impl sp_block_builder::BlockBuilder<Block> for Runtime {
768 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
769 Executive::apply_extrinsic(extrinsic)
770 }
771
772 fn finalize_block() -> <Block as BlockT>::Header {
773 Executive::finalize_block()
774 }
775
776 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
777 data.create_extrinsics()
778 }
779
780 fn check_inherents(
781 block: Block,
782 data: sp_inherents::InherentData,
783 ) -> sp_inherents::CheckInherentsResult {
784 data.check_extrinsics(&block)
785 }
786 }
787
788 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
789 fn validate_transaction(
790 source: TransactionSource,
791 tx: <Block as BlockT>::Extrinsic,
792 block_hash: <Block as BlockT>::Hash,
793 ) -> TransactionValidity {
794 Executive::validate_transaction(source, tx, block_hash)
795 }
796 }
797
798 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
799 fn offchain_worker(header: &<Block as BlockT>::Header) {
800 Executive::offchain_worker(header)
801 }
802 }
803
804 impl sp_session::SessionKeys<Block> for Runtime {
805 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
806 SessionKeys::generate(seed)
807 }
808
809 fn decode_session_keys(
810 encoded: Vec<u8>,
811 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
812 SessionKeys::decode_into_raw_public_keys(&encoded)
813 }
814 }
815
816 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
817 fn account_nonce(account: AccountId) -> Nonce {
818 *System::account_nonce(account)
819 }
820 }
821
822 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {
823 fn query_info(
824 uxt: <Block as BlockT>::Extrinsic,
825 len: u32,
826 ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
827 TransactionPayment::query_info(uxt, len)
828 }
829 fn query_fee_details(
830 uxt: <Block as BlockT>::Extrinsic,
831 len: u32,
832 ) -> pallet_transaction_payment::FeeDetails<Balance> {
833 TransactionPayment::query_fee_details(uxt, len)
834 }
835 fn query_weight_to_fee(weight: Weight) -> Balance {
836 TransactionPayment::weight_to_fee(weight)
837 }
838 fn query_length_to_fee(length: u32) -> Balance {
839 TransactionPayment::length_to_fee(length)
840 }
841 }
842
843 impl sp_domains::core_api::DomainCoreApi<Block> for Runtime {
844 fn extract_signer(
845 extrinsics: Vec<<Block as BlockT>::Extrinsic>,
846 ) -> Vec<(Option<opaque::AccountId>, <Block as BlockT>::Extrinsic)> {
847 extract_signer(extrinsics)
848 }
849
850 fn is_within_tx_range(
851 extrinsic: &<Block as BlockT>::Extrinsic,
852 bundle_vrf_hash: &subspace_core_primitives::U256,
853 tx_range: &subspace_core_primitives::U256
854 ) -> bool {
855 use subspace_core_primitives::U256;
856 use subspace_core_primitives::hashes::blake3_hash;
857
858 let lookup = frame_system::ChainContext::<Runtime>::default();
859 if let Some(signer) = extract_signer_inner(extrinsic, &lookup).and_then(|account_result| {
860 account_result.ok().map(|account_id| account_id.encode())
861 }) {
862 let signer_id_hash = U256::from_be_bytes(*blake3_hash(&signer.encode()));
864 sp_domains::signer_in_tx_range(bundle_vrf_hash, &signer_id_hash, tx_range)
865 } else {
866 true
868 }
869 }
870
871 fn initialize_block_with_post_state_root(header: &<Block as BlockT>::Header) -> Vec<u8> {
872 Executive::initialize_block(header);
873 Executive::storage_root()
874 }
875
876 fn apply_extrinsic_with_post_state_root(extrinsic: <Block as BlockT>::Extrinsic) -> Vec<u8> {
877 let _ = Executive::apply_extrinsic(extrinsic);
878 Executive::storage_root()
879 }
880
881 fn construct_set_code_extrinsic(code: Vec<u8>) -> Vec<u8> {
882 UncheckedExtrinsic::new_bare(
883 domain_pallet_executive::Call::set_code {
884 code
885 }.into()
886 ).encode()
887 }
888
889 fn construct_timestamp_extrinsic(moment: Moment) -> <Block as BlockT>::Extrinsic {
890 UncheckedExtrinsic::new_bare(
891 pallet_timestamp::Call::set{ now: moment }.into()
892 )
893 }
894
895 fn is_inherent_extrinsic(extrinsic: &<Block as BlockT>::Extrinsic) -> bool {
896 match &extrinsic.function {
897 RuntimeCall::Timestamp(call) => Timestamp::is_inherent(call),
898 RuntimeCall::ExecutivePallet(call) => ExecutivePallet::is_inherent(call),
899 RuntimeCall::Messenger(call) => Messenger::is_inherent(call),
900 RuntimeCall::Sudo(call) => Sudo::is_inherent(call),
901 _ => false,
902 }
903 }
904
905 fn check_extrinsics_and_do_pre_dispatch(uxts: Vec<<Block as BlockT>::Extrinsic>, block_number: BlockNumber,
906 block_hash: <Block as BlockT>::Hash) -> Result<(), CheckExtrinsicsValidityError> {
907 System::initialize(
909 &(block_number + BlockNumber::one()),
910 &block_hash,
911 &Default::default(),
912 );
913
914 for (extrinsic_index, uxt) in uxts.iter().enumerate() {
915 check_transaction_and_do_pre_dispatch_inner(uxt).map_err(|e| {
916 CheckExtrinsicsValidityError {
917 extrinsic_index: extrinsic_index as u32,
918 transaction_validity_error: e
919 }
920 })?;
921 }
922
923 Ok(())
924 }
925
926 fn decode_extrinsic(
927 opaque_extrinsic: sp_runtime::OpaqueExtrinsic,
928 ) -> Result<<Block as BlockT>::Extrinsic, DecodeExtrinsicError> {
929 let encoded = opaque_extrinsic.encode();
930
931 UncheckedExtrinsic::decode_with_depth_limit(
932 MAX_CALL_RECURSION_DEPTH,
933 &mut encoded.as_slice(),
934 ).map_err(|err| DecodeExtrinsicError(format!("{}", err)))
935 }
936
937 fn extrinsic_era(
938 extrinsic: &<Block as BlockT>::Extrinsic
939 ) -> Option<Era> {
940 extrinsic_era(extrinsic)
941 }
942
943 fn extrinsic_weight(ext: &<Block as BlockT>::Extrinsic) -> Weight {
944 let len = ext.encoded_size() as u64;
945 let info = ext.get_dispatch_info();
946 info.call_weight
947 .saturating_add(<Runtime as frame_system::Config>::BlockWeights::get().get(info.class).base_extrinsic)
948 .saturating_add(Weight::from_parts(0, len)).saturating_add(info.extension_weight)
949 }
950
951 fn block_fees() -> sp_domains::BlockFees<Balance> {
952 BlockFees::collected_block_fees()
953 }
954
955 fn block_digest() -> Digest {
956 System::digest()
957 }
958
959 fn block_weight() -> Weight {
960 System::block_weight().total()
961 }
962
963 fn construct_consensus_chain_byte_fee_extrinsic(transaction_byte_fee: Balance) -> <Block as BlockT>::Extrinsic {
964 UncheckedExtrinsic::new_bare(
965 pallet_block_fees::Call::set_next_consensus_chain_byte_fee{ transaction_byte_fee }.into()
966 )
967 }
968
969 fn construct_domain_update_chain_allowlist_extrinsic(updates: DomainAllowlistUpdates) -> <Block as BlockT>::Extrinsic {
970 UncheckedExtrinsic::new_bare(
971 pallet_messenger::Call::update_domain_allowlist{ updates }.into()
972 )
973 }
974
975 fn transfers() -> Transfers<Balance> {
976 Transporter::chain_transfers()
977 }
978
979 fn transfers_storage_key() -> Vec<u8> {
980 Transporter::transfers_storage_key()
981 }
982
983 fn block_fees_storage_key() -> Vec<u8> {
984 BlockFees::block_fees_storage_key()
985 }
986 }
987
988 impl sp_messenger::MessengerApi<Block, ConsensusBlockNumber, ConsensusBlockHash> for Runtime {
989 fn is_xdm_mmr_proof_valid(
990 extrinsic: &<Block as BlockT>::Extrinsic,
991 ) -> Option<bool> {
992 is_xdm_mmr_proof_valid(extrinsic)
993 }
994
995 fn extract_xdm_mmr_proof(ext: &<Block as BlockT>::Extrinsic) -> Option<ConsensusChainMmrLeafProof<ConsensusBlockNumber, ConsensusBlockHash, sp_core::H256>> {
996 match &ext.function {
997 RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })
998 | RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
999 Some(msg.proof.consensus_mmr_proof())
1000 }
1001 _ => None,
1002 }
1003 }
1004
1005 fn confirmed_domain_block_storage_key(_domain_id: DomainId) -> Vec<u8> {
1006 vec![]
1008 }
1009
1010 fn outbox_storage_key(message_key: MessageKey) -> Vec<u8> {
1011 Messenger::outbox_storage_key(message_key)
1012 }
1013
1014 fn inbox_response_storage_key(message_key: MessageKey) -> Vec<u8> {
1015 Messenger::inbox_response_storage_key(message_key)
1016 }
1017
1018 fn domain_chains_allowlist_update(_domain_id: DomainId) -> Option<DomainAllowlistUpdates>{
1019 None
1021 }
1022
1023 fn xdm_id(ext: &<Block as BlockT>::Extrinsic) -> Option<XdmId> {
1024 match &ext.function {
1025 RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })=> {
1026 Some(XdmId::RelayMessage((msg.src_chain_id, msg.channel_id, msg.nonce)))
1027 }
1028 RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
1029 Some(XdmId::RelayResponseMessage((msg.src_chain_id, msg.channel_id, msg.nonce)))
1030 }
1031 _ => None,
1032 }
1033 }
1034
1035 fn channel_nonce(chain_id: ChainId, channel_id: ChannelId) -> Option<ChannelNonce> {
1036 Messenger::channel_nonce(chain_id, channel_id)
1037 }
1038 }
1039
1040 impl sp_messenger::RelayerApi<Block, BlockNumber, ConsensusBlockNumber, ConsensusBlockHash> for Runtime {
1041 fn block_messages() -> BlockMessagesWithStorageKey {
1042 Messenger::get_block_messages()
1043 }
1044
1045 fn outbox_message_unsigned(msg: CrossDomainMessage<NumberFor<Block>, <Block as BlockT>::Hash, <Block as BlockT>::Hash>) -> Option<<Block as BlockT>::Extrinsic> {
1046 Messenger::outbox_message_unsigned(msg)
1047 }
1048
1049 fn inbox_response_message_unsigned(msg: CrossDomainMessage<NumberFor<Block>, <Block as BlockT>::Hash, <Block as BlockT>::Hash>) -> Option<<Block as BlockT>::Extrinsic> {
1050 Messenger::inbox_response_message_unsigned(msg)
1051 }
1052
1053 fn should_relay_outbox_message(dst_chain_id: ChainId, msg_id: MessageId) -> bool {
1054 Messenger::should_relay_outbox_message(dst_chain_id, msg_id)
1055 }
1056
1057 fn should_relay_inbox_message_response(dst_chain_id: ChainId, msg_id: MessageId) -> bool {
1058 Messenger::should_relay_inbox_message_response(dst_chain_id, msg_id)
1059 }
1060
1061 fn updated_channels() -> BTreeSet<(ChainId, ChannelId)> {
1062 Messenger::updated_channels()
1063 }
1064
1065 fn channel_storage_key(chain_id: ChainId, channel_id: ChannelId) -> Vec<u8> {
1066 Messenger::channel_storage_key(chain_id, channel_id)
1067 }
1068
1069 fn open_channels() -> BTreeSet<(ChainId, ChannelId)> {
1070 Messenger::open_channels()
1071 }
1072 }
1073
1074 impl sp_domain_sudo::DomainSudoApi<Block> for Runtime {
1075 fn is_valid_sudo_call(extrinsic: Vec<u8>) -> bool {
1076 is_valid_sudo_call(extrinsic)
1077 }
1078
1079 fn construct_domain_sudo_extrinsic(inner: Vec<u8>) -> <Block as BlockT>::Extrinsic {
1080 construct_sudo_call_extrinsic(inner)
1081 }
1082 }
1083
1084 impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
1085 fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
1086 build_state::<RuntimeGenesisConfig>(config)
1087 }
1088
1089 fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
1090 get_preset::<RuntimeGenesisConfig>(id, |_| None)
1091 }
1092
1093 fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
1094 vec![]
1095 }
1096 }
1097
1098 impl domain_test_primitives::OnchainStateApi<Block, AccountId, Balance> for Runtime {
1099 fn free_balance(account_id: AccountId) -> Balance {
1100 Balances::free_balance(account_id)
1101 }
1102
1103 fn get_open_channel_for_chain(dst_chain_id: ChainId) -> Option<ChannelId> {
1104 Messenger::get_open_channel_for_chain(dst_chain_id).map(|(c, _)| c)
1105 }
1106
1107 fn consensus_transaction_byte_fee() -> Balance {
1108 BlockFees::consensus_chain_byte_fee()
1109 }
1110
1111 fn storage_root() -> [u8; 32] {
1112 let version = <Runtime as frame_system::Config>::Version::get().state_version();
1113 let root = sp_io::storage::root(version);
1114 TryInto::<[u8; 32]>::try_into(root)
1115 .expect("root is a SCALE encoded hash which uses H256; qed")
1116 }
1117
1118 fn total_issuance() -> Balance {
1119 Balances::total_issuance()
1120 }
1121 }
1122
1123 #[cfg(feature = "runtime-benchmarks")]
1124 impl frame_benchmarking::Benchmark<Block> for Runtime {
1125 fn benchmark_metadata(extra: bool) -> (
1126 Vec<frame_benchmarking::BenchmarkList>,
1127 Vec<frame_support::traits::StorageInfo>,
1128 ) {
1129 use frame_benchmarking::{baseline, Benchmarking, BenchmarkList};
1130 use frame_support::traits::StorageInfoTrait;
1131 use frame_system_benchmarking::Pallet as SystemBench;
1132 use baseline::Pallet as BaselineBench;
1133
1134 let mut list = Vec::<BenchmarkList>::new();
1135
1136 list_benchmarks!(list, extra);
1137
1138 let storage_info = AllPalletsWithSystem::storage_info();
1139
1140 (list, storage_info)
1141 }
1142
1143 fn dispatch_benchmark(
1144 config: frame_benchmarking::BenchmarkConfig
1145 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, alloc::string::String> {
1146 use frame_benchmarking::{baseline, Benchmarking, BenchmarkBatch};
1147 use sp_storage::TrackedStorageKey;
1148 use frame_system_benchmarking::Pallet as SystemBench;
1149 use frame_support::traits::WhitelistedStorageKeys;
1150 use baseline::Pallet as BaselineBench;
1151
1152 let whitelist: Vec<TrackedStorageKey> = AllPalletsWithSystem::whitelisted_storage_keys();
1153
1154 let mut batches = Vec::<BenchmarkBatch>::new();
1155 let params = (&config, &whitelist);
1156
1157 add_benchmarks!(params, batches);
1158
1159 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }
1160 Ok(batches)
1161 }
1162 }
1163}
1164
1165#[cfg(test)]
1166mod tests {
1167 use crate::{Runtime, RuntimeBlockWeights as BlockWeights};
1168 use subspace_runtime_primitives::tests_utils::FeeMultiplierUtils;
1169
1170 #[test]
1171 fn multiplier_can_grow_from_zero() {
1172 FeeMultiplierUtils::<Runtime, BlockWeights>::multiplier_can_grow_from_zero()
1173 }
1174}