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