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