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