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