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