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::pallet_prelude::TypeInfo;
32use frame_support::traits::{
33 ConstU16, ConstU32, ConstU64, Currency, Everything, FindAuthor, IsInherent, OnFinalize, Time,
34 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 BlockMessagesQuery, BlockMessagesWithStorageKey, ChainId, ChannelId, ChannelStateWithNonce,
64 CrossDomainMessage, MessageId, MessageKey, MessagesWithStorageKey, Nonce as XdmNonce,
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, Checkable, DispatchInfoOf, DispatchTransaction, Dispatchable, IdentityLookup,
72 Keccak256, NumberFor, One, PostDispatchInfoOf, TransactionExtension, UniqueSaturatedInto,
73 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_map::BTreeMap;
85use sp_std::collections::btree_set::BTreeSet;
86use sp_std::marker::PhantomData;
87use sp_std::prelude::*;
88use sp_subspace_mmr::domain_mmr_runtime_interface::{
89 is_consensus_block_finalized, verify_mmr_proof,
90};
91use sp_subspace_mmr::{ConsensusChainMmrLeafProof, MmrLeaf};
92use sp_version::RuntimeVersion;
93use static_assertions::const_assert;
94use subspace_runtime_primitives::utility::{MaybeNestedCall, MaybeUtilityCall};
95use subspace_runtime_primitives::{
96 BlockHashFor, BlockNumber as ConsensusBlockNumber, DomainEventSegmentSize, ExtrinsicFor,
97 Hash as ConsensusBlockHash, HeaderFor, Moment, SlowAdjustingFeeUpdate, XdmAdjustedWeightToFee,
98 XdmFeeMultipler, MAX_CALL_RECURSION_DEPTH, SHANNON, SSC,
99};
100
101pub type Address = AccountId;
103
104pub type Block = generic::Block<Header, UncheckedExtrinsic>;
106
107pub type SignedBlock = generic::SignedBlock<Block>;
109
110pub type BlockId = generic::BlockId<Block>;
112
113pub type Precompiles = crate::precompiles::Precompiles<Runtime>;
115
116pub type SignedExtra = (
118 frame_system::CheckNonZeroSender<Runtime>,
119 frame_system::CheckSpecVersion<Runtime>,
120 frame_system::CheckTxVersion<Runtime>,
121 frame_system::CheckGenesis<Runtime>,
122 frame_system::CheckMortality<Runtime>,
123 frame_system::CheckNonce<Runtime>,
124 domain_check_weight::CheckWeight<Runtime>,
125 pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
126 pallet_evm_tracker::create_contract::CheckContractCreation<Runtime>,
127 pallet_messenger::extensions::MessengerExtension<Runtime>,
128);
129
130type CustomSignedExtra = (
133 frame_system::CheckNonZeroSender<Runtime>,
134 frame_system::CheckSpecVersion<Runtime>,
135 frame_system::CheckTxVersion<Runtime>,
136 frame_system::CheckGenesis<Runtime>,
137 frame_system::CheckMortality<Runtime>,
138 pallet_evm_tracker::CheckNonce<Runtime>,
139 domain_check_weight::CheckWeight<Runtime>,
140 pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
141 pallet_evm_tracker::create_contract::CheckContractCreation<Runtime>,
142 pallet_messenger::extensions::MessengerTrustedMmrExtension<Runtime>,
143);
144
145pub type UncheckedExtrinsic =
147 fp_self_contained::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
148
149pub type CheckedExtrinsic =
151 fp_self_contained::CheckedExtrinsic<AccountId, RuntimeCall, SignedExtra, H160>;
152
153type BalanceOf<T> = <<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::Balance;
154
155pub fn construct_extrinsic_raw_payload(
156 current_block_hash: H256,
157 current_block: BlockNumberFor<Runtime>,
158 genesis_block_hash: H256,
159 function: RuntimeCallFor<Runtime>,
160 immortal: bool,
161 nonce: u32,
162 tip: BalanceOf<Runtime>,
163) -> (
164 SignedPayload<RuntimeCallFor<Runtime>, SignedExtra>,
165 SignedExtra,
166) {
167 let current_block = current_block.saturated_into();
168 let period = u64::from(<Runtime as frame_system::Config>::BlockHashCount::get())
169 .checked_next_power_of_two()
170 .map(|c| c / 2)
171 .unwrap_or(2);
172 let extra: SignedExtra = (
173 frame_system::CheckNonZeroSender::<Runtime>::new(),
174 frame_system::CheckSpecVersion::<Runtime>::new(),
175 frame_system::CheckTxVersion::<Runtime>::new(),
176 frame_system::CheckGenesis::<Runtime>::new(),
177 frame_system::CheckMortality::<Runtime>::from(if immortal {
178 generic::Era::Immortal
179 } else {
180 generic::Era::mortal(period, current_block)
181 }),
182 frame_system::CheckNonce::<Runtime>::from(nonce),
183 domain_check_weight::CheckWeight::<Runtime>::new(),
184 pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(tip),
185 pallet_evm_tracker::create_contract::CheckContractCreation::<Runtime>::new(),
186 pallet_messenger::extensions::MessengerExtension::<Runtime>::new(),
187 );
188 (
189 generic::SignedPayload::<RuntimeCallFor<Runtime>, SignedExtra>::from_raw(
190 function,
191 extra.clone(),
192 (
193 (),
194 1,
195 0,
196 genesis_block_hash,
197 current_block_hash,
198 (),
199 (),
200 (),
201 (),
202 (),
203 ),
204 ),
205 extra,
206 )
207}
208
209pub type Executive = domain_pallet_executive::Executive<
211 Runtime,
212 frame_system::ChainContext<Runtime>,
213 Runtime,
214 AllPalletsWithSystem,
215>;
216
217fn consensus_storage_fee(len: impl TryInto<Balance>) -> Result<Balance, TransactionValidityError> {
219 let len = len.try_into().map_err(|_| {
222 TransactionValidityError::Invalid(InvalidTransaction::Custom(ERR_BALANCE_OVERFLOW))
223 })?;
224
225 BlockFees::consensus_chain_byte_fee()
226 .checked_mul(Into::<Balance>::into(len))
227 .ok_or(TransactionValidityError::Invalid(
228 InvalidTransaction::Custom(ERR_BALANCE_OVERFLOW),
229 ))
230}
231
232impl fp_self_contained::SelfContainedCall for RuntimeCall {
233 type SignedInfo = H160;
234
235 fn is_self_contained(&self) -> bool {
236 match self {
237 RuntimeCall::Ethereum(call) => call.is_self_contained(),
238 _ => false,
239 }
240 }
241
242 fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {
243 match self {
244 RuntimeCall::Ethereum(call) => call.check_self_contained(),
245 _ => None,
246 }
247 }
248
249 fn validate_self_contained(
250 &self,
251 info: &Self::SignedInfo,
252 dispatch_info: &DispatchInfoOf<RuntimeCall>,
253 len: usize,
254 ) -> Option<TransactionValidity> {
255 if !is_create_contract_allowed::<Runtime>(self, &(*info).into()) {
256 return Some(Err(InvalidTransaction::Custom(
257 ERR_CONTRACT_CREATION_NOT_ALLOWED,
258 )
259 .into()));
260 }
261
262 match self {
263 RuntimeCall::Ethereum(call) => call.validate_self_contained(info, dispatch_info, len),
264 _ => None,
265 }
266 }
267
268 fn pre_dispatch_self_contained(
269 &self,
270 info: &Self::SignedInfo,
271 dispatch_info: &DispatchInfoOf<RuntimeCall>,
272 len: usize,
273 ) -> Option<Result<(), TransactionValidityError>> {
274 if !is_create_contract_allowed::<Runtime>(self, &(*info).into()) {
275 return Some(Err(InvalidTransaction::Custom(
276 ERR_CONTRACT_CREATION_NOT_ALLOWED,
277 )
278 .into()));
279 }
280
281 match self {
284 RuntimeCall::Ethereum(call) => {
285 if let pallet_ethereum::Call::transact { transaction } = call {
288 let origin = RuntimeOrigin::signed(AccountId20::from(*info));
289 if let Err(err) =
290 <domain_check_weight::CheckWeight<Runtime> as DispatchTransaction<
291 RuntimeCall,
292 >>::validate_and_prepare(
293 domain_check_weight::CheckWeight::<Runtime>::new(),
294 origin,
295 self,
296 dispatch_info,
297 len,
298 DEFAULT_EXTENSION_VERSION,
299 )
300 {
301 return Some(Err(err));
302 }
303
304 Some(Ethereum::validate_transaction_in_block(*info, transaction))
305 } else {
306 None
307 }
308 }
309 _ => None,
310 }
311 }
312
313 fn apply_self_contained(
314 self,
315 info: Self::SignedInfo,
316 ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {
317 match self {
318 call @ RuntimeCall::Ethereum(pallet_ethereum::Call::transact { .. }) => {
319 Some(call.dispatch(RuntimeOrigin::from(
320 pallet_ethereum::RawOrigin::EthereumTransaction(info),
321 )))
322 }
323 _ => None,
324 }
325 }
326}
327
328impl_opaque_keys! {
329 pub struct SessionKeys {
330 pub operator: sp_domains::OperatorKey,
332 }
333}
334
335#[sp_version::runtime_version]
336pub const VERSION: RuntimeVersion = RuntimeVersion {
337 spec_name: Cow::Borrowed("subspace-evm-domain"),
338 impl_name: Cow::Borrowed("subspace-evm-domain"),
339 authoring_version: 0,
340 spec_version: 1,
341 impl_version: 0,
342 apis: RUNTIME_API_VERSIONS,
343 transaction_version: 0,
344 system_version: 2,
345};
346
347parameter_types! {
348 pub const Version: RuntimeVersion = VERSION;
349 pub const BlockHashCount: BlockNumber = 2400;
350
351 pub RuntimeBlockLength: BlockLength = maximum_block_length();
356 pub RuntimeBlockWeights: BlockWeights = block_weights();
357}
358
359impl frame_system::Config for Runtime {
360 type RuntimeEvent = RuntimeEvent;
362 type BaseCallFilter = Everything;
364 type BlockWeights = RuntimeBlockWeights;
366 type BlockLength = RuntimeBlockLength;
368 type RuntimeOrigin = RuntimeOrigin;
370 type RuntimeCall = RuntimeCall;
372 type RuntimeTask = RuntimeTask;
374 type Nonce = Nonce;
376 type Hash = Hash;
378 type Hashing = BlakeTwo256;
380 type AccountId = AccountId;
382 type Lookup = IdentityLookup<AccountId>;
384 type Block = Block;
386 type BlockHashCount = BlockHashCount;
388 type DbWeight = ParityDbWeight;
390 type Version = Version;
392 type PalletInfo = PalletInfo;
394 type AccountData = pallet_balances::AccountData<Balance>;
396 type OnNewAccount = ();
398 type OnKilledAccount = ();
400 type SystemWeightInfo = frame_system::weights::SubstrateWeight<Runtime>;
402 type ExtensionsWeightInfo = frame_system::ExtensionsWeight<Runtime>;
403 type SS58Prefix = ConstU16<6094>;
404 type OnSetCode = ();
406 type MaxConsumers = ConstU32<16>;
407 type SingleBlockMigrations = ();
408 type MultiBlockMigrator = ();
409 type PreInherents = ();
410 type PostInherents = ();
411 type PostTransactions = ();
412 type EventSegmentSize = DomainEventSegmentSize;
413}
414
415impl pallet_timestamp::Config for Runtime {
416 type Moment = Moment;
418 type OnTimestampSet = ();
419 type MinimumPeriod = ConstU64<{ SLOT_DURATION / 2 }>;
420 type WeightInfo = pallet_timestamp::weights::SubstrateWeight<Runtime>;
421}
422
423parameter_types! {
424 pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
425 pub const MaxLocks: u32 = 50;
426 pub const MaxReserves: u32 = 50;
427}
428
429impl pallet_balances::Config for Runtime {
430 type RuntimeFreezeReason = RuntimeFreezeReason;
431 type MaxLocks = MaxLocks;
432 type Balance = Balance;
434 type RuntimeEvent = RuntimeEvent;
436 type DustRemoval = ();
437 type ExistentialDeposit = ExistentialDeposit;
438 type AccountStore = System;
439 type WeightInfo = pallet_balances::weights::SubstrateWeight<Runtime>;
440 type MaxReserves = MaxReserves;
441 type ReserveIdentifier = [u8; 8];
442 type FreezeIdentifier = ();
443 type MaxFreezes = ();
444 type RuntimeHoldReason = HoldIdentifierWrapper;
445 type DoneSlashHandler = ();
446}
447
448parameter_types! {
449 pub const OperationalFeeMultiplier: u8 = 5;
450 pub const DomainChainByteFee: Balance = 100_000 * SHANNON;
451 pub TransactionWeightFee: Balance = 100_000 * SHANNON;
452}
453
454impl pallet_block_fees::Config for Runtime {
455 type Balance = Balance;
456 type DomainChainByteFee = DomainChainByteFee;
457}
458
459pub struct FinalDomainTransactionByteFee;
460
461impl Get<Balance> for FinalDomainTransactionByteFee {
462 fn get() -> Balance {
463 BlockFees::final_domain_transaction_byte_fee()
464 }
465}
466
467impl pallet_transaction_payment::Config for Runtime {
468 type RuntimeEvent = RuntimeEvent;
469 type OnChargeTransaction = OnChargeDomainTransaction<Balances>;
470 type WeightToFee = ConstantMultiplier<Balance, TransactionWeightFee>;
471 type LengthToFee = ConstantMultiplier<Balance, FinalDomainTransactionByteFee>;
472 type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Runtime, TargetBlockFullness>;
473 type OperationalFeeMultiplier = OperationalFeeMultiplier;
474 type WeightInfo = pallet_transaction_payment::weights::SubstrateWeight<Runtime>;
475}
476
477pub struct ExtrinsicStorageFees;
478
479impl domain_pallet_executive::ExtrinsicStorageFees<Runtime> for ExtrinsicStorageFees {
480 fn extract_signer(xt: UncheckedExtrinsic) -> (Option<AccountId>, DispatchInfo) {
481 let dispatch_info = xt.get_dispatch_info();
482 let lookup = frame_system::ChainContext::<Runtime>::default();
483 let maybe_signer = extract_signer_inner(&xt, &lookup).and_then(|res| res.ok());
484 (maybe_signer, dispatch_info)
485 }
486
487 fn on_storage_fees_charged(
488 charged_fees: Balance,
489 tx_size: u32,
490 ) -> Result<(), TransactionValidityError> {
491 let consensus_storage_fee = consensus_storage_fee(tx_size)?;
492
493 let (paid_consensus_storage_fee, paid_domain_fee) = if charged_fees <= consensus_storage_fee
494 {
495 (charged_fees, Zero::zero())
496 } else {
497 (consensus_storage_fee, charged_fees - consensus_storage_fee)
498 };
499
500 BlockFees::note_consensus_storage_fee(paid_consensus_storage_fee);
501 BlockFees::note_domain_execution_fee(paid_domain_fee);
502 Ok(())
503 }
504}
505
506impl domain_pallet_executive::Config for Runtime {
507 type RuntimeEvent = RuntimeEvent;
508 type WeightInfo = domain_pallet_executive::weights::SubstrateWeight<Runtime>;
509 type Currency = Balances;
510 type LengthToFee = <Runtime as pallet_transaction_payment::Config>::LengthToFee;
511 type ExtrinsicStorageFees = ExtrinsicStorageFees;
512}
513
514parameter_types! {
515 pub SelfChainId: ChainId = SelfDomainId::self_domain_id().into();
516}
517
518pub struct OnXDMRewards;
519
520impl sp_messenger::OnXDMRewards<Balance> for OnXDMRewards {
521 fn on_xdm_rewards(rewards: Balance) {
522 BlockFees::note_domain_execution_fee(rewards)
523 }
524 fn on_chain_protocol_fees(chain_id: ChainId, fees: Balance) {
525 BlockFees::note_chain_rewards(chain_id, fees);
527 }
528}
529
530type MmrHash = <Keccak256 as sp_runtime::traits::Hash>::Output;
531
532pub struct MmrProofVerifier;
533
534impl sp_subspace_mmr::MmrProofVerifier<MmrHash, NumberFor<Block>, Hash> for MmrProofVerifier {
535 fn verify_proof_and_extract_leaf(
536 mmr_leaf_proof: ConsensusChainMmrLeafProof<NumberFor<Block>, Hash, MmrHash>,
537 ) -> Option<MmrLeaf<ConsensusBlockNumber, ConsensusBlockHash>> {
538 let ConsensusChainMmrLeafProof {
539 consensus_block_number,
540 opaque_mmr_leaf: opaque_leaf,
541 proof,
542 ..
543 } = mmr_leaf_proof;
544
545 if !is_consensus_block_finalized(consensus_block_number) {
546 return None;
547 }
548
549 let leaf: MmrLeaf<ConsensusBlockNumber, ConsensusBlockHash> =
550 opaque_leaf.into_opaque_leaf().try_decode()?;
551
552 verify_mmr_proof(vec![EncodableOpaqueLeaf::from_leaf(&leaf)], proof.encode())
553 .then_some(leaf)
554 }
555}
556
557#[derive(
559 PartialEq, Eq, Clone, Encode, Decode, TypeInfo, MaxEncodedLen, Ord, PartialOrd, Copy, Debug,
560)]
561pub struct HoldIdentifierWrapper(HoldIdentifier);
562
563impl VariantCount for HoldIdentifierWrapper {
564 const VARIANT_COUNT: u32 = mem::variant_count::<HoldIdentifier>() as u32;
565}
566
567impl pallet_messenger::HoldIdentifier<Runtime> for HoldIdentifierWrapper {
568 fn messenger_channel() -> Self {
569 Self(HoldIdentifier::MessengerChannel)
570 }
571}
572
573parameter_types! {
574 pub const ChannelReserveFee: Balance = SSC;
575 pub const ChannelInitReservePortion: Perbill = Perbill::from_percent(20);
576 pub const MaxOutgoingMessages: u32 = MAX_OUTGOING_MESSAGES;
577}
578
579const_assert!(MaxOutgoingMessages::get() >= 1);
581
582pub struct StorageKeys;
583
584impl sp_messenger::StorageKeys for StorageKeys {
585 fn confirmed_domain_block_storage_key(domain_id: DomainId) -> Option<Vec<u8>> {
586 get_storage_key(StorageKeyRequest::ConfirmedDomainBlockStorageKey(domain_id))
587 }
588
589 fn outbox_storage_key(chain_id: ChainId, message_key: MessageKey) -> Option<Vec<u8>> {
590 get_storage_key(StorageKeyRequest::OutboxStorageKey {
591 chain_id,
592 message_key,
593 })
594 }
595
596 fn inbox_responses_storage_key(chain_id: ChainId, message_key: MessageKey) -> Option<Vec<u8>> {
597 get_storage_key(StorageKeyRequest::InboxResponseStorageKey {
598 chain_id,
599 message_key,
600 })
601 }
602}
603
604impl pallet_messenger::Config for Runtime {
605 type RuntimeEvent = RuntimeEvent;
606 type SelfChainId = SelfChainId;
607
608 fn get_endpoint_handler(endpoint: &Endpoint) -> Option<Box<dyn EndpointHandlerT<MessageId>>> {
609 if endpoint == &Endpoint::Id(TransporterEndpointId::get()) {
610 Some(Box::new(EndpointHandler(PhantomData::<Runtime>)))
611 } else {
612 None
613 }
614 }
615
616 type Currency = Balances;
617 type WeightInfo = pallet_messenger::weights::SubstrateWeight<Runtime>;
618 type WeightToFee = ConstantMultiplier<Balance, TransactionWeightFee>;
619 type AdjustedWeightToFee = XdmAdjustedWeightToFee<Runtime>;
620 type FeeMultiplier = XdmFeeMultipler;
621 type OnXDMRewards = OnXDMRewards;
622 type MmrHash = MmrHash;
623 type MmrProofVerifier = MmrProofVerifier;
624 type StorageKeys = StorageKeys;
625 type DomainOwner = ();
626 type HoldIdentifier = HoldIdentifierWrapper;
627 type ChannelReserveFee = ChannelReserveFee;
628 type ChannelInitReservePortion = ChannelInitReservePortion;
629 type DomainRegistration = ();
630 type MaxOutgoingMessages = MaxOutgoingMessages;
631 type MessengerOrigin = pallet_messenger::EnsureMessengerOrigin;
632 type NoteChainTransfer = Transporter;
633 type ExtensionWeightInfo = pallet_messenger::extensions::weights::SubstrateWeight<Runtime>;
634}
635
636impl<C> frame_system::offchain::CreateTransactionBase<C> for Runtime
637where
638 RuntimeCall: From<C>,
639{
640 type Extrinsic = UncheckedExtrinsic;
641 type RuntimeCall = RuntimeCall;
642}
643
644parameter_types! {
645 pub const TransporterEndpointId: EndpointId = 1;
646 pub const MinimumTransfer: Balance = 1;
647}
648
649impl pallet_transporter::Config for Runtime {
650 type RuntimeEvent = RuntimeEvent;
651 type SelfChainId = SelfChainId;
652 type SelfEndpointId = TransporterEndpointId;
653 type Currency = Balances;
654 type Sender = Messenger;
655 type AccountIdConverter = domain_runtime_primitives::AccountId20Converter;
656 type WeightInfo = pallet_transporter::weights::SubstrateWeight<Runtime>;
657 type SkipBalanceTransferChecks = ();
658 type MinimumTransfer = MinimumTransfer;
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: &ExtrinsicFor<Block>) -> 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>) -> ExtrinsicFor<Block> {
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) -> ExtrinsicFor<Block> {
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: &ExtrinsicFor<Block>) -> 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: &ExtrinsicFor<Block>,
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: &HeaderFor<Block>) -> 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: ExtrinsicFor<Block>) -> ApplyExtrinsicResult {
1221 Executive::apply_extrinsic(extrinsic)
1222 }
1223
1224 fn finalize_block() -> HeaderFor<Block> {
1225 Executive::finalize_block()
1226 }
1227
1228 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<ExtrinsicFor<Block>> {
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: ExtrinsicFor<Block>,
1244 block_hash: BlockHashFor<Block>,
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: &HeaderFor<Block>) {
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: ExtrinsicFor<Block>,
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: ExtrinsicFor<Block>,
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<ExtrinsicFor<Block>>,
1298 ) -> Vec<(Option<opaque::AccountId>, ExtrinsicFor<Block>)> {
1299 extract_signer(extrinsics)
1300 }
1301
1302 fn is_within_tx_range(
1303 extrinsic: &ExtrinsicFor<Block>,
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 extract_signer_if_all_within_tx_range(
1322 extrinsics: &Vec<ExtrinsicFor<Block>>,
1323 bundle_vrf_hash: &subspace_core_primitives::U256,
1324 tx_range: &subspace_core_primitives::U256
1325 ) -> Result<Vec<Option<opaque::AccountId>> , u32> {
1326 use subspace_core_primitives::U256;
1327 use subspace_core_primitives::hashes::blake3_hash;
1328
1329 let mut signers = Vec::with_capacity(extrinsics.len());
1330 let lookup = frame_system::ChainContext::<Runtime>::default();
1331 for (index, extrinsic) in extrinsics.iter().enumerate() {
1332 let maybe_signer = extract_signer_inner(extrinsic, &lookup).and_then(|account_result| {
1333 account_result.ok().map(|account_id| account_id.encode())
1334 });
1335 if let Some(signer) = &maybe_signer {
1336 let signer_id_hash = U256::from_be_bytes(*blake3_hash(&signer.encode()));
1338 if !sp_domains::signer_in_tx_range(bundle_vrf_hash, &signer_id_hash, tx_range) {
1339 return Err(index as u32)
1340 }
1341 }
1342 signers.push(maybe_signer);
1343 }
1344
1345 Ok(signers)
1346 }
1347
1348 fn initialize_block_with_post_state_root(header: &HeaderFor<Block>) -> Vec<u8> {
1349 Executive::initialize_block(header);
1350 Executive::storage_root()
1351 }
1352
1353 fn apply_extrinsic_with_post_state_root(extrinsic: ExtrinsicFor<Block>) -> Vec<u8> {
1354 let _ = Executive::apply_extrinsic(extrinsic);
1355 Executive::storage_root()
1356 }
1357
1358 fn construct_set_code_extrinsic(code: Vec<u8>) -> Vec<u8> {
1359 UncheckedExtrinsic::new_bare(
1360 domain_pallet_executive::Call::set_code {
1361 code
1362 }.into()
1363 ).encode()
1364 }
1365
1366 fn construct_timestamp_extrinsic(moment: Moment) -> ExtrinsicFor<Block> {
1367 UncheckedExtrinsic::new_bare(
1368 pallet_timestamp::Call::set{ now: moment }.into()
1369 )
1370 }
1371
1372 fn construct_domain_update_chain_allowlist_extrinsic(updates: DomainAllowlistUpdates) -> ExtrinsicFor<Block> {
1373 UncheckedExtrinsic::new_bare(
1374 pallet_messenger::Call::update_domain_allowlist{ updates }.into()
1375 )
1376 }
1377
1378 fn is_inherent_extrinsic(extrinsic: &ExtrinsicFor<Block>) -> bool {
1379 <Self as IsInherent<_>>::is_inherent(extrinsic)
1380 }
1381
1382 fn find_first_inherent_extrinsic(extrinsics: &Vec<ExtrinsicFor<Block>>) -> Option<u32> {
1383 for (index, extrinsic) in extrinsics.iter().enumerate() {
1384 if <Self as IsInherent<_>>::is_inherent(extrinsic) {
1385 return Some(index as u32)
1386 }
1387 }
1388 None
1389 }
1390
1391 fn check_extrinsics_and_do_pre_dispatch(
1392 uxts: Vec<ExtrinsicFor<Block>>,
1393 block_number: BlockNumber,
1394 block_hash: BlockHashFor<Block>) -> Result<(), CheckExtrinsicsValidityError> {
1395 System::initialize(
1397 &(block_number + BlockNumber::one()),
1398 &block_hash,
1399 &Default::default(),
1400 );
1401
1402 for (extrinsic_index, uxt) in uxts.iter().enumerate() {
1403 check_transaction_and_do_pre_dispatch_inner(uxt).map_err(|e| {
1404 CheckExtrinsicsValidityError {
1405 extrinsic_index: extrinsic_index as u32,
1406 transaction_validity_error: e
1407 }
1408 })?;
1409 }
1410
1411 Ok(())
1412 }
1413
1414 fn decode_extrinsic(
1415 opaque_extrinsic: sp_runtime::OpaqueExtrinsic,
1416 ) -> Result<ExtrinsicFor<Block>, DecodeExtrinsicError> {
1417 let encoded = opaque_extrinsic.encode();
1418
1419 UncheckedExtrinsic::decode_with_depth_limit(
1420 MAX_CALL_RECURSION_DEPTH,
1421 &mut encoded.as_slice(),
1422 ).map_err(|err| DecodeExtrinsicError(format!("{}", err)))
1423 }
1424
1425 fn decode_extrinsics_prefix(
1426 opaque_extrinsics: Vec<sp_runtime::OpaqueExtrinsic>,
1427 ) -> Vec<ExtrinsicFor<Block>> {
1428 let mut extrinsics = Vec::with_capacity(opaque_extrinsics.len());
1429 for opaque_ext in opaque_extrinsics {
1430 match UncheckedExtrinsic::decode_with_depth_limit(
1431 MAX_CALL_RECURSION_DEPTH,
1432 &mut opaque_ext.encode().as_slice(),
1433 ) {
1434 Ok(tx) => extrinsics.push(tx),
1435 Err(_) => return extrinsics,
1436 }
1437 }
1438 extrinsics
1439 }
1440
1441 fn extrinsic_era(
1442 extrinsic: &ExtrinsicFor<Block>
1443 ) -> Option<Era> {
1444 extrinsic_era(extrinsic)
1445 }
1446
1447 fn extrinsic_weight(ext: &ExtrinsicFor<Block>) -> Weight {
1448 let len = ext.encoded_size() as u64;
1449 let info = ext.get_dispatch_info();
1450 info.call_weight.saturating_add(info.extension_weight)
1451 .saturating_add(<Runtime as frame_system::Config>::BlockWeights::get().get(info.class).base_extrinsic)
1452 .saturating_add(Weight::from_parts(0, len))
1453 }
1454
1455 fn extrinsics_weight(extrinsics: &Vec<ExtrinsicFor<Block>>) -> Weight {
1456 let mut total_weight = Weight::zero();
1457 for ext in extrinsics {
1458 let ext_weight = {
1459 let len = ext.encoded_size() as u64;
1460 let info = ext.get_dispatch_info();
1461 info.call_weight.saturating_add(info.extension_weight)
1462 .saturating_add(<Runtime as frame_system::Config>::BlockWeights::get().get(info.class).base_extrinsic)
1463 .saturating_add(Weight::from_parts(0, len))
1464 };
1465 total_weight = total_weight.saturating_add(ext_weight);
1466 }
1467 total_weight
1468 }
1469
1470 fn block_fees() -> sp_domains::BlockFees<Balance> {
1471 BlockFees::collected_block_fees()
1472 }
1473
1474 fn block_digest() -> Digest {
1475 System::digest()
1476 }
1477
1478 fn block_weight() -> Weight {
1479 System::block_weight().total()
1480 }
1481
1482 fn construct_consensus_chain_byte_fee_extrinsic(transaction_byte_fee: Balance) -> ExtrinsicFor<Block> {
1483 UncheckedExtrinsic::new_bare(
1484 pallet_block_fees::Call::set_next_consensus_chain_byte_fee{ transaction_byte_fee }.into()
1485 )
1486 }
1487
1488 fn transfers() -> Transfers<Balance> {
1489 Transporter::chain_transfers()
1490 }
1491
1492 fn transfers_storage_key() -> Vec<u8> {
1493 Transporter::transfers_storage_key()
1494 }
1495
1496 fn block_fees_storage_key() -> Vec<u8> {
1497 BlockFees::block_fees_storage_key()
1498 }
1499 }
1500
1501 impl sp_messenger::MessengerApi<Block, ConsensusBlockNumber, ConsensusBlockHash> for Runtime {
1502 fn is_xdm_mmr_proof_valid(
1503 extrinsic: &ExtrinsicFor<Block>
1504 ) -> Option<bool> {
1505 is_xdm_mmr_proof_valid(extrinsic)
1506 }
1507
1508 fn extract_xdm_mmr_proof(ext: &ExtrinsicFor<Block>) -> Option<ConsensusChainMmrLeafProof<ConsensusBlockNumber, ConsensusBlockHash, sp_core::H256>> {
1509 match &ext.0.function {
1510 RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })
1511 | RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
1512 Some(msg.proof.consensus_mmr_proof())
1513 }
1514 _ => None,
1515 }
1516 }
1517
1518 fn batch_extract_xdm_mmr_proof(extrinsics: &Vec<ExtrinsicFor<Block>>) -> BTreeMap<u32, ConsensusChainMmrLeafProof<ConsensusBlockNumber, ConsensusBlockHash, sp_core::H256>> {
1519 let mut mmr_proofs = BTreeMap::new();
1520 for (index, ext) in extrinsics.iter().enumerate() {
1521 match &ext.0.function {
1522 RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })
1523 | RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
1524 mmr_proofs.insert(index as u32, msg.proof.consensus_mmr_proof());
1525 }
1526 _ => {},
1527 }
1528 }
1529 mmr_proofs
1530 }
1531
1532 fn confirmed_domain_block_storage_key(_domain_id: DomainId) -> Vec<u8> {
1533 vec![]
1534 }
1535
1536 fn outbox_storage_key(message_key: MessageKey) -> Vec<u8> {
1537 Messenger::outbox_storage_key(message_key)
1538 }
1539
1540 fn inbox_response_storage_key(message_key: MessageKey) -> Vec<u8> {
1541 Messenger::inbox_response_storage_key(message_key)
1542 }
1543
1544 fn domain_chains_allowlist_update(_domain_id: DomainId) -> Option<DomainAllowlistUpdates>{
1545 None
1547 }
1548
1549 fn xdm_id(ext: &ExtrinsicFor<Block>) -> Option<XdmId> {
1550 match &ext.0.function {
1551 RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })=> {
1552 Some(XdmId::RelayMessage((msg.src_chain_id, msg.channel_id, msg.nonce)))
1553 }
1554 RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
1555 Some(XdmId::RelayResponseMessage((msg.src_chain_id, msg.channel_id, msg.nonce)))
1556 }
1557 _ => None,
1558 }
1559 }
1560
1561 fn channel_nonce(chain_id: ChainId, channel_id: ChannelId) -> Option<ChannelNonce> {
1562 Messenger::channel_nonce(chain_id, channel_id)
1563 }
1564 }
1565
1566 impl sp_messenger::RelayerApi<Block, BlockNumber, ConsensusBlockNumber, ConsensusBlockHash> for Runtime {
1567 fn block_messages() -> BlockMessagesWithStorageKey {
1568 BlockMessagesWithStorageKey::default()
1569 }
1570
1571 fn outbox_message_unsigned(msg: CrossDomainMessage<NumberFor<Block>, BlockHashFor<Block>, BlockHashFor<Block>>) -> Option<ExtrinsicFor<Block>> {
1572 Messenger::outbox_message_unsigned(msg)
1573 }
1574
1575 fn inbox_response_message_unsigned(msg: CrossDomainMessage<NumberFor<Block>, BlockHashFor<Block>, BlockHashFor<Block>>) -> Option<ExtrinsicFor<Block>> {
1576 Messenger::inbox_response_message_unsigned(msg)
1577 }
1578
1579 fn should_relay_outbox_message(_: ChainId, _: MessageId) -> bool {
1580 false
1581 }
1582
1583 fn should_relay_inbox_message_response(_: ChainId, _: MessageId) -> bool {
1584 false
1585 }
1586
1587 fn updated_channels() -> BTreeSet<(ChainId, ChannelId)> {
1588 Messenger::updated_channels()
1589 }
1590
1591 fn channel_storage_key(chain_id: ChainId, channel_id: ChannelId) -> Vec<u8> {
1592 Messenger::channel_storage_key(chain_id, channel_id)
1593 }
1594
1595 fn open_channels() -> BTreeSet<(ChainId, ChannelId)> {
1596 Messenger::open_channels()
1597 }
1598
1599 fn block_messages_with_query(query: BlockMessagesQuery) -> MessagesWithStorageKey {
1600 Messenger::get_block_messages(query)
1601 }
1602
1603 fn channels_and_state() -> Vec<(ChainId, ChannelId, ChannelStateWithNonce)> {
1604 Messenger::channels_and_states()
1605 }
1606
1607 fn first_outbox_message_nonce_to_relay(dst_chain_id: ChainId, channel_id: ChannelId, from_nonce: XdmNonce) -> Option<XdmNonce> {
1608 Messenger::first_outbox_message_nonce_to_relay(dst_chain_id, channel_id, from_nonce)
1609 }
1610
1611 fn first_inbox_message_response_nonce_to_relay(dst_chain_id: ChainId, channel_id: ChannelId, from_nonce: XdmNonce) -> Option<XdmNonce> {
1612 Messenger::first_inbox_message_response_nonce_to_relay(dst_chain_id, channel_id, from_nonce)
1613 }
1614 }
1615
1616 impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {
1617 fn chain_id() -> u64 {
1618 <Runtime as pallet_evm::Config>::ChainId::get()
1619 }
1620
1621 fn account_basic(address: H160) -> EVMAccount {
1622 let (account, _) = EVM::account_basic(&address);
1623 account
1624 }
1625
1626 fn gas_price() -> U256 {
1627 let (gas_price, _) = <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price();
1628 gas_price
1629 }
1630
1631 fn account_code_at(address: H160) -> Vec<u8> {
1632 pallet_evm::AccountCodes::<Runtime>::get(address)
1633 }
1634
1635 fn author() -> H160 {
1636 <pallet_evm::Pallet<Runtime>>::find_author()
1637 }
1638
1639 fn storage_at(address: H160, index: U256) -> H256 {
1640 let tmp = index.to_big_endian();
1641 pallet_evm::AccountStorages::<Runtime>::get(address, H256::from_slice(&tmp[..]))
1642 }
1643
1644 fn call(
1645 from: H160,
1646 to: H160,
1647 data: Vec<u8>,
1648 value: U256,
1649 gas_limit: U256,
1650 max_fee_per_gas: Option<U256>,
1651 max_priority_fee_per_gas: Option<U256>,
1652 nonce: Option<U256>,
1653 estimate: bool,
1654 access_list: Option<Vec<(H160, Vec<H256>)>>,
1655 ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {
1656 let config = if estimate {
1657 let mut config = <Runtime as pallet_evm::Config>::config().clone();
1658 config.estimate = true;
1659 Some(config)
1660 } else {
1661 None
1662 };
1663
1664 let is_transactional = false;
1665 let validate = true;
1666 let weight_limit = None;
1667 let proof_size_base_cost = None;
1668 let evm_config = config.as_ref().unwrap_or(<Runtime as pallet_evm::Config>::config());
1669 <Runtime as pallet_evm::Config>::Runner::call(
1670 from,
1671 to,
1672 data,
1673 value,
1674 gas_limit.unique_saturated_into(),
1675 max_fee_per_gas,
1676 max_priority_fee_per_gas,
1677 nonce,
1678 access_list.unwrap_or_default(),
1679 is_transactional,
1680 validate,
1681 weight_limit,
1682 proof_size_base_cost,
1683 evm_config,
1684 ).map_err(|err| err.error.into())
1685 }
1686
1687 fn create(
1688 from: H160,
1689 data: Vec<u8>,
1690 value: U256,
1691 gas_limit: U256,
1692 max_fee_per_gas: Option<U256>,
1693 max_priority_fee_per_gas: Option<U256>,
1694 nonce: Option<U256>,
1695 estimate: bool,
1696 access_list: Option<Vec<(H160, Vec<H256>)>>,
1697 ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {
1698 let config = if estimate {
1699 let mut config = <Runtime as pallet_evm::Config>::config().clone();
1700 config.estimate = true;
1701 Some(config)
1702 } else {
1703 None
1704 };
1705
1706 let is_transactional = false;
1707 let validate = true;
1708 let weight_limit = None;
1709 let proof_size_base_cost = None;
1710 let evm_config = config.as_ref().unwrap_or(<Runtime as pallet_evm::Config>::config());
1711 <Runtime as pallet_evm::Config>::Runner::create(
1712 from,
1713 data,
1714 value,
1715 gas_limit.unique_saturated_into(),
1716 max_fee_per_gas,
1717 max_priority_fee_per_gas,
1718 nonce,
1719 access_list.unwrap_or_default(),
1720 is_transactional,
1721 validate,
1722 weight_limit,
1723 proof_size_base_cost,
1724 evm_config,
1725 ).map_err(|err| err.error.into())
1726 }
1727
1728 fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {
1729 pallet_ethereum::CurrentTransactionStatuses::<Runtime>::get()
1730 }
1731
1732 fn current_block() -> Option<pallet_ethereum::Block> {
1733 pallet_ethereum::CurrentBlock::<Runtime>::get()
1734 }
1735
1736 fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {
1737 pallet_ethereum::CurrentReceipts::<Runtime>::get()
1738 }
1739
1740 fn current_all() -> (
1741 Option<pallet_ethereum::Block>,
1742 Option<Vec<pallet_ethereum::Receipt>>,
1743 Option<Vec<TransactionStatus>>
1744 ) {
1745 (
1746 pallet_ethereum::CurrentBlock::<Runtime>::get(),
1747 pallet_ethereum::CurrentReceipts::<Runtime>::get(),
1748 pallet_ethereum::CurrentTransactionStatuses::<Runtime>::get()
1749 )
1750 }
1751
1752 fn extrinsic_filter(
1753 xts: Vec<ExtrinsicFor<Block>>,
1754 ) -> Vec<EthereumTransaction> {
1755 xts.into_iter().filter_map(|xt| match xt.0.function {
1756 RuntimeCall::Ethereum(transact { transaction }) => Some(transaction),
1757 _ => None
1758 }).collect::<Vec<EthereumTransaction>>()
1759 }
1760
1761 fn elasticity() -> Option<Permill> {
1762 None
1763 }
1764
1765 fn gas_limit_multiplier_support() {}
1766
1767 fn pending_block(
1768 xts: Vec<ExtrinsicFor<Block>>,
1769 ) -> (Option<pallet_ethereum::Block>, Option<Vec<TransactionStatus>>) {
1770 for ext in xts.into_iter() {
1771 let _ = Executive::apply_extrinsic(ext);
1772 }
1773
1774 Ethereum::on_finalize(System::block_number() + 1);
1775
1776 (
1777 pallet_ethereum::CurrentBlock::<Runtime>::get(),
1778 pallet_ethereum::CurrentTransactionStatuses::<Runtime>::get()
1779 )
1780 }
1781
1782 fn initialize_pending_block(header: &HeaderFor<Block>) {
1783 Executive::initialize_block(header);
1784 }
1785 }
1786
1787 impl fp_rpc::ConvertTransactionRuntimeApi<Block> for Runtime {
1788 fn convert_transaction(transaction: EthereumTransaction) -> ExtrinsicFor<Block> {
1789 UncheckedExtrinsic::new_bare(
1790 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),
1791 )
1792 }
1793 }
1794
1795 impl domain_test_primitives::TimestampApi<Block> for Runtime {
1796 fn domain_timestamp() -> Moment {
1797 Timestamp::now()
1798 }
1799 }
1800
1801 impl domain_test_primitives::OnchainStateApi<Block, AccountId, Balance> for Runtime {
1802 fn free_balance(account_id: AccountId) -> Balance {
1803 Balances::free_balance(account_id)
1804 }
1805
1806 fn get_open_channel_for_chain(dst_chain_id: ChainId) -> Option<ChannelId> {
1807 Messenger::get_open_channel_for_chain(dst_chain_id)
1808 }
1809
1810 fn consensus_transaction_byte_fee() -> Balance {
1811 BlockFees::consensus_chain_byte_fee()
1812 }
1813
1814 fn storage_root() -> [u8; 32] {
1815 let version = <Runtime as frame_system::Config>::Version::get().state_version();
1816 let root = sp_io::storage::root(version);
1817 TryInto::<[u8; 32]>::try_into(root)
1818 .expect("root is a SCALE encoded hash which uses H256; qed")
1819 }
1820
1821 fn total_issuance() -> Balance {
1822 Balances::total_issuance()
1823 }
1824 }
1825
1826 impl domain_test_primitives::EvmOnchainStateApi<Block> for Runtime {
1827 fn evm_contract_creation_allowed_by() -> Option<PermissionedActionAllowedBy<EthereumAccountId>> {
1828 Some(EVMNoncetracker::contract_creation_allowed_by())
1829 }
1830 }
1831
1832 impl sp_domain_sudo::DomainSudoApi<Block> for Runtime {
1833 fn is_valid_sudo_call(extrinsic: Vec<u8>) -> bool {
1834 is_valid_sudo_call(extrinsic)
1835 }
1836
1837 fn construct_domain_sudo_extrinsic(inner: Vec<u8>) -> ExtrinsicFor<Block> {
1838 construct_sudo_call_extrinsic(inner)
1839 }
1840 }
1841
1842 impl sp_evm_tracker::EvmTrackerApi<Block> for Runtime {
1843 fn construct_evm_contract_creation_allowed_by_extrinsic(decoded_argument: PermissionedActionAllowedBy<AccountId>) -> ExtrinsicFor<Block> {
1844 construct_evm_contract_creation_allowed_by_extrinsic(decoded_argument)
1845 }
1846 }
1847
1848 impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
1849 fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
1850 build_state::<RuntimeGenesisConfig>(config)
1851 }
1852
1853 fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
1854 get_preset::<RuntimeGenesisConfig>(id, |_| None)
1855 }
1856
1857 fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
1858 vec![]
1859 }
1860 }
1861}