1#![feature(variant_count)]
2#![cfg_attr(not(feature = "std"), no_std)]
3#![recursion_limit = "256"]
5
6mod precompiles;
7
8#[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::inherent::ProvideInherent;
33use frame_support::pallet_prelude::TypeInfo;
34use frame_support::traits::fungible::Credit;
35use frame_support::traits::{
36 ConstU16, ConstU32, ConstU64, Currency, Everything, FindAuthor, Imbalance, OnFinalize,
37 OnUnbalanced, VariantCount,
38};
39use frame_support::weights::constants::ParityDbWeight;
40use frame_support::weights::{ConstantMultiplier, Weight};
41use frame_support::{construct_runtime, parameter_types};
42use frame_system::limits::{BlockLength, BlockWeights};
43use frame_system::pallet_prelude::RuntimeCallFor;
44use pallet_block_fees::fees::OnChargeDomainTransaction;
45use pallet_ethereum::{
46 PostLogContent, Transaction as EthereumTransaction, TransactionAction, TransactionData,
47 TransactionStatus,
48};
49use pallet_evm::{
50 Account as EVMAccount, EnsureAddressNever, EnsureAddressRoot, FeeCalculator,
51 IdentityAddressMapping, Runner,
52};
53use pallet_evm_tracker::create_contract::{is_create_contract_allowed, CheckContractCreation};
54use pallet_evm_tracker::traits::{MaybeIntoEthCall, MaybeIntoEvmCall};
55use pallet_transporter::EndpointHandler;
56use parity_scale_codec::{Decode, DecodeLimit, Encode, MaxEncodedLen};
57use sp_api::impl_runtime_apis;
58use sp_core::crypto::KeyTypeId;
59use sp_core::{Get, OpaqueMetadata, H160, H256, U256};
60use sp_domains::{
61 ChannelId, DomainAllowlistUpdates, DomainId, PermissionedActionAllowedBy, Transfers,
62};
63use sp_evm_tracker::{
64 BlockGasLimit, GasLimitPovSizeRatio, GasPerByte, StorageFeeRatio, WeightPerGas,
65};
66use sp_messenger::endpoint::{Endpoint, EndpointHandler as EndpointHandlerT, EndpointId};
67use sp_messenger::messages::{
68 BlockMessagesWithStorageKey, ChainId, CrossDomainMessage, FeeModel, MessageId, MessageKey,
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, Block as BlockT, Checkable, DispatchInfoOf, DispatchTransaction, Dispatchable,
76 IdentityLookup, Keccak256, NumberFor, One, PostDispatchInfoOf, TransactionExtension,
77 UniqueSaturatedInto, 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_set::BTreeSet;
89use sp_std::marker::PhantomData;
90use sp_std::prelude::*;
91use sp_subspace_mmr::domain_mmr_runtime_interface::{
92 is_consensus_block_finalized, verify_mmr_proof,
93};
94use sp_subspace_mmr::{ConsensusChainMmrLeafProof, MmrLeaf};
95use sp_version::RuntimeVersion;
96use static_assertions::const_assert;
97use subspace_runtime_primitives::utility::{MaybeNestedCall, MaybeUtilityCall};
98use subspace_runtime_primitives::{
99 BlockNumber as ConsensusBlockNumber, DomainEventSegmentSize, Hash as ConsensusBlockHash,
100 Moment, SlowAdjustingFeeUpdate, XdmAdjustedWeightToFee, XdmFeeMultipler,
101 MAX_CALL_RECURSION_DEPTH, SHANNON, SSC,
102};
103
104pub type Address = AccountId;
106
107pub type Block = generic::Block<Header, UncheckedExtrinsic>;
109
110pub type SignedBlock = generic::SignedBlock<Block>;
112
113pub type BlockId = generic::BlockId<Block>;
115
116pub type Precompiles = crate::precompiles::Precompiles<Runtime>;
118
119pub type SignedExtra = (
121 frame_system::CheckNonZeroSender<Runtime>,
122 frame_system::CheckSpecVersion<Runtime>,
123 frame_system::CheckTxVersion<Runtime>,
124 frame_system::CheckGenesis<Runtime>,
125 frame_system::CheckMortality<Runtime>,
126 frame_system::CheckNonce<Runtime>,
127 domain_check_weight::CheckWeight<Runtime>,
128 pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
129 CheckContractCreation<Runtime>,
130 pallet_messenger::extensions::MessengerExtension<Runtime>,
131);
132
133type CustomSignedExtra = (
136 frame_system::CheckNonZeroSender<Runtime>,
137 frame_system::CheckSpecVersion<Runtime>,
138 frame_system::CheckTxVersion<Runtime>,
139 frame_system::CheckGenesis<Runtime>,
140 frame_system::CheckMortality<Runtime>,
141 pallet_evm_tracker::CheckNonce<Runtime>,
142 domain_check_weight::CheckWeight<Runtime>,
143 pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
144 CheckContractCreation<Runtime>,
145 pallet_messenger::extensions::MessengerTrustedMmrExtension<Runtime>,
146);
147
148pub type UncheckedExtrinsic =
150 fp_self_contained::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
151
152pub type CheckedExtrinsic =
154 fp_self_contained::CheckedExtrinsic<AccountId, RuntimeCall, SignedExtra, H160>;
155
156pub type Executive = domain_pallet_executive::Executive<
158 Runtime,
159 frame_system::ChainContext<Runtime>,
160 Runtime,
161 AllPalletsWithSystem,
162>;
163
164fn consensus_storage_fee(len: impl TryInto<Balance>) -> Result<Balance, TransactionValidityError> {
166 let len = len.try_into().map_err(|_| {
169 TransactionValidityError::Invalid(InvalidTransaction::Custom(ERR_BALANCE_OVERFLOW))
170 })?;
171
172 BlockFees::consensus_chain_byte_fee()
173 .checked_mul(Into::<Balance>::into(len))
174 .ok_or(TransactionValidityError::Invalid(
175 InvalidTransaction::Custom(ERR_BALANCE_OVERFLOW),
176 ))
177}
178
179impl fp_self_contained::SelfContainedCall for RuntimeCall {
180 type SignedInfo = H160;
181
182 fn is_self_contained(&self) -> bool {
183 match self {
184 RuntimeCall::Ethereum(call) => call.is_self_contained(),
185 _ => false,
186 }
187 }
188
189 fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {
190 match self {
191 RuntimeCall::Ethereum(call) => call.check_self_contained(),
192 _ => None,
193 }
194 }
195
196 fn validate_self_contained(
197 &self,
198 info: &Self::SignedInfo,
199 dispatch_info: &DispatchInfoOf<RuntimeCall>,
200 len: usize,
201 ) -> Option<TransactionValidity> {
202 if !is_create_contract_allowed::<Runtime>(self, &(*info).into()) {
203 return Some(Err(InvalidTransaction::Custom(
204 ERR_CONTRACT_CREATION_NOT_ALLOWED,
205 )
206 .into()));
207 }
208
209 match self {
210 RuntimeCall::Ethereum(call) => call.validate_self_contained(info, dispatch_info, len),
211 _ => None,
212 }
213 }
214
215 fn pre_dispatch_self_contained(
216 &self,
217 info: &Self::SignedInfo,
218 dispatch_info: &DispatchInfoOf<RuntimeCall>,
219 len: usize,
220 ) -> Option<Result<(), TransactionValidityError>> {
221 if !is_create_contract_allowed::<Runtime>(self, &(*info).into()) {
222 return Some(Err(InvalidTransaction::Custom(
223 ERR_CONTRACT_CREATION_NOT_ALLOWED,
224 )
225 .into()));
226 }
227
228 match self {
231 RuntimeCall::Ethereum(call) => {
232 if let pallet_ethereum::Call::transact { transaction } = call {
235 let origin = RuntimeOrigin::signed(AccountId20::from(*info));
236 if let Err(err) =
237 <domain_check_weight::CheckWeight<Runtime> as DispatchTransaction<
238 RuntimeCall,
239 >>::validate_and_prepare(
240 domain_check_weight::CheckWeight::<Runtime>::new(),
241 origin,
242 self,
243 dispatch_info,
244 len,
245 DEFAULT_EXTENSION_VERSION,
246 )
247 {
248 return Some(Err(err));
249 }
250
251 Some(Ethereum::validate_transaction_in_block(*info, transaction))
252 } else {
253 None
254 }
255 }
256 _ => None,
257 }
258 }
259
260 fn apply_self_contained(
261 self,
262 info: Self::SignedInfo,
263 ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {
264 match self {
265 call @ RuntimeCall::Ethereum(pallet_ethereum::Call::transact { .. }) => {
266 Some(call.dispatch(RuntimeOrigin::from(
267 pallet_ethereum::RawOrigin::EthereumTransaction(info),
268 )))
269 }
270 _ => None,
271 }
272 }
273}
274
275impl_opaque_keys! {
276 pub struct SessionKeys {
277 pub operator: sp_domains::OperatorKey,
279 }
280}
281
282#[sp_version::runtime_version]
283pub const VERSION: RuntimeVersion = RuntimeVersion {
284 spec_name: Cow::Borrowed("subspace-evm-domain"),
285 impl_name: Cow::Borrowed("subspace-evm-domain"),
286 authoring_version: 0,
287 spec_version: 0,
289 impl_version: 0,
290 apis: RUNTIME_API_VERSIONS,
291 transaction_version: 1,
292 system_version: 2,
293};
294
295parameter_types! {
296 pub const Version: RuntimeVersion = VERSION;
297 pub const BlockHashCount: BlockNumber = 2400;
298
299 pub RuntimeBlockLength: BlockLength = maximum_block_length();
304 pub RuntimeBlockWeights: BlockWeights = block_weights();
305}
306
307impl frame_system::Config for Runtime {
308 type AccountId = AccountId;
310 type RuntimeCall = RuntimeCall;
312 type RuntimeTask = RuntimeTask;
314 type Lookup = IdentityLookup<AccountId>;
316 type Nonce = Nonce;
318 type Hash = Hash;
320 type Hashing = BlakeTwo256;
322 type Block = Block;
324 type RuntimeEvent = RuntimeEvent;
326 type RuntimeOrigin = RuntimeOrigin;
328 type BlockHashCount = BlockHashCount;
330 type Version = Version;
332 type PalletInfo = PalletInfo;
334 type AccountData = pallet_balances::AccountData<Balance>;
336 type OnNewAccount = ();
338 type OnKilledAccount = ();
340 type DbWeight = ParityDbWeight;
342 type BaseCallFilter = Everything;
344 type SystemWeightInfo = frame_system::weights::SubstrateWeight<Runtime>;
346 type BlockWeights = RuntimeBlockWeights;
348 type BlockLength = RuntimeBlockLength;
350 type SS58Prefix = ConstU16<6094>;
351 type OnSetCode = ();
353 type SingleBlockMigrations = ();
354 type MultiBlockMigrator = ();
355 type PreInherents = ();
356 type PostInherents = ();
357 type PostTransactions = ();
358 type MaxConsumers = ConstU32<16>;
359 type ExtensionsWeightInfo = frame_system::ExtensionsWeight<Runtime>;
360 type EventSegmentSize = DomainEventSegmentSize;
361}
362
363impl pallet_timestamp::Config for Runtime {
364 type Moment = Moment;
366 type OnTimestampSet = ();
367 type MinimumPeriod = ConstU64<{ SLOT_DURATION / 2 }>;
368 type WeightInfo = pallet_timestamp::weights::SubstrateWeight<Runtime>;
369}
370
371parameter_types! {
372 pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
373 pub const MaxLocks: u32 = 50;
374 pub const MaxReserves: u32 = 50;
375}
376
377pub struct DustRemovalHandler;
379
380impl OnUnbalanced<Credit<AccountId, Balances>> for DustRemovalHandler {
381 fn on_nonzero_unbalanced(dusted_amount: Credit<AccountId, Balances>) {
382 BlockFees::note_burned_balance(dusted_amount.peek());
383 }
384}
385
386impl pallet_balances::Config for Runtime {
387 type RuntimeFreezeReason = RuntimeFreezeReason;
388 type MaxLocks = MaxLocks;
389 type Balance = Balance;
391 type RuntimeEvent = RuntimeEvent;
393 type DustRemoval = DustRemovalHandler;
394 type ExistentialDeposit = ExistentialDeposit;
395 type AccountStore = System;
396 type WeightInfo = pallet_balances::weights::SubstrateWeight<Runtime>;
397 type MaxReserves = MaxReserves;
398 type ReserveIdentifier = [u8; 8];
399 type FreezeIdentifier = ();
400 type MaxFreezes = ();
401 type RuntimeHoldReason = HoldIdentifierWrapper;
402 type DoneSlashHandler = ();
403}
404
405parameter_types! {
406 pub const OperationalFeeMultiplier: u8 = 5;
407 pub const DomainChainByteFee: Balance = 100_000 * SHANNON;
408 pub TransactionWeightFee: Balance = 100_000 * SHANNON;
409}
410
411impl pallet_block_fees::Config for Runtime {
412 type Balance = Balance;
413 type DomainChainByteFee = DomainChainByteFee;
414}
415
416type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;
417
418pub struct FinalDomainTransactionByteFee;
419
420impl Get<Balance> for FinalDomainTransactionByteFee {
421 fn get() -> Balance {
422 BlockFees::final_domain_transaction_byte_fee()
423 }
424}
425
426impl pallet_transaction_payment::Config for Runtime {
427 type RuntimeEvent = RuntimeEvent;
428 type OnChargeTransaction = OnChargeDomainTransaction<Balances>;
429 type WeightToFee = ConstantMultiplier<Balance, TransactionWeightFee>;
430 type LengthToFee = ConstantMultiplier<Balance, FinalDomainTransactionByteFee>;
431 type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Runtime, TargetBlockFullness>;
432 type OperationalFeeMultiplier = OperationalFeeMultiplier;
433 type WeightInfo = pallet_transaction_payment::weights::SubstrateWeight<Runtime>;
434}
435
436pub struct ExtrinsicStorageFees;
437
438impl domain_pallet_executive::ExtrinsicStorageFees<Runtime> for ExtrinsicStorageFees {
439 fn extract_signer(xt: UncheckedExtrinsic) -> (Option<AccountId>, DispatchInfo) {
440 let dispatch_info = xt.get_dispatch_info();
441 let lookup = frame_system::ChainContext::<Runtime>::default();
442 let maybe_signer = extract_signer_inner(&xt, &lookup).and_then(|res| res.ok());
443 (maybe_signer, dispatch_info)
444 }
445
446 fn on_storage_fees_charged(
447 charged_fees: Balance,
448 tx_size: u32,
449 ) -> Result<(), TransactionValidityError> {
450 let consensus_storage_fee = consensus_storage_fee(tx_size)?;
451
452 let (paid_consensus_storage_fee, paid_domain_fee) = if charged_fees <= consensus_storage_fee
453 {
454 (charged_fees, Zero::zero())
455 } else {
456 (consensus_storage_fee, charged_fees - consensus_storage_fee)
457 };
458
459 BlockFees::note_consensus_storage_fee(paid_consensus_storage_fee);
460 BlockFees::note_domain_execution_fee(paid_domain_fee);
461 Ok(())
462 }
463}
464
465impl domain_pallet_executive::Config for Runtime {
466 type RuntimeEvent = RuntimeEvent;
467 type WeightInfo = domain_pallet_executive::weights::SubstrateWeight<Runtime>;
468 type Currency = Balances;
469 type LengthToFee = <Runtime as pallet_transaction_payment::Config>::LengthToFee;
470 type ExtrinsicStorageFees = ExtrinsicStorageFees;
471}
472
473parameter_types! {
474 pub SelfChainId: ChainId = SelfDomainId::self_domain_id().into();
475}
476
477pub struct OnXDMRewards;
478
479impl sp_messenger::OnXDMRewards<Balance> for OnXDMRewards {
480 fn on_xdm_rewards(rewards: Balance) {
481 BlockFees::note_domain_execution_fee(rewards)
482 }
483
484 fn on_chain_protocol_fees(chain_id: ChainId, fees: Balance) {
485 BlockFees::note_chain_rewards(chain_id, fees);
487 }
488}
489
490type MmrHash = <Keccak256 as sp_runtime::traits::Hash>::Output;
491
492pub struct MmrProofVerifier;
493
494impl sp_subspace_mmr::MmrProofVerifier<MmrHash, NumberFor<Block>, Hash> for MmrProofVerifier {
495 fn verify_proof_and_extract_leaf(
496 mmr_leaf_proof: ConsensusChainMmrLeafProof<NumberFor<Block>, Hash, MmrHash>,
497 ) -> Option<MmrLeaf<ConsensusBlockNumber, ConsensusBlockHash>> {
498 let ConsensusChainMmrLeafProof {
499 consensus_block_number,
500 opaque_mmr_leaf: opaque_leaf,
501 proof,
502 ..
503 } = mmr_leaf_proof;
504
505 if !is_consensus_block_finalized(consensus_block_number) {
506 return None;
507 }
508
509 let leaf: MmrLeaf<ConsensusBlockNumber, ConsensusBlockHash> =
510 opaque_leaf.into_opaque_leaf().try_decode()?;
511
512 verify_mmr_proof(vec![EncodableOpaqueLeaf::from_leaf(&leaf)], proof.encode())
513 .then_some(leaf)
514 }
515}
516
517pub struct StorageKeys;
518
519impl sp_messenger::StorageKeys for StorageKeys {
520 fn confirmed_domain_block_storage_key(domain_id: DomainId) -> Option<Vec<u8>> {
521 get_storage_key(StorageKeyRequest::ConfirmedDomainBlockStorageKey(domain_id))
522 }
523
524 fn outbox_storage_key(chain_id: ChainId, message_key: MessageKey) -> Option<Vec<u8>> {
525 get_storage_key(StorageKeyRequest::OutboxStorageKey {
526 chain_id,
527 message_key,
528 })
529 }
530
531 fn inbox_responses_storage_key(chain_id: ChainId, message_key: MessageKey) -> Option<Vec<u8>> {
532 get_storage_key(StorageKeyRequest::InboxResponseStorageKey {
533 chain_id,
534 message_key,
535 })
536 }
537}
538
539#[derive(
541 PartialEq, Eq, Clone, Encode, Decode, TypeInfo, MaxEncodedLen, Ord, PartialOrd, Copy, Debug,
542)]
543pub struct HoldIdentifierWrapper(HoldIdentifier);
544
545impl VariantCount for HoldIdentifierWrapper {
546 const VARIANT_COUNT: u32 = mem::variant_count::<HoldIdentifier>() as u32;
547}
548
549impl pallet_messenger::HoldIdentifier<Runtime> for HoldIdentifierWrapper {
550 fn messenger_channel() -> Self {
551 Self(HoldIdentifier::MessengerChannel)
552 }
553}
554
555parameter_types! {
556 pub const ChannelReserveFee: Balance = 100 * SSC;
557 pub const ChannelInitReservePortion: Perbill = Perbill::from_percent(20);
558 pub const ChannelFeeModel: FeeModel<Balance> = FeeModel{relay_fee: SSC};
560 pub const MaxOutgoingMessages: u32 = MAX_OUTGOING_MESSAGES;
561 pub const MessageVersion: pallet_messenger::MessageVersion = pallet_messenger::MessageVersion::V1;
562}
563
564const_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 type StorageKeys = StorageKeys;
588 type DomainOwner = ();
589 type HoldIdentifier = HoldIdentifierWrapper;
590 type ChannelReserveFee = ChannelReserveFee;
591 type ChannelInitReservePortion = ChannelInitReservePortion;
592 type DomainRegistration = ();
593 type ChannelFeeModel = ChannelFeeModel;
594 type MaxOutgoingMessages = MaxOutgoingMessages;
595 type MessengerOrigin = pallet_messenger::EnsureMessengerOrigin;
596 type MessageVersion = MessageVersion;
597 type NoteChainTransfer = Transporter;
598}
599
600impl<C> frame_system::offchain::CreateTransactionBase<C> for Runtime
601where
602 RuntimeCall: From<C>,
603{
604 type Extrinsic = UncheckedExtrinsic;
605 type RuntimeCall = RuntimeCall;
606}
607
608parameter_types! {
609 pub const TransporterEndpointId: EndpointId = 1;
610}
611
612impl pallet_transporter::Config for Runtime {
613 type RuntimeEvent = RuntimeEvent;
614 type SelfChainId = SelfChainId;
615 type SelfEndpointId = TransporterEndpointId;
616 type Currency = Balances;
617 type Sender = Messenger;
618 type AccountIdConverter = domain_runtime_primitives::AccountId20Converter;
619 type WeightInfo = pallet_transporter::weights::SubstrateWeight<Runtime>;
620 type SkipBalanceTransferChecks = ();
621}
622
623impl pallet_evm_chain_id::Config for Runtime {}
624
625pub struct FindAuthorTruncated;
626
627impl FindAuthor<H160> for FindAuthorTruncated {
628 fn find_author<'a, I>(_digests: I) -> Option<H160>
629 where
630 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,
631 {
632 None
634 }
635}
636
637parameter_types! {
638 pub PrecompilesValue: Precompiles = Precompiles::default();
639}
640
641type InnerEVMCurrencyAdapter = pallet_evm::EVMCurrencyAdapter<Balances, ()>;
642
643pub struct EVMCurrencyAdapter;
647
648impl pallet_evm::OnChargeEVMTransaction<Runtime> for EVMCurrencyAdapter {
649 type LiquidityInfo = Option<NegativeImbalance>;
650
651 fn withdraw_fee(
652 who: &H160,
653 fee: U256,
654 ) -> Result<Self::LiquidityInfo, pallet_evm::Error<Runtime>> {
655 InnerEVMCurrencyAdapter::withdraw_fee(who, fee)
656 }
657
658 fn correct_and_deposit_fee(
659 who: &H160,
660 corrected_fee: U256,
661 base_fee: U256,
662 already_withdrawn: Self::LiquidityInfo,
663 ) -> Self::LiquidityInfo {
664 if already_withdrawn.is_some() {
665 let (storage_fee, execution_fee) =
667 EvmGasPriceCalculator::split_fee_into_storage_and_execution(
668 corrected_fee.as_u128(),
669 );
670 BlockFees::note_consensus_storage_fee(storage_fee);
671 BlockFees::note_domain_execution_fee(execution_fee);
672 }
673
674 <InnerEVMCurrencyAdapter as pallet_evm::OnChargeEVMTransaction<
675 Runtime,
676 >>::correct_and_deposit_fee(who, corrected_fee, base_fee, already_withdrawn)
677 }
678
679 fn pay_priority_fee(tip: Self::LiquidityInfo) {
680 <InnerEVMCurrencyAdapter as pallet_evm::OnChargeEVMTransaction<Runtime>>::pay_priority_fee(
681 tip,
682 );
683 }
684}
685
686pub type EvmGasPriceCalculator = pallet_evm_tracker::fees::EvmGasPriceCalculator<
687 Runtime,
688 TransactionWeightFee,
689 GasPerByte,
690 StorageFeeRatio,
691>;
692
693impl pallet_evm::Config for Runtime {
694 type AccountProvider = pallet_evm::FrameSystemAccountProvider<Self>;
695 type FeeCalculator = EvmGasPriceCalculator;
696 type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
697 type WeightPerGas = WeightPerGas;
698 type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;
699 type CallOrigin = EnsureAddressRoot<AccountId>;
700 type WithdrawOrigin = EnsureAddressNever<AccountId>;
701 type AddressMapping = IdentityAddressMapping;
702 type Currency = Balances;
703 type RuntimeEvent = RuntimeEvent;
704 type PrecompilesType = Precompiles;
705 type PrecompilesValue = PrecompilesValue;
706 type ChainId = EVMChainId;
707 type BlockGasLimit = BlockGasLimit;
708 type Runner = pallet_evm::runner::stack::Runner<Self>;
709 type OnChargeTransaction = EVMCurrencyAdapter;
710 type OnCreate = ();
711 type FindAuthor = FindAuthorTruncated;
712 type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
713 type GasLimitStorageGrowthRatio = ();
715 type Timestamp = Timestamp;
716 type WeightInfo = pallet_evm::weights::SubstrateWeight<Self>;
717}
718
719impl MaybeIntoEvmCall<Runtime> for RuntimeCall {
720 fn maybe_into_evm_call(&self) -> Option<&pallet_evm::Call<Runtime>> {
722 match self {
723 RuntimeCall::EVM(call) => Some(call),
724 _ => None,
725 }
726 }
727}
728
729impl pallet_evm_tracker::Config for Runtime {}
730
731parameter_types! {
732 pub const PostOnlyBlockHash: PostLogContent = PostLogContent::OnlyBlockHash;
733}
734
735impl pallet_ethereum::Config for Runtime {
736 type RuntimeEvent = RuntimeEvent;
737 type StateRoot = pallet_ethereum::IntermediateStateRoot<Self::Version>;
738 type PostLogContent = PostOnlyBlockHash;
739 type ExtraDataLength = ConstU32<30>;
740}
741
742impl MaybeIntoEthCall<Runtime> for RuntimeCall {
743 fn maybe_into_eth_call(&self) -> Option<&pallet_ethereum::Call<Runtime>> {
745 match self {
746 RuntimeCall::Ethereum(call) => Some(call),
747 _ => None,
748 }
749 }
750}
751
752impl pallet_domain_id::Config for Runtime {}
753
754pub struct IntoRuntimeCall;
755
756impl sp_domain_sudo::IntoRuntimeCall<RuntimeCall> for IntoRuntimeCall {
757 fn runtime_call(call: Vec<u8>) -> RuntimeCall {
758 UncheckedExtrinsic::decode(&mut call.as_slice())
759 .expect("must always be a valid domain extrinsic as checked by consensus chain; qed")
760 .0
761 .function
762 }
763}
764
765impl pallet_domain_sudo::Config for Runtime {
766 type RuntimeEvent = RuntimeEvent;
767 type RuntimeCall = RuntimeCall;
768 type IntoRuntimeCall = IntoRuntimeCall;
769}
770
771impl pallet_utility::Config for Runtime {
772 type RuntimeEvent = RuntimeEvent;
773 type RuntimeCall = RuntimeCall;
774 type PalletsOrigin = OriginCaller;
775 type WeightInfo = pallet_utility::weights::SubstrateWeight<Runtime>;
776}
777
778impl MaybeUtilityCall<Runtime> for RuntimeCall {
779 fn maybe_utility_call(&self) -> Option<&pallet_utility::Call<Runtime>> {
781 match self {
782 RuntimeCall::Utility(call) => Some(call),
783 _ => None,
784 }
785 }
786}
787
788impl MaybeNestedCall<Runtime> for RuntimeCall {
789 fn maybe_nested_call(&self) -> Option<Vec<&RuntimeCallFor<Runtime>>> {
794 self.maybe_nested_utility_calls()
797 }
798}
799
800construct_runtime!(
804 pub struct Runtime {
805 System: frame_system = 0,
807 Timestamp: pallet_timestamp = 1,
811 ExecutivePallet: domain_pallet_executive = 2,
812 Utility: pallet_utility = 8,
813
814 Balances: pallet_balances = 20,
816 TransactionPayment: pallet_transaction_payment = 21,
817
818 Messenger: pallet_messenger = 60,
821 Transporter: pallet_transporter = 61,
822
823 Ethereum: pallet_ethereum = 80,
825 EVM: pallet_evm = 81,
826 EVMChainId: pallet_evm_chain_id = 82,
827 EVMNoncetracker: pallet_evm_tracker = 84,
828
829 SelfDomainId: pallet_domain_id = 90,
831 BlockFees: pallet_block_fees = 91,
832
833 Sudo: pallet_domain_sudo = 100,
835 }
836);
837
838#[derive(Clone, Default)]
839pub struct TransactionConverter;
840
841impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {
842 fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {
843 UncheckedExtrinsic::new_bare(
844 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),
845 )
846 }
847}
848
849impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {
850 fn convert_transaction(
851 &self,
852 transaction: pallet_ethereum::Transaction,
853 ) -> opaque::UncheckedExtrinsic {
854 let extrinsic = UncheckedExtrinsic::new_bare(
855 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),
856 );
857 let encoded = extrinsic.encode();
858 opaque::UncheckedExtrinsic::decode(&mut &encoded[..])
859 .expect("Encoded extrinsic is always valid")
860 }
861}
862
863fn is_xdm_mmr_proof_valid(ext: &<Block as BlockT>::Extrinsic) -> Option<bool> {
864 match &ext.0.function {
865 RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })
866 | RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
867 let ConsensusChainMmrLeafProof {
868 consensus_block_number,
869 opaque_mmr_leaf,
870 proof,
871 ..
872 } = msg.proof.consensus_mmr_proof();
873
874 if !is_consensus_block_finalized(consensus_block_number) {
875 return Some(false);
876 }
877
878 Some(verify_mmr_proof(vec![opaque_mmr_leaf], proof.encode()))
879 }
880 _ => None,
881 }
882}
883
884fn is_valid_sudo_call(encoded_ext: Vec<u8>) -> bool {
886 UncheckedExtrinsic::decode_with_depth_limit(
887 MAX_CALL_RECURSION_DEPTH,
888 &mut encoded_ext.as_slice(),
889 )
890 .is_ok()
891}
892
893fn construct_sudo_call_extrinsic(encoded_ext: Vec<u8>) -> <Block as BlockT>::Extrinsic {
895 let ext = UncheckedExtrinsic::decode(&mut encoded_ext.as_slice()).expect(
896 "must always be a valid extrinsic due to the check above and storage proof check; qed",
897 );
898 UncheckedExtrinsic::new_bare(
899 pallet_domain_sudo::Call::sudo {
900 call: Box::new(ext.0.function),
901 }
902 .into(),
903 )
904}
905
906fn construct_evm_contract_creation_allowed_by_extrinsic(
908 decoded_argument: PermissionedActionAllowedBy<AccountId>,
909) -> <Block as BlockT>::Extrinsic {
910 UncheckedExtrinsic::new_bare(
911 pallet_evm_tracker::Call::set_contract_creation_allowed_by {
912 contract_creation_allowed_by: decoded_argument,
913 }
914 .into(),
915 )
916}
917
918fn extract_signer_inner<Lookup>(
919 ext: &UncheckedExtrinsic,
920 lookup: &Lookup,
921) -> Option<Result<AccountId, TransactionValidityError>>
922where
923 Lookup: sp_runtime::traits::Lookup<Source = Address, Target = AccountId>,
924{
925 if ext.0.function.is_self_contained() {
926 ext.0
927 .function
928 .check_self_contained()
929 .map(|signed_info| signed_info.map(|signer| signer.into()))
930 } else {
931 match &ext.0.preamble {
932 Preamble::Bare(_) | Preamble::General(_, _) => None,
933 Preamble::Signed(address, _, _) => Some(lookup.lookup(*address).map_err(|e| e.into())),
934 }
935 }
936}
937
938pub fn extract_signer(
939 extrinsics: Vec<UncheckedExtrinsic>,
940) -> Vec<(Option<opaque::AccountId>, UncheckedExtrinsic)> {
941 let lookup = frame_system::ChainContext::<Runtime>::default();
942
943 extrinsics
944 .into_iter()
945 .map(|extrinsic| {
946 let maybe_signer =
947 extract_signer_inner(&extrinsic, &lookup).and_then(|account_result| {
948 account_result.ok().map(|account_id| account_id.encode())
949 });
950 (maybe_signer, extrinsic)
951 })
952 .collect()
953}
954
955fn extrinsic_era(extrinsic: &<Block as BlockT>::Extrinsic) -> Option<Era> {
956 match &extrinsic.0.preamble {
957 Preamble::Bare(_) | Preamble::General(_, _) => None,
958 Preamble::Signed(_, _, extra) => Some(extra.4 .0),
959 }
960}
961
962#[cfg(feature = "runtime-benchmarks")]
963mod benches {
964 frame_benchmarking::define_benchmarks!(
965 [frame_benchmarking, BaselineBench::<Runtime>]
966 [frame_system, SystemBench::<Runtime>]
967 [domain_pallet_executive, ExecutivePallet]
968 [pallet_messenger, Messenger]
969 );
970}
971
972fn pre_dispatch_evm_transaction(
978 account_id: H160,
979 call: RuntimeCall,
980 dispatch_info: &DispatchInfoOf<RuntimeCall>,
981 len: usize,
982) -> Result<(), TransactionValidityError> {
983 match call {
984 RuntimeCall::Ethereum(call) => {
985 if let Some(transaction_validity) =
986 call.validate_self_contained(&account_id, dispatch_info, len)
987 {
988 let _ = transaction_validity?;
989
990 let pallet_ethereum::Call::transact { transaction } = call;
991 frame_system::CheckWeight::<Runtime>::do_validate(dispatch_info, len).and_then(
992 |(_, next_len)| {
993 domain_check_weight::CheckWeight::<Runtime>::do_prepare(
994 dispatch_info,
995 len,
996 next_len,
997 )
998 },
999 )?;
1000
1001 let transaction_data: TransactionData = (&transaction).into();
1002 let transaction_nonce = transaction_data.nonce;
1003 let account_nonce = {
1006 let tracked_nonce = EVMNoncetracker::account_nonce(AccountId::from(account_id))
1007 .unwrap_or(U256::zero());
1008 let account_nonce = EVM::account_basic(&account_id).0.nonce;
1009 max(tracked_nonce, account_nonce)
1010 };
1011
1012 match transaction_nonce.cmp(&account_nonce) {
1013 Ordering::Less => return Err(InvalidTransaction::Stale.into()),
1014 Ordering::Greater => return Err(InvalidTransaction::Future.into()),
1015 Ordering::Equal => {}
1016 }
1017
1018 let next_nonce = account_nonce
1019 .checked_add(U256::one())
1020 .ok_or(InvalidTransaction::Custom(ERR_NONCE_OVERFLOW))?;
1021
1022 EVMNoncetracker::set_account_nonce(AccountId::from(account_id), next_nonce);
1023 }
1024
1025 Ok(())
1026 }
1027 _ => Err(InvalidTransaction::Call.into()),
1028 }
1029}
1030
1031fn check_transaction_and_do_pre_dispatch_inner(
1032 uxt: &<Block as BlockT>::Extrinsic,
1033) -> Result<(), TransactionValidityError> {
1034 let lookup = frame_system::ChainContext::<Runtime>::default();
1035
1036 let xt = uxt.clone().check(&lookup)?;
1037
1038 let dispatch_info = xt.get_dispatch_info();
1039
1040 if dispatch_info.class == DispatchClass::Mandatory {
1041 return Err(InvalidTransaction::MandatoryValidation.into());
1042 }
1043
1044 let encoded_len = uxt.encoded_size();
1045
1046 match xt.signed {
1051 CheckedSignature::GenericDelegated(format) => match format {
1052 ExtrinsicFormat::Bare => {
1053 Runtime::pre_dispatch(&xt.function).map(|_| ())?;
1054 <SignedExtra as TransactionExtension<RuntimeCall>>::bare_validate_and_prepare(
1055 &xt.function,
1056 &dispatch_info,
1057 encoded_len,
1058 )
1059 .map(|_| ())
1060 }
1061 ExtrinsicFormat::General(extension_version, extra) => {
1062 let custom_extra: CustomSignedExtra = (
1063 extra.0,
1064 extra.1,
1065 extra.2,
1066 extra.3,
1067 extra.4,
1068 pallet_evm_tracker::CheckNonce::from(extra.5 .0),
1069 extra.6,
1070 extra.7.clone(),
1071 extra.8,
1072 pallet_messenger::extensions::MessengerTrustedMmrExtension::<Runtime>::new(),
1073 );
1074
1075 let origin = RuntimeOrigin::none();
1076 <CustomSignedExtra as DispatchTransaction<RuntimeCall>>::validate_and_prepare(
1077 custom_extra,
1078 origin,
1079 &xt.function,
1080 &dispatch_info,
1081 encoded_len,
1082 extension_version,
1083 )
1084 .map(|_| ())
1085 }
1086 ExtrinsicFormat::Signed(account_id, extra) => {
1087 let custom_extra: CustomSignedExtra = (
1088 extra.0,
1089 extra.1,
1090 extra.2,
1091 extra.3,
1092 extra.4,
1093 pallet_evm_tracker::CheckNonce::from(extra.5 .0),
1094 extra.6,
1095 extra.7.clone(),
1096 extra.8,
1097 pallet_messenger::extensions::MessengerTrustedMmrExtension::<Runtime>::new(),
1100 );
1101
1102 let origin = RuntimeOrigin::signed(account_id);
1103 <CustomSignedExtra as DispatchTransaction<RuntimeCall>>::validate_and_prepare(
1104 custom_extra,
1105 origin,
1106 &xt.function,
1107 &dispatch_info,
1108 encoded_len,
1109 DEFAULT_EXTENSION_VERSION,
1110 )
1111 .map(|_| ())
1112 }
1113 },
1114 CheckedSignature::SelfContained(account_id) => {
1115 pre_dispatch_evm_transaction(account_id, xt.function, &dispatch_info, encoded_len)
1116 }
1117 }
1118}
1119
1120impl pallet_messenger::extensions::MaybeMessengerCall<Runtime> for RuntimeCall {
1121 fn maybe_messenger_call(&self) -> Option<&pallet_messenger::Call<Runtime>> {
1122 match self {
1123 RuntimeCall::Messenger(call) => Some(call),
1124 _ => None,
1125 }
1126 }
1127}
1128
1129impl<C> subspace_runtime_primitives::CreateUnsigned<C> for Runtime
1130where
1131 RuntimeCall: From<C>,
1132{
1133 fn create_unsigned(call: Self::RuntimeCall) -> Self::Extrinsic {
1134 create_unsigned_general_extrinsic(call)
1135 }
1136}
1137
1138fn create_unsigned_general_extrinsic(call: RuntimeCall) -> UncheckedExtrinsic {
1139 let extra: SignedExtra = (
1140 frame_system::CheckNonZeroSender::<Runtime>::new(),
1141 frame_system::CheckSpecVersion::<Runtime>::new(),
1142 frame_system::CheckTxVersion::<Runtime>::new(),
1143 frame_system::CheckGenesis::<Runtime>::new(),
1144 frame_system::CheckMortality::<Runtime>::from(generic::Era::Immortal),
1145 frame_system::CheckNonce::<Runtime>::from(0u32),
1148 domain_check_weight::CheckWeight::<Runtime>::new(),
1149 pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(0u128),
1152 CheckContractCreation::<Runtime>::new(),
1153 pallet_messenger::extensions::MessengerExtension::<Runtime>::new(),
1154 );
1155
1156 UncheckedExtrinsic::from(generic::UncheckedExtrinsic::new_transaction(call, extra))
1157}
1158
1159#[cfg(feature = "runtime-benchmarks")]
1160impl frame_system_benchmarking::Config for Runtime {}
1161
1162#[cfg(feature = "runtime-benchmarks")]
1163impl frame_benchmarking::baseline::Config for Runtime {}
1164
1165impl_runtime_apis! {
1166 impl sp_api::Core<Block> for Runtime {
1167 fn version() -> RuntimeVersion {
1168 VERSION
1169 }
1170
1171 fn execute_block(block: Block) {
1172 Executive::execute_block(block)
1173 }
1174
1175 fn initialize_block(header: &<Block as BlockT>::Header) -> ExtrinsicInclusionMode {
1176 Executive::initialize_block(header)
1177 }
1178 }
1179
1180 impl sp_api::Metadata<Block> for Runtime {
1181 fn metadata() -> OpaqueMetadata {
1182 OpaqueMetadata::new(Runtime::metadata().into())
1183 }
1184
1185 fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
1186 Runtime::metadata_at_version(version)
1187 }
1188
1189 fn metadata_versions() -> Vec<u32> {
1190 Runtime::metadata_versions()
1191 }
1192 }
1193
1194 impl sp_block_builder::BlockBuilder<Block> for Runtime {
1195 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
1196 Executive::apply_extrinsic(extrinsic)
1197 }
1198
1199 fn finalize_block() -> <Block as BlockT>::Header {
1200 Executive::finalize_block()
1201 }
1202
1203 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
1204 data.create_extrinsics()
1205 }
1206
1207 fn check_inherents(
1208 block: Block,
1209 data: sp_inherents::InherentData,
1210 ) -> sp_inherents::CheckInherentsResult {
1211 data.check_extrinsics(&block)
1212 }
1213 }
1214
1215 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
1216 fn validate_transaction(
1217 source: TransactionSource,
1218 tx: <Block as BlockT>::Extrinsic,
1219 block_hash: <Block as BlockT>::Hash,
1220 ) -> TransactionValidity {
1221 Executive::validate_transaction(source, tx, block_hash)
1222 }
1223 }
1224
1225 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
1226 fn offchain_worker(header: &<Block as BlockT>::Header) {
1227 Executive::offchain_worker(header)
1228 }
1229 }
1230
1231 impl sp_session::SessionKeys<Block> for Runtime {
1232 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
1233 SessionKeys::generate(seed)
1234 }
1235
1236 fn decode_session_keys(
1237 encoded: Vec<u8>,
1238 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
1239 SessionKeys::decode_into_raw_public_keys(&encoded)
1240 }
1241 }
1242
1243 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
1244 fn account_nonce(account: AccountId) -> Nonce {
1245 System::account_nonce(account)
1246 }
1247 }
1248
1249 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {
1250 fn query_info(
1251 uxt: <Block as BlockT>::Extrinsic,
1252 len: u32,
1253 ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
1254 TransactionPayment::query_info(uxt, len)
1255 }
1256 fn query_fee_details(
1257 uxt: <Block as BlockT>::Extrinsic,
1258 len: u32,
1259 ) -> pallet_transaction_payment::FeeDetails<Balance> {
1260 TransactionPayment::query_fee_details(uxt, len)
1261 }
1262 fn query_weight_to_fee(weight: Weight) -> Balance {
1263 TransactionPayment::weight_to_fee(weight)
1264 }
1265 fn query_length_to_fee(length: u32) -> Balance {
1266 TransactionPayment::length_to_fee(length)
1267 }
1268 }
1269
1270 impl sp_domains::core_api::DomainCoreApi<Block> for Runtime {
1271 fn extract_signer(
1272 extrinsics: Vec<<Block as BlockT>::Extrinsic>,
1273 ) -> Vec<(Option<opaque::AccountId>, <Block as BlockT>::Extrinsic)> {
1274 extract_signer(extrinsics)
1275 }
1276
1277 fn is_within_tx_range(
1278 extrinsic: &<Block as BlockT>::Extrinsic,
1279 bundle_vrf_hash: &subspace_core_primitives::U256,
1280 tx_range: &subspace_core_primitives::U256
1281 ) -> bool {
1282 use subspace_core_primitives::U256;
1283 use subspace_core_primitives::hashes::blake3_hash;
1284
1285 let lookup = frame_system::ChainContext::<Runtime>::default();
1286 if let Some(signer) = extract_signer_inner(extrinsic, &lookup).and_then(|account_result| {
1287 account_result.ok().map(|account_id| account_id.encode())
1288 }) {
1289 let signer_id_hash = U256::from_be_bytes(*blake3_hash(&signer.encode()));
1291 sp_domains::signer_in_tx_range(bundle_vrf_hash, &signer_id_hash, tx_range)
1292 } else {
1293 true
1295 }
1296 }
1297
1298 fn initialize_block_with_post_state_root(header: &<Block as BlockT>::Header) -> Vec<u8> {
1299 Executive::initialize_block(header);
1300 Executive::storage_root()
1301 }
1302
1303 fn apply_extrinsic_with_post_state_root(extrinsic: <Block as BlockT>::Extrinsic) -> Vec<u8> {
1304 let _ = Executive::apply_extrinsic(extrinsic);
1305 Executive::storage_root()
1306 }
1307
1308 fn construct_set_code_extrinsic(code: Vec<u8>) -> Vec<u8> {
1309 UncheckedExtrinsic::new_bare(
1310 domain_pallet_executive::Call::set_code {
1311 code
1312 }.into()
1313 ).encode()
1314 }
1315
1316 fn construct_timestamp_extrinsic(moment: Moment) -> <Block as BlockT>::Extrinsic {
1317 UncheckedExtrinsic::new_bare(
1318 pallet_timestamp::Call::set{ now: moment }.into()
1319 )
1320 }
1321
1322 fn is_inherent_extrinsic(extrinsic: &<Block as BlockT>::Extrinsic) -> bool {
1323 match &extrinsic.0.function {
1324 RuntimeCall::Timestamp(call) => Timestamp::is_inherent(call),
1325 RuntimeCall::ExecutivePallet(call) => ExecutivePallet::is_inherent(call),
1326 RuntimeCall::Messenger(call) => Messenger::is_inherent(call),
1327 RuntimeCall::Sudo(call) => Sudo::is_inherent(call),
1328 RuntimeCall::EVMNoncetracker(call) => EVMNoncetracker::is_inherent(call),
1329 _ => false,
1330 }
1331 }
1332
1333 fn check_extrinsics_and_do_pre_dispatch(uxts: Vec<<Block as BlockT>::Extrinsic>, block_number: BlockNumber,
1334 block_hash: <Block as BlockT>::Hash) -> Result<(), CheckExtrinsicsValidityError> {
1335 System::initialize(
1337 &(block_number + BlockNumber::one()),
1338 &block_hash,
1339 &Default::default(),
1340 );
1341
1342 for (extrinsic_index, uxt) in uxts.iter().enumerate() {
1343 check_transaction_and_do_pre_dispatch_inner(uxt).map_err(|e| {
1344 CheckExtrinsicsValidityError {
1345 extrinsic_index: extrinsic_index as u32,
1346 transaction_validity_error: e
1347 }
1348 })?;
1349 }
1350
1351 Ok(())
1352 }
1353
1354 fn decode_extrinsic(
1355 opaque_extrinsic: sp_runtime::OpaqueExtrinsic,
1356 ) -> Result<<Block as BlockT>::Extrinsic, DecodeExtrinsicError> {
1357 let encoded = opaque_extrinsic.encode();
1358
1359 UncheckedExtrinsic::decode_with_depth_limit(
1360 MAX_CALL_RECURSION_DEPTH,
1361 &mut encoded.as_slice(),
1362 ).map_err(|err| DecodeExtrinsicError(format!("{}", err)))
1363 }
1364
1365 fn extrinsic_era(
1366 extrinsic: &<Block as BlockT>::Extrinsic
1367 ) -> Option<Era> {
1368 extrinsic_era(extrinsic)
1369 }
1370
1371 fn extrinsic_weight(ext: &<Block as BlockT>::Extrinsic) -> Weight {
1372 let len = ext.encoded_size() as u64;
1373 let info = ext.get_dispatch_info();
1374 info.call_weight.saturating_add(info.extension_weight)
1375 .saturating_add(<Runtime as frame_system::Config>::BlockWeights::get().get(info.class).base_extrinsic)
1376 .saturating_add(Weight::from_parts(0, len))
1377 }
1378
1379 fn block_fees() -> sp_domains::BlockFees<Balance> {
1380 BlockFees::collected_block_fees()
1381 }
1382
1383 fn block_digest() -> Digest {
1384 System::digest()
1385 }
1386
1387 fn block_weight() -> Weight {
1388 System::block_weight().total()
1389 }
1390
1391 fn construct_consensus_chain_byte_fee_extrinsic(transaction_byte_fee: Balance) -> <Block as BlockT>::Extrinsic {
1392 UncheckedExtrinsic::new_bare(
1393 pallet_block_fees::Call::set_next_consensus_chain_byte_fee{ transaction_byte_fee }.into()
1394 )
1395 }
1396
1397 fn construct_domain_update_chain_allowlist_extrinsic(updates: DomainAllowlistUpdates) -> <Block as BlockT>::Extrinsic {
1398 UncheckedExtrinsic::new_bare(
1399 pallet_messenger::Call::update_domain_allowlist{ updates }.into()
1400 )
1401 }
1402
1403 fn transfers() -> Transfers<Balance> {
1404 Transporter::chain_transfers()
1405 }
1406
1407 fn transfers_storage_key() -> Vec<u8> {
1408 Transporter::transfers_storage_key()
1409 }
1410
1411 fn block_fees_storage_key() -> Vec<u8> {
1412 BlockFees::block_fees_storage_key()
1413 }
1414 }
1415
1416 impl sp_messenger::MessengerApi<Block, ConsensusBlockNumber, ConsensusBlockHash> for Runtime {
1417 fn is_xdm_mmr_proof_valid(
1418 extrinsic: &<Block as BlockT>::Extrinsic
1419 ) -> Option<bool> {
1420 is_xdm_mmr_proof_valid(extrinsic)
1421 }
1422
1423 fn extract_xdm_mmr_proof(ext: &<Block as BlockT>::Extrinsic) -> Option<ConsensusChainMmrLeafProof<ConsensusBlockNumber, ConsensusBlockHash, sp_core::H256>> {
1424 match &ext.0.function {
1425 RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })
1426 | RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
1427 Some(msg.proof.consensus_mmr_proof())
1428 }
1429 _ => None,
1430 }
1431 }
1432
1433 fn confirmed_domain_block_storage_key(_domain_id: DomainId) -> Vec<u8> {
1434 vec![]
1436 }
1437
1438 fn outbox_storage_key(message_key: MessageKey) -> Vec<u8> {
1439 Messenger::outbox_storage_key(message_key)
1440 }
1441
1442 fn inbox_response_storage_key(message_key: MessageKey) -> Vec<u8> {
1443 Messenger::inbox_response_storage_key(message_key)
1444 }
1445
1446 fn domain_chains_allowlist_update(_domain_id: DomainId) -> Option<DomainAllowlistUpdates>{
1447 None
1449 }
1450
1451 fn xdm_id(ext: &<Block as BlockT>::Extrinsic) -> Option<XdmId> {
1452 match &ext.0.function {
1453 RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })=> {
1454 Some(XdmId::RelayMessage((msg.src_chain_id, msg.channel_id, msg.nonce)))
1455 }
1456 RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
1457 Some(XdmId::RelayResponseMessage((msg.src_chain_id, msg.channel_id, msg.nonce)))
1458 }
1459 _ => None,
1460 }
1461 }
1462
1463 fn channel_nonce(chain_id: ChainId, channel_id: ChannelId) -> Option<ChannelNonce> {
1464 Messenger::channel_nonce(chain_id, channel_id)
1465 }
1466 }
1467
1468 impl sp_messenger::RelayerApi<Block, BlockNumber, ConsensusBlockNumber, ConsensusBlockHash> for Runtime {
1469 fn block_messages() -> BlockMessagesWithStorageKey {
1470 Messenger::get_block_messages()
1471 }
1472
1473 fn outbox_message_unsigned(msg: CrossDomainMessage<NumberFor<Block>, <Block as BlockT>::Hash, <Block as BlockT>::Hash>) -> Option<<Block as BlockT>::Extrinsic> {
1474 Messenger::outbox_message_unsigned(msg)
1475 }
1476
1477 fn inbox_response_message_unsigned(msg: CrossDomainMessage<NumberFor<Block>, <Block as BlockT>::Hash, <Block as BlockT>::Hash>) -> Option<<Block as BlockT>::Extrinsic> {
1478 Messenger::inbox_response_message_unsigned(msg)
1479 }
1480
1481 fn should_relay_outbox_message(dst_chain_id: ChainId, msg_id: MessageId) -> bool {
1482 Messenger::should_relay_outbox_message(dst_chain_id, msg_id)
1483 }
1484
1485 fn should_relay_inbox_message_response(dst_chain_id: ChainId, msg_id: MessageId) -> bool {
1486 Messenger::should_relay_inbox_message_response(dst_chain_id, msg_id)
1487 }
1488
1489 fn updated_channels() -> BTreeSet<(ChainId, ChannelId)> {
1490 Messenger::updated_channels()
1491 }
1492
1493 fn channel_storage_key(chain_id: ChainId, channel_id: ChannelId) -> Vec<u8> {
1494 Messenger::channel_storage_key(chain_id, channel_id)
1495 }
1496
1497 fn open_channels() -> BTreeSet<(ChainId, ChannelId)> {
1498 Messenger::open_channels()
1499 }
1500 }
1501
1502 impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {
1503 fn chain_id() -> u64 {
1504 <Runtime as pallet_evm::Config>::ChainId::get()
1505 }
1506
1507 fn account_basic(address: H160) -> EVMAccount {
1508 let (account, _) = EVM::account_basic(&address);
1509 account
1510 }
1511
1512 fn gas_price() -> U256 {
1513 let (gas_price, _) = <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price();
1514 gas_price
1515 }
1516
1517 fn account_code_at(address: H160) -> Vec<u8> {
1518 pallet_evm::AccountCodes::<Runtime>::get(address)
1519 }
1520
1521 fn author() -> H160 {
1522 <pallet_evm::Pallet<Runtime>>::find_author()
1523 }
1524
1525 fn storage_at(address: H160, index: U256) -> H256 {
1526 let tmp = index.to_big_endian();
1527 pallet_evm::AccountStorages::<Runtime>::get(address, H256::from_slice(&tmp[..]))
1528 }
1529
1530 fn call(
1531 from: H160,
1532 to: H160,
1533 data: Vec<u8>,
1534 value: U256,
1535 gas_limit: U256,
1536 max_fee_per_gas: Option<U256>,
1537 max_priority_fee_per_gas: Option<U256>,
1538 nonce: Option<U256>,
1539 estimate: bool,
1540 access_list: Option<Vec<(H160, Vec<H256>)>>,
1541 ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {
1542 let config = if estimate {
1543 let mut config = <Runtime as pallet_evm::Config>::config().clone();
1544 config.estimate = true;
1545 Some(config)
1546 } else {
1547 None
1548 };
1549
1550 let is_transactional = false;
1551 let validate = true;
1552 let evm_config = config.as_ref().unwrap_or(<Runtime as pallet_evm::Config>::config());
1553
1554 let gas_limit = gas_limit.min(u64::MAX.into());
1555
1556 let transaction_data = TransactionData::new(
1557 TransactionAction::Call(to),
1558 data.clone(),
1559 nonce.unwrap_or_default(),
1560 gas_limit,
1561 None,
1562 max_fee_per_gas,
1563 max_priority_fee_per_gas,
1564 value,
1565 Some(<Runtime as pallet_evm::Config>::ChainId::get()),
1566 access_list.clone().unwrap_or_default(),
1567 );
1568
1569 let (weight_limit, proof_size_base_cost) = pallet_ethereum::Pallet::<Runtime>::transaction_weight(&transaction_data);
1570
1571 <Runtime as pallet_evm::Config>::Runner::call(
1572 from,
1573 to,
1574 data,
1575 value,
1576 gas_limit.unique_saturated_into(),
1577 max_fee_per_gas,
1578 max_priority_fee_per_gas,
1579 nonce,
1580 access_list.unwrap_or_default(),
1581 is_transactional,
1582 validate,
1583 weight_limit,
1584 proof_size_base_cost,
1585 evm_config,
1586 ).map_err(|err| err.error.into())
1587 }
1588
1589 fn create(
1590 from: H160,
1591 data: Vec<u8>,
1592 value: U256,
1593 gas_limit: U256,
1594 max_fee_per_gas: Option<U256>,
1595 max_priority_fee_per_gas: Option<U256>,
1596 nonce: Option<U256>,
1597 estimate: bool,
1598 access_list: Option<Vec<(H160, Vec<H256>)>>,
1599 ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {
1600 let config = if estimate {
1601 let mut config = <Runtime as pallet_evm::Config>::config().clone();
1602 config.estimate = true;
1603 Some(config)
1604 } else {
1605 None
1606 };
1607
1608 let is_transactional = false;
1609 let validate = true;
1610 let weight_limit = None;
1611 let proof_size_base_cost = None;
1612 let evm_config = config.as_ref().unwrap_or(<Runtime as pallet_evm::Config>::config());
1613 <Runtime as pallet_evm::Config>::Runner::create(
1614 from,
1615 data,
1616 value,
1617 gas_limit.unique_saturated_into(),
1618 max_fee_per_gas,
1619 max_priority_fee_per_gas,
1620 nonce,
1621 access_list.unwrap_or_default(),
1622 is_transactional,
1623 validate,
1624 weight_limit,
1625 proof_size_base_cost,
1626 evm_config,
1627 ).map_err(|err| err.error.into())
1628 }
1629
1630 fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {
1631 pallet_ethereum::CurrentTransactionStatuses::<Runtime>::get()
1632 }
1633
1634 fn current_block() -> Option<pallet_ethereum::Block> {
1635 pallet_ethereum::CurrentBlock::<Runtime>::get()
1636 }
1637
1638 fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {
1639 pallet_ethereum::CurrentReceipts::<Runtime>::get()
1640 }
1641
1642 fn current_all() -> (
1643 Option<pallet_ethereum::Block>,
1644 Option<Vec<pallet_ethereum::Receipt>>,
1645 Option<Vec<TransactionStatus>>
1646 ) {
1647 (
1648 pallet_ethereum::CurrentBlock::<Runtime>::get(),
1649 pallet_ethereum::CurrentReceipts::<Runtime>::get(),
1650 pallet_ethereum::CurrentTransactionStatuses::<Runtime>::get()
1651 )
1652 }
1653
1654 fn extrinsic_filter(
1655 xts: Vec<<Block as BlockT>::Extrinsic>,
1656 ) -> Vec<EthereumTransaction> {
1657 xts.into_iter().filter_map(|xt| match xt.0.function {
1658 RuntimeCall::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),
1659 _ => None
1660 }).collect::<Vec<EthereumTransaction>>()
1661 }
1662
1663 fn elasticity() -> Option<Permill> {
1664 None
1665 }
1666
1667 fn gas_limit_multiplier_support() {}
1668
1669 fn pending_block(
1670 xts: Vec<<Block as BlockT>::Extrinsic>,
1671 ) -> (Option<pallet_ethereum::Block>, Option<Vec<TransactionStatus>>) {
1672 for ext in xts.into_iter() {
1673 let _ = Executive::apply_extrinsic(ext);
1674 }
1675
1676 Ethereum::on_finalize(System::block_number() + 1);
1677
1678 (
1679 pallet_ethereum::CurrentBlock::<Runtime>::get(),
1680 pallet_ethereum::CurrentTransactionStatuses::<Runtime>::get()
1681 )
1682 }
1683
1684 fn initialize_pending_block(header: &<Block as BlockT>::Header) {
1685 Executive::initialize_block(header);
1686 }
1687 }
1688
1689 impl fp_rpc::ConvertTransactionRuntimeApi<Block> for Runtime {
1690 fn convert_transaction(transaction: EthereumTransaction) -> <Block as BlockT>::Extrinsic {
1691 UncheckedExtrinsic::new_bare(
1692 pallet_ethereum::Call::transact { transaction }.into(),
1693 )
1694 }
1695 }
1696
1697 impl sp_domain_sudo::DomainSudoApi<Block> for Runtime {
1698 fn is_valid_sudo_call(extrinsic: Vec<u8>) -> bool {
1699 is_valid_sudo_call(extrinsic)
1700 }
1701
1702 fn construct_domain_sudo_extrinsic(inner: Vec<u8>) -> <Block as BlockT>::Extrinsic {
1703 construct_sudo_call_extrinsic(inner)
1704 }
1705 }
1706
1707 impl sp_evm_tracker::EvmTrackerApi<Block> for Runtime {
1708 fn construct_evm_contract_creation_allowed_by_extrinsic(decoded_argument: PermissionedActionAllowedBy<AccountId>) -> <Block as BlockT>::Extrinsic {
1709 construct_evm_contract_creation_allowed_by_extrinsic(decoded_argument)
1710 }
1711 }
1712
1713 impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
1714 fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
1715 build_state::<RuntimeGenesisConfig>(config)
1716 }
1717
1718 fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
1719 get_preset::<RuntimeGenesisConfig>(id, |_| None)
1720 }
1721
1722 fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
1723 vec![]
1724 }
1725 }
1726
1727 #[cfg(feature = "runtime-benchmarks")]
1728 impl frame_benchmarking::Benchmark<Block> for Runtime {
1729 fn benchmark_metadata(extra: bool) -> (
1730 Vec<frame_benchmarking::BenchmarkList>,
1731 Vec<frame_support::traits::StorageInfo>,
1732 ) {
1733 use frame_benchmarking::{baseline, Benchmarking, BenchmarkList};
1734 use frame_support::traits::StorageInfoTrait;
1735 use frame_system_benchmarking::Pallet as SystemBench;
1736 use baseline::Pallet as BaselineBench;
1737
1738 let mut list = Vec::<BenchmarkList>::new();
1739
1740 list_benchmarks!(list, extra);
1741
1742 let storage_info = AllPalletsWithSystem::storage_info();
1743
1744 (list, storage_info)
1745 }
1746
1747 fn dispatch_benchmark(
1748 config: frame_benchmarking::BenchmarkConfig
1749 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, alloc::string::String> {
1750 use frame_benchmarking::{baseline, Benchmarking, BenchmarkBatch};
1751 use sp_storage::TrackedStorageKey;
1752 use frame_system_benchmarking::Pallet as SystemBench;
1753 use frame_support::traits::WhitelistedStorageKeys;
1754 use baseline::Pallet as BaselineBench;
1755
1756 let whitelist: Vec<TrackedStorageKey> = AllPalletsWithSystem::whitelisted_storage_keys();
1757
1758 let mut batches = Vec::<BenchmarkBatch>::new();
1759 let params = (&config, &whitelist);
1760
1761 add_benchmarks!(params, batches);
1762
1763 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }
1764 Ok(batches)
1765 }
1766 }
1767}
1768
1769#[cfg(test)]
1770mod tests {
1771 use crate::{Runtime, RuntimeBlockWeights as BlockWeights};
1772 use subspace_runtime_primitives::tests_utils::FeeMultiplierUtils;
1773
1774 #[test]
1775 fn multiplier_can_grow_from_zero() {
1776 FeeMultiplierUtils::<Runtime, BlockWeights>::multiplier_can_grow_from_zero()
1777 }
1778}