Skip to main content

evm_domain_runtime/
lib.rs

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