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<Runtime>;
446}
447
448impl<C> frame_system::offchain::CreateTransactionBase<C> for Runtime
449where
450    RuntimeCall: From<C>,
451{
452    type Extrinsic = UncheckedExtrinsic;
453    type RuntimeCall = RuntimeCall;
454}
455
456parameter_types! {
457    pub const TransporterEndpointId: EndpointId = 1;
458    pub const MinimumTransfer: Balance = 1;
459}
460
461impl pallet_transporter::Config for Runtime {
462    type RuntimeEvent = RuntimeEvent;
463    type SelfChainId = SelfChainId;
464    type SelfEndpointId = TransporterEndpointId;
465    type Currency = Balances;
466    type Sender = Messenger;
467    type AccountIdConverter = domain_runtime_primitives::AccountIdConverter;
468    type WeightInfo = pallet_transporter::weights::SubstrateWeight<Runtime>;
469    type SkipBalanceTransferChecks = ();
470    type MinimumTransfer = MinimumTransfer;
471}
472
473impl pallet_domain_id::Config for Runtime {}
474
475pub struct IntoRuntimeCall;
476
477impl sp_domain_sudo::IntoRuntimeCall<RuntimeCall> for IntoRuntimeCall {
478    fn runtime_call(call: Vec<u8>) -> RuntimeCall {
479        UncheckedExtrinsic::decode(&mut call.as_slice())
480            .expect("must always be a valid extrinsic as checked by consensus chain; qed")
481            .function
482    }
483}
484
485impl pallet_domain_sudo::Config for Runtime {
486    type RuntimeEvent = RuntimeEvent;
487    type RuntimeCall = RuntimeCall;
488    type IntoRuntimeCall = IntoRuntimeCall;
489}
490
491impl pallet_storage_overlay_checks::Config for Runtime {}
492
493// Create the runtime by composing the FRAME pallets that were previously configured.
494//
495// NOTE: Currently domain runtime does not naturally support the pallets with inherent extrinsics.
496construct_runtime!(
497    pub struct Runtime {
498        // System support stuff.
499        System: frame_system = 0,
500        // Note: Ensure index of the timestamp matches with the index of timestamp on Consensus
501        //  so that consensus can construct encoded extrinsic that matches with Domain encoded
502        //  extrinsic.
503        Timestamp: pallet_timestamp = 1,
504        ExecutivePallet: domain_pallet_executive = 2,
505
506        // monetary stuff
507        Balances: pallet_balances = 20,
508        TransactionPayment: pallet_transaction_payment = 21,
509
510        // AutoId
511        AutoId: pallet_auto_id = 40,
512
513        // messenger stuff
514        // Note: Indexes should match with indexes on other chains and domains
515        Messenger: pallet_messenger = 60,
516        Transporter: pallet_transporter = 61,
517
518        // domain instance stuff
519        SelfDomainId: pallet_domain_id = 90,
520        BlockFees: pallet_block_fees = 91,
521
522        // Sudo account
523        Sudo: pallet_domain_sudo = 100,
524
525        // checks
526        StorageOverlayChecks: pallet_storage_overlay_checks = 200,
527    }
528);
529
530fn is_xdm_mmr_proof_valid(ext: &ExtrinsicFor<Block>) -> Option<bool> {
531    match &ext.function {
532        RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })
533        | RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
534            let ConsensusChainMmrLeafProof {
535                consensus_block_number,
536                opaque_mmr_leaf,
537                proof,
538                ..
539            } = msg.proof.consensus_mmr_proof();
540
541            if !is_consensus_block_finalized(consensus_block_number) {
542                return Some(false);
543            }
544
545            Some(verify_mmr_proof(vec![opaque_mmr_leaf], proof.encode()))
546        }
547        _ => None,
548    }
549}
550
551/// Returns `true` if this is a validly encoded Sudo call.
552fn is_valid_sudo_call(encoded_ext: Vec<u8>) -> bool {
553    UncheckedExtrinsic::decode_with_depth_limit(
554        MAX_CALL_RECURSION_DEPTH,
555        &mut encoded_ext.as_slice(),
556    )
557    .is_ok()
558}
559
560fn construct_sudo_call_extrinsic(encoded_ext: Vec<u8>) -> ExtrinsicFor<Block> {
561    let ext = UncheckedExtrinsic::decode(&mut encoded_ext.as_slice()).expect(
562        "must always be a valid extrinsic due to the check above and storage proof check; qed",
563    );
564    UncheckedExtrinsic::new_bare(
565        pallet_domain_sudo::Call::sudo {
566            call: Box::new(ext.function),
567        }
568        .into(),
569    )
570}
571
572fn extract_signer_inner<Lookup>(
573    ext: &UncheckedExtrinsic,
574    lookup: &Lookup,
575) -> Option<Result<AccountId, TransactionValidityError>>
576where
577    Lookup: sp_runtime::traits::Lookup<Source = Address, Target = AccountId>,
578{
579    match &ext.preamble {
580        Preamble::Bare(_) | Preamble::General(_, _) => None,
581        Preamble::Signed(address, _, _) => {
582            Some(lookup.lookup(address.clone()).map_err(|e| e.into()))
583        }
584    }
585}
586
587pub fn extract_signer(
588    extrinsics: Vec<UncheckedExtrinsic>,
589) -> Vec<(Option<opaque::AccountId>, UncheckedExtrinsic)> {
590    let lookup = frame_system::ChainContext::<Runtime>::default();
591
592    extrinsics
593        .into_iter()
594        .map(|extrinsic| {
595            let maybe_signer =
596                extract_signer_inner(&extrinsic, &lookup).and_then(|account_result| {
597                    account_result.ok().map(|account_id| account_id.encode())
598                });
599            (maybe_signer, extrinsic)
600        })
601        .collect()
602}
603
604fn extrinsic_era(extrinsic: &ExtrinsicFor<Block>) -> Option<Era> {
605    match &extrinsic.preamble {
606        Preamble::Bare(_) | Preamble::General(_, _) => None,
607        Preamble::Signed(_, _, extra) => Some(extra.4.0),
608    }
609}
610
611impl pallet_messenger::extensions::MaybeMessengerCall<Runtime> for RuntimeCall {
612    fn maybe_messenger_call(&self) -> Option<&pallet_messenger::Call<Runtime>> {
613        match self {
614            RuntimeCall::Messenger(call) => Some(call),
615            _ => None,
616        }
617    }
618}
619
620impl<C> subspace_runtime_primitives::CreateUnsigned<C> for Runtime
621where
622    RuntimeCall: From<C>,
623{
624    fn create_unsigned(call: Self::RuntimeCall) -> Self::Extrinsic {
625        create_unsigned_general_extrinsic(call)
626    }
627}
628
629fn create_unsigned_general_extrinsic(call: RuntimeCall) -> UncheckedExtrinsic {
630    let extra: SignedExtra = (
631        frame_system::CheckNonZeroSender::<Runtime>::new(),
632        frame_system::CheckSpecVersion::<Runtime>::new(),
633        frame_system::CheckTxVersion::<Runtime>::new(),
634        frame_system::CheckGenesis::<Runtime>::new(),
635        frame_system::CheckMortality::<Runtime>::from(generic::Era::Immortal),
636        // for unsigned extrinsic, nonce check will be skipped
637        // so set a default value
638        frame_system::CheckNonce::<Runtime>::from(0u32.into()),
639        domain_check_weight::CheckWeight::<Runtime>::new(),
640        // for unsigned extrinsic, transaction fee check will be skipped
641        // so set a default value
642        pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(0u128),
643        pallet_messenger::extensions::MessengerExtension::<Runtime>::new(),
644    );
645
646    UncheckedExtrinsic::new_transaction(call, extra)
647}
648
649#[cfg(feature = "runtime-benchmarks")]
650mod benches {
651    frame_benchmarking::define_benchmarks!(
652        [frame_benchmarking, BaselineBench::<Runtime>]
653        [frame_system, SystemBench::<Runtime>]
654        [domain_pallet_executive, ExecutivePallet]
655        [pallet_messenger, Messenger]
656        [pallet_auto_id, AutoId]
657    );
658}
659
660fn check_transaction_and_do_pre_dispatch_inner(
661    uxt: &ExtrinsicFor<Block>,
662) -> Result<(), TransactionValidityError> {
663    let lookup = frame_system::ChainContext::<Runtime>::default();
664
665    let xt = uxt.clone().check(&lookup)?;
666
667    let dispatch_info = xt.get_dispatch_info();
668
669    if dispatch_info.class == DispatchClass::Mandatory {
670        return Err(InvalidTransaction::MandatoryValidation.into());
671    }
672
673    let encoded_len = uxt.encoded_size();
674
675    // We invoke `pre_dispatch` in addition to `validate_transaction`(even though the validation is almost same)
676    // as that will add the side effect of SignedExtension in the storage buffer
677    // which would help to maintain context across multiple transaction validity check against same
678    // runtime instance.
679    match xt.format {
680        ExtrinsicFormat::General(extension_version, extra) => {
681            let origin = RuntimeOrigin::none();
682            <SignedExtra as DispatchTransaction<RuntimeCall>>::validate_and_prepare(
683                extra,
684                origin,
685                &xt.function,
686                &dispatch_info,
687                encoded_len,
688                extension_version,
689            )
690            .map(|_| ())
691        }
692        // signed transaction
693        ExtrinsicFormat::Signed(account_id, extra) => {
694            let custom_extra: CustomSignedExtra = (
695                extra.0,
696                extra.1,
697                extra.2,
698                extra.3,
699                extra.4,
700                extra.5,
701                extra.6.clone(),
702                extra.7,
703                pallet_messenger::extensions::MessengerTrustedMmrExtension::<Runtime>::new(),
704            );
705            let origin = RuntimeOrigin::signed(account_id);
706            <CustomSignedExtra as DispatchTransaction<RuntimeCall>>::validate_and_prepare(
707                custom_extra,
708                origin,
709                &xt.function,
710                &dispatch_info,
711                encoded_len,
712                // default extension version define here -
713                // https://github.com/paritytech/polkadot-sdk/blob/master/substrate/primitives/runtime/src/generic/checked_extrinsic.rs#L37
714                0,
715            )
716            .map(|_| ())
717        }
718        // unsigned transaction
719        ExtrinsicFormat::Bare => {
720            Runtime::pre_dispatch(&xt.function).map(|_| ())?;
721            <SignedExtra as TransactionExtension<RuntimeCall>>::bare_validate_and_prepare(
722                &xt.function,
723                &dispatch_info,
724                encoded_len,
725            )
726            .map(|_| ())
727        }
728    }
729}
730
731#[cfg(feature = "runtime-benchmarks")]
732impl frame_system_benchmarking::Config for Runtime {}
733
734#[cfg(feature = "runtime-benchmarks")]
735impl frame_benchmarking::baseline::Config for Runtime {}
736
737impl_runtime_apis! {
738    impl sp_api::Core<Block> for Runtime {
739        fn version() -> RuntimeVersion {
740            VERSION
741        }
742
743        fn execute_block(block: Block) {
744            Executive::execute_block(block)
745        }
746
747        fn initialize_block(header: &HeaderFor<Block>) -> ExtrinsicInclusionMode {
748            Executive::initialize_block(header)
749        }
750    }
751
752    impl sp_api::Metadata<Block> for Runtime {
753        fn metadata() -> OpaqueMetadata {
754            OpaqueMetadata::new(Runtime::metadata().into())
755        }
756
757        fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
758            Runtime::metadata_at_version(version)
759        }
760
761        fn metadata_versions() -> Vec<u32> {
762            Runtime::metadata_versions()
763        }
764    }
765
766    impl sp_block_builder::BlockBuilder<Block> for Runtime {
767        fn apply_extrinsic(extrinsic: ExtrinsicFor<Block>) -> ApplyExtrinsicResult {
768            Executive::apply_extrinsic(extrinsic)
769        }
770
771        fn finalize_block() -> HeaderFor<Block> {
772            Executive::finalize_block()
773        }
774
775        fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<ExtrinsicFor<Block>> {
776            data.create_extrinsics()
777        }
778
779        fn check_inherents(
780            block: Block,
781            data: sp_inherents::InherentData,
782        ) -> sp_inherents::CheckInherentsResult {
783            data.check_extrinsics(&block)
784        }
785    }
786
787    impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
788        fn validate_transaction(
789            source: TransactionSource,
790            tx: ExtrinsicFor<Block>,
791            block_hash: BlockHashFor<Block>,
792        ) -> TransactionValidity {
793            Executive::validate_transaction(source, tx, block_hash)
794        }
795    }
796
797    impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
798        fn offchain_worker(header: &HeaderFor<Block>) {
799            Executive::offchain_worker(header)
800        }
801    }
802
803    impl sp_session::SessionKeys<Block> for Runtime {
804        fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
805            SessionKeys::generate(seed)
806        }
807
808        fn decode_session_keys(
809            encoded: Vec<u8>,
810        ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
811            SessionKeys::decode_into_raw_public_keys(&encoded)
812        }
813    }
814
815    impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
816        fn account_nonce(account: AccountId) -> Nonce {
817            *System::account_nonce(account)
818        }
819    }
820
821    impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {
822        fn query_info(
823            uxt: ExtrinsicFor<Block>,
824            len: u32,
825        ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
826            TransactionPayment::query_info(uxt, len)
827        }
828        fn query_fee_details(
829            uxt: ExtrinsicFor<Block>,
830            len: u32,
831        ) -> pallet_transaction_payment::FeeDetails<Balance> {
832            TransactionPayment::query_fee_details(uxt, len)
833        }
834        fn query_weight_to_fee(weight: Weight) -> Balance {
835            TransactionPayment::weight_to_fee(weight)
836        }
837        fn query_length_to_fee(length: u32) -> Balance {
838            TransactionPayment::length_to_fee(length)
839        }
840    }
841
842    impl sp_domains::core_api::DomainCoreApi<Block> for Runtime {
843        fn extract_signer(
844            extrinsics: Vec<ExtrinsicFor<Block>>,
845        ) -> Vec<(Option<opaque::AccountId>, ExtrinsicFor<Block>)> {
846            extract_signer(extrinsics)
847        }
848
849        fn is_within_tx_range(
850            extrinsic: &ExtrinsicFor<Block>,
851            bundle_vrf_hash: &subspace_core_primitives::U256,
852            tx_range: &subspace_core_primitives::U256
853        ) -> bool {
854            use subspace_core_primitives::U256;
855            use subspace_core_primitives::hashes::blake3_hash;
856
857            let lookup = frame_system::ChainContext::<Runtime>::default();
858            if let Some(signer) = extract_signer_inner(extrinsic, &lookup).and_then(|account_result| {
859                    account_result.ok().map(|account_id| account_id.encode())
860                }) {
861                // Check if the signer Id hash is within the tx range
862                let signer_id_hash = U256::from_be_bytes(*blake3_hash(&signer.encode()));
863                sp_domains::signer_in_tx_range(bundle_vrf_hash, &signer_id_hash, tx_range)
864            } else {
865                // Unsigned transactions are always in the range.
866                true
867            }
868        }
869
870        fn extract_signer_if_all_within_tx_range(
871            extrinsics: &Vec<ExtrinsicFor<Block>>,
872            bundle_vrf_hash: &subspace_core_primitives::U256,
873            tx_range: &subspace_core_primitives::U256
874        ) -> Result<Vec<Option<opaque::AccountId>> , u32> {
875            use subspace_core_primitives::U256;
876            use subspace_core_primitives::hashes::blake3_hash;
877
878            let mut signers = Vec::with_capacity(extrinsics.len());
879            let lookup = frame_system::ChainContext::<Runtime>::default();
880            for (index, extrinsic) in extrinsics.iter().enumerate() {
881                let maybe_signer = extract_signer_inner(extrinsic, &lookup).and_then(|account_result| {
882                    account_result.ok().map(|account_id| account_id.encode())
883                });
884                if let Some(signer) = &maybe_signer {
885                    // Check if the signer Id hash is within the tx range
886                    let signer_id_hash = U256::from_be_bytes(*blake3_hash(&signer.encode()));
887                    if !sp_domains::signer_in_tx_range(bundle_vrf_hash, &signer_id_hash, tx_range) {
888                        return Err(index as u32)
889                    }
890                }
891                signers.push(maybe_signer);
892            }
893
894            Ok(signers)
895        }
896
897        fn initialize_block_with_post_state_root(header: &HeaderFor<Block>) -> Vec<u8> {
898            Executive::initialize_block(header);
899            Executive::storage_root()
900        }
901
902        fn apply_extrinsic_with_post_state_root(extrinsic: ExtrinsicFor<Block>) -> Vec<u8> {
903            let _ = Executive::apply_extrinsic(extrinsic);
904            Executive::storage_root()
905        }
906
907        fn construct_set_code_extrinsic(code: Vec<u8>) -> Vec<u8> {
908            UncheckedExtrinsic::new_bare(
909                domain_pallet_executive::Call::set_code {
910                    code
911                }.into()
912            ).encode()
913        }
914
915        fn construct_timestamp_extrinsic(moment: Moment) -> ExtrinsicFor<Block> {
916            UncheckedExtrinsic::new_bare(
917                pallet_timestamp::Call::set{ now: moment }.into()
918            )
919        }
920
921        fn is_inherent_extrinsic(extrinsic: &ExtrinsicFor<Block>) -> bool {
922            <Self as IsInherent<_>>::is_inherent(extrinsic)
923        }
924
925        fn find_first_inherent_extrinsic(extrinsics: &Vec<ExtrinsicFor<Block>>) -> Option<u32> {
926            for (index, extrinsic) in extrinsics.iter().enumerate() {
927                if <Self as IsInherent<_>>::is_inherent(extrinsic) {
928                    return Some(index as u32)
929                }
930            }
931            None
932        }
933
934        fn check_extrinsics_and_do_pre_dispatch(uxts: Vec<ExtrinsicFor<Block>>, block_number: BlockNumber,
935            block_hash: BlockHashFor<Block>) -> Result<(), CheckExtrinsicsValidityError> {
936            // Initializing block related storage required for validation
937            System::initialize(
938                &(block_number + BlockNumber::one()),
939                &block_hash,
940                &Default::default(),
941            );
942
943            for (extrinsic_index, uxt) in uxts.iter().enumerate() {
944                check_transaction_and_do_pre_dispatch_inner(uxt).map_err(|e| {
945                    CheckExtrinsicsValidityError {
946                        extrinsic_index: extrinsic_index as u32,
947                        transaction_validity_error: e
948                    }
949                })?;
950            }
951
952            Ok(())
953        }
954
955        fn decode_extrinsic(
956            opaque_extrinsic: sp_runtime::OpaqueExtrinsic,
957        ) -> Result<ExtrinsicFor<Block>, DecodeExtrinsicError> {
958            let encoded = opaque_extrinsic.encode();
959
960            UncheckedExtrinsic::decode_with_depth_limit(
961                MAX_CALL_RECURSION_DEPTH,
962                &mut encoded.as_slice(),
963            ).map_err(|err| DecodeExtrinsicError(format!("{err}")))
964        }
965
966        fn decode_extrinsics_prefix(
967            opaque_extrinsics: Vec<sp_runtime::OpaqueExtrinsic>,
968        ) -> Vec<ExtrinsicFor<Block>> {
969            let mut extrinsics = Vec::with_capacity(opaque_extrinsics.len());
970            for opaque_ext in opaque_extrinsics {
971                match UncheckedExtrinsic::decode_with_depth_limit(
972                    MAX_CALL_RECURSION_DEPTH,
973                    &mut opaque_ext.encode().as_slice(),
974                ) {
975                    Ok(tx) => extrinsics.push(tx),
976                    Err(_) => return extrinsics,
977                }
978            }
979            extrinsics
980        }
981
982        fn extrinsic_era(
983          extrinsic: &ExtrinsicFor<Block>
984        ) -> Option<Era> {
985            extrinsic_era(extrinsic)
986        }
987
988        fn extrinsic_weight(ext: &ExtrinsicFor<Block>) -> Weight {
989            let len = ext.encoded_size() as u64;
990            let info = ext.get_dispatch_info();
991            info.call_weight
992                .saturating_add(<Runtime as frame_system::Config>::BlockWeights::get().get(info.class).base_extrinsic)
993                .saturating_add(Weight::from_parts(0, len)).saturating_add(info.extension_weight)
994        }
995
996        fn extrinsics_weight(extrinsics: &Vec<ExtrinsicFor<Block>>) -> Weight {
997            let mut total_weight = Weight::zero();
998            for ext in extrinsics {
999                let ext_weight = {
1000                    let len = ext.encoded_size() as u64;
1001                    let info = ext.get_dispatch_info();
1002                    info.call_weight.saturating_add(info.extension_weight)
1003                        .saturating_add(<Runtime as frame_system::Config>::BlockWeights::get().get(info.class).base_extrinsic)
1004                        .saturating_add(Weight::from_parts(0, len))
1005                };
1006                total_weight = total_weight.saturating_add(ext_weight);
1007            }
1008            total_weight
1009        }
1010
1011        fn block_fees() -> sp_domains::BlockFees<Balance> {
1012            BlockFees::collected_block_fees()
1013        }
1014
1015        fn block_digest() -> Digest {
1016            System::digest()
1017        }
1018
1019        fn block_weight() -> Weight {
1020            System::block_weight().total()
1021        }
1022
1023        fn construct_consensus_chain_byte_fee_extrinsic(transaction_byte_fee: Balance) -> ExtrinsicFor<Block> {
1024            UncheckedExtrinsic::new_bare(
1025                pallet_block_fees::Call::set_next_consensus_chain_byte_fee{ transaction_byte_fee }.into()
1026            )
1027        }
1028
1029        fn construct_domain_update_chain_allowlist_extrinsic(updates: DomainAllowlistUpdates) -> ExtrinsicFor<Block> {
1030             UncheckedExtrinsic::new_bare(
1031                pallet_messenger::Call::update_domain_allowlist{ updates }.into()
1032            )
1033        }
1034
1035        fn transfers() -> Transfers<Balance> {
1036            Transporter::chain_transfers()
1037        }
1038
1039        fn transfers_storage_key() -> Vec<u8> {
1040            Transporter::transfers_storage_key()
1041        }
1042
1043        fn block_fees_storage_key() -> Vec<u8> {
1044            BlockFees::block_fees_storage_key()
1045        }
1046    }
1047
1048    impl sp_messenger::MessengerApi<Block, ConsensusBlockNumber, ConsensusBlockHash> for Runtime {
1049        fn is_xdm_mmr_proof_valid(
1050            extrinsic: &ExtrinsicFor<Block>,
1051        ) -> Option<bool> {
1052            is_xdm_mmr_proof_valid(extrinsic)
1053        }
1054
1055        fn extract_xdm_mmr_proof(ext: &ExtrinsicFor<Block>) -> Option<ConsensusChainMmrLeafProof<ConsensusBlockNumber, ConsensusBlockHash, sp_core::H256>> {
1056            match &ext.function {
1057                RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })
1058                | RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
1059                    Some(msg.proof.consensus_mmr_proof())
1060                }
1061                _ => None,
1062            }
1063        }
1064
1065        fn batch_extract_xdm_mmr_proof(extrinsics: &Vec<ExtrinsicFor<Block>>) -> BTreeMap<u32, ConsensusChainMmrLeafProof<ConsensusBlockNumber, ConsensusBlockHash, sp_core::H256>> {
1066            let mut mmr_proofs = BTreeMap::new();
1067            for (index, ext) in extrinsics.iter().enumerate() {
1068                match &ext.function {
1069                    RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })
1070                    | RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
1071                        mmr_proofs.insert(index as u32, msg.proof.consensus_mmr_proof());
1072                    }
1073                    _ => {},
1074                }
1075            }
1076            mmr_proofs
1077        }
1078
1079        fn confirmed_domain_block_storage_key(_domain_id: DomainId) -> Vec<u8> {
1080            // invalid call from Domain runtime
1081            vec![]
1082        }
1083
1084        fn outbox_storage_key(message_key: MessageKey) -> Vec<u8> {
1085            Messenger::outbox_storage_key(message_key)
1086        }
1087
1088        fn inbox_response_storage_key(message_key: MessageKey) -> Vec<u8> {
1089            Messenger::inbox_response_storage_key(message_key)
1090        }
1091
1092        fn domain_chains_allowlist_update(_domain_id: DomainId) -> Option<DomainAllowlistUpdates>{
1093            // not valid call on domains
1094            None
1095        }
1096
1097        fn xdm_id(ext: &ExtrinsicFor<Block>) -> Option<XdmId> {
1098            match &ext.function {
1099                RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })=> {
1100                    Some(XdmId::RelayMessage((msg.src_chain_id, msg.channel_id, msg.nonce)))
1101                }
1102                RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
1103                    Some(XdmId::RelayResponseMessage((msg.src_chain_id, msg.channel_id, msg.nonce)))
1104                }
1105                _ => None,
1106            }
1107        }
1108
1109        fn channel_nonce(chain_id: ChainId, channel_id: ChannelId) -> Option<ChannelNonce> {
1110            Messenger::channel_nonce(chain_id, channel_id)
1111        }
1112    }
1113
1114    impl sp_messenger::RelayerApi<Block, BlockNumber, ConsensusBlockNumber, ConsensusBlockHash> for Runtime {
1115        fn block_messages() -> BlockMessagesWithStorageKey {
1116            BlockMessagesWithStorageKey::default()
1117        }
1118
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 should_relay_outbox_message(_: ChainId, _: MessageId) -> bool {
1128            false
1129        }
1130
1131        fn should_relay_inbox_message_response(_: ChainId, _: MessageId) -> bool {
1132            false
1133        }
1134
1135        fn updated_channels() -> BTreeSet<(ChainId, ChannelId)> {
1136            Messenger::updated_channels()
1137        }
1138
1139        fn channel_storage_key(chain_id: ChainId, channel_id: ChannelId) -> Vec<u8> {
1140            Messenger::channel_storage_key(chain_id, channel_id)
1141        }
1142
1143        fn open_channels() -> BTreeSet<(ChainId, ChannelId)> {
1144            Messenger::open_channels()
1145        }
1146
1147        fn block_messages_with_query(query: BlockMessagesQuery) -> MessagesWithStorageKey {
1148            Messenger::get_block_messages(query)
1149        }
1150
1151        fn channels_and_state() -> Vec<(ChainId, ChannelId, ChannelStateWithNonce)> {
1152            Messenger::channels_and_states()
1153        }
1154
1155        fn first_outbox_message_nonce_to_relay(dst_chain_id: ChainId, channel_id: ChannelId, from_nonce: XdmNonce) -> Option<XdmNonce> {
1156            Messenger::first_outbox_message_nonce_to_relay(dst_chain_id, channel_id, from_nonce)
1157        }
1158
1159        fn first_inbox_message_response_nonce_to_relay(dst_chain_id: ChainId, channel_id: ChannelId, from_nonce: XdmNonce) -> Option<XdmNonce> {
1160            Messenger::first_inbox_message_response_nonce_to_relay(dst_chain_id, channel_id, from_nonce)
1161        }
1162    }
1163
1164    impl sp_domain_sudo::DomainSudoApi<Block> for Runtime {
1165        fn is_valid_sudo_call(extrinsic: Vec<u8>) -> bool {
1166            is_valid_sudo_call(extrinsic)
1167        }
1168
1169        fn construct_domain_sudo_extrinsic(inner: Vec<u8>) -> ExtrinsicFor<Block> {
1170            construct_sudo_call_extrinsic(inner)
1171        }
1172    }
1173
1174    impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
1175        fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
1176            build_state::<RuntimeGenesisConfig>(config)
1177        }
1178
1179        fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
1180            get_preset::<RuntimeGenesisConfig>(id, |_| None)
1181        }
1182
1183        fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
1184            vec![]
1185        }
1186    }
1187
1188    impl domain_test_primitives::OnchainStateApi<Block, AccountId, Balance> for Runtime {
1189        fn free_balance(account_id: AccountId) -> Balance {
1190            Balances::free_balance(account_id)
1191        }
1192
1193        fn get_open_channel_for_chain(dst_chain_id: ChainId) -> Option<ChannelId> {
1194            Messenger::get_open_channel_for_chain(dst_chain_id)
1195        }
1196
1197        fn consensus_transaction_byte_fee() -> Balance {
1198            BlockFees::consensus_chain_byte_fee()
1199        }
1200
1201        fn storage_root() -> [u8; 32] {
1202            let version = <Runtime as frame_system::Config>::Version::get().state_version();
1203            let root = sp_io::storage::root(version);
1204            TryInto::<[u8; 32]>::try_into(root)
1205                .expect("root is a SCALE encoded hash which uses H256; qed")
1206        }
1207
1208        fn total_issuance() -> Balance {
1209            Balances::total_issuance()
1210        }
1211    }
1212
1213    #[cfg(feature = "runtime-benchmarks")]
1214    impl frame_benchmarking::Benchmark<Block> for Runtime {
1215        fn benchmark_metadata(extra: bool) -> (
1216            Vec<frame_benchmarking::BenchmarkList>,
1217            Vec<frame_support::traits::StorageInfo>,
1218        ) {
1219            use frame_benchmarking::{baseline, Benchmarking, BenchmarkList};
1220            use frame_support::traits::StorageInfoTrait;
1221            use frame_system_benchmarking::Pallet as SystemBench;
1222            use baseline::Pallet as BaselineBench;
1223
1224            let mut list = Vec::<BenchmarkList>::new();
1225
1226            list_benchmarks!(list, extra);
1227
1228            let storage_info = AllPalletsWithSystem::storage_info();
1229
1230            (list, storage_info)
1231        }
1232
1233        fn dispatch_benchmark(
1234            config: frame_benchmarking::BenchmarkConfig
1235        ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, alloc::string::String> {
1236            use frame_benchmarking::{baseline, Benchmarking, BenchmarkBatch};
1237            use sp_storage::TrackedStorageKey;
1238            use frame_system_benchmarking::Pallet as SystemBench;
1239            use frame_support::traits::WhitelistedStorageKeys;
1240            use baseline::Pallet as BaselineBench;
1241
1242            let whitelist: Vec<TrackedStorageKey> = AllPalletsWithSystem::whitelisted_storage_keys();
1243
1244            let mut batches = Vec::<BenchmarkBatch>::new();
1245            let params = (&config, &whitelist);
1246
1247            add_benchmarks!(params, batches);
1248
1249            if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }
1250            Ok(batches)
1251        }
1252    }
1253}
1254
1255#[cfg(test)]
1256mod tests {
1257    use crate::{Runtime, RuntimeBlockWeights as BlockWeights};
1258    use subspace_runtime_primitives::tests_utils::FeeMultiplierUtils;
1259
1260    #[test]
1261    fn multiplier_can_grow_from_zero() {
1262        FeeMultiplierUtils::<Runtime, BlockWeights>::multiplier_can_grow_from_zero()
1263    }
1264}