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    (pallet_transporter::migrations::VersionCheckedMigrateTransporterV0ToV1<Runtime>,),
163>;
164
165/// Returns the storage fee for `len` bytes, or an overflow error.
166fn consensus_storage_fee(len: impl TryInto<Balance>) -> Result<Balance, TransactionValidityError> {
167    // This should never fail with the current types.
168    // But if converting to Balance would overflow, so would any multiplication.
169    let len = len.try_into().map_err(|_| {
170        TransactionValidityError::Invalid(InvalidTransaction::Custom(ERR_BALANCE_OVERFLOW))
171    })?;
172
173    BlockFees::consensus_chain_byte_fee()
174        .checked_mul(Into::<Balance>::into(len))
175        .ok_or(TransactionValidityError::Invalid(
176            InvalidTransaction::Custom(ERR_BALANCE_OVERFLOW),
177        ))
178}
179
180impl fp_self_contained::SelfContainedCall for RuntimeCall {
181    type SignedInfo = H160;
182
183    fn is_self_contained(&self) -> bool {
184        match self {
185            RuntimeCall::Ethereum(call) => call.is_self_contained(),
186            _ => false,
187        }
188    }
189
190    fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {
191        match self {
192            RuntimeCall::Ethereum(call) => call.check_self_contained(),
193            _ => None,
194        }
195    }
196
197    fn validate_self_contained(
198        &self,
199        info: &Self::SignedInfo,
200        dispatch_info: &DispatchInfoOf<RuntimeCall>,
201        len: usize,
202    ) -> Option<TransactionValidity> {
203        let (is_allowed, _call_count) =
204            is_create_contract_allowed::<Runtime>(self, &(*info).into());
205        if !is_allowed {
206            return Some(Err(InvalidTransaction::Custom(
207                ERR_CONTRACT_CREATION_NOT_ALLOWED,
208            )
209            .into()));
210        }
211
212        match self {
213            RuntimeCall::Ethereum(call) => call.validate_self_contained(info, dispatch_info, len),
214            _ => None,
215        }
216    }
217
218    fn pre_dispatch_self_contained(
219        &self,
220        info: &Self::SignedInfo,
221        dispatch_info: &DispatchInfoOf<RuntimeCall>,
222        len: usize,
223    ) -> Option<Result<(), TransactionValidityError>> {
224        let (is_allowed, _call_count) =
225            is_create_contract_allowed::<Runtime>(self, &(*info).into());
226        if !is_allowed {
227            return Some(Err(InvalidTransaction::Custom(
228                ERR_CONTRACT_CREATION_NOT_ALLOWED,
229            )
230            .into()));
231        }
232
233        // TODO: move this code into pallet-block-fees, so it can be used from the production and
234        // test runtimes.
235        match self {
236            RuntimeCall::Ethereum(call) => {
237                // Copied from [`pallet_ethereum::Call::pre_dispatch_self_contained`] with `frame_system::CheckWeight`
238                // replaced with `domain_check_weight::CheckWeight`
239                if let pallet_ethereum::Call::transact { transaction } = call {
240                    let origin = RuntimeOrigin::signed(AccountId20::from(*info));
241                    if let Err(err) =
242                        <domain_check_weight::CheckWeight<Runtime> as DispatchTransaction<
243                            RuntimeCall,
244                        >>::validate_and_prepare(
245                            domain_check_weight::CheckWeight::<Runtime>::new(),
246                            origin,
247                            self,
248                            dispatch_info,
249                            len,
250                            DEFAULT_EXTENSION_VERSION,
251                        )
252                    {
253                        return Some(Err(err));
254                    }
255
256                    Some(Ethereum::validate_transaction_in_block(*info, transaction))
257                } else {
258                    None
259                }
260            }
261            _ => None,
262        }
263    }
264
265    fn apply_self_contained(
266        self,
267        info: Self::SignedInfo,
268    ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {
269        match self {
270            call @ RuntimeCall::Ethereum(pallet_ethereum::Call::transact { .. }) => {
271                let post_info = call.dispatch(RuntimeOrigin::from(
272                    pallet_ethereum::RawOrigin::EthereumTransaction(info),
273                ));
274
275                // is_self_contained() checks for an Ethereum call, which is always a single call.
276                // This call has the same number of contract checks as an EVM call, and similar
277                // fields, so we can use the EVM benchmark weight here.
278                let create_contract_ext_weight = CheckContractCreation::<Runtime>::get_weights(1);
279
280                // Add the weight of the contract creation extension check to the post info
281                Some(
282                    post_info
283                        .map(|mut post_info| {
284                            post_info.actual_weight = Some(
285                                post_info
286                                    .actual_weight
287                                    .unwrap_or_default()
288                                    .saturating_add(create_contract_ext_weight),
289                            );
290                            post_info
291                        })
292                        .map_err(|mut err_with_post_info| {
293                            err_with_post_info.post_info.actual_weight = Some(
294                                err_with_post_info
295                                    .post_info
296                                    .actual_weight
297                                    .unwrap_or_default()
298                                    .saturating_add(create_contract_ext_weight),
299                            );
300                            err_with_post_info
301                        }),
302                )
303            }
304            _ => None,
305        }
306    }
307}
308
309impl_opaque_keys! {
310    pub struct SessionKeys {
311        /// Primarily used for adding the operator signing key into the Keystore.
312        pub operator: sp_domains::OperatorKey,
313    }
314}
315
316#[sp_version::runtime_version]
317pub const VERSION: RuntimeVersion = RuntimeVersion {
318    spec_name: Cow::Borrowed("subspace-evm-domain"),
319    impl_name: Cow::Borrowed("subspace-evm-domain"),
320    authoring_version: 0,
321    spec_version: 4,
322    impl_version: 0,
323    apis: RUNTIME_API_VERSIONS,
324    transaction_version: 1,
325    system_version: 2,
326};
327
328parameter_types! {
329    pub const Version: RuntimeVersion = VERSION;
330    pub const BlockHashCount: BlockNumber = 2400;
331
332    // This part is copied from Substrate's `bin/node/runtime/src/lib.rs`.
333    //  The `RuntimeBlockLength` and `RuntimeBlockWeights` exist here because the
334    // `DeletionWeightLimit` and `DeletionQueueDepth` depend on those to parameterize
335    // the lazy contract deletion.
336    pub RuntimeBlockLength: BlockLength = maximum_block_length();
337    pub RuntimeBlockWeights: BlockWeights = block_weights();
338}
339
340impl frame_system::Config for Runtime {
341    type RuntimeEvent = RuntimeEvent;
342    /// The identifier used to distinguish between accounts.
343    type AccountId = AccountId;
344    /// The aggregated dispatch type that is available for extrinsics.
345    type RuntimeCall = RuntimeCall;
346    /// The aggregated `RuntimeTask` type.
347    type RuntimeTask = RuntimeTask;
348    /// The lookup mechanism to get account ID from whatever is passed in dispatchers.
349    type Lookup = IdentityLookup<AccountId>;
350    /// The type for storing how many extrinsics an account has signed.
351    type Nonce = Nonce;
352    /// The type for hashing blocks and tries.
353    type Hash = Hash;
354    /// The hashing algorithm used.
355    type Hashing = BlakeTwo256;
356    /// The block type.
357    type Block = Block;
358    /// The ubiquitous event type.
359    /// The ubiquitous origin type.
360    type RuntimeOrigin = RuntimeOrigin;
361    /// Maximum number of block number to block hash mappings to keep (oldest pruned first).
362    type BlockHashCount = BlockHashCount;
363    /// Runtime version.
364    type Version = Version;
365    /// Converts a module to an index of this module in the runtime.
366    type PalletInfo = PalletInfo;
367    /// The data to be stored in an account.
368    type AccountData = pallet_balances::AccountData<Balance>;
369    /// What to do if a new account is created.
370    type OnNewAccount = ();
371    /// What to do if an account is fully reaped from the system.
372    type OnKilledAccount = ();
373    /// The weight of database operations that the runtime can invoke.
374    type DbWeight = ParityDbWeight;
375    /// The basic call filter to use in dispatchable.
376    type BaseCallFilter = Everything;
377    /// Weight information for the extrinsics of this pallet.
378    type SystemWeightInfo = weights::frame_system::WeightInfo<Runtime>;
379    /// Block & extrinsics weights: base values and limits.
380    type BlockWeights = RuntimeBlockWeights;
381    /// The maximum length of a block (in bytes).
382    type BlockLength = RuntimeBlockLength;
383    type SS58Prefix = ConstU16<6094>;
384    /// The action to take on a Runtime Upgrade
385    type OnSetCode = ();
386    type SingleBlockMigrations = ();
387    type MultiBlockMigrator = ();
388    type PreInherents = ();
389    type PostInherents = ();
390    type PostTransactions = ();
391    type MaxConsumers = ConstU32<16>;
392    type ExtensionsWeightInfo = frame_system::SubstrateExtensionsWeight<Runtime>;
393    type EventSegmentSize = DomainEventSegmentSize;
394}
395
396impl pallet_timestamp::Config for Runtime {
397    /// A timestamp: milliseconds since the unix epoch.
398    type Moment = Moment;
399    type OnTimestampSet = ();
400    type MinimumPeriod = ConstU64<{ SLOT_DURATION / 2 }>;
401    type WeightInfo = weights::pallet_timestamp::WeightInfo<Runtime>;
402}
403
404parameter_types! {
405    pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
406    pub const MaxLocks: u32 = 50;
407    pub const MaxReserves: u32 = 50;
408}
409
410/// `DustRemovalHandler` used to collect all the AI3 dust left when the account is reaped.
411pub struct DustRemovalHandler;
412
413impl OnUnbalanced<Credit<AccountId, Balances>> for DustRemovalHandler {
414    fn on_nonzero_unbalanced(dusted_amount: Credit<AccountId, Balances>) {
415        BlockFees::note_burned_balance(dusted_amount.peek());
416    }
417}
418
419impl pallet_balances::Config for Runtime {
420    type RuntimeEvent = RuntimeEvent;
421    type RuntimeFreezeReason = RuntimeFreezeReason;
422    type MaxLocks = MaxLocks;
423    /// The type for recording an account's balance.
424    type Balance = Balance;
425    /// The ubiquitous event type.
426    type DustRemoval = DustRemovalHandler;
427    type ExistentialDeposit = ExistentialDeposit;
428    type AccountStore = System;
429    type WeightInfo = weights::pallet_balances::WeightInfo<Runtime>;
430    type MaxReserves = MaxReserves;
431    type ReserveIdentifier = [u8; 8];
432    type FreezeIdentifier = ();
433    type MaxFreezes = ();
434    type RuntimeHoldReason = HoldIdentifierWrapper;
435    type DoneSlashHandler = ();
436}
437
438parameter_types! {
439    pub const OperationalFeeMultiplier: u8 = 5;
440    pub const DomainChainByteFee: Balance = 100_000 * SHANNON;
441    pub TransactionWeightFee: Balance = 100_000 * SHANNON;
442}
443
444impl pallet_block_fees::Config for Runtime {
445    type Balance = Balance;
446    type DomainChainByteFee = DomainChainByteFee;
447}
448
449type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;
450
451pub struct FinalDomainTransactionByteFee;
452
453impl Get<Balance> for FinalDomainTransactionByteFee {
454    fn get() -> Balance {
455        BlockFees::final_domain_transaction_byte_fee()
456    }
457}
458
459impl pallet_transaction_payment::Config for Runtime {
460    type RuntimeEvent = RuntimeEvent;
461    type OnChargeTransaction = OnChargeDomainTransaction<Balances>;
462    type WeightToFee = ConstantMultiplier<Balance, TransactionWeightFee>;
463    type LengthToFee = ConstantMultiplier<Balance, FinalDomainTransactionByteFee>;
464    type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Runtime, TargetBlockFullness>;
465    type OperationalFeeMultiplier = OperationalFeeMultiplier;
466    type WeightInfo = weights::pallet_transaction_payment::WeightInfo<Runtime>;
467}
468
469pub struct ExtrinsicStorageFees;
470
471impl domain_pallet_executive::ExtrinsicStorageFees<Runtime> for ExtrinsicStorageFees {
472    fn extract_signer(xt: UncheckedExtrinsic) -> (Option<AccountId>, DispatchInfo) {
473        let dispatch_info = xt.get_dispatch_info();
474        let lookup = frame_system::ChainContext::<Runtime>::default();
475        let maybe_signer = extract_signer_inner(&xt, &lookup).and_then(|res| res.ok());
476        (maybe_signer, dispatch_info)
477    }
478
479    fn on_storage_fees_charged(
480        charged_fees: Balance,
481        tx_size: u32,
482    ) -> Result<(), TransactionValidityError> {
483        let consensus_storage_fee = consensus_storage_fee(tx_size)?;
484
485        let (paid_consensus_storage_fee, paid_domain_fee) = if charged_fees <= consensus_storage_fee
486        {
487            (charged_fees, Zero::zero())
488        } else {
489            (consensus_storage_fee, charged_fees - consensus_storage_fee)
490        };
491
492        BlockFees::note_consensus_storage_fee(paid_consensus_storage_fee);
493        BlockFees::note_domain_execution_fee(paid_domain_fee);
494        Ok(())
495    }
496}
497
498impl domain_pallet_executive::Config for Runtime {
499    type WeightInfo = weights::domain_pallet_executive::WeightInfo<Runtime>;
500    type Currency = Balances;
501    type LengthToFee = <Runtime as pallet_transaction_payment::Config>::LengthToFee;
502    type ExtrinsicStorageFees = ExtrinsicStorageFees;
503}
504
505parameter_types! {
506    pub SelfChainId: ChainId = SelfDomainId::self_domain_id().into();
507}
508
509pub struct OnXDMRewards;
510
511impl sp_messenger::OnXDMRewards<Balance> for OnXDMRewards {
512    fn on_xdm_rewards(rewards: Balance) {
513        BlockFees::note_domain_execution_fee(rewards)
514    }
515
516    fn on_chain_protocol_fees(chain_id: ChainId, fees: Balance) {
517        // note the chain rewards
518        BlockFees::note_chain_rewards(chain_id, fees);
519    }
520}
521
522type MmrHash = <Keccak256 as sp_runtime::traits::Hash>::Output;
523
524pub struct MmrProofVerifier;
525
526impl sp_subspace_mmr::MmrProofVerifier<MmrHash, NumberFor<Block>, Hash> for MmrProofVerifier {
527    fn verify_proof_and_extract_leaf(
528        mmr_leaf_proof: ConsensusChainMmrLeafProof<NumberFor<Block>, Hash, MmrHash>,
529    ) -> Option<MmrLeaf<ConsensusBlockNumber, ConsensusBlockHash>> {
530        let ConsensusChainMmrLeafProof {
531            consensus_block_number,
532            opaque_mmr_leaf: opaque_leaf,
533            proof,
534            ..
535        } = mmr_leaf_proof;
536
537        if !is_consensus_block_finalized(consensus_block_number) {
538            return None;
539        }
540
541        let leaf: MmrLeaf<ConsensusBlockNumber, ConsensusBlockHash> =
542            opaque_leaf.into_opaque_leaf().try_decode()?;
543
544        verify_mmr_proof(vec![EncodableOpaqueLeaf::from_leaf(&leaf)], proof.encode())
545            .then_some(leaf)
546    }
547}
548
549pub struct StorageKeys;
550
551impl sp_messenger::StorageKeys for StorageKeys {
552    fn confirmed_domain_block_storage_key(domain_id: DomainId) -> Option<Vec<u8>> {
553        get_storage_key(StorageKeyRequest::ConfirmedDomainBlockStorageKey(domain_id))
554    }
555
556    fn outbox_storage_key(chain_id: ChainId, message_key: MessageKey) -> Option<Vec<u8>> {
557        get_storage_key(StorageKeyRequest::OutboxStorageKey {
558            chain_id,
559            message_key,
560        })
561    }
562
563    fn inbox_responses_storage_key(chain_id: ChainId, message_key: MessageKey) -> Option<Vec<u8>> {
564        get_storage_key(StorageKeyRequest::InboxResponseStorageKey {
565            chain_id,
566            message_key,
567        })
568    }
569}
570
571/// Hold identifier for balances for this runtime.
572#[derive(
573    PartialEq,
574    Eq,
575    Clone,
576    Encode,
577    Decode,
578    TypeInfo,
579    MaxEncodedLen,
580    Ord,
581    PartialOrd,
582    Copy,
583    Debug,
584    DecodeWithMemTracking,
585)]
586pub struct HoldIdentifierWrapper(HoldIdentifier);
587
588impl VariantCount for HoldIdentifierWrapper {
589    const VARIANT_COUNT: u32 = mem::variant_count::<HoldIdentifier>() as u32;
590}
591
592impl pallet_messenger::HoldIdentifier<Runtime> for HoldIdentifierWrapper {
593    fn messenger_channel() -> Self {
594        Self(HoldIdentifier::MessengerChannel)
595    }
596}
597
598parameter_types! {
599    pub const ChannelReserveFee: Balance = 100 * AI3;
600    pub const ChannelInitReservePortion: Perbill = Perbill::from_percent(20);
601    pub const MaxOutgoingMessages: u32 = MAX_OUTGOING_MESSAGES;
602}
603
604// ensure the max outgoing messages is not 0.
605const_assert!(MaxOutgoingMessages::get() >= 1);
606
607impl pallet_messenger::Config for Runtime {
608    type SelfChainId = SelfChainId;
609
610    fn get_endpoint_handler(endpoint: &Endpoint) -> Option<Box<dyn EndpointHandlerT<MessageId>>> {
611        if endpoint == &Endpoint::Id(TransporterEndpointId::get()) {
612            Some(Box::new(EndpointHandler(PhantomData::<Runtime>)))
613        } else {
614            None
615        }
616    }
617
618    type Currency = Balances;
619    type WeightInfo = weights::pallet_messenger::WeightInfo<Runtime>;
620    type WeightToFee = ConstantMultiplier<Balance, TransactionWeightFee>;
621    type AdjustedWeightToFee = XdmAdjustedWeightToFee<Runtime>;
622    type FeeMultiplier = XdmFeeMultipler;
623    type OnXDMRewards = OnXDMRewards;
624    type MmrHash = MmrHash;
625    type MmrProofVerifier = MmrProofVerifier;
626    #[cfg(feature = "runtime-benchmarks")]
627    type StorageKeys = sp_messenger::BenchmarkStorageKeys;
628    #[cfg(not(feature = "runtime-benchmarks"))]
629    type StorageKeys = StorageKeys;
630    type DomainOwner = ();
631    type HoldIdentifier = HoldIdentifierWrapper;
632    type ChannelReserveFee = ChannelReserveFee;
633    type ChannelInitReservePortion = ChannelInitReservePortion;
634    type DomainRegistration = ();
635    type MaxOutgoingMessages = MaxOutgoingMessages;
636    type MessengerOrigin = pallet_messenger::EnsureMessengerOrigin;
637    type NoteChainTransfer = Transporter;
638    type ExtensionWeightInfo = pallet_messenger::extensions::weights::SubstrateWeight<
639        Runtime,
640        weights::pallet_messenger_from_consensus_extension::WeightInfo<Runtime>,
641        weights::pallet_messenger_between_domains_extension::WeightInfo<Runtime>,
642    >;
643}
644
645impl<C> frame_system::offchain::CreateTransactionBase<C> for Runtime
646where
647    RuntimeCall: From<C>,
648{
649    type Extrinsic = UncheckedExtrinsic;
650    type RuntimeCall = RuntimeCall;
651}
652
653parameter_types! {
654    pub const TransporterEndpointId: EndpointId = 1;
655    pub const MinimumTransfer: Balance = AI3;
656}
657
658impl pallet_transporter::Config for Runtime {
659    type SelfChainId = SelfChainId;
660    type SelfEndpointId = TransporterEndpointId;
661    type Currency = Balances;
662    type Sender = Messenger;
663    type AccountIdConverter = domain_runtime_primitives::AccountId20Converter;
664    type WeightInfo = weights::pallet_transporter::WeightInfo<Runtime>;
665    type MinimumTransfer = MinimumTransfer;
666}
667
668impl pallet_evm_chain_id::Config for Runtime {}
669
670pub struct FindAuthorTruncated;
671
672impl FindAuthor<H160> for FindAuthorTruncated {
673    fn find_author<'a, I>(_digests: I) -> Option<H160>
674    where
675        I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,
676    {
677        // TODO: returns the executor reward address once we start collecting them
678        None
679    }
680}
681
682parameter_types! {
683    pub PrecompilesValue: Precompiles = Precompiles::default();
684}
685
686/// UnbalancedHandler that will just burn any unbalanced funds
687pub struct UnbalancedHandler {}
688impl OnUnbalanced<NegativeImbalance> for UnbalancedHandler {}
689
690type InnerEVMCurrencyAdapter = pallet_evm::EVMCurrencyAdapter<Balances, UnbalancedHandler>;
691
692// Implementation of [`pallet_transaction_payment::OnChargeTransaction`] that charges evm transaction
693// fees from the transaction sender and collect all the fees (including both the base fee and tip) in
694// `pallet_block_fees`
695pub struct EVMCurrencyAdapter;
696
697impl pallet_evm::OnChargeEVMTransaction<Runtime> for EVMCurrencyAdapter {
698    type LiquidityInfo = Option<NegativeImbalance>;
699
700    fn withdraw_fee(
701        who: &H160,
702        fee: U256,
703    ) -> Result<Self::LiquidityInfo, pallet_evm::Error<Runtime>> {
704        InnerEVMCurrencyAdapter::withdraw_fee(who, fee)
705    }
706
707    fn correct_and_deposit_fee(
708        who: &H160,
709        corrected_fee: U256,
710        base_fee: U256,
711        already_withdrawn: Self::LiquidityInfo,
712    ) -> Self::LiquidityInfo {
713        if already_withdrawn.is_some() {
714            // Record the evm actual transaction fee and storage fee
715            let (storage_fee, execution_fee) =
716                EvmGasPriceCalculator::split_fee_into_storage_and_execution(
717                    corrected_fee.as_u128(),
718                );
719            BlockFees::note_consensus_storage_fee(storage_fee);
720            BlockFees::note_domain_execution_fee(execution_fee);
721        }
722
723        <InnerEVMCurrencyAdapter as pallet_evm::OnChargeEVMTransaction<
724            Runtime,
725        >>::correct_and_deposit_fee(who, corrected_fee, base_fee, already_withdrawn)
726    }
727
728    fn pay_priority_fee(tip: Self::LiquidityInfo) {
729        if let Some(fee) = tip {
730            // handle the priority fee just like the base fee.
731            // for eip-1559, total fees will be base_fee + priority_fee
732            UnbalancedHandler::on_unbalanced(fee)
733        }
734    }
735}
736
737pub type EvmGasPriceCalculator = pallet_evm_tracker::fees::EvmGasPriceCalculator<
738    Runtime,
739    TransactionWeightFee,
740    GasPerByte,
741    StorageFeeRatio,
742>;
743
744impl pallet_evm::Config for Runtime {
745    type AccountProvider = pallet_evm::FrameSystemAccountProvider<Self>;
746    type FeeCalculator = EvmGasPriceCalculator;
747    type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
748    type WeightPerGas = WeightPerGas;
749    type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;
750    type CallOrigin = EnsureAddressRoot<AccountId>;
751    type CreateOriginFilter = ();
752    type CreateInnerOriginFilter = ();
753    type WithdrawOrigin = EnsureAddressNever<AccountId>;
754    type AddressMapping = IdentityAddressMapping;
755    type Currency = Balances;
756    type PrecompilesType = Precompiles;
757    type PrecompilesValue = PrecompilesValue;
758    type ChainId = EVMChainId;
759    type BlockGasLimit = BlockGasLimit;
760    type Runner = pallet_evm::runner::stack::Runner<Self>;
761    type OnChargeTransaction = EVMCurrencyAdapter;
762    type OnCreate = ();
763    type FindAuthor = FindAuthorTruncated;
764    type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
765    // TODO: re-check this value mostly from moonbeam
766    type GasLimitStorageGrowthRatio = ();
767    type Timestamp = Timestamp;
768    type WeightInfo = weights::pallet_evm::WeightInfo<Runtime>;
769}
770
771impl MaybeIntoEvmCall<Runtime> for RuntimeCall {
772    /// If this call is a `pallet_evm::Call<Runtime>` call, returns the inner call.
773    fn maybe_into_evm_call(&self) -> Option<&pallet_evm::Call<Runtime>> {
774        match self {
775            RuntimeCall::EVM(call) => Some(call),
776            _ => None,
777        }
778    }
779}
780
781impl pallet_evm_tracker::Config for Runtime {}
782
783parameter_types! {
784    pub const PostOnlyBlockHash: PostLogContent = PostLogContent::OnlyBlockHash;
785}
786
787impl pallet_ethereum::Config for Runtime {
788    type StateRoot = pallet_ethereum::IntermediateStateRoot<Self::Version>;
789    type PostLogContent = PostOnlyBlockHash;
790    type ExtraDataLength = ConstU32<30>;
791}
792
793impl MaybeIntoEthCall<Runtime> for RuntimeCall {
794    /// If this call is a `pallet_ethereum::Call<Runtime>` call, returns the inner call.
795    fn maybe_into_eth_call(&self) -> Option<&pallet_ethereum::Call<Runtime>> {
796        match self {
797            RuntimeCall::Ethereum(call) => Some(call),
798            _ => None,
799        }
800    }
801}
802
803impl pallet_domain_id::Config for Runtime {}
804
805pub struct IntoRuntimeCall;
806
807impl sp_domain_sudo::IntoRuntimeCall<RuntimeCall> for IntoRuntimeCall {
808    fn runtime_call(call: Vec<u8>) -> RuntimeCall {
809        UncheckedExtrinsic::decode(&mut call.as_slice())
810            .expect("must always be a valid domain extrinsic as checked by consensus chain; qed")
811            .0
812            .function
813    }
814}
815
816impl pallet_domain_sudo::Config for Runtime {
817    type RuntimeCall = RuntimeCall;
818    type IntoRuntimeCall = IntoRuntimeCall;
819}
820
821impl pallet_utility::Config for Runtime {
822    type RuntimeEvent = RuntimeEvent;
823    type RuntimeCall = RuntimeCall;
824    type PalletsOrigin = OriginCaller;
825    type WeightInfo = weights::pallet_utility::WeightInfo<Runtime>;
826}
827
828impl MaybeUtilityCall<Runtime> for RuntimeCall {
829    /// If this call is a `pallet_utility::Call<Runtime>` call, returns the inner call.
830    fn maybe_utility_call(&self) -> Option<&pallet_utility::Call<Runtime>> {
831        match self {
832            RuntimeCall::Utility(call) => Some(call),
833            _ => None,
834        }
835    }
836}
837
838impl MaybeNestedCall<Runtime> for RuntimeCall {
839    /// If this call is a nested runtime call, returns the inner call(s).
840    ///
841    /// Ignored calls (such as `pallet_utility::Call::__Ignore`) should be yielded themsevles, but
842    /// their contents should not be yielded.
843    fn maybe_nested_call(&self) -> Option<Vec<&RuntimeCallFor<Runtime>>> {
844        // We currently ignore privileged calls, because privileged users can already change
845        // runtime code. Domain sudo `RuntimeCall`s also have to pass inherent validation.
846        self.maybe_nested_utility_calls()
847    }
848}
849
850// Create the runtime by composing the FRAME pallets that were previously configured.
851//
852// NOTE: Currently domain runtime does not naturally support the pallets with inherent extrinsics.
853construct_runtime!(
854    pub struct Runtime {
855        // System support stuff.
856        System: frame_system = 0,
857        // Note: Ensure index of the timestamp matches with the index of timestamp on Consensus
858        //  so that consensus can constructed encoded extrinsic that matches with Domain encoded
859        //  extrinsic.
860        Timestamp: pallet_timestamp = 1,
861        ExecutivePallet: domain_pallet_executive = 2,
862        Utility: pallet_utility = 8,
863
864        // monetary stuff
865        Balances: pallet_balances = 20,
866        TransactionPayment: pallet_transaction_payment = 21,
867
868        // messenger stuff
869        // Note: Indexes should match with indexes on other chains and domains
870        Messenger: pallet_messenger = 60,
871        Transporter: pallet_transporter = 61,
872
873        // evm stuff
874        Ethereum: pallet_ethereum = 80,
875        EVM: pallet_evm = 81,
876        EVMChainId: pallet_evm_chain_id = 82,
877        EVMNoncetracker: pallet_evm_tracker = 84,
878
879        // domain instance stuff
880        SelfDomainId: pallet_domain_id = 90,
881        BlockFees: pallet_block_fees = 91,
882
883        // Sudo account
884        Sudo: pallet_domain_sudo = 100,
885    }
886);
887
888#[derive(Clone, Default)]
889pub struct TransactionConverter;
890
891impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {
892    fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {
893        UncheckedExtrinsic::new_bare(
894            pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),
895        )
896    }
897}
898
899impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {
900    fn convert_transaction(
901        &self,
902        transaction: pallet_ethereum::Transaction,
903    ) -> opaque::UncheckedExtrinsic {
904        let extrinsic = UncheckedExtrinsic::new_bare(
905            pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),
906        );
907        let encoded = extrinsic.encode();
908        opaque::UncheckedExtrinsic::decode(&mut &encoded[..])
909            .expect("Encoded extrinsic is always valid")
910    }
911}
912
913fn is_xdm_mmr_proof_valid(ext: &ExtrinsicFor<Block>) -> Option<bool> {
914    match &ext.0.function {
915        RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })
916        | RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
917            let ConsensusChainMmrLeafProof {
918                consensus_block_number,
919                opaque_mmr_leaf,
920                proof,
921                ..
922            } = msg.proof.consensus_mmr_proof();
923
924            if !is_consensus_block_finalized(consensus_block_number) {
925                return Some(false);
926            }
927
928            Some(verify_mmr_proof(vec![opaque_mmr_leaf], proof.encode()))
929        }
930        _ => None,
931    }
932}
933
934/// Returns `true` if this is a validly encoded Sudo call.
935fn is_valid_sudo_call(encoded_ext: Vec<u8>) -> bool {
936    UncheckedExtrinsic::decode_all_with_depth_limit(
937        MAX_CALL_RECURSION_DEPTH,
938        &mut encoded_ext.as_slice(),
939    )
940    .is_ok()
941}
942
943/// Constructs a domain-sudo call extrinsic from the given encoded extrinsic.
944fn construct_sudo_call_extrinsic(encoded_ext: Vec<u8>) -> ExtrinsicFor<Block> {
945    let ext = UncheckedExtrinsic::decode(&mut encoded_ext.as_slice()).expect(
946        "must always be a valid extrinsic due to the check above and storage proof check; qed",
947    );
948    UncheckedExtrinsic::new_bare(
949        pallet_domain_sudo::Call::sudo {
950            call: Box::new(ext.0.function),
951        }
952        .into(),
953    )
954}
955
956/// Constructs an evm-tracker call extrinsic from the given extrinsic.
957fn construct_evm_contract_creation_allowed_by_extrinsic(
958    decoded_argument: PermissionedActionAllowedBy<AccountId>,
959) -> ExtrinsicFor<Block> {
960    UncheckedExtrinsic::new_bare(
961        pallet_evm_tracker::Call::set_contract_creation_allowed_by {
962            contract_creation_allowed_by: decoded_argument,
963        }
964        .into(),
965    )
966}
967
968fn extract_signer_inner<Lookup>(
969    ext: &UncheckedExtrinsic,
970    lookup: &Lookup,
971) -> Option<Result<AccountId, TransactionValidityError>>
972where
973    Lookup: sp_runtime::traits::Lookup<Source = Address, Target = AccountId>,
974{
975    if ext.0.function.is_self_contained() {
976        ext.0
977            .function
978            .check_self_contained()
979            .map(|signed_info| signed_info.map(|signer| signer.into()))
980    } else {
981        match &ext.0.preamble {
982            Preamble::Bare(_) | Preamble::General(_, _) => None,
983            Preamble::Signed(address, _, _) => Some(lookup.lookup(*address).map_err(|e| e.into())),
984        }
985    }
986}
987
988pub fn extract_signer(
989    extrinsics: Vec<UncheckedExtrinsic>,
990) -> Vec<(Option<opaque::AccountId>, UncheckedExtrinsic)> {
991    let lookup = frame_system::ChainContext::<Runtime>::default();
992
993    extrinsics
994        .into_iter()
995        .map(|extrinsic| {
996            let maybe_signer =
997                extract_signer_inner(&extrinsic, &lookup).and_then(|account_result| {
998                    account_result.ok().map(|account_id| account_id.encode())
999                });
1000            (maybe_signer, extrinsic)
1001        })
1002        .collect()
1003}
1004
1005fn extrinsic_era(extrinsic: &ExtrinsicFor<Block>) -> Option<Era> {
1006    match &extrinsic.0.preamble {
1007        Preamble::Bare(_) | Preamble::General(_, _) => None,
1008        Preamble::Signed(_, _, extra) => Some(extra.4.0),
1009    }
1010}
1011
1012#[cfg(feature = "runtime-benchmarks")]
1013mod benches {
1014    frame_benchmarking::define_benchmarks!(
1015        [frame_benchmarking, BaselineBench::<Runtime>]
1016        [frame_system, SystemBench::<Runtime>]
1017        [pallet_timestamp, Timestamp]
1018        [domain_pallet_executive, ExecutivePallet]
1019        [pallet_utility, Utility]
1020        [pallet_balances, Balances]
1021        [pallet_transaction_payment, TransactionPayment]
1022        [pallet_messenger, Messenger]
1023        [pallet_messenger_from_consensus_extension, MessengerFromConsensusExtensionBench::<Runtime>]
1024        [pallet_messenger_between_domains_extension, MessengerBetweenDomainsExtensionBench::<Runtime>]
1025        [pallet_transporter, Transporter]
1026        // pallet_ethereum uses `pallet_evm::Config::GasWeightMapping::gas_to_weight` to weight its calls
1027        [pallet_evm, EVM]
1028        // pallet_evm_chain_id has no calls to benchmark
1029        [pallet_evm_tracker, EVMNoncetracker]
1030        // TODO: pallet_evm_tracker CheckNonce extension benchmarks
1031        // pallet_domain_id has no calls to benchmark
1032        // pallet_block_fees uses a default over-estimated weight
1033        // pallet_domain_sudo only has inherent calls
1034    );
1035}
1036
1037/// Custom pre_dispatch for extrinsic verification.
1038/// Most of the logic is same as `pre_dispatch_self_contained` except
1039/// - we use `validate_self_contained` instead `pre_dispatch_self_contained`
1040///   since the nonce is not incremented in `pre_dispatch_self_contained`
1041/// - Manually track the account nonce to check either Stale or Future nonce.
1042fn pre_dispatch_evm_transaction(
1043    account_id: H160,
1044    call: RuntimeCall,
1045    dispatch_info: &DispatchInfoOf<RuntimeCall>,
1046    len: usize,
1047) -> Result<(), TransactionValidityError> {
1048    match call {
1049        RuntimeCall::Ethereum(call) => {
1050            if let Some(transaction_validity) =
1051                call.validate_self_contained(&account_id, dispatch_info, len)
1052            {
1053                let _ = transaction_validity?;
1054
1055                let pallet_ethereum::Call::transact { transaction } = call;
1056                frame_system::CheckWeight::<Runtime>::do_validate(dispatch_info, len).and_then(
1057                    |(_, next_len)| {
1058                        domain_check_weight::CheckWeight::<Runtime>::do_prepare(
1059                            dispatch_info,
1060                            len,
1061                            next_len,
1062                        )
1063                    },
1064                )?;
1065
1066                let transaction_data: TransactionData = (&transaction).into();
1067                let transaction_nonce = transaction_data.nonce;
1068                // If the current account nonce is greater than the tracked nonce, then
1069                // pick the highest nonce
1070                let account_nonce = {
1071                    let tracked_nonce = EVMNoncetracker::account_nonce(AccountId::from(account_id))
1072                        .unwrap_or(U256::zero());
1073                    let account_nonce = EVM::account_basic(&account_id).0.nonce;
1074                    max(tracked_nonce, account_nonce)
1075                };
1076
1077                match transaction_nonce.cmp(&account_nonce) {
1078                    Ordering::Less => return Err(InvalidTransaction::Stale.into()),
1079                    Ordering::Greater => return Err(InvalidTransaction::Future.into()),
1080                    Ordering::Equal => {}
1081                }
1082
1083                let next_nonce = account_nonce
1084                    .checked_add(U256::one())
1085                    .ok_or(InvalidTransaction::Custom(ERR_EVM_NONCE_OVERFLOW))?;
1086
1087                EVMNoncetracker::set_account_nonce(AccountId::from(account_id), next_nonce);
1088            }
1089
1090            Ok(())
1091        }
1092        _ => Err(InvalidTransaction::Call.into()),
1093    }
1094}
1095
1096fn check_transaction_and_do_pre_dispatch_inner(
1097    uxt: &ExtrinsicFor<Block>,
1098) -> Result<(), TransactionValidityError> {
1099    let lookup = frame_system::ChainContext::<Runtime>::default();
1100
1101    let xt = uxt.clone().check(&lookup)?;
1102
1103    let dispatch_info = xt.get_dispatch_info();
1104
1105    if dispatch_info.class == DispatchClass::Mandatory {
1106        return Err(InvalidTransaction::MandatoryValidation.into());
1107    }
1108
1109    let encoded_len = uxt.encoded_size();
1110
1111    // We invoke `pre_dispatch` in addition to `validate_transaction`(even though the validation is almost same)
1112    // as that will add the side effect of SignedExtension in the storage buffer
1113    // which would help to maintain context across multiple transaction validity check against same
1114    // runtime instance.
1115    match xt.signed {
1116        CheckedSignature::GenericDelegated(format) => match format {
1117            ExtrinsicFormat::Bare => {
1118                Runtime::pre_dispatch(&xt.function).map(|_| ())?;
1119                <SignedExtra as TransactionExtension<RuntimeCall>>::bare_validate_and_prepare(
1120                    &xt.function,
1121                    &dispatch_info,
1122                    encoded_len,
1123                )
1124                .map(|_| ())
1125            }
1126            ExtrinsicFormat::General(extension_version, extra) => {
1127                let custom_extra: CustomSignedExtra = (
1128                    extra.0,
1129                    extra.1,
1130                    extra.2,
1131                    extra.3,
1132                    extra.4,
1133                    pallet_evm_tracker::CheckNonce::from(extra.5.0),
1134                    extra.6,
1135                    extra.7.clone(),
1136                    extra.8,
1137                    pallet_messenger::extensions::MessengerTrustedMmrExtension::<Runtime>::new(),
1138                );
1139
1140                let origin = RuntimeOrigin::none();
1141                <CustomSignedExtra as DispatchTransaction<RuntimeCall>>::validate_and_prepare(
1142                    custom_extra,
1143                    origin,
1144                    &xt.function,
1145                    &dispatch_info,
1146                    encoded_len,
1147                    extension_version,
1148                )
1149                .map(|_| ())
1150            }
1151            ExtrinsicFormat::Signed(account_id, extra) => {
1152                let custom_extra: CustomSignedExtra = (
1153                    extra.0,
1154                    extra.1,
1155                    extra.2,
1156                    extra.3,
1157                    extra.4,
1158                    pallet_evm_tracker::CheckNonce::from(extra.5.0),
1159                    extra.6,
1160                    extra.7.clone(),
1161                    extra.8,
1162                    // trusted MMR extension here does not matter since this extension
1163                    // will only affect unsigned extrinsics but not signed extrinsics
1164                    pallet_messenger::extensions::MessengerTrustedMmrExtension::<Runtime>::new(),
1165                );
1166
1167                let origin = RuntimeOrigin::signed(account_id);
1168                <CustomSignedExtra as DispatchTransaction<RuntimeCall>>::validate_and_prepare(
1169                    custom_extra,
1170                    origin,
1171                    &xt.function,
1172                    &dispatch_info,
1173                    encoded_len,
1174                    DEFAULT_EXTENSION_VERSION,
1175                )
1176                .map(|_| ())
1177            }
1178        },
1179        CheckedSignature::SelfContained(account_id) => {
1180            pre_dispatch_evm_transaction(account_id, xt.function, &dispatch_info, encoded_len)
1181        }
1182    }
1183}
1184
1185impl pallet_messenger::extensions::MaybeMessengerCall<Runtime> for RuntimeCall {
1186    fn maybe_messenger_call(&self) -> Option<&pallet_messenger::Call<Runtime>> {
1187        match self {
1188            RuntimeCall::Messenger(call) => Some(call),
1189            _ => None,
1190        }
1191    }
1192}
1193
1194impl<C> subspace_runtime_primitives::CreateUnsigned<C> for Runtime
1195where
1196    RuntimeCall: From<C>,
1197{
1198    fn create_unsigned(call: Self::RuntimeCall) -> Self::Extrinsic {
1199        create_unsigned_general_extrinsic(call)
1200    }
1201}
1202
1203fn create_unsigned_general_extrinsic(call: RuntimeCall) -> UncheckedExtrinsic {
1204    let extra: SignedExtra = (
1205        frame_system::CheckNonZeroSender::<Runtime>::new(),
1206        frame_system::CheckSpecVersion::<Runtime>::new(),
1207        frame_system::CheckTxVersion::<Runtime>::new(),
1208        frame_system::CheckGenesis::<Runtime>::new(),
1209        frame_system::CheckMortality::<Runtime>::from(generic::Era::Immortal),
1210        // for unsigned extrinsic, nonce check will be skipped
1211        // so set a default value
1212        frame_system::CheckNonce::<Runtime>::from(0u32),
1213        domain_check_weight::CheckWeight::<Runtime>::new(),
1214        // for unsigned extrinsic, transaction fee check will be skipped
1215        // so set a default value
1216        pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(0u128),
1217        CheckContractCreation::<Runtime>::new(),
1218        pallet_messenger::extensions::MessengerExtension::<Runtime>::new(),
1219    );
1220
1221    UncheckedExtrinsic::from(generic::UncheckedExtrinsic::new_transaction(call, extra))
1222}
1223
1224#[cfg(feature = "runtime-benchmarks")]
1225impl frame_system_benchmarking::Config for Runtime {}
1226
1227#[cfg(feature = "runtime-benchmarks")]
1228impl frame_benchmarking::baseline::Config for Runtime {}
1229
1230impl_runtime_apis! {
1231    impl sp_api::Core<Block> for Runtime {
1232        fn version() -> RuntimeVersion {
1233            VERSION
1234        }
1235
1236        fn execute_block(block: <Block as sp_runtime::traits::Block>::LazyBlock) {
1237            Executive::execute_block(block)
1238        }
1239
1240        fn initialize_block(header: &HeaderFor<Block>) -> ExtrinsicInclusionMode {
1241            Executive::initialize_block(header)
1242        }
1243    }
1244
1245    impl sp_api::Metadata<Block> for Runtime {
1246        fn metadata() -> OpaqueMetadata {
1247            OpaqueMetadata::new(Runtime::metadata().into())
1248        }
1249
1250        fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
1251            Runtime::metadata_at_version(version)
1252        }
1253
1254        fn metadata_versions() -> Vec<u32> {
1255            Runtime::metadata_versions()
1256        }
1257    }
1258
1259    impl sp_block_builder::BlockBuilder<Block> for Runtime {
1260        fn apply_extrinsic(extrinsic: ExtrinsicFor<Block>) -> ApplyExtrinsicResult {
1261            Executive::apply_extrinsic(extrinsic)
1262        }
1263
1264        fn finalize_block() -> HeaderFor<Block> {
1265            Executive::finalize_block()
1266        }
1267
1268        fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<ExtrinsicFor<Block>> {
1269            data.create_extrinsics()
1270        }
1271
1272        fn check_inherents(
1273            block: <Block as sp_runtime::traits::Block>::LazyBlock,
1274            data: sp_inherents::InherentData,
1275        ) -> sp_inherents::CheckInherentsResult {
1276            data.check_extrinsics(&block)
1277        }
1278    }
1279
1280    impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
1281        fn validate_transaction(
1282            source: TransactionSource,
1283            tx: ExtrinsicFor<Block>,
1284            block_hash: BlockHashFor<Block>,
1285        ) -> TransactionValidity {
1286            Executive::validate_transaction(source, tx, block_hash)
1287        }
1288    }
1289
1290    impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
1291        fn offchain_worker(header: &HeaderFor<Block>) {
1292            Executive::offchain_worker(header)
1293        }
1294    }
1295
1296    impl sp_session::SessionKeys<Block> for Runtime {
1297        fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
1298            SessionKeys::generate(seed)
1299        }
1300
1301        fn decode_session_keys(
1302            encoded: Vec<u8>,
1303        ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
1304            SessionKeys::decode_into_raw_public_keys(&encoded)
1305        }
1306    }
1307
1308    impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
1309        fn account_nonce(account: AccountId) -> Nonce {
1310            System::account_nonce(account)
1311        }
1312    }
1313
1314    impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {
1315        fn query_info(
1316            uxt: ExtrinsicFor<Block>,
1317            len: u32,
1318        ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
1319            TransactionPayment::query_info(uxt, len)
1320        }
1321        fn query_fee_details(
1322            uxt: ExtrinsicFor<Block>,
1323            len: u32,
1324        ) -> pallet_transaction_payment::FeeDetails<Balance> {
1325            TransactionPayment::query_fee_details(uxt, len)
1326        }
1327        fn query_weight_to_fee(weight: Weight) -> Balance {
1328            TransactionPayment::weight_to_fee(weight)
1329        }
1330        fn query_length_to_fee(length: u32) -> Balance {
1331            TransactionPayment::length_to_fee(length)
1332        }
1333    }
1334
1335    impl sp_domains::core_api::DomainCoreApi<Block> for Runtime {
1336        fn extract_signer(
1337            extrinsics: Vec<ExtrinsicFor<Block>>,
1338        ) -> Vec<(Option<opaque::AccountId>, ExtrinsicFor<Block>)> {
1339            extract_signer(extrinsics)
1340        }
1341
1342        fn is_within_tx_range(
1343            extrinsic: &ExtrinsicFor<Block>,
1344            bundle_vrf_hash: &subspace_core_primitives::U256,
1345            tx_range: &subspace_core_primitives::U256
1346        ) -> bool {
1347            use subspace_core_primitives::U256;
1348            use subspace_core_primitives::hashes::blake3_hash;
1349
1350            let lookup = frame_system::ChainContext::<Runtime>::default();
1351            if let Some(signer) = extract_signer_inner(extrinsic, &lookup).and_then(|account_result| {
1352                    account_result.ok().map(|account_id| account_id.encode())
1353                }) {
1354                // Check if the signer Id hash is within the tx range
1355                let signer_id_hash = U256::from_be_bytes(*blake3_hash(&signer.encode()));
1356                sp_domains::signer_in_tx_range(bundle_vrf_hash, &signer_id_hash, tx_range)
1357            } else {
1358                // Unsigned transactions are always in the range.
1359                true
1360            }
1361        }
1362
1363        fn extract_signer_if_all_within_tx_range(
1364            extrinsics: &Vec<ExtrinsicFor<Block>>,
1365            bundle_vrf_hash: &subspace_core_primitives::U256,
1366            tx_range: &subspace_core_primitives::U256
1367        ) -> Result<Vec<Option<opaque::AccountId>> , u32> {
1368            use subspace_core_primitives::U256;
1369            use subspace_core_primitives::hashes::blake3_hash;
1370
1371            let mut signers = Vec::with_capacity(extrinsics.len());
1372            let lookup = frame_system::ChainContext::<Runtime>::default();
1373            for (index, extrinsic) in extrinsics.iter().enumerate() {
1374                let maybe_signer = extract_signer_inner(extrinsic, &lookup).and_then(|account_result| {
1375                    account_result.ok().map(|account_id| account_id.encode())
1376                });
1377                if let Some(signer) = &maybe_signer {
1378                    // Check if the signer Id hash is within the tx range
1379                    let signer_id_hash = U256::from_be_bytes(*blake3_hash(&signer.encode()));
1380                    if !sp_domains::signer_in_tx_range(bundle_vrf_hash, &signer_id_hash, tx_range) {
1381                        return Err(index as u32)
1382                    }
1383                }
1384                signers.push(maybe_signer);
1385            }
1386
1387            Ok(signers)
1388        }
1389
1390        fn initialize_block_with_post_state_root(header: &HeaderFor<Block>) -> Vec<u8> {
1391            Executive::initialize_block(header);
1392            Executive::storage_root()
1393        }
1394
1395        fn apply_extrinsic_with_post_state_root(extrinsic: ExtrinsicFor<Block>) -> Vec<u8> {
1396            let _ = Executive::apply_extrinsic(extrinsic);
1397            Executive::storage_root()
1398        }
1399
1400        fn construct_set_code_extrinsic(code: Vec<u8>) -> Vec<u8> {
1401            UncheckedExtrinsic::new_bare(
1402                domain_pallet_executive::Call::set_code {
1403                    code
1404                }.into()
1405            ).encode()
1406        }
1407
1408        fn construct_timestamp_extrinsic(moment: Moment) -> ExtrinsicFor<Block> {
1409            UncheckedExtrinsic::new_bare(
1410                pallet_timestamp::Call::set{ now: moment }.into()
1411            )
1412        }
1413
1414        fn is_inherent_extrinsic(extrinsic: &ExtrinsicFor<Block>) -> bool {
1415            <Self as IsInherent<_>>::is_inherent(extrinsic)
1416        }
1417
1418        fn find_first_inherent_extrinsic(extrinsics: &Vec<ExtrinsicFor<Block>>) -> Option<u32> {
1419            for (index, extrinsic) in extrinsics.iter().enumerate() {
1420                if <Self as IsInherent<_>>::is_inherent(extrinsic) {
1421                    return Some(index as u32)
1422                }
1423            }
1424            None
1425        }
1426
1427        fn check_extrinsics_and_do_pre_dispatch(uxts: Vec<ExtrinsicFor<Block>>, block_number: BlockNumber,
1428            block_hash: BlockHashFor<Block>) -> Result<(), CheckExtrinsicsValidityError> {
1429            // Initializing block related storage required for validation
1430            // Only initialize if not already at the expected block number,
1431            // as this may be called multiple times with the same block_number
1432            let next_block_number = block_number + BlockNumber::one();
1433            if System::block_number() != next_block_number {
1434                System::initialize(
1435                    &next_block_number,
1436                    &block_hash,
1437                    &Default::default(),
1438                );
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}