evm_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
6mod weights;
7
8// Make the WASM binary available.
9#[cfg(feature = "std")]
10include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
11
12extern crate alloc;
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    AccountId20, CheckExtrinsicsValidityError, DEFAULT_EXTENSION_VERSION, DecodeExtrinsicError,
21    ERR_BALANCE_OVERFLOW, ERR_CONTRACT_CREATION_NOT_ALLOWED, ERR_EVM_NONCE_OVERFLOW,
22    HoldIdentifier, MAX_OUTGOING_MESSAGES, SLOT_DURATION, TargetBlockFullness,
23};
24pub use domain_runtime_primitives::{
25    Balance, BlockNumber, EXISTENTIAL_DEPOSIT, EthereumAccountId as AccountId,
26    EthereumSignature as Signature, Hash, Nonce, block_weights, maximum_block_length,
27    maximum_domain_block_weight, opaque,
28};
29use fp_self_contained::{CheckedSignature, SelfContainedCall};
30use frame_support::dispatch::{DispatchClass, DispatchInfo, GetDispatchInfo};
31use frame_support::genesis_builder_helper::{build_state, get_preset};
32use frame_support::pallet_prelude::TypeInfo;
33use frame_support::traits::fungible::Credit;
34use frame_support::traits::{
35    ConstU16, ConstU32, ConstU64, Currency, Everything, FindAuthor, Imbalance, IsInherent,
36    OnFinalize, OnUnbalanced, VariantCount,
37};
38use frame_support::weights::constants::ParityDbWeight;
39use frame_support::weights::{ConstantMultiplier, Weight};
40use frame_support::{construct_runtime, parameter_types};
41use frame_system::limits::{BlockLength, BlockWeights};
42use frame_system::pallet_prelude::RuntimeCallFor;
43use pallet_block_fees::fees::OnChargeDomainTransaction;
44use pallet_ethereum::{
45    PostLogContent, Transaction as EthereumTransaction, TransactionAction, TransactionData,
46    TransactionStatus,
47};
48use pallet_evm::{
49    Account as EVMAccount, EnsureAddressNever, EnsureAddressRoot, FeeCalculator,
50    IdentityAddressMapping, Runner,
51};
52use pallet_evm_tracker::create_contract::{CheckContractCreation, is_create_contract_allowed};
53use pallet_evm_tracker::traits::{MaybeIntoEthCall, MaybeIntoEvmCall};
54use pallet_transporter::EndpointHandler;
55use parity_scale_codec::{Decode, DecodeLimit, Encode, MaxEncodedLen};
56use sp_api::impl_runtime_apis;
57use sp_core::crypto::KeyTypeId;
58use sp_core::{Get, H160, H256, OpaqueMetadata, U256};
59use sp_domains::execution_receipt::Transfers;
60use sp_domains::{ChannelId, DomainAllowlistUpdates, DomainId, PermissionedActionAllowedBy};
61use sp_evm_tracker::{
62    BlockGasLimit, GasLimitPovSizeRatio, GasPerByte, StorageFeeRatio, WeightPerGas,
63};
64use sp_messenger::endpoint::{Endpoint, EndpointHandler as EndpointHandlerT, EndpointId};
65use sp_messenger::messages::{
66    BlockMessagesQuery, ChainId, ChannelStateWithNonce, CrossDomainMessage, MessageId, MessageKey,
67    MessagesWithStorageKey, Nonce as XdmNonce,
68};
69use sp_messenger::{ChannelNonce, XdmId};
70use sp_messenger_host_functions::{StorageKeyRequest, get_storage_key};
71use sp_mmr_primitives::EncodableOpaqueLeaf;
72use sp_runtime::generic::{Era, ExtrinsicFormat, Preamble};
73use sp_runtime::traits::{
74    BlakeTwo256, Checkable, DispatchInfoOf, DispatchTransaction, Dispatchable, IdentityLookup,
75    Keccak256, NumberFor, One, PostDispatchInfoOf, TransactionExtension, UniqueSaturatedInto,
76    ValidateUnsigned, Zero,
77};
78use sp_runtime::transaction_validity::{
79    InvalidTransaction, TransactionSource, TransactionValidity, TransactionValidityError,
80};
81use sp_runtime::{
82    ApplyExtrinsicResult, ConsensusEngineId, Digest, ExtrinsicInclusionMode, generic,
83    impl_opaque_keys,
84};
85pub use sp_runtime::{MultiAddress, Perbill, Permill};
86use sp_std::cmp::{Ordering, max};
87use sp_std::collections::btree_map::BTreeMap;
88use sp_std::collections::btree_set::BTreeSet;
89use sp_std::marker::PhantomData;
90use sp_std::prelude::*;
91use sp_subspace_mmr::domain_mmr_runtime_interface::{
92    is_consensus_block_finalized, verify_mmr_proof,
93};
94use sp_subspace_mmr::{ConsensusChainMmrLeafProof, MmrLeaf};
95use sp_version::RuntimeVersion;
96use static_assertions::const_assert;
97use subspace_runtime_primitives::utility::{MaybeNestedCall, MaybeUtilityCall};
98use subspace_runtime_primitives::{
99    AI3, BlockHashFor, BlockNumber as ConsensusBlockNumber, DomainEventSegmentSize, ExtrinsicFor,
100    Hash as ConsensusBlockHash, HeaderFor, MAX_CALL_RECURSION_DEPTH, Moment, SHANNON,
101    SlowAdjustingFeeUpdate, XdmAdjustedWeightToFee, XdmFeeMultipler,
102};
103
104/// The address format for describing accounts.
105pub type Address = AccountId;
106
107/// Block type as expected by this runtime.
108pub type Block = generic::Block<Header, UncheckedExtrinsic>;
109
110/// A Block signed with a Justification
111pub type SignedBlock = generic::SignedBlock<Block>;
112
113/// BlockId type as expected by this runtime.
114pub type BlockId = generic::BlockId<Block>;
115
116/// Precompiles we use for EVM
117pub type Precompiles = sp_evm_precompiles::Precompiles<Runtime>;
118
119/// The SignedExtension to the basic transaction logic.
120pub type SignedExtra = (
121    frame_system::CheckNonZeroSender<Runtime>,
122    frame_system::CheckSpecVersion<Runtime>,
123    frame_system::CheckTxVersion<Runtime>,
124    frame_system::CheckGenesis<Runtime>,
125    frame_system::CheckMortality<Runtime>,
126    frame_system::CheckNonce<Runtime>,
127    domain_check_weight::CheckWeight<Runtime>,
128    pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
129    CheckContractCreation<Runtime>,
130    pallet_messenger::extensions::MessengerExtension<Runtime>,
131);
132
133/// Custom signed extra for check_and_pre_dispatch.
134/// Only Nonce check is updated and rest remains same
135type CustomSignedExtra = (
136    frame_system::CheckNonZeroSender<Runtime>,
137    frame_system::CheckSpecVersion<Runtime>,
138    frame_system::CheckTxVersion<Runtime>,
139    frame_system::CheckGenesis<Runtime>,
140    frame_system::CheckMortality<Runtime>,
141    pallet_evm_tracker::CheckNonce<Runtime>,
142    domain_check_weight::CheckWeight<Runtime>,
143    pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
144    CheckContractCreation<Runtime>,
145    pallet_messenger::extensions::MessengerTrustedMmrExtension<Runtime>,
146);
147
148/// Unchecked extrinsic type as expected by this runtime.
149pub type UncheckedExtrinsic =
150    fp_self_contained::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
151
152/// Extrinsic type that has already been checked.
153pub type CheckedExtrinsic =
154    fp_self_contained::CheckedExtrinsic<AccountId, RuntimeCall, SignedExtra, H160>;
155
156/// Executive: handles dispatch to the various modules.
157pub type Executive = domain_pallet_executive::Executive<
158    Runtime,
159    frame_system::ChainContext<Runtime>,
160    Runtime,
161    AllPalletsWithSystem,
162>;
163
164/// Returns the storage fee for `len` bytes, or an overflow error.
165fn consensus_storage_fee(len: impl TryInto<Balance>) -> Result<Balance, TransactionValidityError> {
166    // This should never fail with the current types.
167    // But if converting to Balance would overflow, so would any multiplication.
168    let len = len.try_into().map_err(|_| {
169        TransactionValidityError::Invalid(InvalidTransaction::Custom(ERR_BALANCE_OVERFLOW))
170    })?;
171
172    BlockFees::consensus_chain_byte_fee()
173        .checked_mul(Into::<Balance>::into(len))
174        .ok_or(TransactionValidityError::Invalid(
175            InvalidTransaction::Custom(ERR_BALANCE_OVERFLOW),
176        ))
177}
178
179impl fp_self_contained::SelfContainedCall for RuntimeCall {
180    type SignedInfo = H160;
181
182    fn is_self_contained(&self) -> bool {
183        match self {
184            RuntimeCall::Ethereum(call) => call.is_self_contained(),
185            _ => false,
186        }
187    }
188
189    fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {
190        match self {
191            RuntimeCall::Ethereum(call) => call.check_self_contained(),
192            _ => None,
193        }
194    }
195
196    fn validate_self_contained(
197        &self,
198        info: &Self::SignedInfo,
199        dispatch_info: &DispatchInfoOf<RuntimeCall>,
200        len: usize,
201    ) -> Option<TransactionValidity> {
202        let (is_allowed, _call_count) =
203            is_create_contract_allowed::<Runtime>(self, &(*info).into());
204        if !is_allowed {
205            return Some(Err(InvalidTransaction::Custom(
206                ERR_CONTRACT_CREATION_NOT_ALLOWED,
207            )
208            .into()));
209        }
210
211        match self {
212            RuntimeCall::Ethereum(call) => call.validate_self_contained(info, dispatch_info, len),
213            _ => None,
214        }
215    }
216
217    fn pre_dispatch_self_contained(
218        &self,
219        info: &Self::SignedInfo,
220        dispatch_info: &DispatchInfoOf<RuntimeCall>,
221        len: usize,
222    ) -> Option<Result<(), TransactionValidityError>> {
223        let (is_allowed, _call_count) =
224            is_create_contract_allowed::<Runtime>(self, &(*info).into());
225        if !is_allowed {
226            return Some(Err(InvalidTransaction::Custom(
227                ERR_CONTRACT_CREATION_NOT_ALLOWED,
228            )
229            .into()));
230        }
231
232        // TODO: move this code into pallet-block-fees, so it can be used from the production and
233        // test runtimes.
234        match self {
235            RuntimeCall::Ethereum(call) => {
236                // Copied from [`pallet_ethereum::Call::pre_dispatch_self_contained`] with `frame_system::CheckWeight`
237                // replaced with `domain_check_weight::CheckWeight`
238                if let pallet_ethereum::Call::transact { transaction } = call {
239                    let origin = RuntimeOrigin::signed(AccountId20::from(*info));
240                    if let Err(err) =
241                        <domain_check_weight::CheckWeight<Runtime> as DispatchTransaction<
242                            RuntimeCall,
243                        >>::validate_and_prepare(
244                            domain_check_weight::CheckWeight::<Runtime>::new(),
245                            origin,
246                            self,
247                            dispatch_info,
248                            len,
249                            DEFAULT_EXTENSION_VERSION,
250                        )
251                    {
252                        return Some(Err(err));
253                    }
254
255                    Some(Ethereum::validate_transaction_in_block(*info, transaction))
256                } else {
257                    None
258                }
259            }
260            _ => None,
261        }
262    }
263
264    fn apply_self_contained(
265        self,
266        info: Self::SignedInfo,
267    ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {
268        match self {
269            call @ RuntimeCall::Ethereum(pallet_ethereum::Call::transact { .. }) => {
270                let post_info = call.dispatch(RuntimeOrigin::from(
271                    pallet_ethereum::RawOrigin::EthereumTransaction(info),
272                ));
273
274                // is_self_contained() checks for an Ethereum call, which is always a single call.
275                // This call has the same number of contract checks as an EVM call, and similar
276                // fields, so we can use the EVM benchmark weight here.
277                let create_contract_ext_weight = CheckContractCreation::<Runtime>::get_weights(1);
278
279                // Add the weight of the contract creation extension check to the post info
280                Some(
281                    post_info
282                        .map(|mut post_info| {
283                            post_info.actual_weight = Some(
284                                post_info
285                                    .actual_weight
286                                    .unwrap_or_default()
287                                    .saturating_add(create_contract_ext_weight),
288                            );
289                            post_info
290                        })
291                        .map_err(|mut err_with_post_info| {
292                            err_with_post_info.post_info.actual_weight = Some(
293                                err_with_post_info
294                                    .post_info
295                                    .actual_weight
296                                    .unwrap_or_default()
297                                    .saturating_add(create_contract_ext_weight),
298                            );
299                            err_with_post_info
300                        }),
301                )
302            }
303            _ => None,
304        }
305    }
306}
307
308impl_opaque_keys! {
309    pub struct SessionKeys {
310        /// Primarily used for adding the operator signing key into the Keystore.
311        pub operator: sp_domains::OperatorKey,
312    }
313}
314
315#[sp_version::runtime_version]
316pub const VERSION: RuntimeVersion = RuntimeVersion {
317    spec_name: Cow::Borrowed("subspace-evm-domain"),
318    impl_name: Cow::Borrowed("subspace-evm-domain"),
319    authoring_version: 0,
320    spec_version: 1,
321    impl_version: 0,
322    apis: RUNTIME_API_VERSIONS,
323    transaction_version: 1,
324    system_version: 2,
325};
326
327parameter_types! {
328    pub const Version: RuntimeVersion = VERSION;
329    pub const BlockHashCount: BlockNumber = 2400;
330
331    // This part is copied from Substrate's `bin/node/runtime/src/lib.rs`.
332    //  The `RuntimeBlockLength` and `RuntimeBlockWeights` exist here because the
333    // `DeletionWeightLimit` and `DeletionQueueDepth` depend on those to parameterize
334    // the lazy contract deletion.
335    pub RuntimeBlockLength: BlockLength = maximum_block_length();
336    pub RuntimeBlockWeights: BlockWeights = block_weights();
337}
338
339impl frame_system::Config for Runtime {
340    /// The identifier used to distinguish between accounts.
341    type AccountId = AccountId;
342    /// The aggregated dispatch type that is available for extrinsics.
343    type RuntimeCall = RuntimeCall;
344    /// The aggregated `RuntimeTask` type.
345    type RuntimeTask = RuntimeTask;
346    /// The lookup mechanism to get account ID from whatever is passed in dispatchers.
347    type Lookup = IdentityLookup<AccountId>;
348    /// The type for storing how many extrinsics an account has signed.
349    type Nonce = Nonce;
350    /// The type for hashing blocks and tries.
351    type Hash = Hash;
352    /// The hashing algorithm used.
353    type Hashing = BlakeTwo256;
354    /// The block type.
355    type Block = Block;
356    /// The ubiquitous event type.
357    type RuntimeEvent = RuntimeEvent;
358    /// The ubiquitous origin type.
359    type RuntimeOrigin = RuntimeOrigin;
360    /// Maximum number of block number to block hash mappings to keep (oldest pruned first).
361    type BlockHashCount = BlockHashCount;
362    /// Runtime version.
363    type Version = Version;
364    /// Converts a module to an index of this module in the runtime.
365    type PalletInfo = PalletInfo;
366    /// The data to be stored in an account.
367    type AccountData = pallet_balances::AccountData<Balance>;
368    /// What to do if a new account is created.
369    type OnNewAccount = ();
370    /// What to do if an account is fully reaped from the system.
371    type OnKilledAccount = ();
372    /// The weight of database operations that the runtime can invoke.
373    type DbWeight = ParityDbWeight;
374    /// The basic call filter to use in dispatchable.
375    type BaseCallFilter = Everything;
376    /// Weight information for the extrinsics of this pallet.
377    type SystemWeightInfo = weights::frame_system::WeightInfo<Runtime>;
378    /// Block & extrinsics weights: base values and limits.
379    type BlockWeights = RuntimeBlockWeights;
380    /// The maximum length of a block (in bytes).
381    type BlockLength = RuntimeBlockLength;
382    type SS58Prefix = ConstU16<6094>;
383    /// The action to take on a Runtime Upgrade
384    type OnSetCode = ();
385    type SingleBlockMigrations = ();
386    type MultiBlockMigrator = ();
387    type PreInherents = ();
388    type PostInherents = ();
389    type PostTransactions = ();
390    type MaxConsumers = ConstU32<16>;
391    type ExtensionsWeightInfo = frame_system::ExtensionsWeight<Runtime>;
392    type EventSegmentSize = DomainEventSegmentSize;
393}
394
395impl pallet_timestamp::Config for Runtime {
396    /// A timestamp: milliseconds since the unix epoch.
397    type Moment = Moment;
398    type OnTimestampSet = ();
399    type MinimumPeriod = ConstU64<{ SLOT_DURATION / 2 }>;
400    type WeightInfo = weights::pallet_timestamp::WeightInfo<Runtime>;
401}
402
403parameter_types! {
404    pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
405    pub const MaxLocks: u32 = 50;
406    pub const MaxReserves: u32 = 50;
407}
408
409/// `DustRemovalHandler` used to collect all the AI3 dust left when the account is reaped.
410pub struct DustRemovalHandler;
411
412impl OnUnbalanced<Credit<AccountId, Balances>> for DustRemovalHandler {
413    fn on_nonzero_unbalanced(dusted_amount: Credit<AccountId, Balances>) {
414        BlockFees::note_burned_balance(dusted_amount.peek());
415    }
416}
417
418impl pallet_balances::Config for Runtime {
419    type RuntimeFreezeReason = RuntimeFreezeReason;
420    type MaxLocks = MaxLocks;
421    /// The type for recording an account's balance.
422    type Balance = Balance;
423    /// The ubiquitous event type.
424    type RuntimeEvent = RuntimeEvent;
425    type DustRemoval = DustRemovalHandler;
426    type ExistentialDeposit = ExistentialDeposit;
427    type AccountStore = System;
428    type WeightInfo = weights::pallet_balances::WeightInfo<Runtime>;
429    type MaxReserves = MaxReserves;
430    type ReserveIdentifier = [u8; 8];
431    type FreezeIdentifier = ();
432    type MaxFreezes = ();
433    type RuntimeHoldReason = HoldIdentifierWrapper;
434    type DoneSlashHandler = ();
435}
436
437parameter_types! {
438    pub const OperationalFeeMultiplier: u8 = 5;
439    pub const DomainChainByteFee: Balance = 100_000 * SHANNON;
440    pub TransactionWeightFee: Balance = 100_000 * SHANNON;
441}
442
443impl pallet_block_fees::Config for Runtime {
444    type Balance = Balance;
445    type DomainChainByteFee = DomainChainByteFee;
446}
447
448type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;
449
450pub struct FinalDomainTransactionByteFee;
451
452impl Get<Balance> for FinalDomainTransactionByteFee {
453    fn get() -> Balance {
454        BlockFees::final_domain_transaction_byte_fee()
455    }
456}
457
458impl pallet_transaction_payment::Config for Runtime {
459    type RuntimeEvent = RuntimeEvent;
460    type OnChargeTransaction = OnChargeDomainTransaction<Balances>;
461    type WeightToFee = ConstantMultiplier<Balance, TransactionWeightFee>;
462    type LengthToFee = ConstantMultiplier<Balance, FinalDomainTransactionByteFee>;
463    type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Runtime, TargetBlockFullness>;
464    type OperationalFeeMultiplier = OperationalFeeMultiplier;
465    type WeightInfo = weights::pallet_transaction_payment::WeightInfo<Runtime>;
466}
467
468pub struct ExtrinsicStorageFees;
469
470impl domain_pallet_executive::ExtrinsicStorageFees<Runtime> for ExtrinsicStorageFees {
471    fn extract_signer(xt: UncheckedExtrinsic) -> (Option<AccountId>, DispatchInfo) {
472        let dispatch_info = xt.get_dispatch_info();
473        let lookup = frame_system::ChainContext::<Runtime>::default();
474        let maybe_signer = extract_signer_inner(&xt, &lookup).and_then(|res| res.ok());
475        (maybe_signer, dispatch_info)
476    }
477
478    fn on_storage_fees_charged(
479        charged_fees: Balance,
480        tx_size: u32,
481    ) -> Result<(), TransactionValidityError> {
482        let consensus_storage_fee = consensus_storage_fee(tx_size)?;
483
484        let (paid_consensus_storage_fee, paid_domain_fee) = if charged_fees <= consensus_storage_fee
485        {
486            (charged_fees, Zero::zero())
487        } else {
488            (consensus_storage_fee, charged_fees - consensus_storage_fee)
489        };
490
491        BlockFees::note_consensus_storage_fee(paid_consensus_storage_fee);
492        BlockFees::note_domain_execution_fee(paid_domain_fee);
493        Ok(())
494    }
495}
496
497impl domain_pallet_executive::Config for Runtime {
498    type RuntimeEvent = RuntimeEvent;
499    type WeightInfo = weights::domain_pallet_executive::WeightInfo<Runtime>;
500    type Currency = Balances;
501    type LengthToFee = <Runtime as pallet_transaction_payment::Config>::LengthToFee;
502    type ExtrinsicStorageFees = ExtrinsicStorageFees;
503}
504
505parameter_types! {
506    pub SelfChainId: ChainId = SelfDomainId::self_domain_id().into();
507}
508
509pub struct OnXDMRewards;
510
511impl sp_messenger::OnXDMRewards<Balance> for OnXDMRewards {
512    fn on_xdm_rewards(rewards: Balance) {
513        BlockFees::note_domain_execution_fee(rewards)
514    }
515
516    fn on_chain_protocol_fees(chain_id: ChainId, fees: Balance) {
517        // note the chain rewards
518        BlockFees::note_chain_rewards(chain_id, fees);
519    }
520}
521
522type MmrHash = <Keccak256 as sp_runtime::traits::Hash>::Output;
523
524pub struct MmrProofVerifier;
525
526impl sp_subspace_mmr::MmrProofVerifier<MmrHash, NumberFor<Block>, Hash> for MmrProofVerifier {
527    fn verify_proof_and_extract_leaf(
528        mmr_leaf_proof: ConsensusChainMmrLeafProof<NumberFor<Block>, Hash, MmrHash>,
529    ) -> Option<MmrLeaf<ConsensusBlockNumber, ConsensusBlockHash>> {
530        let ConsensusChainMmrLeafProof {
531            consensus_block_number,
532            opaque_mmr_leaf: opaque_leaf,
533            proof,
534            ..
535        } = mmr_leaf_proof;
536
537        if !is_consensus_block_finalized(consensus_block_number) {
538            return None;
539        }
540
541        let leaf: MmrLeaf<ConsensusBlockNumber, ConsensusBlockHash> =
542            opaque_leaf.into_opaque_leaf().try_decode()?;
543
544        verify_mmr_proof(vec![EncodableOpaqueLeaf::from_leaf(&leaf)], proof.encode())
545            .then_some(leaf)
546    }
547}
548
549pub struct StorageKeys;
550
551impl sp_messenger::StorageKeys for StorageKeys {
552    fn confirmed_domain_block_storage_key(domain_id: DomainId) -> Option<Vec<u8>> {
553        get_storage_key(StorageKeyRequest::ConfirmedDomainBlockStorageKey(domain_id))
554    }
555
556    fn outbox_storage_key(chain_id: ChainId, message_key: MessageKey) -> Option<Vec<u8>> {
557        get_storage_key(StorageKeyRequest::OutboxStorageKey {
558            chain_id,
559            message_key,
560        })
561    }
562
563    fn inbox_responses_storage_key(chain_id: ChainId, message_key: MessageKey) -> Option<Vec<u8>> {
564        get_storage_key(StorageKeyRequest::InboxResponseStorageKey {
565            chain_id,
566            message_key,
567        })
568    }
569}
570
571/// Hold identifier for balances for this runtime.
572#[derive(
573    PartialEq, Eq, Clone, Encode, Decode, TypeInfo, MaxEncodedLen, Ord, PartialOrd, Copy, Debug,
574)]
575pub struct HoldIdentifierWrapper(HoldIdentifier);
576
577impl VariantCount for HoldIdentifierWrapper {
578    const VARIANT_COUNT: u32 = mem::variant_count::<HoldIdentifier>() as u32;
579}
580
581impl pallet_messenger::HoldIdentifier<Runtime> for HoldIdentifierWrapper {
582    fn messenger_channel() -> Self {
583        Self(HoldIdentifier::MessengerChannel)
584    }
585}
586
587parameter_types! {
588    pub const ChannelReserveFee: Balance = 100 * AI3;
589    pub const ChannelInitReservePortion: Perbill = Perbill::from_percent(20);
590    pub const MaxOutgoingMessages: u32 = MAX_OUTGOING_MESSAGES;
591}
592
593// ensure the max outgoing messages is not 0.
594const_assert!(MaxOutgoingMessages::get() >= 1);
595
596impl pallet_messenger::Config for Runtime {
597    type RuntimeEvent = RuntimeEvent;
598    type SelfChainId = SelfChainId;
599
600    fn get_endpoint_handler(endpoint: &Endpoint) -> Option<Box<dyn EndpointHandlerT<MessageId>>> {
601        if endpoint == &Endpoint::Id(TransporterEndpointId::get()) {
602            Some(Box::new(EndpointHandler(PhantomData::<Runtime>)))
603        } else {
604            None
605        }
606    }
607
608    type Currency = Balances;
609    type WeightInfo = weights::pallet_messenger::WeightInfo<Runtime>;
610    type WeightToFee = ConstantMultiplier<Balance, TransactionWeightFee>;
611    type AdjustedWeightToFee = XdmAdjustedWeightToFee<Runtime>;
612    type FeeMultiplier = XdmFeeMultipler;
613    type OnXDMRewards = OnXDMRewards;
614    type MmrHash = MmrHash;
615    type MmrProofVerifier = MmrProofVerifier;
616    #[cfg(feature = "runtime-benchmarks")]
617    type StorageKeys = sp_messenger::BenchmarkStorageKeys;
618    #[cfg(not(feature = "runtime-benchmarks"))]
619    type StorageKeys = StorageKeys;
620    type DomainOwner = ();
621    type HoldIdentifier = HoldIdentifierWrapper;
622    type ChannelReserveFee = ChannelReserveFee;
623    type ChannelInitReservePortion = ChannelInitReservePortion;
624    type DomainRegistration = ();
625    type MaxOutgoingMessages = MaxOutgoingMessages;
626    type MessengerOrigin = pallet_messenger::EnsureMessengerOrigin;
627    type NoteChainTransfer = Transporter;
628    type ExtensionWeightInfo = pallet_messenger::extensions::weights::SubstrateWeight<
629        Runtime,
630        weights::pallet_messenger_from_consensus_extension::WeightInfo<Runtime>,
631        weights::pallet_messenger_between_domains_extension::WeightInfo<Runtime>,
632    >;
633}
634
635impl<C> frame_system::offchain::CreateTransactionBase<C> for Runtime
636where
637    RuntimeCall: From<C>,
638{
639    type Extrinsic = UncheckedExtrinsic;
640    type RuntimeCall = RuntimeCall;
641}
642
643parameter_types! {
644    pub const TransporterEndpointId: EndpointId = 1;
645    pub const MinimumTransfer: Balance = AI3;
646}
647
648impl pallet_transporter::Config for Runtime {
649    type RuntimeEvent = RuntimeEvent;
650    type SelfChainId = SelfChainId;
651    type SelfEndpointId = TransporterEndpointId;
652    type Currency = Balances;
653    type Sender = Messenger;
654    type AccountIdConverter = domain_runtime_primitives::AccountId20Converter;
655    type WeightInfo = weights::pallet_transporter::WeightInfo<Runtime>;
656    type MinimumTransfer = MinimumTransfer;
657}
658
659impl pallet_evm_chain_id::Config for Runtime {}
660
661pub struct FindAuthorTruncated;
662
663impl FindAuthor<H160> for FindAuthorTruncated {
664    fn find_author<'a, I>(_digests: I) -> Option<H160>
665    where
666        I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,
667    {
668        // TODO: returns the executor reward address once we start collecting them
669        None
670    }
671}
672
673parameter_types! {
674    pub PrecompilesValue: Precompiles = Precompiles::default();
675}
676
677/// UnbalancedHandler that will just burn any unbalanced funds
678pub struct UnbalancedHandler {}
679impl OnUnbalanced<NegativeImbalance> for UnbalancedHandler {}
680
681type InnerEVMCurrencyAdapter = pallet_evm::EVMCurrencyAdapter<Balances, UnbalancedHandler>;
682
683// Implementation of [`pallet_transaction_payment::OnChargeTransaction`] that charges evm transaction
684// fees from the transaction sender and collect all the fees (including both the base fee and tip) in
685// `pallet_block_fees`
686pub struct EVMCurrencyAdapter;
687
688impl pallet_evm::OnChargeEVMTransaction<Runtime> for EVMCurrencyAdapter {
689    type LiquidityInfo = Option<NegativeImbalance>;
690
691    fn withdraw_fee(
692        who: &H160,
693        fee: U256,
694    ) -> Result<Self::LiquidityInfo, pallet_evm::Error<Runtime>> {
695        InnerEVMCurrencyAdapter::withdraw_fee(who, fee)
696    }
697
698    fn correct_and_deposit_fee(
699        who: &H160,
700        corrected_fee: U256,
701        base_fee: U256,
702        already_withdrawn: Self::LiquidityInfo,
703    ) -> Self::LiquidityInfo {
704        if already_withdrawn.is_some() {
705            // Record the evm actual transaction fee and storage fee
706            let (storage_fee, execution_fee) =
707                EvmGasPriceCalculator::split_fee_into_storage_and_execution(
708                    corrected_fee.as_u128(),
709                );
710            BlockFees::note_consensus_storage_fee(storage_fee);
711            BlockFees::note_domain_execution_fee(execution_fee);
712        }
713
714        <InnerEVMCurrencyAdapter as pallet_evm::OnChargeEVMTransaction<
715            Runtime,
716        >>::correct_and_deposit_fee(who, corrected_fee, base_fee, already_withdrawn)
717    }
718
719    fn pay_priority_fee(tip: Self::LiquidityInfo) {
720        if let Some(fee) = tip {
721            // handle the priority fee just like the base fee.
722            // for eip-1559, total fees will be base_fee + priority_fee
723            UnbalancedHandler::on_unbalanced(fee)
724        }
725    }
726}
727
728pub type EvmGasPriceCalculator = pallet_evm_tracker::fees::EvmGasPriceCalculator<
729    Runtime,
730    TransactionWeightFee,
731    GasPerByte,
732    StorageFeeRatio,
733>;
734
735impl pallet_evm::Config for Runtime {
736    type AccountProvider = pallet_evm::FrameSystemAccountProvider<Self>;
737    type FeeCalculator = EvmGasPriceCalculator;
738    type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
739    type WeightPerGas = WeightPerGas;
740    type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;
741    type CallOrigin = EnsureAddressRoot<AccountId>;
742    type WithdrawOrigin = EnsureAddressNever<AccountId>;
743    type AddressMapping = IdentityAddressMapping;
744    type Currency = Balances;
745    type RuntimeEvent = RuntimeEvent;
746    type PrecompilesType = Precompiles;
747    type PrecompilesValue = PrecompilesValue;
748    type ChainId = EVMChainId;
749    type BlockGasLimit = BlockGasLimit;
750    type Runner = pallet_evm::runner::stack::Runner<Self>;
751    type OnChargeTransaction = EVMCurrencyAdapter;
752    type OnCreate = ();
753    type FindAuthor = FindAuthorTruncated;
754    type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
755    // TODO: re-check this value mostly from moonbeam
756    type GasLimitStorageGrowthRatio = ();
757    type Timestamp = Timestamp;
758    type WeightInfo = weights::pallet_evm::WeightInfo<Runtime>;
759}
760
761impl MaybeIntoEvmCall<Runtime> for RuntimeCall {
762    /// If this call is a `pallet_evm::Call<Runtime>` call, returns the inner call.
763    fn maybe_into_evm_call(&self) -> Option<&pallet_evm::Call<Runtime>> {
764        match self {
765            RuntimeCall::EVM(call) => Some(call),
766            _ => None,
767        }
768    }
769}
770
771impl pallet_evm_tracker::Config for Runtime {}
772
773parameter_types! {
774    pub const PostOnlyBlockHash: PostLogContent = PostLogContent::OnlyBlockHash;
775}
776
777impl pallet_ethereum::Config for Runtime {
778    type RuntimeEvent = RuntimeEvent;
779    type StateRoot = pallet_ethereum::IntermediateStateRoot<Self::Version>;
780    type PostLogContent = PostOnlyBlockHash;
781    type ExtraDataLength = ConstU32<30>;
782}
783
784impl MaybeIntoEthCall<Runtime> for RuntimeCall {
785    /// If this call is a `pallet_ethereum::Call<Runtime>` call, returns the inner call.
786    fn maybe_into_eth_call(&self) -> Option<&pallet_ethereum::Call<Runtime>> {
787        match self {
788            RuntimeCall::Ethereum(call) => Some(call),
789            _ => None,
790        }
791    }
792}
793
794impl pallet_domain_id::Config for Runtime {}
795
796pub struct IntoRuntimeCall;
797
798impl sp_domain_sudo::IntoRuntimeCall<RuntimeCall> for IntoRuntimeCall {
799    fn runtime_call(call: Vec<u8>) -> RuntimeCall {
800        UncheckedExtrinsic::decode(&mut call.as_slice())
801            .expect("must always be a valid domain extrinsic as checked by consensus chain; qed")
802            .0
803            .function
804    }
805}
806
807impl pallet_domain_sudo::Config for Runtime {
808    type RuntimeEvent = RuntimeEvent;
809    type RuntimeCall = RuntimeCall;
810    type IntoRuntimeCall = IntoRuntimeCall;
811}
812
813impl pallet_utility::Config for Runtime {
814    type RuntimeEvent = RuntimeEvent;
815    type RuntimeCall = RuntimeCall;
816    type PalletsOrigin = OriginCaller;
817    type WeightInfo = weights::pallet_utility::WeightInfo<Runtime>;
818}
819
820impl MaybeUtilityCall<Runtime> for RuntimeCall {
821    /// If this call is a `pallet_utility::Call<Runtime>` call, returns the inner call.
822    fn maybe_utility_call(&self) -> Option<&pallet_utility::Call<Runtime>> {
823        match self {
824            RuntimeCall::Utility(call) => Some(call),
825            _ => None,
826        }
827    }
828}
829
830impl MaybeNestedCall<Runtime> for RuntimeCall {
831    /// If this call is a nested runtime call, returns the inner call(s).
832    ///
833    /// Ignored calls (such as `pallet_utility::Call::__Ignore`) should be yielded themsevles, but
834    /// their contents should not be yielded.
835    fn maybe_nested_call(&self) -> Option<Vec<&RuntimeCallFor<Runtime>>> {
836        // We currently ignore privileged calls, because privileged users can already change
837        // runtime code. Domain sudo `RuntimeCall`s also have to pass inherent validation.
838        self.maybe_nested_utility_calls()
839    }
840}
841
842// Create the runtime by composing the FRAME pallets that were previously configured.
843//
844// NOTE: Currently domain runtime does not naturally support the pallets with inherent extrinsics.
845construct_runtime!(
846    pub struct Runtime {
847        // System support stuff.
848        System: frame_system = 0,
849        // Note: Ensure index of the timestamp matches with the index of timestamp on Consensus
850        //  so that consensus can constructed encoded extrinsic that matches with Domain encoded
851        //  extrinsic.
852        Timestamp: pallet_timestamp = 1,
853        ExecutivePallet: domain_pallet_executive = 2,
854        Utility: pallet_utility = 8,
855
856        // monetary stuff
857        Balances: pallet_balances = 20,
858        TransactionPayment: pallet_transaction_payment = 21,
859
860        // messenger stuff
861        // Note: Indexes should match with indexes on other chains and domains
862        Messenger: pallet_messenger = 60,
863        Transporter: pallet_transporter = 61,
864
865        // evm stuff
866        Ethereum: pallet_ethereum = 80,
867        EVM: pallet_evm = 81,
868        EVMChainId: pallet_evm_chain_id = 82,
869        EVMNoncetracker: pallet_evm_tracker = 84,
870
871        // domain instance stuff
872        SelfDomainId: pallet_domain_id = 90,
873        BlockFees: pallet_block_fees = 91,
874
875        // Sudo account
876        Sudo: pallet_domain_sudo = 100,
877    }
878);
879
880#[derive(Clone, Default)]
881pub struct TransactionConverter;
882
883impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {
884    fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {
885        UncheckedExtrinsic::new_bare(
886            pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),
887        )
888    }
889}
890
891impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {
892    fn convert_transaction(
893        &self,
894        transaction: pallet_ethereum::Transaction,
895    ) -> opaque::UncheckedExtrinsic {
896        let extrinsic = UncheckedExtrinsic::new_bare(
897            pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),
898        );
899        let encoded = extrinsic.encode();
900        opaque::UncheckedExtrinsic::decode(&mut &encoded[..])
901            .expect("Encoded extrinsic is always valid")
902    }
903}
904
905fn is_xdm_mmr_proof_valid(ext: &ExtrinsicFor<Block>) -> Option<bool> {
906    match &ext.0.function {
907        RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })
908        | RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
909            let ConsensusChainMmrLeafProof {
910                consensus_block_number,
911                opaque_mmr_leaf,
912                proof,
913                ..
914            } = msg.proof.consensus_mmr_proof();
915
916            if !is_consensus_block_finalized(consensus_block_number) {
917                return Some(false);
918            }
919
920            Some(verify_mmr_proof(vec![opaque_mmr_leaf], proof.encode()))
921        }
922        _ => None,
923    }
924}
925
926/// Returns `true` if this is a validly encoded Sudo call.
927fn is_valid_sudo_call(encoded_ext: Vec<u8>) -> bool {
928    UncheckedExtrinsic::decode_all_with_depth_limit(
929        MAX_CALL_RECURSION_DEPTH,
930        &mut encoded_ext.as_slice(),
931    )
932    .is_ok()
933}
934
935/// Constructs a domain-sudo call extrinsic from the given encoded extrinsic.
936fn construct_sudo_call_extrinsic(encoded_ext: Vec<u8>) -> ExtrinsicFor<Block> {
937    let ext = UncheckedExtrinsic::decode(&mut encoded_ext.as_slice()).expect(
938        "must always be a valid extrinsic due to the check above and storage proof check; qed",
939    );
940    UncheckedExtrinsic::new_bare(
941        pallet_domain_sudo::Call::sudo {
942            call: Box::new(ext.0.function),
943        }
944        .into(),
945    )
946}
947
948/// Constructs an evm-tracker call extrinsic from the given extrinsic.
949fn construct_evm_contract_creation_allowed_by_extrinsic(
950    decoded_argument: PermissionedActionAllowedBy<AccountId>,
951) -> ExtrinsicFor<Block> {
952    UncheckedExtrinsic::new_bare(
953        pallet_evm_tracker::Call::set_contract_creation_allowed_by {
954            contract_creation_allowed_by: decoded_argument,
955        }
956        .into(),
957    )
958}
959
960fn extract_signer_inner<Lookup>(
961    ext: &UncheckedExtrinsic,
962    lookup: &Lookup,
963) -> Option<Result<AccountId, TransactionValidityError>>
964where
965    Lookup: sp_runtime::traits::Lookup<Source = Address, Target = AccountId>,
966{
967    if ext.0.function.is_self_contained() {
968        ext.0
969            .function
970            .check_self_contained()
971            .map(|signed_info| signed_info.map(|signer| signer.into()))
972    } else {
973        match &ext.0.preamble {
974            Preamble::Bare(_) | Preamble::General(_, _) => None,
975            Preamble::Signed(address, _, _) => Some(lookup.lookup(*address).map_err(|e| e.into())),
976        }
977    }
978}
979
980pub fn extract_signer(
981    extrinsics: Vec<UncheckedExtrinsic>,
982) -> Vec<(Option<opaque::AccountId>, UncheckedExtrinsic)> {
983    let lookup = frame_system::ChainContext::<Runtime>::default();
984
985    extrinsics
986        .into_iter()
987        .map(|extrinsic| {
988            let maybe_signer =
989                extract_signer_inner(&extrinsic, &lookup).and_then(|account_result| {
990                    account_result.ok().map(|account_id| account_id.encode())
991                });
992            (maybe_signer, extrinsic)
993        })
994        .collect()
995}
996
997fn extrinsic_era(extrinsic: &ExtrinsicFor<Block>) -> Option<Era> {
998    match &extrinsic.0.preamble {
999        Preamble::Bare(_) | Preamble::General(_, _) => None,
1000        Preamble::Signed(_, _, extra) => Some(extra.4.0),
1001    }
1002}
1003
1004#[cfg(feature = "runtime-benchmarks")]
1005mod benches {
1006    frame_benchmarking::define_benchmarks!(
1007        [frame_benchmarking, BaselineBench::<Runtime>]
1008        [frame_system, SystemBench::<Runtime>]
1009        [pallet_timestamp, Timestamp]
1010        [domain_pallet_executive, ExecutivePallet]
1011        [pallet_utility, Utility]
1012        [pallet_balances, Balances]
1013        [pallet_transaction_payment, TransactionPayment]
1014        [pallet_messenger, Messenger]
1015        [pallet_messenger_from_consensus_extension, MessengerFromConsensusExtensionBench::<Runtime>]
1016        [pallet_messenger_between_domains_extension, MessengerBetweenDomainsExtensionBench::<Runtime>]
1017        [pallet_transporter, Transporter]
1018        // pallet_ethereum uses `pallet_evm::Config::GasWeightMapping::gas_to_weight` to weight its calls
1019        [pallet_evm, EVM]
1020        // pallet_evm_chain_id has no calls to benchmark
1021        [pallet_evm_tracker, EVMNoncetracker]
1022        // TODO: pallet_evm_tracker CheckNonce extension benchmarks
1023        // pallet_domain_id has no calls to benchmark
1024        // pallet_block_fees uses a default over-estimated weight
1025        // pallet_domain_sudo only has inherent calls
1026    );
1027}
1028
1029/// Custom pre_dispatch for extrinsic verification.
1030/// Most of the logic is same as `pre_dispatch_self_contained` except
1031/// - we use `validate_self_contained` instead `pre_dispatch_self_contained`
1032///   since the nonce is not incremented in `pre_dispatch_self_contained`
1033/// - Manually track the account nonce to check either Stale or Future nonce.
1034fn pre_dispatch_evm_transaction(
1035    account_id: H160,
1036    call: RuntimeCall,
1037    dispatch_info: &DispatchInfoOf<RuntimeCall>,
1038    len: usize,
1039) -> Result<(), TransactionValidityError> {
1040    match call {
1041        RuntimeCall::Ethereum(call) => {
1042            if let Some(transaction_validity) =
1043                call.validate_self_contained(&account_id, dispatch_info, len)
1044            {
1045                let _ = transaction_validity?;
1046
1047                let pallet_ethereum::Call::transact { transaction } = call;
1048                frame_system::CheckWeight::<Runtime>::do_validate(dispatch_info, len).and_then(
1049                    |(_, next_len)| {
1050                        domain_check_weight::CheckWeight::<Runtime>::do_prepare(
1051                            dispatch_info,
1052                            len,
1053                            next_len,
1054                        )
1055                    },
1056                )?;
1057
1058                let transaction_data: TransactionData = (&transaction).into();
1059                let transaction_nonce = transaction_data.nonce;
1060                // If the current account nonce is greater than the tracked nonce, then
1061                // pick the highest nonce
1062                let account_nonce = {
1063                    let tracked_nonce = EVMNoncetracker::account_nonce(AccountId::from(account_id))
1064                        .unwrap_or(U256::zero());
1065                    let account_nonce = EVM::account_basic(&account_id).0.nonce;
1066                    max(tracked_nonce, account_nonce)
1067                };
1068
1069                match transaction_nonce.cmp(&account_nonce) {
1070                    Ordering::Less => return Err(InvalidTransaction::Stale.into()),
1071                    Ordering::Greater => return Err(InvalidTransaction::Future.into()),
1072                    Ordering::Equal => {}
1073                }
1074
1075                let next_nonce = account_nonce
1076                    .checked_add(U256::one())
1077                    .ok_or(InvalidTransaction::Custom(ERR_EVM_NONCE_OVERFLOW))?;
1078
1079                EVMNoncetracker::set_account_nonce(AccountId::from(account_id), next_nonce);
1080            }
1081
1082            Ok(())
1083        }
1084        _ => Err(InvalidTransaction::Call.into()),
1085    }
1086}
1087
1088fn check_transaction_and_do_pre_dispatch_inner(
1089    uxt: &ExtrinsicFor<Block>,
1090) -> Result<(), TransactionValidityError> {
1091    let lookup = frame_system::ChainContext::<Runtime>::default();
1092
1093    let xt = uxt.clone().check(&lookup)?;
1094
1095    let dispatch_info = xt.get_dispatch_info();
1096
1097    if dispatch_info.class == DispatchClass::Mandatory {
1098        return Err(InvalidTransaction::MandatoryValidation.into());
1099    }
1100
1101    let encoded_len = uxt.encoded_size();
1102
1103    // We invoke `pre_dispatch` in addition to `validate_transaction`(even though the validation is almost same)
1104    // as that will add the side effect of SignedExtension in the storage buffer
1105    // which would help to maintain context across multiple transaction validity check against same
1106    // runtime instance.
1107    match xt.signed {
1108        CheckedSignature::GenericDelegated(format) => match format {
1109            ExtrinsicFormat::Bare => {
1110                Runtime::pre_dispatch(&xt.function).map(|_| ())?;
1111                <SignedExtra as TransactionExtension<RuntimeCall>>::bare_validate_and_prepare(
1112                    &xt.function,
1113                    &dispatch_info,
1114                    encoded_len,
1115                )
1116                .map(|_| ())
1117            }
1118            ExtrinsicFormat::General(extension_version, extra) => {
1119                let custom_extra: CustomSignedExtra = (
1120                    extra.0,
1121                    extra.1,
1122                    extra.2,
1123                    extra.3,
1124                    extra.4,
1125                    pallet_evm_tracker::CheckNonce::from(extra.5.0),
1126                    extra.6,
1127                    extra.7.clone(),
1128                    extra.8,
1129                    pallet_messenger::extensions::MessengerTrustedMmrExtension::<Runtime>::new(),
1130                );
1131
1132                let origin = RuntimeOrigin::none();
1133                <CustomSignedExtra as DispatchTransaction<RuntimeCall>>::validate_and_prepare(
1134                    custom_extra,
1135                    origin,
1136                    &xt.function,
1137                    &dispatch_info,
1138                    encoded_len,
1139                    extension_version,
1140                )
1141                .map(|_| ())
1142            }
1143            ExtrinsicFormat::Signed(account_id, extra) => {
1144                let custom_extra: CustomSignedExtra = (
1145                    extra.0,
1146                    extra.1,
1147                    extra.2,
1148                    extra.3,
1149                    extra.4,
1150                    pallet_evm_tracker::CheckNonce::from(extra.5.0),
1151                    extra.6,
1152                    extra.7.clone(),
1153                    extra.8,
1154                    // trusted MMR extension here does not matter since this extension
1155                    // will only affect unsigned extrinsics but not signed extrinsics
1156                    pallet_messenger::extensions::MessengerTrustedMmrExtension::<Runtime>::new(),
1157                );
1158
1159                let origin = RuntimeOrigin::signed(account_id);
1160                <CustomSignedExtra as DispatchTransaction<RuntimeCall>>::validate_and_prepare(
1161                    custom_extra,
1162                    origin,
1163                    &xt.function,
1164                    &dispatch_info,
1165                    encoded_len,
1166                    DEFAULT_EXTENSION_VERSION,
1167                )
1168                .map(|_| ())
1169            }
1170        },
1171        CheckedSignature::SelfContained(account_id) => {
1172            pre_dispatch_evm_transaction(account_id, xt.function, &dispatch_info, encoded_len)
1173        }
1174    }
1175}
1176
1177impl pallet_messenger::extensions::MaybeMessengerCall<Runtime> for RuntimeCall {
1178    fn maybe_messenger_call(&self) -> Option<&pallet_messenger::Call<Runtime>> {
1179        match self {
1180            RuntimeCall::Messenger(call) => Some(call),
1181            _ => None,
1182        }
1183    }
1184}
1185
1186impl<C> subspace_runtime_primitives::CreateUnsigned<C> for Runtime
1187where
1188    RuntimeCall: From<C>,
1189{
1190    fn create_unsigned(call: Self::RuntimeCall) -> Self::Extrinsic {
1191        create_unsigned_general_extrinsic(call)
1192    }
1193}
1194
1195fn create_unsigned_general_extrinsic(call: RuntimeCall) -> UncheckedExtrinsic {
1196    let extra: SignedExtra = (
1197        frame_system::CheckNonZeroSender::<Runtime>::new(),
1198        frame_system::CheckSpecVersion::<Runtime>::new(),
1199        frame_system::CheckTxVersion::<Runtime>::new(),
1200        frame_system::CheckGenesis::<Runtime>::new(),
1201        frame_system::CheckMortality::<Runtime>::from(generic::Era::Immortal),
1202        // for unsigned extrinsic, nonce check will be skipped
1203        // so set a default value
1204        frame_system::CheckNonce::<Runtime>::from(0u32),
1205        domain_check_weight::CheckWeight::<Runtime>::new(),
1206        // for unsigned extrinsic, transaction fee check will be skipped
1207        // so set a default value
1208        pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(0u128),
1209        CheckContractCreation::<Runtime>::new(),
1210        pallet_messenger::extensions::MessengerExtension::<Runtime>::new(),
1211    );
1212
1213    UncheckedExtrinsic::from(generic::UncheckedExtrinsic::new_transaction(call, extra))
1214}
1215
1216#[cfg(feature = "runtime-benchmarks")]
1217impl frame_system_benchmarking::Config for Runtime {}
1218
1219#[cfg(feature = "runtime-benchmarks")]
1220impl frame_benchmarking::baseline::Config for Runtime {}
1221
1222impl_runtime_apis! {
1223    impl sp_api::Core<Block> for Runtime {
1224        fn version() -> RuntimeVersion {
1225            VERSION
1226        }
1227
1228        fn execute_block(block: Block) {
1229            Executive::execute_block(block)
1230        }
1231
1232        fn initialize_block(header: &HeaderFor<Block>) -> ExtrinsicInclusionMode {
1233            Executive::initialize_block(header)
1234        }
1235    }
1236
1237    impl sp_api::Metadata<Block> for Runtime {
1238        fn metadata() -> OpaqueMetadata {
1239            OpaqueMetadata::new(Runtime::metadata().into())
1240        }
1241
1242        fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
1243            Runtime::metadata_at_version(version)
1244        }
1245
1246        fn metadata_versions() -> Vec<u32> {
1247            Runtime::metadata_versions()
1248        }
1249    }
1250
1251    impl sp_block_builder::BlockBuilder<Block> for Runtime {
1252        fn apply_extrinsic(extrinsic: ExtrinsicFor<Block>) -> ApplyExtrinsicResult {
1253            Executive::apply_extrinsic(extrinsic)
1254        }
1255
1256        fn finalize_block() -> HeaderFor<Block> {
1257            Executive::finalize_block()
1258        }
1259
1260        fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<ExtrinsicFor<Block>> {
1261            data.create_extrinsics()
1262        }
1263
1264        fn check_inherents(
1265            block: Block,
1266            data: sp_inherents::InherentData,
1267        ) -> sp_inherents::CheckInherentsResult {
1268            data.check_extrinsics(&block)
1269        }
1270    }
1271
1272    impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
1273        fn validate_transaction(
1274            source: TransactionSource,
1275            tx: ExtrinsicFor<Block>,
1276            block_hash: BlockHashFor<Block>,
1277        ) -> TransactionValidity {
1278            Executive::validate_transaction(source, tx, block_hash)
1279        }
1280    }
1281
1282    impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
1283        fn offchain_worker(header: &HeaderFor<Block>) {
1284            Executive::offchain_worker(header)
1285        }
1286    }
1287
1288    impl sp_session::SessionKeys<Block> for Runtime {
1289        fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
1290            SessionKeys::generate(seed)
1291        }
1292
1293        fn decode_session_keys(
1294            encoded: Vec<u8>,
1295        ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
1296            SessionKeys::decode_into_raw_public_keys(&encoded)
1297        }
1298    }
1299
1300    impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
1301        fn account_nonce(account: AccountId) -> Nonce {
1302            System::account_nonce(account)
1303        }
1304    }
1305
1306    impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {
1307        fn query_info(
1308            uxt: ExtrinsicFor<Block>,
1309            len: u32,
1310        ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
1311            TransactionPayment::query_info(uxt, len)
1312        }
1313        fn query_fee_details(
1314            uxt: ExtrinsicFor<Block>,
1315            len: u32,
1316        ) -> pallet_transaction_payment::FeeDetails<Balance> {
1317            TransactionPayment::query_fee_details(uxt, len)
1318        }
1319        fn query_weight_to_fee(weight: Weight) -> Balance {
1320            TransactionPayment::weight_to_fee(weight)
1321        }
1322        fn query_length_to_fee(length: u32) -> Balance {
1323            TransactionPayment::length_to_fee(length)
1324        }
1325    }
1326
1327    impl sp_domains::core_api::DomainCoreApi<Block> for Runtime {
1328        fn extract_signer(
1329            extrinsics: Vec<ExtrinsicFor<Block>>,
1330        ) -> Vec<(Option<opaque::AccountId>, ExtrinsicFor<Block>)> {
1331            extract_signer(extrinsics)
1332        }
1333
1334        fn is_within_tx_range(
1335            extrinsic: &ExtrinsicFor<Block>,
1336            bundle_vrf_hash: &subspace_core_primitives::U256,
1337            tx_range: &subspace_core_primitives::U256
1338        ) -> bool {
1339            use subspace_core_primitives::U256;
1340            use subspace_core_primitives::hashes::blake3_hash;
1341
1342            let lookup = frame_system::ChainContext::<Runtime>::default();
1343            if let Some(signer) = extract_signer_inner(extrinsic, &lookup).and_then(|account_result| {
1344                    account_result.ok().map(|account_id| account_id.encode())
1345                }) {
1346                // Check if the signer Id hash is within the tx range
1347                let signer_id_hash = U256::from_be_bytes(*blake3_hash(&signer.encode()));
1348                sp_domains::signer_in_tx_range(bundle_vrf_hash, &signer_id_hash, tx_range)
1349            } else {
1350                // Unsigned transactions are always in the range.
1351                true
1352            }
1353        }
1354
1355        fn extract_signer_if_all_within_tx_range(
1356            extrinsics: &Vec<ExtrinsicFor<Block>>,
1357            bundle_vrf_hash: &subspace_core_primitives::U256,
1358            tx_range: &subspace_core_primitives::U256
1359        ) -> Result<Vec<Option<opaque::AccountId>> , u32> {
1360            use subspace_core_primitives::U256;
1361            use subspace_core_primitives::hashes::blake3_hash;
1362
1363            let mut signers = Vec::with_capacity(extrinsics.len());
1364            let lookup = frame_system::ChainContext::<Runtime>::default();
1365            for (index, extrinsic) in extrinsics.iter().enumerate() {
1366                let maybe_signer = extract_signer_inner(extrinsic, &lookup).and_then(|account_result| {
1367                    account_result.ok().map(|account_id| account_id.encode())
1368                });
1369                if let Some(signer) = &maybe_signer {
1370                    // Check if the signer Id hash is within the tx range
1371                    let signer_id_hash = U256::from_be_bytes(*blake3_hash(&signer.encode()));
1372                    if !sp_domains::signer_in_tx_range(bundle_vrf_hash, &signer_id_hash, tx_range) {
1373                        return Err(index as u32)
1374                    }
1375                }
1376                signers.push(maybe_signer);
1377            }
1378
1379            Ok(signers)
1380        }
1381
1382        fn initialize_block_with_post_state_root(header: &HeaderFor<Block>) -> Vec<u8> {
1383            Executive::initialize_block(header);
1384            Executive::storage_root()
1385        }
1386
1387        fn apply_extrinsic_with_post_state_root(extrinsic: ExtrinsicFor<Block>) -> Vec<u8> {
1388            let _ = Executive::apply_extrinsic(extrinsic);
1389            Executive::storage_root()
1390        }
1391
1392        fn construct_set_code_extrinsic(code: Vec<u8>) -> Vec<u8> {
1393            UncheckedExtrinsic::new_bare(
1394                domain_pallet_executive::Call::set_code {
1395                    code
1396                }.into()
1397            ).encode()
1398        }
1399
1400        fn construct_timestamp_extrinsic(moment: Moment) -> ExtrinsicFor<Block> {
1401            UncheckedExtrinsic::new_bare(
1402                pallet_timestamp::Call::set{ now: moment }.into()
1403            )
1404        }
1405
1406        fn is_inherent_extrinsic(extrinsic: &ExtrinsicFor<Block>) -> bool {
1407            <Self as IsInherent<_>>::is_inherent(extrinsic)
1408        }
1409
1410        fn find_first_inherent_extrinsic(extrinsics: &Vec<ExtrinsicFor<Block>>) -> Option<u32> {
1411            for (index, extrinsic) in extrinsics.iter().enumerate() {
1412                if <Self as IsInherent<_>>::is_inherent(extrinsic) {
1413                    return Some(index as u32)
1414                }
1415            }
1416            None
1417        }
1418
1419        fn check_extrinsics_and_do_pre_dispatch(uxts: Vec<ExtrinsicFor<Block>>, block_number: BlockNumber,
1420            block_hash: BlockHashFor<Block>) -> Result<(), CheckExtrinsicsValidityError> {
1421            // Initializing block related storage required for validation
1422            System::initialize(
1423                &(block_number + BlockNumber::one()),
1424                &block_hash,
1425                &Default::default(),
1426            );
1427
1428            for (extrinsic_index, uxt) in uxts.iter().enumerate() {
1429                check_transaction_and_do_pre_dispatch_inner(uxt).map_err(|e| {
1430                    CheckExtrinsicsValidityError {
1431                        extrinsic_index: extrinsic_index as u32,
1432                        transaction_validity_error: e
1433                    }
1434                })?;
1435            }
1436
1437            Ok(())
1438        }
1439
1440        fn decode_extrinsic(
1441            opaque_extrinsic: sp_runtime::OpaqueExtrinsic,
1442        ) -> Result<ExtrinsicFor<Block>, DecodeExtrinsicError> {
1443            let encoded = opaque_extrinsic.encode();
1444
1445            UncheckedExtrinsic::decode_all_with_depth_limit(
1446                MAX_CALL_RECURSION_DEPTH,
1447                &mut encoded.as_slice(),
1448            ).map_err(|err| DecodeExtrinsicError(format!("{err}")))
1449        }
1450
1451        fn decode_extrinsics_prefix(
1452            opaque_extrinsics: Vec<sp_runtime::OpaqueExtrinsic>,
1453        ) -> Vec<ExtrinsicFor<Block>> {
1454            let mut extrinsics = Vec::with_capacity(opaque_extrinsics.len());
1455            for opaque_ext in opaque_extrinsics {
1456                match UncheckedExtrinsic::decode_all_with_depth_limit(
1457                    MAX_CALL_RECURSION_DEPTH,
1458                    &mut opaque_ext.encode().as_slice(),
1459                ) {
1460                    Ok(tx) => extrinsics.push(tx),
1461                    Err(_) => return extrinsics,
1462                }
1463            }
1464            extrinsics
1465        }
1466
1467        fn extrinsic_era(
1468          extrinsic: &ExtrinsicFor<Block>
1469        ) -> Option<Era> {
1470            extrinsic_era(extrinsic)
1471        }
1472
1473        fn extrinsic_weight(ext: &ExtrinsicFor<Block>) -> Weight {
1474            let len = ext.encoded_size() as u64;
1475            let info = ext.get_dispatch_info();
1476            info.call_weight.saturating_add(info.extension_weight)
1477                .saturating_add(<Runtime as frame_system::Config>::BlockWeights::get().get(info.class).base_extrinsic)
1478                .saturating_add(Weight::from_parts(0, len))
1479        }
1480
1481        fn extrinsics_weight(extrinsics: &Vec<ExtrinsicFor<Block>>) -> Weight {
1482            let mut total_weight = Weight::zero();
1483            for ext in extrinsics {
1484                let ext_weight = {
1485                    let len = ext.encoded_size() as u64;
1486                    let info = ext.get_dispatch_info();
1487                    info.call_weight.saturating_add(info.extension_weight)
1488                        .saturating_add(<Runtime as frame_system::Config>::BlockWeights::get().get(info.class).base_extrinsic)
1489                        .saturating_add(Weight::from_parts(0, len))
1490                };
1491                total_weight = total_weight.saturating_add(ext_weight);
1492            }
1493            total_weight
1494        }
1495
1496        fn block_fees() -> sp_domains::execution_receipt::BlockFees<Balance> {
1497            BlockFees::collected_block_fees()
1498        }
1499
1500        fn block_digest() -> Digest {
1501            System::digest()
1502        }
1503
1504        fn block_weight() -> Weight {
1505            System::block_weight().total()
1506        }
1507
1508        fn construct_consensus_chain_byte_fee_extrinsic(transaction_byte_fee: Balance) -> ExtrinsicFor<Block> {
1509            UncheckedExtrinsic::new_bare(
1510                pallet_block_fees::Call::set_next_consensus_chain_byte_fee { transaction_byte_fee }.into()
1511            )
1512        }
1513
1514        fn construct_domain_update_chain_allowlist_extrinsic(updates: DomainAllowlistUpdates) -> ExtrinsicFor<Block> {
1515             UncheckedExtrinsic::new_bare(
1516                pallet_messenger::Call::update_domain_allowlist{ updates }.into()
1517            )
1518        }
1519
1520        fn transfers() -> Transfers<Balance> {
1521            Transporter::chain_transfers()
1522        }
1523
1524        fn transfers_storage_key() -> Vec<u8> {
1525            Transporter::transfers_storage_key()
1526        }
1527
1528        fn block_fees_storage_key() -> Vec<u8> {
1529            BlockFees::block_fees_storage_key()
1530        }
1531    }
1532
1533    impl sp_messenger::MessengerApi<Block, ConsensusBlockNumber, ConsensusBlockHash> for Runtime {
1534        fn is_xdm_mmr_proof_valid(
1535            extrinsic: &ExtrinsicFor<Block>
1536        ) -> Option<bool> {
1537            is_xdm_mmr_proof_valid(extrinsic)
1538        }
1539
1540        fn extract_xdm_mmr_proof(ext: &ExtrinsicFor<Block>) -> Option<ConsensusChainMmrLeafProof<ConsensusBlockNumber, ConsensusBlockHash, sp_core::H256>> {
1541            match &ext.0.function {
1542                RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })
1543                | RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
1544                    Some(msg.proof.consensus_mmr_proof())
1545                }
1546                _ => None,
1547            }
1548        }
1549
1550        fn batch_extract_xdm_mmr_proof(extrinsics: &Vec<ExtrinsicFor<Block>>) -> BTreeMap<u32, ConsensusChainMmrLeafProof<ConsensusBlockNumber, ConsensusBlockHash, sp_core::H256>> {
1551            let mut mmr_proofs = BTreeMap::new();
1552            for (index, ext) in extrinsics.iter().enumerate() {
1553                match &ext.0.function {
1554                    RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })
1555                    | RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
1556                        mmr_proofs.insert(index as u32, msg.proof.consensus_mmr_proof());
1557                    }
1558                    _ => {},
1559                }
1560            }
1561            mmr_proofs
1562        }
1563
1564        fn confirmed_domain_block_storage_key(_domain_id: DomainId) -> Vec<u8> {
1565            // invalid call from Domain runtime
1566            vec![]
1567        }
1568
1569        fn outbox_storage_key(message_key: MessageKey) -> Vec<u8> {
1570            Messenger::outbox_storage_key(message_key)
1571        }
1572
1573        fn inbox_response_storage_key(message_key: MessageKey) -> Vec<u8> {
1574            Messenger::inbox_response_storage_key(message_key)
1575        }
1576
1577        fn domain_chains_allowlist_update(_domain_id: DomainId) -> Option<DomainAllowlistUpdates>{
1578            // not valid call on domains
1579            None
1580        }
1581
1582        fn xdm_id(ext: &ExtrinsicFor<Block>) -> Option<XdmId> {
1583            match &ext.0.function {
1584                RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })=> {
1585                    Some(XdmId::RelayMessage((msg.src_chain_id, msg.channel_id, msg.nonce)))
1586                }
1587                RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
1588                    Some(XdmId::RelayResponseMessage((msg.src_chain_id, msg.channel_id, msg.nonce)))
1589                }
1590                _ => None,
1591            }
1592        }
1593
1594        fn channel_nonce(chain_id: ChainId, channel_id: ChannelId) -> Option<ChannelNonce> {
1595            Messenger::channel_nonce(chain_id, channel_id)
1596        }
1597    }
1598
1599    impl sp_messenger::RelayerApi<Block, BlockNumber, ConsensusBlockNumber, ConsensusBlockHash> for Runtime {
1600        fn outbox_message_unsigned(msg: CrossDomainMessage<NumberFor<Block>, BlockHashFor<Block>, BlockHashFor<Block>>) -> Option<ExtrinsicFor<Block>> {
1601            Messenger::outbox_message_unsigned(msg)
1602        }
1603
1604        fn inbox_response_message_unsigned(msg: CrossDomainMessage<NumberFor<Block>, BlockHashFor<Block>, BlockHashFor<Block>>) -> Option<ExtrinsicFor<Block>> {
1605            Messenger::inbox_response_message_unsigned(msg)
1606        }
1607
1608        fn updated_channels() -> BTreeSet<(ChainId, ChannelId)> {
1609            Messenger::updated_channels()
1610        }
1611
1612        fn channel_storage_key(chain_id: ChainId, channel_id: ChannelId) -> Vec<u8> {
1613            Messenger::channel_storage_key(chain_id, channel_id)
1614        }
1615
1616        fn open_channels() -> BTreeSet<(ChainId, ChannelId)> {
1617            Messenger::open_channels()
1618        }
1619
1620        fn block_messages_with_query(query: BlockMessagesQuery) -> MessagesWithStorageKey {
1621            Messenger::get_block_messages(query)
1622        }
1623
1624        fn channels_and_state() -> Vec<(ChainId, ChannelId, ChannelStateWithNonce)> {
1625            Messenger::channels_and_states()
1626        }
1627
1628        fn first_outbox_message_nonce_to_relay(dst_chain_id: ChainId, channel_id: ChannelId, from_nonce: XdmNonce) -> Option<XdmNonce> {
1629            Messenger::first_outbox_message_nonce_to_relay(dst_chain_id, channel_id, from_nonce)
1630        }
1631
1632        fn first_inbox_message_response_nonce_to_relay(dst_chain_id: ChainId, channel_id: ChannelId, from_nonce: XdmNonce) -> Option<XdmNonce> {
1633            Messenger::first_inbox_message_response_nonce_to_relay(dst_chain_id, channel_id, from_nonce)
1634        }
1635    }
1636
1637    impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {
1638        fn chain_id() -> u64 {
1639            <Runtime as pallet_evm::Config>::ChainId::get()
1640        }
1641
1642        fn account_basic(address: H160) -> EVMAccount {
1643            let (account, _) = EVM::account_basic(&address);
1644            account
1645        }
1646
1647        fn gas_price() -> U256 {
1648            let (gas_price, _) = <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price();
1649            gas_price
1650        }
1651
1652        fn account_code_at(address: H160) -> Vec<u8> {
1653            pallet_evm::AccountCodes::<Runtime>::get(address)
1654        }
1655
1656        fn author() -> H160 {
1657            <pallet_evm::Pallet<Runtime>>::find_author()
1658        }
1659
1660        fn storage_at(address: H160, index: U256) -> H256 {
1661            let tmp = index.to_big_endian();
1662            pallet_evm::AccountStorages::<Runtime>::get(address, H256::from_slice(&tmp[..]))
1663        }
1664
1665        fn call(
1666            from: H160,
1667            to: H160,
1668            data: Vec<u8>,
1669            value: U256,
1670            gas_limit: U256,
1671            max_fee_per_gas: Option<U256>,
1672            max_priority_fee_per_gas: Option<U256>,
1673            nonce: Option<U256>,
1674            estimate: bool,
1675            access_list: Option<Vec<(H160, Vec<H256>)>>,
1676        ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {
1677            let config = if estimate {
1678                let mut config = <Runtime as pallet_evm::Config>::config().clone();
1679                config.estimate = true;
1680                Some(config)
1681            } else {
1682                None
1683            };
1684
1685            let is_transactional = false;
1686            let validate = true;
1687            let evm_config = config.as_ref().unwrap_or(<Runtime as pallet_evm::Config>::config());
1688
1689            let gas_limit = gas_limit.min(u64::MAX.into());
1690
1691            let transaction_data = TransactionData::new(
1692                TransactionAction::Call(to),
1693                data.clone(),
1694                nonce.unwrap_or_default(),
1695                gas_limit,
1696                None,
1697                max_fee_per_gas,
1698                max_priority_fee_per_gas,
1699                value,
1700                Some(<Runtime as pallet_evm::Config>::ChainId::get()),
1701                access_list.clone().unwrap_or_default(),
1702            );
1703
1704            let (weight_limit, proof_size_base_cost) = pallet_ethereum::Pallet::<Runtime>::transaction_weight(&transaction_data);
1705
1706            <Runtime as pallet_evm::Config>::Runner::call(
1707                from,
1708                to,
1709                data,
1710                value,
1711                gas_limit.unique_saturated_into(),
1712                max_fee_per_gas,
1713                max_priority_fee_per_gas,
1714                nonce,
1715                access_list.unwrap_or_default(),
1716                is_transactional,
1717                validate,
1718                weight_limit,
1719                proof_size_base_cost,
1720                evm_config,
1721            ).map_err(|err| err.error.into())
1722        }
1723
1724        fn create(
1725            from: H160,
1726            data: Vec<u8>,
1727            value: U256,
1728            gas_limit: U256,
1729            max_fee_per_gas: Option<U256>,
1730            max_priority_fee_per_gas: Option<U256>,
1731            nonce: Option<U256>,
1732            estimate: bool,
1733            access_list: Option<Vec<(H160, Vec<H256>)>>,
1734        ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {
1735            let config = if estimate {
1736                let mut config = <Runtime as pallet_evm::Config>::config().clone();
1737                config.estimate = true;
1738                Some(config)
1739            } else {
1740                None
1741            };
1742
1743            let is_transactional = false;
1744            let validate = true;
1745            let weight_limit = None;
1746            let proof_size_base_cost = None;
1747            let evm_config = config.as_ref().unwrap_or(<Runtime as pallet_evm::Config>::config());
1748            <Runtime as pallet_evm::Config>::Runner::create(
1749                from,
1750                data,
1751                value,
1752                gas_limit.unique_saturated_into(),
1753                max_fee_per_gas,
1754                max_priority_fee_per_gas,
1755                nonce,
1756                access_list.unwrap_or_default(),
1757                is_transactional,
1758                validate,
1759                weight_limit,
1760                proof_size_base_cost,
1761                evm_config,
1762            ).map_err(|err| err.error.into())
1763        }
1764
1765        fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {
1766            pallet_ethereum::CurrentTransactionStatuses::<Runtime>::get()
1767        }
1768
1769        fn current_block() -> Option<pallet_ethereum::Block> {
1770            pallet_ethereum::CurrentBlock::<Runtime>::get()
1771        }
1772
1773        fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {
1774            pallet_ethereum::CurrentReceipts::<Runtime>::get()
1775        }
1776
1777        fn current_all() -> (
1778            Option<pallet_ethereum::Block>,
1779            Option<Vec<pallet_ethereum::Receipt>>,
1780            Option<Vec<TransactionStatus>>
1781        ) {
1782            (
1783                pallet_ethereum::CurrentBlock::<Runtime>::get(),
1784                pallet_ethereum::CurrentReceipts::<Runtime>::get(),
1785                pallet_ethereum::CurrentTransactionStatuses::<Runtime>::get()
1786            )
1787        }
1788
1789        fn extrinsic_filter(
1790            xts: Vec<ExtrinsicFor<Block>>,
1791        ) -> Vec<EthereumTransaction> {
1792            xts.into_iter().filter_map(|xt| match xt.0.function {
1793                RuntimeCall::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),
1794                _ => None
1795            }).collect::<Vec<EthereumTransaction>>()
1796        }
1797
1798        fn elasticity() -> Option<Permill> {
1799            None
1800        }
1801
1802        fn gas_limit_multiplier_support() {}
1803
1804        fn pending_block(
1805            xts: Vec<ExtrinsicFor<Block>>,
1806        ) -> (Option<pallet_ethereum::Block>, Option<Vec<TransactionStatus>>) {
1807            for ext in xts.into_iter() {
1808                let _ = Executive::apply_extrinsic(ext);
1809            }
1810
1811            Ethereum::on_finalize(System::block_number() + 1);
1812
1813            (
1814                pallet_ethereum::CurrentBlock::<Runtime>::get(),
1815                pallet_ethereum::CurrentTransactionStatuses::<Runtime>::get()
1816            )
1817        }
1818
1819        fn initialize_pending_block(header: &HeaderFor<Block>) {
1820            Executive::initialize_block(header);
1821        }
1822    }
1823
1824    impl fp_rpc::ConvertTransactionRuntimeApi<Block> for Runtime {
1825        fn convert_transaction(transaction: EthereumTransaction) -> ExtrinsicFor<Block> {
1826            UncheckedExtrinsic::new_bare(
1827                pallet_ethereum::Call::transact { transaction }.into(),
1828            )
1829        }
1830    }
1831
1832    impl sp_domain_sudo::DomainSudoApi<Block> for Runtime {
1833        fn is_valid_sudo_call(extrinsic: Vec<u8>) -> bool {
1834            is_valid_sudo_call(extrinsic)
1835        }
1836
1837        fn construct_domain_sudo_extrinsic(inner: Vec<u8>) -> ExtrinsicFor<Block> {
1838            construct_sudo_call_extrinsic(inner)
1839        }
1840    }
1841
1842    impl sp_evm_tracker::EvmTrackerApi<Block> for Runtime {
1843        fn construct_evm_contract_creation_allowed_by_extrinsic(decoded_argument: PermissionedActionAllowedBy<AccountId>) -> ExtrinsicFor<Block> {
1844            construct_evm_contract_creation_allowed_by_extrinsic(decoded_argument)
1845        }
1846    }
1847
1848    impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
1849        fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
1850            build_state::<RuntimeGenesisConfig>(config)
1851        }
1852
1853        fn get_preset(_id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
1854            // By passing `None` the upstream `get_preset` will return the default value of `RuntimeGenesisConfig`
1855            get_preset::<RuntimeGenesisConfig>(&None, |_| None)
1856        }
1857
1858        fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
1859            vec![]
1860        }
1861    }
1862
1863    #[cfg(feature = "runtime-benchmarks")]
1864    impl frame_benchmarking::Benchmark<Block> for Runtime {
1865        fn benchmark_metadata(extra: bool) -> (
1866            Vec<frame_benchmarking::BenchmarkList>,
1867            Vec<frame_support::traits::StorageInfo>,
1868        ) {
1869            use frame_benchmarking::{baseline, Benchmarking, BenchmarkList};
1870            use frame_support::traits::StorageInfoTrait;
1871            use frame_system_benchmarking::Pallet as SystemBench;
1872            use baseline::Pallet as BaselineBench;
1873            use pallet_messenger::extensions::benchmarking_from_consensus::Pallet as MessengerFromConsensusExtensionBench;
1874            use pallet_messenger::extensions::benchmarking_between_domains::Pallet as MessengerBetweenDomainsExtensionBench;
1875
1876            let mut list = Vec::<BenchmarkList>::new();
1877
1878            list_benchmarks!(list, extra);
1879
1880            let storage_info = AllPalletsWithSystem::storage_info();
1881
1882            (list, storage_info)
1883        }
1884
1885        fn dispatch_benchmark(
1886            config: frame_benchmarking::BenchmarkConfig
1887        ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, alloc::string::String> {
1888            use frame_benchmarking::{baseline, Benchmarking, BenchmarkBatch};
1889            use sp_storage::TrackedStorageKey;
1890            use frame_system_benchmarking::Pallet as SystemBench;
1891            use frame_support::traits::WhitelistedStorageKeys;
1892            use baseline::Pallet as BaselineBench;
1893            use pallet_messenger::extensions::benchmarking_from_consensus::Pallet as MessengerFromConsensusExtensionBench;
1894            use pallet_messenger::extensions::benchmarking_between_domains::Pallet as MessengerBetweenDomainsExtensionBench;
1895
1896            let whitelist: Vec<TrackedStorageKey> = AllPalletsWithSystem::whitelisted_storage_keys();
1897
1898            let mut batches = Vec::<BenchmarkBatch>::new();
1899            let params = (&config, &whitelist);
1900
1901            add_benchmarks!(params, batches);
1902
1903            if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }
1904            Ok(batches)
1905        }
1906    }
1907}
1908
1909#[cfg(test)]
1910mod tests {
1911    use crate::{Runtime, RuntimeBlockWeights as BlockWeights};
1912    use subspace_runtime_primitives::tests_utils::FeeMultiplierUtils;
1913
1914    #[test]
1915    fn multiplier_can_grow_from_zero() {
1916        FeeMultiplierUtils::<Runtime, BlockWeights>::multiplier_can_grow_from_zero()
1917    }
1918}