auto_id_domain_test_runtime/
lib.rs

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