evm_domain_test_runtime/
lib.rs

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