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