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::execution_receipt::Transfers;
43use sp_domains::{ChannelId, DomainAllowlistUpdates, DomainId};
44use sp_messenger::endpoint::{Endpoint, EndpointHandler as EndpointHandlerT, EndpointId};
45use sp_messenger::messages::{
46    BlockMessagesQuery, ChainId, ChannelStateWithNonce, CrossDomainMessage, MessageId, MessageKey,
47    MessagesWithStorageKey, Nonce as XdmNonce,
48};
49use sp_messenger::{ChannelNonce, XdmId};
50use sp_messenger_host_functions::{StorageKeyRequest, get_storage_key};
51use sp_mmr_primitives::EncodableOpaqueLeaf;
52use sp_runtime::generic::{Era, ExtrinsicFormat, Preamble};
53use sp_runtime::traits::{
54    AccountIdLookup, BlakeTwo256, Checkable, DispatchTransaction, Keccak256, NumberFor, One,
55    TransactionExtension, ValidateUnsigned, Zero,
56};
57use sp_runtime::transaction_validity::{
58    InvalidTransaction, TransactionSource, TransactionValidity, TransactionValidityError,
59};
60use sp_runtime::type_with_default::TypeWithDefault;
61use sp_runtime::{ApplyExtrinsicResult, Digest, ExtrinsicInclusionMode, generic, impl_opaque_keys};
62pub use sp_runtime::{MultiAddress, Perbill, Permill};
63use sp_std::collections::btree_map::BTreeMap;
64use sp_std::collections::btree_set::BTreeSet;
65use sp_std::marker::PhantomData;
66use sp_std::prelude::*;
67use sp_subspace_mmr::domain_mmr_runtime_interface::{
68    is_consensus_block_finalized, verify_mmr_proof,
69};
70use sp_subspace_mmr::{ConsensusChainMmrLeafProof, MmrLeaf};
71use sp_version::RuntimeVersion;
72use static_assertions::const_assert;
73use subspace_runtime_primitives::utility::DefaultNonceProvider;
74use subspace_runtime_primitives::{
75    AI3, BlockHashFor, BlockNumber as ConsensusBlockNumber, DomainEventSegmentSize, ExtrinsicFor,
76    Hash as ConsensusBlockHash, HeaderFor, MAX_CALL_RECURSION_DEPTH, Moment,
77    SlowAdjustingFeeUpdate, XdmAdjustedWeightToFee, XdmFeeMultipler,
78};
79
80/// Block type as expected by this runtime.
81pub type Block = generic::Block<Header, UncheckedExtrinsic>;
82
83/// A Block signed with a Justification
84pub type SignedBlock = generic::SignedBlock<Block>;
85
86/// BlockId type as expected by this runtime.
87pub type BlockId = generic::BlockId<Block>;
88
89/// The SignedExtension to the basic transaction logic.
90pub type SignedExtra = (
91    frame_system::CheckNonZeroSender<Runtime>,
92    frame_system::CheckSpecVersion<Runtime>,
93    frame_system::CheckTxVersion<Runtime>,
94    frame_system::CheckGenesis<Runtime>,
95    frame_system::CheckMortality<Runtime>,
96    frame_system::CheckNonce<Runtime>,
97    domain_check_weight::CheckWeight<Runtime>,
98    pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
99    pallet_messenger::extensions::MessengerExtension<Runtime>,
100);
101
102/// The Custom SignedExtension used for pre_dispatch checks for bundle extrinsic verification
103pub type CustomSignedExtra = (
104    frame_system::CheckNonZeroSender<Runtime>,
105    frame_system::CheckSpecVersion<Runtime>,
106    frame_system::CheckTxVersion<Runtime>,
107    frame_system::CheckGenesis<Runtime>,
108    frame_system::CheckMortality<Runtime>,
109    frame_system::CheckNonce<Runtime>,
110    domain_check_weight::CheckWeight<Runtime>,
111    pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
112    pallet_messenger::extensions::MessengerTrustedMmrExtension<Runtime>,
113);
114
115/// Unchecked extrinsic type as expected by this runtime.
116pub type UncheckedExtrinsic =
117    generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
118
119/// Extrinsic type that has already been checked.
120pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, RuntimeCall, SignedExtra>;
121
122/// Executive: handles dispatch to the various modules.
123pub type Executive = domain_pallet_executive::Executive<
124    Runtime,
125    frame_system::ChainContext<Runtime>,
126    Runtime,
127    AllPalletsWithSystem,
128>;
129
130impl_opaque_keys! {
131    pub struct SessionKeys {
132        /// Primarily used for adding the operator signing key into the Keystore.
133        pub operator: sp_domains::OperatorKey,
134    }
135}
136
137#[sp_version::runtime_version]
138pub const VERSION: RuntimeVersion = RuntimeVersion {
139    spec_name: Cow::Borrowed("subspace-auto-id-domain"),
140    impl_name: Cow::Borrowed("subspace-auto-id-domain"),
141    authoring_version: 0,
142    spec_version: 1,
143    impl_version: 0,
144    apis: RUNTIME_API_VERSIONS,
145    transaction_version: 0,
146    system_version: 2,
147};
148
149parameter_types! {
150    pub const Version: RuntimeVersion = VERSION;
151    pub const BlockHashCount: BlockNumber = 2400;
152    pub RuntimeBlockLength: BlockLength = maximum_block_length();
153    pub RuntimeBlockWeights: BlockWeights = block_weights();
154}
155
156impl frame_system::Config for Runtime {
157    /// The identifier used to distinguish between accounts.
158    type AccountId = AccountId;
159    /// The aggregated dispatch type that is available for extrinsics.
160    type RuntimeCall = RuntimeCall;
161    /// The aggregated `RuntimeTask` type.
162    type RuntimeTask = RuntimeTask;
163    /// The lookup mechanism to get account ID from whatever is passed in dispatchers.
164    type Lookup = AccountIdLookup<AccountId, ()>;
165    /// The type for storing how many extrinsics an account has signed.
166    type Nonce = TypeWithDefault<Nonce, DefaultNonceProvider<System, Nonce>>;
167    /// The type for hashing blocks and tries.
168    type Hash = Hash;
169    /// The hashing algorithm used.
170    type Hashing = BlakeTwo256;
171    /// The block type.
172    type Block = Block;
173    /// The ubiquitous event type.
174    type RuntimeEvent = RuntimeEvent;
175    /// The ubiquitous origin type.
176    type RuntimeOrigin = RuntimeOrigin;
177    /// Maximum number of block number to block hash mappings to keep (oldest pruned first).
178    type BlockHashCount = BlockHashCount;
179    /// Runtime version.
180    type Version = Version;
181    /// Converts a module to an index of this module in the runtime.
182    type PalletInfo = PalletInfo;
183    /// The data to be stored in an account.
184    type AccountData = pallet_balances::AccountData<Balance>;
185    /// What to do if a new account is created.
186    type OnNewAccount = ();
187    /// What to do if an account is fully reaped from the system.
188    type OnKilledAccount = ();
189    /// The weight of database operations that the runtime can invoke.
190    type DbWeight = ParityDbWeight;
191    /// The basic call filter to use in dispatchable.
192    type BaseCallFilter = Everything;
193    /// Weight information for the extrinsics of this pallet.
194    type SystemWeightInfo = frame_system::weights::SubstrateWeight<Runtime>;
195    /// Block & extrinsics weights: base values and limits.
196    type BlockWeights = RuntimeBlockWeights;
197    /// The maximum length of a block (in bytes).
198    type BlockLength = RuntimeBlockLength;
199    type SS58Prefix = ConstU16<6094>;
200    /// The action to take on a Runtime Upgrade
201    type OnSetCode = ();
202    type SingleBlockMigrations = ();
203    type MultiBlockMigrator = ();
204    type PreInherents = ();
205    type PostInherents = ();
206    type PostTransactions = ();
207    type MaxConsumers = ConstU32<16>;
208    type ExtensionsWeightInfo = frame_system::ExtensionsWeight<Runtime>;
209    type EventSegmentSize = DomainEventSegmentSize;
210}
211
212impl pallet_timestamp::Config for Runtime {
213    /// A timestamp: milliseconds since the unix epoch.
214    type Moment = Moment;
215    type OnTimestampSet = ();
216    type MinimumPeriod = ConstU64<{ SLOT_DURATION / 2 }>;
217    type WeightInfo = pallet_timestamp::weights::SubstrateWeight<Runtime>;
218}
219
220parameter_types! {
221    pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
222    pub const MaxLocks: u32 = 50;
223    pub const MaxReserves: u32 = 50;
224}
225
226/// `DustRemovalHandler` used to collect all the AI3 dust left when the account is reaped.
227pub struct DustRemovalHandler;
228
229impl OnUnbalanced<Credit<AccountId, Balances>> for DustRemovalHandler {
230    fn on_nonzero_unbalanced(dusted_amount: Credit<AccountId, Balances>) {
231        BlockFees::note_burned_balance(dusted_amount.peek());
232    }
233}
234
235impl pallet_balances::Config for Runtime {
236    type RuntimeFreezeReason = RuntimeFreezeReason;
237    type MaxLocks = MaxLocks;
238    /// The type for recording an account's balance.
239    type Balance = Balance;
240    /// The ubiquitous event type.
241    type RuntimeEvent = RuntimeEvent;
242    type DustRemoval = DustRemovalHandler;
243    type ExistentialDeposit = ExistentialDeposit;
244    type AccountStore = System;
245    type WeightInfo = pallet_balances::weights::SubstrateWeight<Runtime>;
246    type MaxReserves = MaxReserves;
247    type ReserveIdentifier = [u8; 8];
248    type FreezeIdentifier = ();
249    type MaxFreezes = ();
250    type RuntimeHoldReason = HoldIdentifierWrapper;
251    type DoneSlashHandler = ();
252}
253
254parameter_types! {
255    pub const OperationalFeeMultiplier: u8 = 5;
256    pub const DomainChainByteFee: Balance = 1;
257}
258
259impl pallet_block_fees::Config for Runtime {
260    type Balance = Balance;
261    type DomainChainByteFee = DomainChainByteFee;
262}
263
264pub struct FinalDomainTransactionByteFee;
265
266impl Get<Balance> for FinalDomainTransactionByteFee {
267    fn get() -> Balance {
268        BlockFees::final_domain_transaction_byte_fee()
269    }
270}
271
272impl pallet_transaction_payment::Config for Runtime {
273    type RuntimeEvent = RuntimeEvent;
274    type OnChargeTransaction = OnChargeDomainTransaction<Balances>;
275    type WeightToFee = IdentityFee<Balance>;
276    type LengthToFee = ConstantMultiplier<Balance, FinalDomainTransactionByteFee>;
277    type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Runtime, TargetBlockFullness>;
278    type OperationalFeeMultiplier = OperationalFeeMultiplier;
279    type WeightInfo = pallet_transaction_payment::weights::SubstrateWeight<Runtime>;
280}
281
282impl pallet_auto_id::Config for Runtime {
283    type RuntimeEvent = RuntimeEvent;
284    type Time = Timestamp;
285    type Weights = pallet_auto_id::weights::SubstrateWeight<Self>;
286}
287
288pub struct ExtrinsicStorageFees;
289
290impl domain_pallet_executive::ExtrinsicStorageFees<Runtime> for ExtrinsicStorageFees {
291    fn extract_signer(xt: UncheckedExtrinsic) -> (Option<AccountId>, DispatchInfo) {
292        let dispatch_info = xt.get_dispatch_info();
293        let lookup = frame_system::ChainContext::<Runtime>::default();
294        let maybe_signer = extract_signer_inner(&xt, &lookup).and_then(|res| res.ok());
295        (maybe_signer, dispatch_info)
296    }
297
298    fn on_storage_fees_charged(
299        charged_fees: Balance,
300        tx_size: u32,
301    ) -> Result<(), TransactionValidityError> {
302        let consensus_storage_fee = BlockFees::consensus_chain_byte_fee()
303            .checked_mul(Balance::from(tx_size))
304            .ok_or(InvalidTransaction::Custom(ERR_BALANCE_OVERFLOW))?;
305
306        let (paid_consensus_storage_fee, paid_domain_fee) = if charged_fees <= consensus_storage_fee
307        {
308            (charged_fees, Zero::zero())
309        } else {
310            (consensus_storage_fee, charged_fees - consensus_storage_fee)
311        };
312
313        BlockFees::note_consensus_storage_fee(paid_consensus_storage_fee);
314        BlockFees::note_domain_execution_fee(paid_domain_fee);
315        Ok(())
316    }
317}
318
319impl domain_pallet_executive::Config for Runtime {
320    type RuntimeEvent = RuntimeEvent;
321    type WeightInfo = domain_pallet_executive::weights::SubstrateWeight<Runtime>;
322    type Currency = Balances;
323    type LengthToFee = <Runtime as pallet_transaction_payment::Config>::LengthToFee;
324    type ExtrinsicStorageFees = ExtrinsicStorageFees;
325}
326
327parameter_types! {
328    pub SelfChainId: ChainId = SelfDomainId::self_domain_id().into();
329}
330
331pub struct OnXDMRewards;
332
333impl sp_messenger::OnXDMRewards<Balance> for OnXDMRewards {
334    fn on_xdm_rewards(rewards: Balance) {
335        BlockFees::note_domain_execution_fee(rewards)
336    }
337    fn on_chain_protocol_fees(chain_id: ChainId, fees: Balance) {
338        // note the chain rewards
339        BlockFees::note_chain_rewards(chain_id, fees);
340    }
341}
342
343type MmrHash = <Keccak256 as sp_runtime::traits::Hash>::Output;
344
345pub struct MmrProofVerifier;
346
347impl sp_subspace_mmr::MmrProofVerifier<MmrHash, NumberFor<Block>, Hash> for MmrProofVerifier {
348    fn verify_proof_and_extract_leaf(
349        mmr_leaf_proof: ConsensusChainMmrLeafProof<NumberFor<Block>, Hash, MmrHash>,
350    ) -> Option<MmrLeaf<ConsensusBlockNumber, ConsensusBlockHash>> {
351        let ConsensusChainMmrLeafProof {
352            consensus_block_number,
353            opaque_mmr_leaf: opaque_leaf,
354            proof,
355            ..
356        } = mmr_leaf_proof;
357
358        if !is_consensus_block_finalized(consensus_block_number) {
359            return None;
360        }
361
362        let leaf: MmrLeaf<ConsensusBlockNumber, ConsensusBlockHash> =
363            opaque_leaf.into_opaque_leaf().try_decode()?;
364
365        verify_mmr_proof(vec![EncodableOpaqueLeaf::from_leaf(&leaf)], proof.encode())
366            .then_some(leaf)
367    }
368}
369
370pub struct StorageKeys;
371
372impl sp_messenger::StorageKeys for StorageKeys {
373    fn confirmed_domain_block_storage_key(domain_id: DomainId) -> Option<Vec<u8>> {
374        get_storage_key(StorageKeyRequest::ConfirmedDomainBlockStorageKey(domain_id))
375    }
376
377    fn outbox_storage_key(chain_id: ChainId, message_key: MessageKey) -> Option<Vec<u8>> {
378        get_storage_key(StorageKeyRequest::OutboxStorageKey {
379            chain_id,
380            message_key,
381        })
382    }
383
384    fn inbox_responses_storage_key(chain_id: ChainId, message_key: MessageKey) -> Option<Vec<u8>> {
385        get_storage_key(StorageKeyRequest::InboxResponseStorageKey {
386            chain_id,
387            message_key,
388        })
389    }
390}
391
392/// Hold identifier for balances for this runtime.
393#[derive(
394    PartialEq, Eq, Clone, Encode, Decode, TypeInfo, MaxEncodedLen, Ord, PartialOrd, Copy, Debug,
395)]
396pub struct HoldIdentifierWrapper(HoldIdentifier);
397
398impl VariantCount for HoldIdentifierWrapper {
399    const VARIANT_COUNT: u32 = mem::variant_count::<HoldIdentifier>() as u32;
400}
401
402impl pallet_messenger::HoldIdentifier<Runtime> for HoldIdentifierWrapper {
403    fn messenger_channel() -> Self {
404        Self(HoldIdentifier::MessengerChannel)
405    }
406}
407
408parameter_types! {
409    pub const ChannelReserveFee: Balance = 100 * AI3;
410    pub const ChannelInitReservePortion: Perbill = Perbill::from_percent(20);
411    pub const MaxOutgoingMessages: u32 = MAX_OUTGOING_MESSAGES;
412}
413
414// ensure the max outgoing messages is not 0.
415const_assert!(MaxOutgoingMessages::get() >= 1);
416
417impl pallet_messenger::Config for Runtime {
418    type RuntimeEvent = RuntimeEvent;
419    type SelfChainId = SelfChainId;
420
421    fn get_endpoint_handler(endpoint: &Endpoint) -> Option<Box<dyn EndpointHandlerT<MessageId>>> {
422        if endpoint == &Endpoint::Id(TransporterEndpointId::get()) {
423            Some(Box::new(EndpointHandler(PhantomData::<Runtime>)))
424        } else {
425            None
426        }
427    }
428
429    type Currency = Balances;
430    type WeightInfo = pallet_messenger::weights::SubstrateWeight<Runtime>;
431    type WeightToFee = IdentityFee<Balance>;
432    type AdjustedWeightToFee = XdmAdjustedWeightToFee<Runtime>;
433    type FeeMultiplier = XdmFeeMultipler;
434    type OnXDMRewards = OnXDMRewards;
435    type MmrHash = MmrHash;
436    type MmrProofVerifier = MmrProofVerifier;
437    type StorageKeys = StorageKeys;
438    type DomainOwner = ();
439    type HoldIdentifier = HoldIdentifierWrapper;
440    type ChannelReserveFee = ChannelReserveFee;
441    type ChannelInitReservePortion = ChannelInitReservePortion;
442    type DomainRegistration = ();
443    type MaxOutgoingMessages = MaxOutgoingMessages;
444    type MessengerOrigin = pallet_messenger::EnsureMessengerOrigin;
445    type NoteChainTransfer = Transporter;
446    type ExtensionWeightInfo = pallet_messenger::extensions::weights::SubstrateWeight<
447        Runtime,
448        pallet_messenger::extensions::WeightsFromConsensus<Runtime>,
449        pallet_messenger::extensions::WeightsFromDomains<Runtime>,
450    >;
451}
452
453impl<C> frame_system::offchain::CreateTransactionBase<C> for Runtime
454where
455    RuntimeCall: From<C>,
456{
457    type Extrinsic = UncheckedExtrinsic;
458    type RuntimeCall = RuntimeCall;
459}
460
461parameter_types! {
462    pub const TransporterEndpointId: EndpointId = 1;
463    pub const MinimumTransfer: Balance = 1;
464}
465
466impl pallet_transporter::Config for Runtime {
467    type RuntimeEvent = RuntimeEvent;
468    type SelfChainId = SelfChainId;
469    type SelfEndpointId = TransporterEndpointId;
470    type Currency = Balances;
471    type Sender = Messenger;
472    type AccountIdConverter = domain_runtime_primitives::AccountIdConverter;
473    type WeightInfo = pallet_transporter::weights::SubstrateWeight<Runtime>;
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::execution_receipt::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 outbox_message_unsigned(msg: CrossDomainMessage<NumberFor<Block>, BlockHashFor<Block>, BlockHashFor<Block>>) -> Option<ExtrinsicFor<Block>> {
1120            Messenger::outbox_message_unsigned(msg)
1121        }
1122
1123        fn inbox_response_message_unsigned(msg: CrossDomainMessage<NumberFor<Block>, BlockHashFor<Block>, BlockHashFor<Block>>) -> Option<ExtrinsicFor<Block>> {
1124            Messenger::inbox_response_message_unsigned(msg)
1125        }
1126
1127        fn updated_channels() -> BTreeSet<(ChainId, ChannelId)> {
1128            Messenger::updated_channels()
1129        }
1130
1131        fn channel_storage_key(chain_id: ChainId, channel_id: ChannelId) -> Vec<u8> {
1132            Messenger::channel_storage_key(chain_id, channel_id)
1133        }
1134
1135        fn open_channels() -> BTreeSet<(ChainId, ChannelId)> {
1136            Messenger::open_channels()
1137        }
1138
1139        fn block_messages_with_query(query: BlockMessagesQuery) -> MessagesWithStorageKey {
1140            Messenger::get_block_messages(query)
1141        }
1142
1143        fn channels_and_state() -> Vec<(ChainId, ChannelId, ChannelStateWithNonce)> {
1144            Messenger::channels_and_states()
1145        }
1146
1147        fn first_outbox_message_nonce_to_relay(dst_chain_id: ChainId, channel_id: ChannelId, from_nonce: XdmNonce) -> Option<XdmNonce> {
1148            Messenger::first_outbox_message_nonce_to_relay(dst_chain_id, channel_id, from_nonce)
1149        }
1150
1151        fn first_inbox_message_response_nonce_to_relay(dst_chain_id: ChainId, channel_id: ChannelId, from_nonce: XdmNonce) -> Option<XdmNonce> {
1152            Messenger::first_inbox_message_response_nonce_to_relay(dst_chain_id, channel_id, from_nonce)
1153        }
1154    }
1155
1156    impl sp_domain_sudo::DomainSudoApi<Block> for Runtime {
1157        fn is_valid_sudo_call(extrinsic: Vec<u8>) -> bool {
1158            is_valid_sudo_call(extrinsic)
1159        }
1160
1161        fn construct_domain_sudo_extrinsic(inner: Vec<u8>) -> ExtrinsicFor<Block> {
1162            construct_sudo_call_extrinsic(inner)
1163        }
1164    }
1165
1166    impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
1167        fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
1168            build_state::<RuntimeGenesisConfig>(config)
1169        }
1170
1171        fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
1172            get_preset::<RuntimeGenesisConfig>(id, |_| None)
1173        }
1174
1175        fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
1176            vec![]
1177        }
1178    }
1179
1180    impl domain_test_primitives::OnchainStateApi<Block, AccountId, Balance> for Runtime {
1181        fn free_balance(account_id: AccountId) -> Balance {
1182            Balances::free_balance(account_id)
1183        }
1184
1185        fn get_open_channel_for_chain(dst_chain_id: ChainId) -> Option<ChannelId> {
1186            Messenger::get_open_channel_for_chain(dst_chain_id)
1187        }
1188
1189        fn consensus_transaction_byte_fee() -> Balance {
1190            BlockFees::consensus_chain_byte_fee()
1191        }
1192
1193        fn storage_root() -> [u8; 32] {
1194            let version = <Runtime as frame_system::Config>::Version::get().state_version();
1195            let root = sp_io::storage::root(version);
1196            TryInto::<[u8; 32]>::try_into(root)
1197                .expect("root is a SCALE encoded hash which uses H256; qed")
1198        }
1199
1200        fn total_issuance() -> Balance {
1201            Balances::total_issuance()
1202        }
1203    }
1204
1205    #[cfg(feature = "runtime-benchmarks")]
1206    impl frame_benchmarking::Benchmark<Block> for Runtime {
1207        fn benchmark_metadata(extra: bool) -> (
1208            Vec<frame_benchmarking::BenchmarkList>,
1209            Vec<frame_support::traits::StorageInfo>,
1210        ) {
1211            use frame_benchmarking::{baseline, Benchmarking, BenchmarkList};
1212            use frame_support::traits::StorageInfoTrait;
1213            use frame_system_benchmarking::Pallet as SystemBench;
1214            use baseline::Pallet as BaselineBench;
1215
1216            let mut list = Vec::<BenchmarkList>::new();
1217
1218            list_benchmarks!(list, extra);
1219
1220            let storage_info = AllPalletsWithSystem::storage_info();
1221
1222            (list, storage_info)
1223        }
1224
1225        fn dispatch_benchmark(
1226            config: frame_benchmarking::BenchmarkConfig
1227        ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, alloc::string::String> {
1228            use frame_benchmarking::{baseline, Benchmarking, BenchmarkBatch};
1229            use sp_storage::TrackedStorageKey;
1230            use frame_system_benchmarking::Pallet as SystemBench;
1231            use frame_support::traits::WhitelistedStorageKeys;
1232            use baseline::Pallet as BaselineBench;
1233
1234            let whitelist: Vec<TrackedStorageKey> = AllPalletsWithSystem::whitelisted_storage_keys();
1235
1236            let mut batches = Vec::<BenchmarkBatch>::new();
1237            let params = (&config, &whitelist);
1238
1239            add_benchmarks!(params, batches);
1240
1241            if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }
1242            Ok(batches)
1243        }
1244    }
1245}
1246
1247#[cfg(test)]
1248mod tests {
1249    use crate::{Runtime, RuntimeBlockWeights as BlockWeights};
1250    use subspace_runtime_primitives::tests_utils::FeeMultiplierUtils;
1251
1252    #[test]
1253    fn multiplier_can_grow_from_zero() {
1254        FeeMultiplierUtils::<Runtime, BlockWeights>::multiplier_can_grow_from_zero()
1255    }
1256}