Skip to main content

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