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