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