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