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