Skip to main content

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