Skip to main content

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