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