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