1#![doc = include_str!("../README.md")]
19#![allow(rustdoc::private_intra_doc_links)]
20#![cfg_attr(not(feature = "std"), no_std)]
21#![cfg_attr(feature = "runtime-benchmarks", recursion_limit = "1024")]
22
23extern crate alloc;
24
25mod address;
26mod benchmarking;
27#[cfg(any(feature = "runtime-benchmarks", test))]
28pub mod call_builder;
29mod debug;
30mod deposit_payment;
31mod exec;
32mod impl_fungibles;
33mod limits;
34mod metering;
35mod primitives;
36#[doc(hidden)]
37pub mod state_overrides;
38mod storage;
39#[cfg(test)]
40mod tests;
41mod transient_storage;
42mod vm;
43mod weightinfo_extension;
44
45pub mod evm;
46pub mod migrations;
47pub mod mock;
48pub mod precompiles;
49pub mod test_utils;
50pub mod tracing;
51pub mod weights;
52
53use crate::{
54 evm::{
55 CallTracer, CreateCallMode, ExecutionTracer, GenericTransaction, PrestateTracer,
56 TYPE_EIP1559, Trace, Tracer, TracerType, block_hash::EthereumBlockBuilderIR, block_storage,
57 fees::InfoT as FeeInfo, runtime::SetWeightLimit,
58 },
59 exec::{AccountIdOf, ExecError, ReentrancyProtection, Stack as ExecStack},
60 sp_runtime::TransactionOutcome,
61 storage::{AccountType, DeletionQueueManager},
62 tracing::if_tracing,
63 vm::{CodeInfo, RuntimeCosts, pvm::extract_code_and_data},
64 weightinfo_extension::OnFinalizeBlockParts,
65};
66use alloc::{boxed::Box, format, vec};
67use codec::{Codec, Decode, Encode};
68use environmental::*;
69use frame_support::{
70 BoundedVec,
71 dispatch::{
72 DispatchErrorWithPostInfo, DispatchResult, DispatchResultWithPostInfo, GetDispatchInfo,
73 Pays, PostDispatchInfo, RawOrigin,
74 },
75 ensure,
76 pallet_prelude::DispatchClass,
77 storage::with_transaction,
78 traits::{
79 ConstU32, ConstU64, DefensiveResult, EnsureOrigin, Get, IsSubType, IsType, OnUnbalanced,
80 OriginTrait,
81 fungible::{Balanced, Credit, Inspect, Mutate, MutateHold},
82 tokens::Balance,
83 },
84 weights::WeightMeter,
85};
86use frame_system::{
87 Pallet as System, ensure_signed,
88 pallet_prelude::{BlockNumberFor, OriginFor},
89};
90use scale_info::TypeInfo;
91use sp_runtime::{
92 AccountId32, DispatchError, FixedPointNumber, FixedU128, SaturatedConversion,
93 traits::{
94 BadOrigin, Bounded, Convert, Dispatchable, Saturating, UniqueSaturatedFrom,
95 UniqueSaturatedInto, Zero,
96 },
97};
98
99pub use crate::{
100 address::{AccountId32Mapper, AddressMapper, AutoMapper, TestAccountMapper, create1, create2},
101 debug::DebugSettings,
102 deposit_payment::{Deposit, PGasDeposit},
103 evm::{
104 Address as EthAddress, Block as EthBlock, DryRunConfig, ReceiptInfo, TracingConfig,
105 block_hash::ReceiptGasInfo,
106 },
107 exec::{CallResources, DelegateInfo, Executable, Key, MomentOf, Origin as ExecOrigin},
108 limits::TRANSIENT_STORAGE_BYTES as TRANSIENT_STORAGE_LIMIT,
109 metering::{
110 EthTxInfo, FrameMeter, ResourceMeter, Token as WeightToken, TransactionLimits,
111 TransactionMeter,
112 },
113 pallet::{genesis, *},
114 storage::{AccountInfo, ContractInfo},
115 transient_storage::{MeterEntry, StorageMeter as TransientStorageMeter, TransientStorage},
116 vm::{BytecodeType, ContractBlob},
117};
118pub use codec;
119use frame_support::traits::tokens::Precision;
120pub use frame_support::{self, dispatch::DispatchInfo, traits::Time, weights::Weight};
121pub use frame_system::{self, limits::BlockWeights};
122pub use primitives::*;
123pub use sp_core::{H160, H256, U256, keccak_256};
124pub use sp_runtime;
125pub use weights::WeightInfo;
126
127#[cfg(doc)]
128pub use crate::vm::pvm::SyscallDoc;
129
130pub type BalanceOf<T> = <T as Config>::Balance;
131pub type CreditOf<T> = Credit<<T as frame_system::Config>::AccountId, <T as Config>::Currency>;
132type TrieId = BoundedVec<u8, ConstU32<128>>;
133type ImmutableData = BoundedVec<u8, ConstU32<{ limits::IMMUTABLE_BYTES }>>;
134type CallOf<T> = <T as Config>::RuntimeCall;
135
136const SENTINEL: u32 = u32::MAX;
143
144const LOG_TARGET: &str = "runtime::revive";
150
151#[frame_support::pallet]
152pub mod pallet {
153 use super::*;
154 use frame_support::{pallet_prelude::*, traits::FindAuthor};
155 use frame_system::pallet_prelude::*;
156 use sp_core::U256;
157 use sp_runtime::Perbill;
158
159 pub(crate) const STORAGE_VERSION: StorageVersion = StorageVersion::new(0);
161
162 #[pallet::pallet]
163 #[pallet::storage_version(STORAGE_VERSION)]
164 pub struct Pallet<T>(_);
165
166 #[pallet::config(with_default)]
167 pub trait Config: frame_system::Config {
168 type Time: Time<Moment: Into<U256>>;
170
171 #[pallet::no_default]
175 type Balance: Balance
176 + TryFrom<U256>
177 + Into<U256>
178 + Bounded
179 + UniqueSaturatedInto<u64>
180 + UniqueSaturatedFrom<u64>
181 + UniqueSaturatedInto<u128>;
182
183 #[pallet::no_default]
185 type Currency: Inspect<Self::AccountId, Balance = Self::Balance>
186 + Mutate<Self::AccountId>
187 + MutateHold<Self::AccountId, Reason = Self::RuntimeHoldReason>
188 + Balanced<Self::AccountId>;
189
190 #[pallet::no_default_bounds]
197 type OnBurn: OnUnbalanced<CreditOf<Self>>;
198
199 #[pallet::no_default_bounds]
201 #[allow(deprecated)]
202 type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
203
204 #[pallet::no_default_bounds]
206 type RuntimeCall: Parameter
207 + Dispatchable<
208 RuntimeOrigin = OriginFor<Self>,
209 Info = DispatchInfo,
210 PostInfo = PostDispatchInfo,
211 > + IsType<<Self as frame_system::Config>::RuntimeCall>
212 + From<Call<Self>>
213 + IsSubType<Call<Self>>
214 + GetDispatchInfo;
215
216 #[pallet::no_default_bounds]
218 type RuntimeOrigin: IsType<OriginFor<Self>>
219 + From<Origin<Self>>
220 + Into<Result<Origin<Self>, OriginFor<Self>>>;
221
222 #[pallet::no_default_bounds]
224 type RuntimeHoldReason: From<HoldReason>;
225
226 type WeightInfo: WeightInfo;
229
230 #[pallet::no_default_bounds]
234 #[allow(private_bounds)]
235 type Precompiles: precompiles::Precompiles<Self>;
236
237 type FindAuthor: FindAuthor<Self::AccountId>;
239
240 #[pallet::constant]
246 #[pallet::no_default_bounds]
247 type DepositPerByte: Get<BalanceOf<Self>>;
248
249 #[pallet::constant]
255 #[pallet::no_default_bounds]
256 type DepositPerItem: Get<BalanceOf<Self>>;
257
258 #[pallet::constant]
268 #[pallet::no_default_bounds]
269 type DepositPerChildTrieItem: Get<BalanceOf<Self>>;
270
271 #[pallet::constant]
275 type CodeHashLockupDepositPercent: Get<Perbill>;
276
277 #[pallet::no_default]
279 type AddressMapper: AddressMapper<Self>;
280
281 #[pallet::constant]
283 type AllowEVMBytecode: Get<bool>;
284
285 #[pallet::no_default_bounds]
290 type UploadOrigin: EnsureOrigin<OriginFor<Self>, Success = Self::AccountId>;
291
292 #[pallet::no_default_bounds]
303 type InstantiateOrigin: EnsureOrigin<OriginFor<Self>, Success = Self::AccountId>;
304
305 type RuntimeMemory: Get<u32>;
310
311 type PVFMemory: Get<u32>;
319
320 #[pallet::constant]
325 type ChainId: Get<u64>;
326
327 #[pallet::constant]
329 type NativeToEthRatio: Get<u32>;
330
331 #[pallet::no_default_bounds]
336 type FeeInfo: FeeInfo<Self>;
337
338 #[pallet::no_default_bounds]
341 type Deposit: Deposit<Self>;
342
343 #[pallet::constant]
356 type MaxEthExtrinsicWeight: Get<FixedU128>;
357
358 #[pallet::constant]
360 type DebugEnabled: Get<bool>;
361
362 #[pallet::constant]
369 type AutoMap: Get<bool>;
370
371 #[pallet::constant]
389 #[pallet::no_default_bounds]
390 type GasScale: Get<u32>;
391 }
392
393 pub mod config_preludes {
395 use super::*;
396 use frame_support::{
397 derive_impl,
398 traits::{ConstBool, ConstU32},
399 };
400 use frame_system::EnsureSigned;
401 use sp_core::parameter_types;
402
403 type Balance = u64;
404
405 pub const DOLLARS: Balance = 1_000_000_000_000;
406 pub const CENTS: Balance = DOLLARS / 100;
407 pub const MILLICENTS: Balance = CENTS / 1_000;
408
409 pub const fn deposit(items: u32, bytes: u32) -> Balance {
410 items as Balance * 20 * CENTS + (bytes as Balance) * MILLICENTS
411 }
412
413 parameter_types! {
414 pub const DepositPerItem: Balance = deposit(1, 0);
415 pub const DepositPerChildTrieItem: Balance = deposit(1, 0) / 100;
416 pub const DepositPerByte: Balance = deposit(0, 1);
417 pub const CodeHashLockupDepositPercent: Perbill = Perbill::from_percent(0);
418 pub const MaxEthExtrinsicWeight: FixedU128 = FixedU128::from_rational(9, 10);
419 pub const GasScale: u32 = 10u32;
420 }
421
422 pub struct TestDefaultConfig;
424
425 impl Time for TestDefaultConfig {
426 type Moment = u64;
427 fn now() -> Self::Moment {
428 0u64
429 }
430 }
431
432 impl<T: From<u64>> Convert<Weight, T> for TestDefaultConfig {
433 fn convert(w: Weight) -> T {
434 w.ref_time().into()
435 }
436 }
437
438 #[derive_impl(frame_system::config_preludes::TestDefaultConfig, no_aggregated_types)]
439 impl frame_system::DefaultConfig for TestDefaultConfig {}
440
441 #[frame_support::register_default_impl(TestDefaultConfig)]
442 impl DefaultConfig for TestDefaultConfig {
443 #[inject_runtime_type]
444 type RuntimeEvent = ();
445
446 #[inject_runtime_type]
447 type RuntimeHoldReason = ();
448
449 #[inject_runtime_type]
450 type RuntimeCall = ();
451
452 #[inject_runtime_type]
453 type RuntimeOrigin = ();
454
455 type Precompiles = ();
456 type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent;
457 type DepositPerByte = DepositPerByte;
458 type DepositPerItem = DepositPerItem;
459 type DepositPerChildTrieItem = DepositPerChildTrieItem;
460 type Time = Self;
461 type AllowEVMBytecode = ConstBool<true>;
462 type UploadOrigin = EnsureSigned<Self::AccountId>;
463 type InstantiateOrigin = EnsureSigned<Self::AccountId>;
464 type WeightInfo = ();
465 type RuntimeMemory = ConstU32<{ 128 * 1024 * 1024 }>;
466 type PVFMemory = ConstU32<{ 512 * 1024 * 1024 }>;
467 type ChainId = ConstU64<42>;
468 type NativeToEthRatio = ConstU32<1_000_000>;
469 type FindAuthor = ();
470 type FeeInfo = ();
471 type Deposit = ();
472 type MaxEthExtrinsicWeight = MaxEthExtrinsicWeight;
473 type DebugEnabled = ConstBool<false>;
474 type AutoMap = ConstBool<false>;
475 type GasScale = GasScale;
476 type OnBurn = ();
477 }
478 }
479
480 #[pallet::event]
481 pub enum Event<T: Config> {
482 ContractEmitted {
484 contract: H160,
486 data: Vec<u8>,
489 topics: Vec<H256>,
492 },
493
494 Instantiated { deployer: H160, contract: H160 },
496
497 EthExtrinsicRevert { dispatch_error: DispatchError },
504 }
505
506 #[pallet::error]
507 #[repr(u8)]
508 pub enum Error<T> {
509 InvalidSchedule = 0x01,
511 InvalidCallFlags = 0x02,
513 OutOfGas = 0x03,
515 TransferFailed = 0x04,
518 MaxCallDepthReached = 0x05,
521 ContractNotFound = 0x06,
523 CodeNotFound = 0x07,
525 CodeInfoNotFound = 0x08,
527 OutOfBounds = 0x09,
529 DecodingFailed = 0x0A,
531 ContractTrapped = 0x0B,
533 ValueTooLarge = 0x0C,
535 TerminatedWhileReentrant = 0x0D,
538 InputForwarded = 0x0E,
540 TooManyTopics = 0x0F,
542 DuplicateContract = 0x12,
544 TerminatedInConstructor = 0x13,
548 ReentranceDenied = 0x14,
550 ReenteredPallet = 0x15,
552 StateChangeDenied = 0x16,
554 StorageDepositNotEnoughFunds = 0x17,
556 StorageDepositLimitExhausted = 0x18,
558 CodeInUse = 0x19,
560 ContractReverted = 0x1A,
565 CodeRejected = 0x1B,
570 BlobTooLarge = 0x1C,
572 StaticMemoryTooLarge = 0x1D,
574 BasicBlockTooLarge = 0x1E,
576 InvalidInstruction = 0x1F,
578 MaxDelegateDependenciesReached = 0x20,
580 DelegateDependencyNotFound = 0x21,
582 DelegateDependencyAlreadyExists = 0x22,
584 CannotAddSelfAsDelegateDependency = 0x23,
586 OutOfTransientStorage = 0x24,
588 InvalidSyscall = 0x25,
590 InvalidStorageFlags = 0x26,
592 ExecutionFailed = 0x27,
594 BalanceConversionFailed = 0x28,
596 InvalidImmutableAccess = 0x2A,
599 AccountUnmapped = 0x2B,
603 AccountAlreadyMapped = 0x2C,
605 InvalidGenericTransaction = 0x2D,
607 RefcountOverOrUnderflow = 0x2E,
609 UnsupportedPrecompileAddress = 0x2F,
611 CallDataTooLarge = 0x30,
613 ReturnDataTooLarge = 0x31,
615 InvalidJump = 0x32,
617 StackUnderflow = 0x33,
619 StackOverflow = 0x34,
621 TxFeeOverdraw = 0x35,
625 EvmConstructorNonEmptyData = 0x36,
629 EvmConstructedFromHash = 0x37,
634 StorageRefundNotEnoughFunds = 0x38,
638 StorageRefundLocked = 0x39,
643 PrecompileDelegateDenied = 0x40,
648 EcdsaRecoveryFailed = 0x41,
650 AutoMappingEnabled = 0x42,
652 PendingDepositCleanup = 0x43,
656 #[cfg(feature = "runtime-benchmarks")]
658 BenchmarkingError = 0xFF,
659 }
660
661 #[pallet::composite_enum]
663 pub enum HoldReason {
664 CodeUploadDepositReserve,
666 StorageDepositReserve,
668 AddressMapping,
670 }
671
672 #[pallet::composite_enum]
674 pub enum FreezeReason {
675 PGasMinBalance,
680 }
681
682 #[derive(
683 PartialEq, Eq, Clone, MaxEncodedLen, Encode, Decode, DecodeWithMemTracking, TypeInfo, Debug,
684 )]
685 #[pallet::origin]
686 pub enum Origin<T: Config> {
687 EthTransaction(T::AccountId),
688 }
689
690 #[pallet::storage]
694 #[pallet::unbounded]
695 pub(crate) type PristineCode<T: Config> = StorageMap<_, Identity, H256, Vec<u8>>;
696
697 #[pallet::storage]
699 pub(crate) type CodeInfoOf<T: Config> = StorageMap<_, Identity, H256, CodeInfo<T>>;
700
701 #[pallet::storage]
703 pub(crate) type AccountInfoOf<T: Config> = StorageMap<_, Identity, H160, AccountInfo<T>>;
704
705 #[pallet::storage]
716 pub(crate) type NativeDepositOf<T: Config> = StorageDoubleMap<
717 _,
718 Identity,
719 T::AccountId,
720 Identity,
721 T::AccountId,
722 BalanceOf<T>,
723 ValueQuery,
724 >;
725
726 #[pallet::storage]
728 pub(crate) type ImmutableDataOf<T: Config> = StorageMap<_, Identity, H160, ImmutableData>;
729
730 #[pallet::storage]
736 pub(crate) type DeletionQueue<T: Config> =
737 StorageMap<_, Twox64Concat, u32, crate::storage::DeletionQueueItem<T>>;
738
739 #[pallet::storage]
742 pub(crate) type DeletionQueueCounter<T: Config> =
743 StorageValue<_, DeletionQueueManager<T>, ValueQuery>;
744
745 #[pallet::storage]
752 pub(crate) type OriginalAccount<T: Config> = StorageMap<_, Identity, H160, AccountId32>;
753
754 #[pallet::storage]
764 #[pallet::unbounded]
765 pub(crate) type EthereumBlock<T> = StorageValue<_, EthBlock, ValueQuery>;
766
767 #[pallet::storage]
771 pub(crate) type BlockHash<T: Config> =
772 StorageMap<_, Identity, BlockNumberFor<T>, H256, ValueQuery>;
773
774 #[pallet::storage]
781 #[pallet::unbounded]
782 pub(crate) type ReceiptInfoData<T: Config> = StorageValue<_, Vec<ReceiptGasInfo>, ValueQuery>;
783
784 #[pallet::storage]
786 #[pallet::unbounded]
787 pub(crate) type EthBlockBuilderIR<T: Config> =
788 StorageValue<_, EthereumBlockBuilderIR<T>, ValueQuery>;
789
790 #[pallet::storage]
795 #[pallet::unbounded]
796 pub(crate) type EthBlockBuilderFirstValues<T: Config> =
797 StorageValue<_, Option<(Vec<u8>, Vec<u8>)>, ValueQuery>;
798
799 #[pallet::storage]
801 pub(crate) type DebugSettingsOf<T: Config> = StorageValue<_, DebugSettings, ValueQuery>;
802
803 pub mod genesis {
804 use super::*;
805 use crate::evm::Bytes32;
806
807 #[derive(Clone, PartialEq, Debug, Default, serde::Serialize, serde::Deserialize)]
809 pub struct ContractData {
810 pub code: crate::evm::Bytes,
812 pub storage: alloc::collections::BTreeMap<Bytes32, Bytes32>,
814 }
815
816 #[derive(PartialEq, Default, Debug, Clone, serde::Serialize, serde::Deserialize)]
818 pub struct Account<T: Config> {
819 pub address: H160,
821 #[serde(default)]
823 pub balance: U256,
824 #[serde(default)]
826 pub nonce: T::Nonce,
827 #[serde(flatten, skip_serializing_if = "Option::is_none")]
829 pub contract_data: Option<ContractData>,
830 }
831 }
832
833 #[pallet::genesis_config]
834 #[derive(Debug, PartialEq, frame_support::DefaultNoBound)]
835 pub struct GenesisConfig<T: Config> {
836 #[serde(default, skip_serializing_if = "Vec::is_empty")]
839 pub mapped_accounts: Vec<T::AccountId>,
840
841 #[serde(default, skip_serializing_if = "Vec::is_empty")]
843 pub accounts: Vec<genesis::Account<T>>,
844
845 #[serde(default, skip_serializing_if = "Option::is_none")]
847 pub debug_settings: Option<DebugSettings>,
848 }
849
850 #[pallet::genesis_build]
851 impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
852 fn build(&self) {
853 use crate::{exec::Key, vm::ContractBlob};
854 use frame_support::traits::fungible::Mutate;
855
856 if !System::<T>::account_exists(&Pallet::<T>::account_id()) {
857 let _ = T::Currency::mint_into(
858 &Pallet::<T>::account_id(),
859 T::Currency::minimum_balance(),
860 );
861 }
862
863 for id in &self.mapped_accounts {
864 if let Err(err) = T::AddressMapper::map_no_deposit(id) {
865 log::error!(target: LOG_TARGET, "Failed to map account {id:?}: {err:?}");
866 }
867 }
868
869 let owner = Pallet::<T>::account_id();
870
871 for genesis::Account { address, balance, nonce, contract_data } in &self.accounts {
872 let account_id = T::AddressMapper::to_account_id(address);
873
874 if !System::<T>::account_exists(&account_id) {
875 let _ = T::Currency::mint_into(&account_id, T::Currency::minimum_balance());
876 }
877
878 frame_system::Account::<T>::mutate(&account_id, |info| {
879 info.nonce = (*nonce).into();
880 });
881
882 match contract_data {
883 None => {
884 AccountInfoOf::<T>::insert(
885 address,
886 AccountInfo { account_type: AccountType::EOA, dust: 0 },
887 );
888 },
889 Some(genesis::ContractData { code, storage }) => {
890 let blob = if code.0.starts_with(&polkavm_common::program::BLOB_MAGIC) {
891 ContractBlob::<T>::from_pvm_code(code.0.clone(), owner.clone())
892 .inspect_err(|err| {
893 log::error!(target: LOG_TARGET, "Failed to create PVM ContractBlob for {address:?}: {err:?}");
894 })
895 } else {
896 ContractBlob::<T>::from_evm_runtime_code(code.0.clone(), account_id)
897 .inspect_err(|err| {
898 log::error!(target: LOG_TARGET, "Failed to create EVM ContractBlob for {address:?}: {err:?}");
899 })
900 };
901
902 let Ok(blob) = blob else {
903 continue;
904 };
905
906 let code_hash = *blob.code_hash();
907 let Ok(info) = <ContractInfo<T>>::new(&address, 0u32.into(), code_hash)
908 .inspect_err(|err| {
909 log::error!(target: LOG_TARGET, "Failed to create ContractInfo for {address:?}: {err:?}");
910 })
911 else {
912 continue;
913 };
914
915 AccountInfoOf::<T>::insert(
916 address,
917 AccountInfo { account_type: info.clone().into(), dust: 0 },
918 );
919
920 <PristineCode<T>>::insert(blob.code_hash(), code.0.clone());
921 <CodeInfoOf<T>>::insert(blob.code_hash(), blob.code_info().clone());
922 for (k, v) in storage {
923 let _ = info.write(&Key::from_fixed(k.0), Some(v.0.to_vec()), None, false).inspect_err(|err| {
924 log::error!(target: LOG_TARGET, "Failed to write genesis storage for {address:?} at key {k:?}: {err:?}");
925 });
926 }
927 },
928 }
929
930 let _ = Pallet::<T>::set_evm_balance(address, *balance).inspect_err(|err| {
931 log::error!(target: LOG_TARGET, "Failed to set EVM balance for {address:?}: {err:?}");
932 });
933 }
934
935 block_storage::on_finalize_build_eth_block::<T>(
937 frame_system::Pallet::<T>::block_number(),
940 );
941
942 if let Some(settings) = self.debug_settings.as_ref() {
944 settings.write_to_storage::<T>()
945 }
946 }
947 }
948
949 #[pallet::hooks]
950 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
951 fn on_idle(_block: BlockNumberFor<T>, limit: Weight) -> Weight {
952 let mut meter = WeightMeter::with_limit(limit);
953 ContractInfo::<T>::process_deletion_queue_batch(&mut meter);
954 meter.consumed()
955 }
956
957 fn on_initialize(_n: BlockNumberFor<T>) -> Weight {
958 block_storage::on_initialize::<T>();
960
961 System::<T>::account_exists(&Pallet::<T>::account_id());
963 <T as Config>::WeightInfo::on_finalize_block_fixed()
965 }
966
967 fn on_finalize(block_number: BlockNumberFor<T>) {
968 block_storage::on_finalize_build_eth_block::<T>(block_number);
970 }
971
972 fn integrity_test() {
973 assert!(T::ChainId::get() > 0, "ChainId must be greater than 0");
974
975 assert!(T::GasScale::get() > 0u32.into(), "GasScale must not be 0");
976
977 T::FeeInfo::integrity_test();
978
979 let max_runtime_mem: u64 = T::RuntimeMemory::get().into();
981
982 const TOTAL_MEMORY_DEVIDER: u64 = 2;
985
986 let max_block_weight = T::BlockWeights::get()
992 .get(DispatchClass::Normal)
993 .max_total
994 .unwrap_or_else(|| T::BlockWeights::get().max_block);
995 let max_key_size: u64 =
996 Key::try_from_var(alloc::vec![0u8; limits::STORAGE_KEY_BYTES as usize])
997 .expect("Key of maximal size shall be created")
998 .hash()
999 .len()
1000 .try_into()
1001 .unwrap();
1002
1003 let max_immutable_key_size: u64 = T::AccountId::max_encoded_len().try_into().unwrap();
1004 let max_immutable_size: u64 = max_block_weight
1005 .checked_div_per_component(&<RuntimeCosts as WeightToken<T>>::weight(
1006 &RuntimeCosts::SetImmutableData(limits::IMMUTABLE_BYTES),
1007 ))
1008 .unwrap()
1009 .saturating_mul(
1010 u64::from(limits::IMMUTABLE_BYTES)
1011 .saturating_add(max_immutable_key_size)
1012 .into(),
1013 );
1014
1015 let max_pvf_mem: u64 = T::PVFMemory::get().into();
1016 let storage_size_limit = max_pvf_mem.saturating_sub(max_runtime_mem) / 2;
1017
1018 let max_events_size = max_block_weight
1022 .checked_div_per_component(
1023 &(<RuntimeCosts as WeightToken<T>>::weight(&RuntimeCosts::DepositEvent {
1024 num_topic: 0,
1025 len: limits::EVENT_BYTES,
1026 })
1027 .saturating_add(<RuntimeCosts as WeightToken<T>>::weight(
1028 &RuntimeCosts::HostFn,
1029 ))),
1030 )
1031 .unwrap()
1032 .saturating_mul(limits::EVENT_BYTES.into());
1033
1034 assert!(
1035 max_events_size <= storage_size_limit,
1036 "Maximal events size {} exceeds the events limit {}",
1037 max_events_size,
1038 storage_size_limit
1039 );
1040
1041 let max_eth_block_builder_bytes =
1076 block_storage::block_builder_bytes_usage(max_events_size.try_into().unwrap());
1077
1078 log::debug!(
1079 target: LOG_TARGET,
1080 "Integrity check: max_eth_block_builder_bytes={} KB using max_events_size={} KB",
1081 max_eth_block_builder_bytes / 1024,
1082 max_events_size / 1024,
1083 );
1084
1085 let memory_left = i128::from(max_runtime_mem)
1090 .saturating_div(TOTAL_MEMORY_DEVIDER.into())
1091 .saturating_sub(limits::MEMORY_REQUIRED.into())
1092 .saturating_sub(max_eth_block_builder_bytes.into());
1093
1094 log::debug!(target: LOG_TARGET, "Integrity check: memory_left={} KB", memory_left / 1024);
1095
1096 assert!(
1097 memory_left >= 0,
1098 "Runtime does not have enough memory for current limits. Additional runtime memory required: {} KB",
1099 memory_left.saturating_mul(TOTAL_MEMORY_DEVIDER.into()).abs() / 1024
1100 );
1101
1102 let max_storage_size = max_block_weight
1105 .checked_div_per_component(
1106 &<RuntimeCosts as WeightToken<T>>::weight(&RuntimeCosts::SetStorage {
1107 new_bytes: limits::STORAGE_BYTES,
1108 old_bytes: 0,
1109 })
1110 .saturating_mul(u64::from(limits::STORAGE_BYTES).saturating_add(max_key_size)),
1111 )
1112 .unwrap()
1113 .saturating_add(max_immutable_size.into())
1114 .saturating_add(max_eth_block_builder_bytes.into());
1115
1116 assert!(
1117 max_storage_size <= storage_size_limit,
1118 "Maximal storage size {} exceeds the storage limit {}",
1119 max_storage_size,
1120 storage_size_limit
1121 );
1122 }
1123 }
1124
1125 #[pallet::call]
1126 impl<T: Config> Pallet<T> {
1127 #[allow(unused_variables)]
1140 #[pallet::call_index(0)]
1141 #[pallet::weight(Weight::MAX)]
1142 pub fn eth_transact(origin: OriginFor<T>, payload: Vec<u8>) -> DispatchResultWithPostInfo {
1143 Err(frame_system::Error::CallFiltered::<T>.into())
1144 }
1145
1146 #[pallet::call_index(1)]
1163 #[pallet::weight(<T as Config>::WeightInfo::call().saturating_add(*weight_limit))]
1164 pub fn call(
1165 origin: OriginFor<T>,
1166 dest: H160,
1167 #[pallet::compact] value: BalanceOf<T>,
1168 weight_limit: Weight,
1169 #[pallet::compact] storage_deposit_limit: BalanceOf<T>,
1170 data: Vec<u8>,
1171 ) -> DispatchResultWithPostInfo {
1172 Self::ensure_non_contract_if_signed(&origin)?;
1173 let mut output = Self::bare_call(
1174 origin,
1175 dest,
1176 Pallet::<T>::convert_native_to_evm(value),
1177 TransactionLimits::WeightAndDeposit {
1178 weight_limit,
1179 deposit_limit: storage_deposit_limit,
1180 },
1181 data,
1182 &ExecConfig::new_substrate_tx(),
1183 );
1184
1185 if let Ok(return_value) = &output.result &&
1186 return_value.did_revert()
1187 {
1188 output.result = Err(<Error<T>>::ContractReverted.into());
1189 }
1190 dispatch_result(
1191 output.result,
1192 output.weight_consumed,
1193 <T as Config>::WeightInfo::call(),
1194 )
1195 }
1196
1197 #[pallet::call_index(2)]
1203 #[pallet::weight(
1204 <T as Config>::WeightInfo::instantiate(data.len() as u32).saturating_add(*weight_limit)
1205 )]
1206 pub fn instantiate(
1207 origin: OriginFor<T>,
1208 #[pallet::compact] value: BalanceOf<T>,
1209 weight_limit: Weight,
1210 #[pallet::compact] storage_deposit_limit: BalanceOf<T>,
1211 code_hash: sp_core::H256,
1212 data: Vec<u8>,
1213 salt: Option<[u8; 32]>,
1214 ) -> DispatchResultWithPostInfo {
1215 Self::ensure_non_contract_if_signed(&origin)?;
1216 let data_len = data.len() as u32;
1217 let mut output = Self::bare_instantiate(
1218 origin,
1219 Pallet::<T>::convert_native_to_evm(value),
1220 TransactionLimits::WeightAndDeposit {
1221 weight_limit,
1222 deposit_limit: storage_deposit_limit,
1223 },
1224 Code::Existing(code_hash),
1225 data,
1226 salt,
1227 &ExecConfig::new_substrate_tx(),
1228 );
1229 if let Ok(retval) = &output.result &&
1230 retval.result.did_revert()
1231 {
1232 output.result = Err(<Error<T>>::ContractReverted.into());
1233 }
1234 dispatch_result(
1235 output.result.map(|result| result.result),
1236 output.weight_consumed,
1237 <T as Config>::WeightInfo::instantiate(data_len),
1238 )
1239 }
1240
1241 #[pallet::call_index(3)]
1269 #[pallet::weight(
1270 <T as Config>::WeightInfo::instantiate_with_code(code.len() as u32, data.len() as u32)
1271 .saturating_add(*weight_limit)
1272 )]
1273 pub fn instantiate_with_code(
1274 origin: OriginFor<T>,
1275 #[pallet::compact] value: BalanceOf<T>,
1276 weight_limit: Weight,
1277 #[pallet::compact] storage_deposit_limit: BalanceOf<T>,
1278 code: Vec<u8>,
1279 data: Vec<u8>,
1280 salt: Option<[u8; 32]>,
1281 ) -> DispatchResultWithPostInfo {
1282 Self::ensure_non_contract_if_signed(&origin)?;
1283 let code_len = code.len() as u32;
1284 let data_len = data.len() as u32;
1285 let mut output = Self::bare_instantiate(
1286 origin,
1287 Pallet::<T>::convert_native_to_evm(value),
1288 TransactionLimits::WeightAndDeposit {
1289 weight_limit,
1290 deposit_limit: storage_deposit_limit,
1291 },
1292 Code::Upload(code),
1293 data,
1294 salt,
1295 &ExecConfig::new_substrate_tx(),
1296 );
1297 if let Ok(retval) = &output.result &&
1298 retval.result.did_revert()
1299 {
1300 output.result = Err(<Error<T>>::ContractReverted.into());
1301 }
1302 dispatch_result(
1303 output.result.map(|result| result.result),
1304 output.weight_consumed,
1305 <T as Config>::WeightInfo::instantiate_with_code(code_len, data_len),
1306 )
1307 }
1308
1309 #[pallet::call_index(10)]
1331 #[pallet::weight(
1332 <T as Config>::WeightInfo::eth_instantiate_with_code(code.len() as u32, data.len() as u32, Pallet::<T>::has_dust(*value).into())
1333 .saturating_add(*weight_limit)
1334 .saturating_add(T::WeightInfo::on_finalize_block_per_tx(transaction_encoded.len() as u32))
1335 )]
1336 pub fn eth_instantiate_with_code(
1337 origin: OriginFor<T>,
1338 value: U256,
1339 weight_limit: Weight,
1340 eth_gas_limit: U256,
1341 code: Vec<u8>,
1342 data: Vec<u8>,
1343 transaction_encoded: Vec<u8>,
1344 effective_gas_price: U256,
1345 encoded_len: u32,
1346 ) -> DispatchResultWithPostInfo {
1347 let signer = Self::ensure_eth_signed(origin)?;
1348 let origin = OriginFor::<T>::signed(signer.clone());
1349 Self::ensure_non_contract_if_signed(&origin)?;
1350 let mut call = Call::<T>::eth_instantiate_with_code {
1351 value,
1352 weight_limit,
1353 eth_gas_limit,
1354 code: code.clone(),
1355 data: data.clone(),
1356 transaction_encoded: transaction_encoded.clone(),
1357 effective_gas_price,
1358 encoded_len,
1359 }
1360 .into();
1361 let info = T::FeeInfo::dispatch_info(&call);
1362 let base_info = T::FeeInfo::base_dispatch_info(&mut call);
1363 drop(call);
1364
1365 block_storage::with_ethereum_context::<T>(transaction_encoded, || {
1366 let extra_weight = base_info.total_weight();
1367 let output = Self::bare_instantiate(
1368 origin,
1369 value,
1370 TransactionLimits::EthereumGas {
1371 eth_gas_limit: eth_gas_limit.saturated_into(),
1372 weight_limit,
1373 eth_tx_info: EthTxInfo::new(encoded_len, extra_weight),
1374 },
1375 Code::Upload(code),
1376 data,
1377 None,
1378 &ExecConfig::new_eth_tx(effective_gas_price, encoded_len, extra_weight),
1379 );
1380
1381 block_storage::EthereumCallResult::new::<T>(
1382 signer,
1383 output.map_result(|r| r.result),
1384 base_info.call_weight,
1385 encoded_len,
1386 &info,
1387 effective_gas_price,
1388 )
1389 })
1390 }
1391
1392 #[pallet::call_index(11)]
1409 #[pallet::weight(
1410 T::WeightInfo::eth_call(Pallet::<T>::has_dust(*value).into())
1411 .saturating_add(*weight_limit)
1412 .saturating_add(T::WeightInfo::on_finalize_block_per_tx(transaction_encoded.len() as u32))
1413 )]
1414 pub fn eth_call(
1415 origin: OriginFor<T>,
1416 dest: H160,
1417 value: U256,
1418 weight_limit: Weight,
1419 eth_gas_limit: U256,
1420 data: Vec<u8>,
1421 transaction_encoded: Vec<u8>,
1422 effective_gas_price: U256,
1423 encoded_len: u32,
1424 ) -> DispatchResultWithPostInfo {
1425 let signer = Self::ensure_eth_signed(origin)?;
1426 let origin = OriginFor::<T>::signed(signer.clone());
1427
1428 Self::ensure_non_contract_if_signed(&origin)?;
1429 let mut call = Call::<T>::eth_call {
1430 dest,
1431 value,
1432 weight_limit,
1433 eth_gas_limit,
1434 data: data.clone(),
1435 transaction_encoded: transaction_encoded.clone(),
1436 effective_gas_price,
1437 encoded_len,
1438 }
1439 .into();
1440 let info = T::FeeInfo::dispatch_info(&call);
1441 let base_info = T::FeeInfo::base_dispatch_info(&mut call);
1442 drop(call);
1443
1444 block_storage::with_ethereum_context::<T>(transaction_encoded, || {
1445 let extra_weight = base_info.total_weight();
1446 let output = Self::bare_call(
1447 origin,
1448 dest,
1449 value,
1450 TransactionLimits::EthereumGas {
1451 eth_gas_limit: eth_gas_limit.saturated_into(),
1452 weight_limit,
1453 eth_tx_info: EthTxInfo::new(encoded_len, extra_weight),
1454 },
1455 data,
1456 &ExecConfig::new_eth_tx(effective_gas_price, encoded_len, extra_weight),
1457 );
1458
1459 block_storage::EthereumCallResult::new::<T>(
1460 signer,
1461 output,
1462 base_info.call_weight,
1463 encoded_len,
1464 &info,
1465 effective_gas_price,
1466 )
1467 })
1468 }
1469
1470 #[pallet::call_index(12)]
1481 #[pallet::weight(
1482 T::WeightInfo::eth_substrate_call(transaction_encoded.len() as u32)
1483 .saturating_add(call.get_dispatch_info().call_weight)
1484 .saturating_add(T::WeightInfo::on_finalize_block_per_tx(transaction_encoded.len() as u32))
1485 )]
1486 pub fn eth_substrate_call(
1487 origin: OriginFor<T>,
1488 call: Box<<T as Config>::RuntimeCall>,
1489 transaction_encoded: Vec<u8>,
1490 ) -> DispatchResultWithPostInfo {
1491 let signer = Self::ensure_eth_signed(origin)?;
1494 Self::ensure_non_contract_if_signed(&OriginFor::<T>::signed(signer.clone()))?;
1495 let tx_len = transaction_encoded.len() as u32;
1496 let weight_overhead = T::WeightInfo::eth_substrate_call(tx_len)
1497 .saturating_add(T::WeightInfo::on_finalize_block_per_tx(tx_len));
1498
1499 block_storage::with_ethereum_context::<T>(transaction_encoded, || {
1500 let call_weight = call.get_dispatch_info().call_weight;
1501 let mut call_result = call.dispatch(RawOrigin::Signed(signer).into());
1502
1503 match &mut call_result {
1505 Ok(post_info) | Err(DispatchErrorWithPostInfo { post_info, .. }) => {
1506 post_info.actual_weight = Some(
1507 post_info
1508 .actual_weight
1509 .unwrap_or_else(|| call_weight)
1510 .saturating_add(weight_overhead),
1511 );
1512 },
1513 }
1514
1515 block_storage::EthereumCallResult {
1518 receipt_gas_info: ReceiptGasInfo::default(),
1519 result: call_result,
1520 }
1521 })
1522 }
1523
1524 #[pallet::call_index(4)]
1539 #[pallet::weight(<T as Config>::WeightInfo::upload_code(code.len() as u32))]
1540 pub fn upload_code(
1541 origin: OriginFor<T>,
1542 code: Vec<u8>,
1543 #[pallet::compact] storage_deposit_limit: BalanceOf<T>,
1544 ) -> DispatchResult {
1545 Self::ensure_non_contract_if_signed(&origin)?;
1546 Self::bare_upload_code(origin, code, storage_deposit_limit).map(|_| ())
1547 }
1548
1549 #[pallet::call_index(5)]
1554 #[pallet::weight(<T as Config>::WeightInfo::remove_code())]
1555 pub fn remove_code(
1556 origin: OriginFor<T>,
1557 code_hash: sp_core::H256,
1558 ) -> DispatchResultWithPostInfo {
1559 let origin = ensure_signed(origin)?;
1560 <ContractBlob<T>>::remove(&origin, code_hash)?;
1561 Ok(Pays::No.into())
1563 }
1564
1565 #[pallet::call_index(6)]
1576 #[pallet::weight(<T as Config>::WeightInfo::set_code())]
1577 pub fn set_code(
1578 origin: OriginFor<T>,
1579 dest: H160,
1580 code_hash: sp_core::H256,
1581 ) -> DispatchResult {
1582 ensure_root(origin)?;
1583 <AccountInfoOf<T>>::try_mutate(&dest, |account| {
1584 let Some(account) = account else {
1585 return Err(<Error<T>>::ContractNotFound.into());
1586 };
1587
1588 let AccountType::Contract(ref mut contract) = account.account_type else {
1589 return Err(<Error<T>>::ContractNotFound.into());
1590 };
1591
1592 <CodeInfo<T>>::increment_refcount(code_hash)?;
1593 let _ = <CodeInfo<T>>::decrement_refcount(contract.code_hash)?;
1594 contract.code_hash = code_hash;
1595
1596 Ok(())
1597 })
1598 }
1599
1600 #[pallet::call_index(7)]
1608 #[pallet::weight(<T as Config>::WeightInfo::map_account())]
1609 pub fn map_account(origin: OriginFor<T>) -> DispatchResult {
1610 #[cfg(not(feature = "runtime-benchmarks"))]
1611 if T::AutoMap::get() {
1612 return Ok(());
1613 }
1614
1615 Self::ensure_non_contract_if_signed(&origin)?;
1616 let origin = ensure_signed(origin)?;
1617 T::AddressMapper::map(&origin)
1618 }
1619
1620 #[pallet::call_index(13)]
1622 #[pallet::weight(<T as Config>::WeightInfo::batch_map_accounts(accounts.len() as u32))]
1623 pub fn batch_map_accounts(
1624 origin: OriginFor<T>,
1625 accounts: Vec<T::AccountId>,
1626 ) -> DispatchResultWithPostInfo {
1627 ensure_signed(origin.clone())?;
1628 Self::ensure_non_contract_if_signed(&origin)?;
1629
1630 let total = accounts.len() as u32;
1631 let mut mapped = 0;
1632
1633 for account_id in &accounts {
1634 let mut useful = false;
1635
1636 if T::AddressMapper::is_eth_derived(account_id) {
1637 } else {
1639 match T::AddressMapper::map_no_deposit(account_id) {
1640 Ok(()) => {
1641 useful = true;
1642 },
1643 Err(err) => log::debug!(
1644 target: LOG_TARGET,
1645 "Failed to map account {account_id:?}: {err:?}",
1646 ),
1647 }
1648
1649 match T::Currency::release_all(
1650 &HoldReason::AddressMapping.into(),
1651 account_id,
1652 Precision::BestEffort,
1653 ) {
1654 Ok(released) if !released.is_zero() => {
1657 useful = true;
1658 },
1659 Ok(_) => {},
1660 Err(err) => log::debug!(
1661 target: LOG_TARGET,
1662 "Failed to release mapping deposit for {account_id:?}: {err:?}",
1663 ),
1664 }
1665 }
1666
1667 if useful {
1668 mapped += 1;
1669 }
1670 }
1671
1672 if total == 0 || mapped == 0 {
1674 return Ok(Pays::Yes.into());
1675 }
1676
1677 let proportion_mapped = Perbill::from_rational(mapped, total);
1678 if proportion_mapped >= Perbill::from_percent(90) {
1679 Ok(Pays::No.into())
1680 } else {
1681 Ok(Pays::Yes.into())
1682 }
1683 }
1684
1685 #[pallet::call_index(8)]
1693 #[pallet::weight(<T as Config>::WeightInfo::unmap_account())]
1694 pub fn unmap_account(origin: OriginFor<T>) -> DispatchResult {
1695 #[cfg(not(feature = "runtime-benchmarks"))]
1696 ensure!(!T::AutoMap::get(), <Error<T>>::AutoMappingEnabled);
1697 let origin = ensure_signed(origin)?;
1698 T::AddressMapper::unmap(&origin)
1699 }
1700
1701 #[pallet::call_index(9)]
1707 #[pallet::weight({
1708 let dispatch_info = call.get_dispatch_info();
1709 (
1710 <T as Config>::WeightInfo::dispatch_as_fallback_account().saturating_add(dispatch_info.call_weight),
1711 dispatch_info.class
1712 )
1713 })]
1714 pub fn dispatch_as_fallback_account(
1715 mut origin: OriginFor<T>,
1716 call: Box<<T as Config>::RuntimeCall>,
1717 ) -> DispatchResultWithPostInfo {
1718 Self::ensure_non_contract_if_signed(&origin)?;
1719 let account_id = origin.as_signer().ok_or(DispatchError::BadOrigin)?;
1720 let unmapped_account = T::AddressMapper::to_fallback_account_id(
1721 &T::AddressMapper::to_address(&account_id),
1722 );
1723 origin.set_caller_from(RawOrigin::Signed(unmapped_account));
1724 call.dispatch(origin)
1725 }
1726 }
1727}
1728
1729fn dispatch_result<R>(
1731 result: Result<R, DispatchError>,
1732 weight_consumed: Weight,
1733 base_weight: Weight,
1734) -> DispatchResultWithPostInfo {
1735 let post_info = PostDispatchInfo {
1736 actual_weight: Some(weight_consumed.saturating_add(base_weight)),
1737 pays_fee: Default::default(),
1738 };
1739
1740 result
1741 .map(|_| post_info)
1742 .map_err(|e| DispatchErrorWithPostInfo { post_info, error: e })
1743}
1744
1745impl<T: Config> Pallet<T> {
1746 pub fn bare_call(
1753 origin: OriginFor<T>,
1754 dest: H160,
1755 evm_value: U256,
1756 transaction_limits: TransactionLimits<T>,
1757 data: Vec<u8>,
1758 exec_config: &ExecConfig<T>,
1759 ) -> ContractResult<ExecReturnValue, BalanceOf<T>> {
1760 let mut transaction_meter = match TransactionMeter::new(transaction_limits) {
1761 Ok(transaction_meter) => transaction_meter,
1762 Err(error) => return ContractResult { result: Err(error), ..Default::default() },
1763 };
1764 let mut storage_deposit = Default::default();
1765
1766 let try_call = || {
1767 let origin = ExecOrigin::from_runtime_origin(origin)?;
1768 let result = ExecStack::<T, ContractBlob<T>>::run_call(
1769 origin.clone(),
1770 dest,
1771 &mut transaction_meter,
1772 evm_value,
1773 data,
1774 &exec_config,
1775 )?;
1776
1777 storage_deposit = transaction_meter
1778 .execute_postponed_deposits(&origin, &exec_config)
1779 .inspect_err(|err| {
1780 log::debug!(target: LOG_TARGET, "Failed to transfer deposit: {err:?}");
1781 })?;
1782
1783 Ok(result)
1784 };
1785 let result = Self::run_guarded(try_call);
1786
1787 log::trace!(target: LOG_TARGET, "Bare call ends: \
1788 result={result:?}, \
1789 weight_consumed={:?}, \
1790 weight_required={:?}, \
1791 storage_deposit={:?}, \
1792 gas_consumed={:?}, \
1793 max_storage_deposit={:?}",
1794 transaction_meter.weight_consumed(),
1795 transaction_meter.weight_required(),
1796 storage_deposit,
1797 transaction_meter.total_consumed_gas(),
1798 transaction_meter.deposit_required()
1799 );
1800
1801 ContractResult {
1802 result: result.map_err(|r| r.error),
1803 weight_consumed: transaction_meter.weight_consumed(),
1804 weight_required: transaction_meter.weight_required(),
1805 storage_deposit,
1806 gas_consumed: transaction_meter.total_consumed_gas(),
1807 max_storage_deposit: transaction_meter.deposit_required(),
1808 }
1809 }
1810
1811 pub fn prepare_dry_run(account: &T::AccountId) {
1817 frame_system::Pallet::<T>::inc_account_nonce(account);
1820 }
1821
1822 pub fn bare_instantiate(
1828 origin: OriginFor<T>,
1829 evm_value: U256,
1830 transaction_limits: TransactionLimits<T>,
1831 code: Code,
1832 data: Vec<u8>,
1833 salt: Option<[u8; 32]>,
1834 exec_config: &ExecConfig<T>,
1835 ) -> ContractResult<InstantiateReturnValue, BalanceOf<T>> {
1836 let mut transaction_meter = match TransactionMeter::new(transaction_limits) {
1837 Ok(transaction_meter) => transaction_meter,
1838 Err(error) => return ContractResult { result: Err(error), ..Default::default() },
1839 };
1840
1841 let mut storage_deposit = Default::default();
1842
1843 let try_instantiate = || {
1844 let instantiate_account = T::InstantiateOrigin::ensure_origin(origin.clone())?;
1845
1846 if_tracing(|t| t.instantiate_code(&code, salt.as_ref()));
1847 let executable = match code {
1848 Code::Upload(code) if code.starts_with(&polkavm_common::program::BLOB_MAGIC) => {
1849 let upload_account = T::UploadOrigin::ensure_origin(origin)?;
1850 let executable = Self::try_upload_code(
1851 upload_account,
1852 code,
1853 BytecodeType::Pvm,
1854 &mut transaction_meter,
1855 &exec_config,
1856 )?;
1857 executable
1858 },
1859 Code::Upload(code) => {
1860 if T::AllowEVMBytecode::get() {
1861 ensure!(data.is_empty(), <Error<T>>::EvmConstructorNonEmptyData);
1862 let origin = T::UploadOrigin::ensure_origin(origin)?;
1863 let executable = ContractBlob::from_evm_init_code(code, origin)?;
1864 executable
1865 } else {
1866 return Err(<Error<T>>::CodeRejected.into());
1867 }
1868 },
1869 Code::Existing(code_hash) => {
1870 let executable = ContractBlob::from_storage(code_hash, &mut transaction_meter)?;
1871 ensure!(executable.code_info().is_pvm(), <Error<T>>::EvmConstructedFromHash);
1872 executable
1873 },
1874 };
1875 let instantiate_origin = ExecOrigin::from_account_id(instantiate_account.clone());
1876 let result = ExecStack::<T, ContractBlob<T>>::run_instantiate(
1877 instantiate_account,
1878 executable,
1879 &mut transaction_meter,
1880 evm_value,
1881 data,
1882 salt.as_ref(),
1883 &exec_config,
1884 );
1885
1886 storage_deposit = transaction_meter
1887 .execute_postponed_deposits(&instantiate_origin, &exec_config)
1888 .inspect_err(|err| {
1889 log::debug!(target: LOG_TARGET, "Failed to transfer deposit: {err:?}");
1890 })?;
1891 result
1892 };
1893 let output = Self::run_guarded(try_instantiate);
1894
1895 log::trace!(target: LOG_TARGET, "Bare instantiate ends: weight_consumed={:?}\
1896 weight_required={:?} \
1897 storage_deposit={:?} \
1898 gas_consumed={:?} \
1899 max_storage_deposit={:?}",
1900 transaction_meter.weight_consumed(),
1901 transaction_meter.weight_required(),
1902 storage_deposit,
1903 transaction_meter.total_consumed_gas(),
1904 transaction_meter.deposit_required()
1905 );
1906
1907 ContractResult {
1908 result: output
1909 .map(|(addr, result)| InstantiateReturnValue { result, addr })
1910 .map_err(|e| e.error),
1911 weight_consumed: transaction_meter.weight_consumed(),
1912 weight_required: transaction_meter.weight_required(),
1913 storage_deposit,
1914 gas_consumed: transaction_meter.total_consumed_gas(),
1915 max_storage_deposit: transaction_meter.deposit_required(),
1916 }
1917 }
1918
1919 pub fn eth_estimate_gas(
1931 tx: GenericTransaction,
1932 config: DryRunConfig<<<T as Config>::Time as Time>::Moment>,
1933 ) -> Result<U256, EthTransactError>
1934 where
1935 T::Nonce: Into<U256> + TryFrom<U256>,
1936 CallOf<T>: SetWeightLimit,
1937 {
1938 log::debug!(target: LOG_TARGET, "eth_estimate_gas: {tx:?}");
1939
1940 let mut low = U256::zero();
1941 let mut high = Self::evm_block_gas_limit();
1942
1943 log::trace!(target: LOG_TARGET, "eth_estimate_gas starting with low={low}, high={high}");
1944
1945 let perform_balance_checks = if let Some(gas_limit) = tx.gas {
1949 high = gas_limit;
1950 log::trace!(target: LOG_TARGET, "eth_estimate_gas high limited by the gas limit high={high}");
1951 true
1952 } else {
1953 false
1954 };
1955
1956 let fee_cap = tx.max_fee_per_gas.or(tx.gas_price);
1958 if let (Some(fee_cap), Some(from), true) = (fee_cap, tx.from, perform_balance_checks) {
1959 let mut available_balance = Self::evm_balance(&from);
1960 if let Some(value) = tx.value {
1961 available_balance = available_balance.checked_sub(value).ok_or_else(|| {
1962 EthTransactError::Message("insufficient funds for value transfer".into())
1963 })?;
1964 }
1965 if let Some(allowance) = available_balance.checked_div(fee_cap) {
1966 if high > allowance && allowance != U256::zero() {
1967 log::trace!(target: LOG_TARGET, "eth_estimate_gas high limited by the user's allowance high={high} allowance={allowance}");
1968 high = allowance
1969 }
1970 }
1971 }
1972
1973 let dry_run_results = [high, Self::evm_max_extrinsic_weight_in_gas()].map(|gas_limit| {
1981 let mut transaction = tx.clone();
1982 transaction.gas = Some(gas_limit);
1983 let dry_run_config = config.clone().with_perform_balance_checks(perform_balance_checks);
1984 let eth_transact_result = with_transaction(|| {
1985 TransactionOutcome::Rollback(Ok::<_, DispatchError>(Self::dry_run_eth_transact(
1986 transaction,
1987 dry_run_config,
1988 )))
1989 })
1990 .expect("Rollback shouldn't error out");
1991 (gas_limit, eth_transact_result)
1992 });
1993 let (gas_limit, first_dry_run_result) = match dry_run_results {
1994 [(gas_limit1, Ok(dry_run_result1)), (gas_limit2, Ok(dry_run_result2))] => {
1995 if dry_run_result2.eth_gas >= gas_limit2 {
1996 (gas_limit1, dry_run_result1)
1997 } else {
1998 (gas_limit2, dry_run_result2)
1999 }
2000 },
2001 [(gas_limit, Ok(dry_run_result)), (_, Err(_))] |
2002 [(_, Err(_)), (gas_limit, Ok(dry_run_result))] => (gas_limit, dry_run_result),
2003 [(_, Err(err)), (_, Err(..))] => return Err(err),
2004 };
2005 log::trace!(
2006 target: LOG_TARGET,
2007 "eth_estimate_gas first dry run succeeded with gas_limit={} consumed={}",
2008 gas_limit,
2009 first_dry_run_result.eth_gas
2010 );
2011 low = first_dry_run_result.eth_gas;
2012 high = gas_limit;
2013
2014 while low + U256::one() < high {
2015 log::trace!(target: LOG_TARGET, "eth_estimate_gas estimation iteration with low={low} high={high}");
2016 let error_ratio = high
2017 .checked_sub(low)
2018 .and_then(|value| value.checked_mul(U256::from(1000)))
2019 .and_then(|value| value.checked_div(high))
2020 .ok_or_else(|| {
2021 EthTransactError::Message(
2022 "failed to calculate error ratio in gas estimation".into(),
2023 )
2024 })?;
2025 if error_ratio <= U256::from(15) {
2026 log::trace!(
2027 target: LOG_TARGET,
2028 "eth_estimate_gas finished due to error ratio being less than 1.5% high={}",
2029 high
2030 );
2031 break;
2032 }
2033
2034 let mut midpoint = high
2035 .checked_sub(low)
2036 .and_then(|value| value.checked_div(U256::from(2)))
2037 .and_then(|value| value.checked_add(low))
2038 .ok_or_else(|| {
2039 EthTransactError::Message(
2040 "failed to calculate midpoint in gas estimation".into(),
2041 )
2042 })?;
2043
2044 if let Some(other_midpoint) = low.checked_mul(U256::from(2)) {
2045 if other_midpoint != U256::zero() {
2046 midpoint = midpoint.min(other_midpoint)
2047 }
2048 };
2049
2050 let mut transaction = tx.clone();
2051 transaction.gas = Some(midpoint);
2052 let dry_run_config = config.clone().with_perform_balance_checks(perform_balance_checks);
2053 let dry_run_result = with_transaction(|| {
2054 TransactionOutcome::Rollback(Ok::<_, DispatchError>(Self::dry_run_eth_transact(
2055 transaction,
2056 dry_run_config,
2057 )))
2058 })
2059 .expect("Rollback shouldn't error out");
2060 log::trace!(target: LOG_TARGET, "eth_estimate_gas dry run result with midpoint={midpoint} is dry_run_result={dry_run_result:?}");
2061 match dry_run_result {
2062 Ok(..) => {
2063 log::trace!(target: LOG_TARGET, "eth_estimate_gas dry run succeeded, new high={midpoint}");
2064 high = midpoint
2065 },
2066 Err(..) => {
2067 log::trace!(target: LOG_TARGET, "eth_estimate_gas dry run failed, new low={midpoint}");
2068 low = midpoint
2069 },
2070 }
2071 }
2072
2073 log::trace!(target: LOG_TARGET, "eth_estimate_gas completed. high={high}");
2074 Ok(high)
2075 }
2076
2077 pub fn eth_pre_dispatch_weight(transaction_encoded: Vec<u8>) -> Result<Weight, EthTransactError>
2085 where
2086 CallOf<T>: SetWeightLimit,
2087 {
2088 let signed_tx =
2089 crate::evm::TransactionSigned::decode(&transaction_encoded).map_err(|err| {
2090 EthTransactError::Message(format!("Failed to decode transaction: {err:?}"))
2091 })?;
2092 let signer_addr = signed_tx.recover_eth_address().map_err(|err| {
2093 EthTransactError::Message(format!("Failed to recover signer: {err:?}"))
2094 })?;
2095 let tx =
2096 GenericTransaction::from_signed(signed_tx, Self::evm_base_fee(), Some(signer_addr));
2097 let encoded_len = T::FeeInfo::encoded_len(
2098 crate::Call::<T>::eth_transact { payload: transaction_encoded.clone() }.into(),
2099 );
2100 let call_info = tx
2101 .into_call::<T>(CreateCallMode::ExtrinsicExecution(encoded_len, transaction_encoded))
2102 .map_err(|err| EthTransactError::Message(format!("Invalid call: {err:?}")))?;
2103 let info = T::FeeInfo::dispatch_info(&call_info.call);
2104
2105 Ok(frame_system::calculate_consumed_extrinsic_weight::<CallOf<T>>(
2106 &T::BlockWeights::get(),
2107 &info,
2108 call_info.encoded_len as usize,
2109 ))
2110 }
2111
2112 pub fn dry_run_eth_transact(
2118 mut tx: GenericTransaction,
2119 mut dry_run_config: DryRunConfig<<<T as Config>::Time as Time>::Moment>,
2120 ) -> Result<EthTransactInfo<BalanceOf<T>>, EthTransactError>
2121 where
2122 T::Nonce: Into<U256> + TryFrom<U256>,
2123 CallOf<T>: SetWeightLimit,
2124 {
2125 log::debug!(target: LOG_TARGET, "dry_run_eth_transact: {tx:?}");
2126
2127 let origin = T::AddressMapper::to_account_id(&tx.from.unwrap_or_default());
2128 Self::prepare_dry_run(&origin);
2129
2130 if let Some(overrides) = dry_run_config.state_overrides.take() {
2131 state_overrides::apply_state_overrides::<T>(overrides)?;
2132 }
2133
2134 let base_fee = Self::evm_base_fee();
2135 let effective_gas_price = tx.effective_gas_price(base_fee).unwrap_or(base_fee);
2136
2137 if effective_gas_price < base_fee {
2138 Err(EthTransactError::Message(format!(
2139 "Effective gas price {effective_gas_price:?} lower than base fee {base_fee:?}"
2140 )))?;
2141 }
2142
2143 if tx.nonce.is_none() {
2144 tx.nonce = Some(<System<T>>::account_nonce(&origin).into());
2145 }
2146 if tx.chain_id.is_none() {
2147 tx.chain_id = Some(T::ChainId::get().into());
2148 }
2149
2150 tx.gas_price = Some(effective_gas_price);
2152 tx.max_priority_fee_per_gas = Some(0.into());
2155 if tx.max_fee_per_gas.is_none() {
2156 tx.max_fee_per_gas = Some(effective_gas_price);
2157 }
2158
2159 let gas = tx.gas;
2160 if tx.gas.is_none() {
2161 tx.gas = Some(Self::evm_block_gas_limit());
2162 }
2163 if tx.r#type.is_none() {
2164 tx.r#type = Some(TYPE_EIP1559.into());
2165 }
2166
2167 let value = tx.value.unwrap_or_default();
2169 let input = tx.input.clone().to_vec();
2170 let from = tx.from;
2171 let to = tx.to;
2172
2173 let mut call_info = tx
2176 .into_call::<T>(CreateCallMode::DryRun)
2177 .map_err(|err| EthTransactError::Message(format!("Invalid call: {err:?}")))?;
2178
2179 let base_info = T::FeeInfo::base_dispatch_info(&mut call_info.call);
2183 let base_weight = base_info.total_weight();
2184 let perform_balance_checks = dry_run_config.perform_balance_checks;
2185 let exec_config =
2186 ExecConfig::new_eth_tx(effective_gas_price, call_info.encoded_len, base_weight)
2187 .with_dry_run(dry_run_config);
2188
2189 let fees = call_info.tx_fee.saturating_add(call_info.storage_deposit);
2191 if let Some(from) = &from {
2192 let fees = if gas.is_some() && matches!(perform_balance_checks, Some(true)) {
2193 fees
2194 } else {
2195 Zero::zero()
2196 };
2197 let balance = Self::evm_balance(from);
2198 if balance < Pallet::<T>::convert_native_to_evm(fees).saturating_add(value) {
2199 return Err(EthTransactError::Message(format!(
2200 "insufficient funds for gas * price + value ({fees:?}): address {from:?} have {balance:?} (supplied gas {gas:?})",
2201 )));
2202 }
2203 }
2204
2205 T::FeeInfo::deposit_txfee(T::Currency::issue(fees));
2208
2209 let extract_error = |err| {
2210 if err == Error::<T>::StorageDepositNotEnoughFunds.into() {
2211 Err(EthTransactError::Message(format!("Not enough gas supplied: {err:?}")))
2212 } else {
2213 Err(EthTransactError::Message(format!("failed to run contract: {err:?}")))
2214 }
2215 };
2216
2217 let transaction_limits = TransactionLimits::EthereumGas {
2218 eth_gas_limit: call_info.eth_gas_limit.saturated_into(),
2219 weight_limit: Self::evm_max_extrinsic_weight(),
2220 eth_tx_info: EthTxInfo::new(call_info.encoded_len, base_weight),
2221 };
2222
2223 let mut dry_run = match to {
2225 Some(dest) => {
2227 if dest == RUNTIME_PALLETS_ADDR {
2228 let Ok(dispatch_call) = <CallOf<T>>::decode(&mut &input[..]) else {
2229 return Err(EthTransactError::Message(format!(
2230 "Failed to decode pallet-call {input:?}"
2231 )));
2232 };
2233
2234 if let Err(result) =
2235 dispatch_call.clone().dispatch(RawOrigin::Signed(origin).into())
2236 {
2237 return Err(EthTransactError::Message(format!(
2238 "Failed to dispatch call: {:?}",
2239 result.error,
2240 )));
2241 };
2242
2243 Default::default()
2244 } else {
2245 let result = crate::Pallet::<T>::bare_call(
2247 OriginFor::<T>::signed(origin),
2248 dest,
2249 value,
2250 transaction_limits,
2251 input.clone(),
2252 &exec_config,
2253 );
2254
2255 let data = match result.result {
2256 Ok(return_value) => {
2257 if return_value.did_revert() {
2258 return Err(EthTransactError::Data(return_value.data));
2259 }
2260 return_value.data
2261 },
2262 Err(err) => {
2263 log::debug!(target: LOG_TARGET, "Failed to execute call: {err:?}");
2264 return extract_error(err);
2265 },
2266 };
2267
2268 EthTransactInfo {
2269 weight_required: result.weight_required,
2270 storage_deposit: result.storage_deposit.charge_or_zero(),
2271 max_storage_deposit: result.max_storage_deposit.charge_or_zero(),
2272 data,
2273 eth_gas: Default::default(),
2274 }
2275 }
2276 },
2277 None => {
2279 let (code, data) = if input.starts_with(&polkavm_common::program::BLOB_MAGIC) {
2281 extract_code_and_data(&input).unwrap_or_else(|| (input, Default::default()))
2282 } else {
2283 (input, vec![])
2284 };
2285
2286 let result = crate::Pallet::<T>::bare_instantiate(
2288 OriginFor::<T>::signed(origin),
2289 value,
2290 transaction_limits,
2291 Code::Upload(code.clone()),
2292 data.clone(),
2293 None,
2294 &exec_config,
2295 );
2296
2297 let returned_data = match result.result {
2298 Ok(return_value) => {
2299 if return_value.result.did_revert() {
2300 return Err(EthTransactError::Data(return_value.result.data));
2301 }
2302 return_value.result.data
2303 },
2304 Err(err) => {
2305 log::debug!(target: LOG_TARGET, "Failed to instantiate: {err:?}");
2306 return extract_error(err);
2307 },
2308 };
2309
2310 EthTransactInfo {
2311 weight_required: result.weight_required,
2312 storage_deposit: result.storage_deposit.charge_or_zero(),
2313 max_storage_deposit: result.max_storage_deposit.charge_or_zero(),
2314 data: returned_data,
2315 eth_gas: Default::default(),
2316 }
2317 },
2318 };
2319
2320 call_info.call.set_weight_limit(dry_run.weight_required);
2322
2323 let total_weight = T::FeeInfo::dispatch_info(&call_info.call).total_weight();
2325 let max_weight = Self::evm_max_extrinsic_weight();
2326 if total_weight.any_gt(max_weight) {
2327 log::debug!(target: LOG_TARGET, "Transaction weight estimate exceeds extrinsic maximum: \
2328 total_weight={total_weight:?} \
2329 max_weight={max_weight:?}",
2330 );
2331
2332 Err(EthTransactError::Message(format!(
2333 "\
2334 The transaction consumes more than the allowed weight. \
2335 needed={total_weight} \
2336 allowed={max_weight} \
2337 overweight_by={}\
2338 ",
2339 total_weight.saturating_sub(max_weight),
2340 )))?;
2341 }
2342
2343 let transaction_fee = T::FeeInfo::tx_fee(call_info.encoded_len, &call_info.call);
2345 let available_fee = T::FeeInfo::remaining_txfee();
2346 if transaction_fee > available_fee {
2347 Err(EthTransactError::Message(format!(
2348 "Not enough gas supplied: Off by: {:?}",
2349 transaction_fee.saturating_sub(available_fee),
2350 )))?;
2351 }
2352
2353 let total_cost = transaction_fee.saturating_add(dry_run.max_storage_deposit);
2354 let total_cost_wei = Pallet::<T>::convert_native_to_evm(total_cost);
2355 let (mut eth_gas, rest) = total_cost_wei.div_mod(base_fee);
2356 if !rest.is_zero() {
2357 eth_gas = eth_gas.saturating_add(1_u32.into());
2358 }
2359
2360 log::debug!(target: LOG_TARGET, "\
2361 dry_run_eth_transact finished: \
2362 weight_limit={}, \
2363 total_weight={total_weight}, \
2364 max_weight={max_weight}, \
2365 weight_left={}, \
2366 eth_gas={eth_gas}, \
2367 encoded_len={}, \
2368 tx_fee={transaction_fee:?}, \
2369 storage_deposit={:?}, \
2370 max_storage_deposit={:?}\
2371 ",
2372 dry_run.weight_required,
2373 max_weight.saturating_sub(total_weight),
2374 call_info.encoded_len,
2375 dry_run.storage_deposit,
2376 dry_run.max_storage_deposit,
2377
2378 );
2379 dry_run.eth_gas = eth_gas;
2380 Ok(dry_run)
2381 }
2382
2383 pub fn evm_balance(address: &H160) -> U256 {
2387 let balance = AccountInfo::<T>::balance_of((*address).into());
2388 Self::convert_native_to_evm(balance)
2389 }
2390
2391 pub fn eth_block() -> EthBlock {
2393 EthereumBlock::<T>::get()
2394 }
2395
2396 pub fn eth_block_hash_from_number(number: U256) -> Option<H256> {
2403 let number = BlockNumberFor::<T>::try_from(number).ok()?;
2404 let hash = <BlockHash<T>>::get(number);
2405 if hash == H256::zero() { None } else { Some(hash) }
2406 }
2407
2408 pub fn eth_receipt_data() -> Vec<ReceiptGasInfo> {
2410 ReceiptInfoData::<T>::get()
2411 }
2412
2413 pub fn set_evm_balance(address: &H160, evm_value: U256) -> Result<(), Error<T>> {
2419 let (balance, dust) = Self::new_balance_with_dust(evm_value)
2420 .map_err(|_| <Error<T>>::BalanceConversionFailed)?;
2421 let account_id = T::AddressMapper::to_account_id(&address);
2422 T::Currency::set_balance(&account_id, balance);
2423 AccountInfoOf::<T>::mutate(&address, |account| {
2424 if let Some(account) = account {
2425 account.dust = dust;
2426 } else {
2427 *account = Some(AccountInfo { dust, ..Default::default() });
2428 }
2429 });
2430
2431 Ok(())
2432 }
2433
2434 pub fn new_balance_with_dust(
2438 evm_value: U256,
2439 ) -> Result<(BalanceOf<T>, u32), BalanceConversionError> {
2440 let ed = T::Currency::minimum_balance();
2441 let balance_with_dust = BalanceWithDust::<BalanceOf<T>>::from_value::<T>(evm_value)?;
2442 let (value, dust) = balance_with_dust.deconstruct();
2443
2444 Ok((ed.saturating_add(value), dust))
2445 }
2446
2447 pub fn evm_nonce(address: &H160) -> u32
2449 where
2450 T::Nonce: Into<u32>,
2451 {
2452 let account = T::AddressMapper::to_account_id(&address);
2453 System::<T>::account_nonce(account).into()
2454 }
2455
2456 pub fn evm_block_gas_limit() -> U256 {
2458 u64::MAX.into()
2465 }
2466
2467 pub fn evm_max_extrinsic_weight_in_gas() -> U256 {
2469 let max_extrinsic_fee = T::FeeInfo::weight_to_fee(&Self::evm_max_extrinsic_weight());
2470 let gas_scale: BalanceOf<T> = T::GasScale::get().into();
2471 (max_extrinsic_fee / gas_scale).into()
2472 }
2473
2474 pub fn evm_max_extrinsic_weight() -> Weight {
2476 let factor = <T as Config>::MaxEthExtrinsicWeight::get();
2477 let max_weight = <T as frame_system::Config>::BlockWeights::get()
2478 .get(DispatchClass::Normal)
2479 .max_extrinsic
2480 .unwrap_or_else(|| <T as frame_system::Config>::BlockWeights::get().max_block);
2481 Weight::from_parts(
2482 factor.saturating_mul_int(max_weight.ref_time()),
2483 factor.saturating_mul_int(max_weight.proof_size()),
2484 )
2485 }
2486
2487 pub fn evm_base_fee() -> U256 {
2489 let gas_scale = <T as Config>::GasScale::get();
2490 let multiplier = T::FeeInfo::next_fee_multiplier();
2491 multiplier
2492 .saturating_mul_int::<u128>(T::NativeToEthRatio::get().into())
2493 .saturating_mul(gas_scale.saturated_into())
2494 .into()
2495 }
2496
2497 pub fn evm_tracer(tracer_type: TracerType) -> Tracer<T>
2499 where
2500 T::Nonce: Into<u32>,
2501 {
2502 match tracer_type {
2503 TracerType::CallTracer(config) => CallTracer::new(config.unwrap_or_default()).into(),
2504 TracerType::PrestateTracer(config) => {
2505 PrestateTracer::new(config.unwrap_or_default()).into()
2506 },
2507 TracerType::ExecutionTracer(config) => {
2508 ExecutionTracer::new(config.unwrap_or_default()).into()
2509 },
2510 }
2511 }
2512
2513 pub fn bare_upload_code(
2517 origin: OriginFor<T>,
2518 code: Vec<u8>,
2519 storage_deposit_limit: BalanceOf<T>,
2520 ) -> CodeUploadResult<BalanceOf<T>> {
2521 let origin = T::UploadOrigin::ensure_origin(origin)?;
2522
2523 let bytecode_type = if code.starts_with(&polkavm_common::program::BLOB_MAGIC) {
2524 BytecodeType::Pvm
2525 } else {
2526 if !T::AllowEVMBytecode::get() {
2527 return Err(<Error<T>>::CodeRejected.into());
2528 }
2529 BytecodeType::Evm
2530 };
2531
2532 let mut meter = TransactionMeter::new(TransactionLimits::WeightAndDeposit {
2533 weight_limit: Default::default(),
2534 deposit_limit: storage_deposit_limit,
2535 })?;
2536
2537 let module = Self::try_upload_code(
2538 origin,
2539 code,
2540 bytecode_type,
2541 &mut meter,
2542 &ExecConfig::new_substrate_tx(),
2543 )?;
2544 Ok(CodeUploadReturnValue {
2545 code_hash: *module.code_hash(),
2546 deposit: meter.deposit_consumed().charge_or_zero(),
2547 })
2548 }
2549
2550 pub fn get_storage(address: H160, key: [u8; 32]) -> GetStorageResult {
2552 let contract_info =
2553 AccountInfo::<T>::load_contract(&address).ok_or(ContractAccessError::DoesntExist)?;
2554
2555 let maybe_value = contract_info.read(&Key::from_fixed(key));
2556 Ok(maybe_value)
2557 }
2558
2559 pub fn get_immutables(address: H160) -> Option<ImmutableData> {
2563 let immutable_data = <ImmutableDataOf<T>>::get(address);
2564 immutable_data
2565 }
2566
2567 pub fn set_immutables(address: H160, data: ImmutableData) -> Result<(), ContractAccessError> {
2575 AccountInfo::<T>::load_contract(&address).ok_or(ContractAccessError::DoesntExist)?;
2576 <ImmutableDataOf<T>>::insert(address, data);
2577 Ok(())
2578 }
2579
2580 pub fn get_storage_var_key(address: H160, key: Vec<u8>) -> GetStorageResult {
2582 let contract_info =
2583 AccountInfo::<T>::load_contract(&address).ok_or(ContractAccessError::DoesntExist)?;
2584
2585 let maybe_value = contract_info.read(
2586 &Key::try_from_var(key)
2587 .map_err(|_| ContractAccessError::KeyDecodingFailed)?
2588 .into(),
2589 );
2590 Ok(maybe_value)
2591 }
2592
2593 pub fn convert_native_to_evm(value: impl Into<BalanceWithDust<BalanceOf<T>>>) -> U256 {
2595 let (value, dust) = value.into().deconstruct();
2596 value
2597 .into()
2598 .saturating_mul(T::NativeToEthRatio::get().into())
2599 .saturating_add(dust.into())
2600 }
2601
2602 pub fn set_storage(address: H160, key: [u8; 32], value: Option<Vec<u8>>) -> SetStorageResult {
2612 let contract_info =
2613 AccountInfo::<T>::load_contract(&address).ok_or(ContractAccessError::DoesntExist)?;
2614
2615 contract_info
2616 .write(&Key::from_fixed(key), value, None, false)
2617 .map_err(ContractAccessError::StorageWriteFailed)
2618 }
2619
2620 pub fn set_storage_var_key(
2631 address: H160,
2632 key: Vec<u8>,
2633 value: Option<Vec<u8>>,
2634 ) -> SetStorageResult {
2635 let contract_info =
2636 AccountInfo::<T>::load_contract(&address).ok_or(ContractAccessError::DoesntExist)?;
2637
2638 contract_info
2639 .write(
2640 &Key::try_from_var(key)
2641 .map_err(|_| ContractAccessError::KeyDecodingFailed)?
2642 .into(),
2643 value,
2644 None,
2645 false,
2646 )
2647 .map_err(ContractAccessError::StorageWriteFailed)
2648 }
2649
2650 pub fn account_id() -> T::AccountId {
2652 use frame_support::PalletId;
2653 use sp_runtime::traits::AccountIdConversion;
2654 PalletId(*b"py/reviv").into_account_truncating()
2655 }
2656
2657 pub fn block_author() -> H160 {
2659 use frame_support::traits::FindAuthor;
2660
2661 let digest = <frame_system::Pallet<T>>::digest();
2662 let pre_runtime_digests = digest.logs.iter().filter_map(|d| d.as_pre_runtime());
2663
2664 T::FindAuthor::find_author(pre_runtime_digests)
2665 .map(|account_id| T::AddressMapper::to_address(&account_id))
2666 .unwrap_or_default()
2667 }
2668
2669 pub fn code(address: &H160) -> Vec<u8> {
2673 use precompiles::{All, Precompiles};
2674 if let Some(code) = <All<T>>::code(address.as_fixed_bytes()) {
2675 return code.into();
2676 }
2677 AccountInfo::<T>::load_contract(&address)
2678 .and_then(|contract| <PristineCode<T>>::get(contract.code_hash))
2679 .map(|code| code.into())
2680 .unwrap_or_default()
2681 }
2682
2683 pub fn try_upload_code(
2685 origin: T::AccountId,
2686 code: Vec<u8>,
2687 code_type: BytecodeType,
2688 meter: &mut TransactionMeter<T>,
2689 exec_config: &ExecConfig<T>,
2690 ) -> Result<ContractBlob<T>, DispatchError> {
2691 let mut module = match code_type {
2692 BytecodeType::Pvm => ContractBlob::from_pvm_code(code, origin)?,
2693 BytecodeType::Evm => ContractBlob::from_evm_runtime_code(code, origin)?,
2694 };
2695 module.store_code(exec_config, meter)?;
2696 Ok(module)
2697 }
2698
2699 fn run_guarded<R, F: FnOnce() -> Result<R, ExecError>>(f: F) -> Result<R, ExecError> {
2701 executing_contract::using_once(&mut false, || {
2702 executing_contract::with(|f| {
2703 if *f {
2705 return Err(())
2706 }
2707 *f = true;
2709 Ok(())
2710 })
2711 .expect("Returns `Ok` if called within `using_once`. It is syntactically obvious that this is the case; qed")
2712 .map_err(|_| <Error<T>>::ReenteredPallet.into())
2713 .map(|_| f())
2714 .and_then(|r| r)
2715 })
2716 }
2717
2718 fn charge_deposit(
2723 hold_reason: HoldReason,
2724 from: &T::AccountId,
2725 to: &T::AccountId,
2726 amount: BalanceOf<T>,
2727 exec_config: &ExecConfig<T>,
2728 ) -> DispatchResult {
2729 if amount.is_zero() {
2730 return Ok(());
2731 }
2732
2733 T::Deposit::charge_and_hold(hold_reason, exec_config.funds(from), to, amount)
2734 .map_err(|_| Error::<T>::StorageDepositNotEnoughFunds)?;
2735 Ok(())
2736 }
2737
2738 fn refund_deposit(
2743 hold_reason: HoldReason,
2744 from: &T::AccountId,
2745 dst: deposit_payment::Funds<T::AccountId>,
2746 amount: BalanceOf<T>,
2747 ) -> Result<(), DispatchError> {
2748 if amount.is_zero() {
2749 return Ok(());
2750 }
2751
2752 let to = match &dst {
2753 deposit_payment::Funds::Balance(to) | deposit_payment::Funds::TxFee(to) => *to,
2754 };
2755 let result = T::Deposit::refund_on_hold(hold_reason, from, dst, amount);
2756
2757 result.defensive_map_err(|err| {
2758 let available = T::Deposit::total_on_hold(hold_reason, from);
2759 if available < amount {
2760 log::error!(
2763 target: LOG_TARGET,
2764 "Failed to refund storage deposit {amount:?} from contract {from:?} to origin {to:?}. Not enough deposit: {available:?}. This is a bug.",
2765 );
2766 Error::<T>::StorageRefundNotEnoughFunds.into()
2767 } else {
2768 log::warn!(
2773 target: LOG_TARGET,
2774 "Failed to refund storage deposit {amount:?} from contract {from:?} to origin {to:?}: {err:?}. First remove locks (staking, governance) from the contracts account.",
2775 );
2776 Error::<T>::StorageRefundLocked.into()
2777 }
2778 })
2779 }
2780
2781 fn has_dust(value: U256) -> bool {
2783 value % U256::from(<T>::NativeToEthRatio::get()) != U256::zero()
2784 }
2785
2786 fn has_balance(value: U256) -> bool {
2788 value >= U256::from(<T>::NativeToEthRatio::get())
2789 }
2790
2791 #[cfg(any(feature = "runtime-benchmarks", feature = "try-runtime", test))]
2793 fn min_balance() -> BalanceOf<T> {
2794 <T::Currency as Inspect<AccountIdOf<T>>>::minimum_balance()
2795 }
2796
2797 fn deposit_event(event: Event<T>) {
2802 <frame_system::Pallet<T>>::deposit_event(<T as Config>::RuntimeEvent::from(event))
2803 }
2804
2805 fn ensure_eth_signed(origin: OriginFor<T>) -> Result<AccountIdOf<T>, DispatchError> {
2807 match <T as Config>::RuntimeOrigin::from(origin).into() {
2808 Ok(Origin::EthTransaction(signer)) => Ok(signer),
2809 _ => Err(BadOrigin.into()),
2810 }
2811 }
2812
2813 fn ensure_non_contract_if_signed(origin: &OriginFor<T>) -> DispatchResult {
2817 if DebugSettings::bypass_eip_3607::<T>() {
2818 return Ok(());
2819 }
2820 let Some(address) = origin
2821 .as_system_ref()
2822 .and_then(|o| o.as_signed())
2823 .map(<T::AddressMapper as AddressMapper<T>>::to_address)
2824 else {
2825 return Ok(());
2826 };
2827 if exec::is_precompile::<T, ContractBlob<T>>(&address) ||
2828 <AccountInfo<T>>::is_contract(&address)
2829 {
2830 log::debug!(
2831 target: crate::LOG_TARGET,
2832 "EIP-3607: reject tx as pre-compile or account exist at {address:?}",
2833 );
2834 Err(DispatchError::BadOrigin)
2835 } else {
2836 Ok(())
2837 }
2838 }
2839}
2840
2841pub const RUNTIME_PALLETS_ADDR: H160 =
2846 H160(hex_literal::hex!("6d6f646c70792f70616464720000000000000000"));
2847
2848environmental!(executing_contract: bool);
2850
2851sp_api::decl_runtime_apis! {
2852 #[api_version(1)]
2854 pub trait ReviveApi<AccountId, Balance, Nonce, BlockNumber, Moment> where
2855 AccountId: Codec,
2856 Balance: Codec,
2857 Nonce: Codec,
2858 BlockNumber: Codec,
2859 Moment: Codec,
2860 {
2861 fn eth_block() -> EthBlock;
2865
2866 fn eth_block_hash(number: U256) -> Option<H256>;
2868
2869 fn eth_receipt_data() -> Vec<ReceiptGasInfo>;
2875
2876 fn block_gas_limit() -> U256;
2878
2879 fn max_extrinsic_weight_in_gas() -> U256;
2881
2882 fn balance(address: H160) -> U256;
2884
2885 fn gas_price() -> U256;
2887
2888 fn nonce(address: H160) -> Nonce;
2890
2891 fn call(
2895 origin: AccountId,
2896 dest: H160,
2897 value: Balance,
2898 gas_limit: Option<Weight>,
2899 storage_deposit_limit: Option<Balance>,
2900 input_data: Vec<u8>,
2901 ) -> ContractResult<ExecReturnValue, Balance>;
2902
2903 fn instantiate(
2907 origin: AccountId,
2908 value: Balance,
2909 gas_limit: Option<Weight>,
2910 storage_deposit_limit: Option<Balance>,
2911 code: Code,
2912 data: Vec<u8>,
2913 salt: Option<[u8; 32]>,
2914 ) -> ContractResult<InstantiateReturnValue, Balance>;
2915
2916
2917 fn eth_transact(tx: GenericTransaction) -> Result<EthTransactInfo<Balance>, EthTransactError>;
2922
2923 fn eth_transact_with_config(
2927 tx: GenericTransaction,
2928 config: DryRunConfig<Moment>,
2929 ) -> Result<EthTransactInfo<Balance>, EthTransactError>;
2930
2931 fn eth_estimate_gas(
2937 tx: GenericTransaction,
2938 config: DryRunConfig<Moment>
2939 ) -> Result<U256, EthTransactError>;
2940
2941 fn eth_pre_dispatch_weight(tx: Vec<u8>) -> Result<Weight, EthTransactError>;
2943
2944 fn upload_code(
2948 origin: AccountId,
2949 code: Vec<u8>,
2950 storage_deposit_limit: Option<Balance>,
2951 ) -> CodeUploadResult<Balance>;
2952
2953 fn get_storage(
2959 address: H160,
2960 key: [u8; 32],
2961 ) -> GetStorageResult;
2962
2963 fn get_storage_var_key(
2969 address: H160,
2970 key: Vec<u8>,
2971 ) -> GetStorageResult;
2972
2973 fn trace_block(
2980 block: Block,
2981 config: TracerType
2982 ) -> Vec<(u32, Trace)>;
2983
2984 fn trace_tx(
2991 block: Block,
2992 tx_index: u32,
2993 config: TracerType
2994 ) -> Option<Trace>;
2995
2996 fn trace_call(tx: GenericTransaction, config: TracerType) -> Result<Trace, EthTransactError>;
3000
3001 fn trace_call_with_config(
3007 tx: GenericTransaction,
3008 tracer_type: TracerType,
3009 config: TracingConfig,
3010 ) -> Result<Trace, EthTransactError>;
3011
3012 fn block_author() -> H160;
3014
3015 fn address(account_id: AccountId) -> H160;
3017
3018 fn account_id(address: H160) -> AccountId;
3020
3021 fn runtime_pallets_address() -> H160;
3023
3024 fn code(address: H160) -> Vec<u8>;
3026
3027 fn new_balance_with_dust(balance: U256) -> Result<(Balance, u32), BalanceConversionError>;
3029 }
3030}
3031
3032#[macro_export]
3046macro_rules! impl_runtime_apis_plus_revive_traits {
3047 ($Runtime: ty, $Revive: ident, $Executive: ty, $EthExtra: ty, $($rest:tt)*) => {
3048
3049 type __ReviveMacroMoment = <<$Runtime as $crate::Config>::Time as $crate::Time>::Moment;
3050
3051 impl $crate::evm::runtime::SetWeightLimit for RuntimeCall {
3052 fn set_weight_limit(&mut self, new_weight_limit: Weight) -> Weight {
3053 use $crate::pallet::Call as ReviveCall;
3054 match self {
3055 Self::$Revive(
3056 ReviveCall::eth_call{ weight_limit, .. } |
3057 ReviveCall::eth_instantiate_with_code{ weight_limit, .. }
3058 ) => {
3059 let old = *weight_limit;
3060 *weight_limit = new_weight_limit;
3061 old
3062 },
3063 _ => Weight::default(),
3064 }
3065 }
3066 }
3067
3068 impl_runtime_apis! {
3069 $($rest)*
3070
3071
3072 impl pallet_revive::ReviveApi<Block, AccountId, Balance, Nonce, BlockNumber, __ReviveMacroMoment> for $Runtime
3073 {
3074 fn eth_block() -> $crate::EthBlock {
3075 $crate::Pallet::<Self>::eth_block()
3076 }
3077
3078 fn eth_block_hash(number: $crate::U256) -> Option<$crate::H256> {
3079 $crate::Pallet::<Self>::eth_block_hash_from_number(number)
3080 }
3081
3082 fn eth_receipt_data() -> Vec<$crate::ReceiptGasInfo> {
3083 $crate::Pallet::<Self>::eth_receipt_data()
3084 }
3085
3086 fn balance(address: $crate::H160) -> $crate::U256 {
3087 $crate::Pallet::<Self>::evm_balance(&address)
3088 }
3089
3090 fn block_author() -> $crate::H160 {
3091 $crate::Pallet::<Self>::block_author()
3092 }
3093
3094 fn block_gas_limit() -> $crate::U256 {
3095 $crate::Pallet::<Self>::evm_block_gas_limit()
3096 }
3097
3098 fn max_extrinsic_weight_in_gas() -> $crate::U256 {
3099 $crate::Pallet::<Self>::evm_max_extrinsic_weight_in_gas()
3100 }
3101
3102 fn gas_price() -> $crate::U256 {
3103 $crate::Pallet::<Self>::evm_base_fee()
3104 }
3105
3106 fn nonce(address: $crate::H160) -> Nonce {
3107 use $crate::AddressMapper;
3108 let account = <Self as $crate::Config>::AddressMapper::to_account_id(&address);
3109 $crate::frame_system::Pallet::<Self>::account_nonce(account)
3110 }
3111
3112 fn address(account_id: AccountId) -> $crate::H160 {
3113 use $crate::AddressMapper;
3114 <Self as $crate::Config>::AddressMapper::to_address(&account_id)
3115 }
3116
3117 fn eth_transact(
3118 tx: $crate::evm::GenericTransaction,
3119 ) -> Result<$crate::EthTransactInfo<Balance>, $crate::EthTransactError> {
3120 use $crate::{
3121 codec::Encode, evm::runtime::EthExtra, frame_support::traits::Get,
3122 sp_runtime::traits::TransactionExtension,
3123 sp_runtime::traits::Block as BlockT
3124 };
3125 $crate::Pallet::<Self>::dry_run_eth_transact(tx, Default::default())
3126 }
3127
3128 fn eth_transact_with_config(
3129 tx: $crate::evm::GenericTransaction,
3130 config: $crate::DryRunConfig<__ReviveMacroMoment>,
3131 ) -> Result<$crate::EthTransactInfo<Balance>, $crate::EthTransactError> {
3132 use $crate::{
3133 codec::Encode, evm::runtime::EthExtra, frame_support::traits::Get,
3134 sp_runtime::traits::TransactionExtension,
3135 sp_runtime::traits::Block as BlockT
3136 };
3137 $crate::Pallet::<Self>::dry_run_eth_transact(tx, config)
3138 }
3139
3140 fn eth_estimate_gas(
3141 tx: $crate::evm::GenericTransaction,
3142 config: $crate::DryRunConfig<__ReviveMacroMoment>,
3143 ) -> Result<$crate::U256, $crate::EthTransactError> {
3144 use $crate::{
3145 codec::Encode, evm::runtime::EthExtra, frame_support::traits::Get,
3146 sp_runtime::traits::TransactionExtension,
3147 sp_runtime::traits::Block as BlockT
3148 };
3149 $crate::Pallet::<Self>::eth_estimate_gas(tx, config)
3150 }
3151
3152 fn eth_pre_dispatch_weight(
3153 tx: Vec<u8>,
3154 ) -> Result<$crate::Weight, $crate::EthTransactError> {
3155 $crate::Pallet::<Self>::eth_pre_dispatch_weight(tx)
3156 }
3157
3158 fn call(
3159 origin: AccountId,
3160 dest: $crate::H160,
3161 value: Balance,
3162 weight_limit: Option<$crate::Weight>,
3163 storage_deposit_limit: Option<Balance>,
3164 input_data: Vec<u8>,
3165 ) -> $crate::ContractResult<$crate::ExecReturnValue, Balance> {
3166 use $crate::frame_support::traits::Get;
3167 let blockweights: $crate::BlockWeights =
3168 <Self as $crate::frame_system::Config>::BlockWeights::get();
3169
3170 $crate::Pallet::<Self>::prepare_dry_run(&origin);
3171 $crate::Pallet::<Self>::bare_call(
3172 <Self as $crate::frame_system::Config>::RuntimeOrigin::signed(origin),
3173 dest,
3174 $crate::Pallet::<Self>::convert_native_to_evm(value),
3175 $crate::TransactionLimits::WeightAndDeposit {
3176 weight_limit: weight_limit.unwrap_or(blockweights.max_block),
3177 deposit_limit: storage_deposit_limit.unwrap_or(u128::MAX),
3178 },
3179 input_data,
3180 &$crate::ExecConfig::new_substrate_tx().with_dry_run(Default::default()),
3181 )
3182 }
3183
3184 fn instantiate(
3185 origin: AccountId,
3186 value: Balance,
3187 weight_limit: Option<$crate::Weight>,
3188 storage_deposit_limit: Option<Balance>,
3189 code: $crate::Code,
3190 data: Vec<u8>,
3191 salt: Option<[u8; 32]>,
3192 ) -> $crate::ContractResult<$crate::InstantiateReturnValue, Balance> {
3193 use $crate::frame_support::traits::Get;
3194 let blockweights: $crate::BlockWeights =
3195 <Self as $crate::frame_system::Config>::BlockWeights::get();
3196
3197 $crate::Pallet::<Self>::prepare_dry_run(&origin);
3198 $crate::Pallet::<Self>::bare_instantiate(
3199 <Self as $crate::frame_system::Config>::RuntimeOrigin::signed(origin),
3200 $crate::Pallet::<Self>::convert_native_to_evm(value),
3201 $crate::TransactionLimits::WeightAndDeposit {
3202 weight_limit: weight_limit.unwrap_or(blockweights.max_block),
3203 deposit_limit: storage_deposit_limit.unwrap_or(u128::MAX),
3204 },
3205 code,
3206 data,
3207 salt,
3208 &$crate::ExecConfig::new_substrate_tx().with_dry_run(Default::default()),
3209 )
3210 }
3211
3212 fn upload_code(
3213 origin: AccountId,
3214 code: Vec<u8>,
3215 storage_deposit_limit: Option<Balance>,
3216 ) -> $crate::CodeUploadResult<Balance> {
3217 let origin =
3218 <Self as $crate::frame_system::Config>::RuntimeOrigin::signed(origin);
3219 $crate::Pallet::<Self>::bare_upload_code(
3220 origin,
3221 code,
3222 storage_deposit_limit.unwrap_or(u128::MAX),
3223 )
3224 }
3225
3226 fn get_storage_var_key(
3227 address: $crate::H160,
3228 key: Vec<u8>,
3229 ) -> $crate::GetStorageResult {
3230 $crate::Pallet::<Self>::get_storage_var_key(address, key)
3231 }
3232
3233 fn get_storage(address: $crate::H160, key: [u8; 32]) -> $crate::GetStorageResult {
3234 $crate::Pallet::<Self>::get_storage(address, key)
3235 }
3236
3237 fn trace_block(
3238 block: Block,
3239 tracer_type: $crate::evm::TracerType,
3240 ) -> Vec<(u32, $crate::evm::Trace)> {
3241 use $crate::{sp_runtime::traits::Block, tracing::trace};
3242
3243 if matches!(tracer_type, $crate::evm::TracerType::ExecutionTracer(_)) &&
3244 !$crate::DebugSettings::is_execution_tracing_enabled::<Runtime>()
3245 {
3246 return Default::default()
3247 }
3248
3249 let mut traces = vec![];
3250 let (header, extrinsics) = block.deconstruct();
3251 <$Executive>::initialize_block(&header);
3252 for (index, ext) in extrinsics.into_iter().enumerate() {
3253 let mut tracer = $crate::Pallet::<Self>::evm_tracer(tracer_type.clone());
3254 let t = tracer.as_tracing();
3255 let _ = trace(t, || <$Executive>::apply_extrinsic(ext));
3256
3257 if let Some(tx_trace) = tracer.collect_trace() {
3258 traces.push((index as u32, tx_trace));
3259 }
3260 }
3261
3262 traces
3263 }
3264
3265 fn trace_tx(
3266 block: Block,
3267 tx_index: u32,
3268 tracer_type: $crate::evm::TracerType,
3269 ) -> Option<$crate::evm::Trace> {
3270 use $crate::{sp_runtime::traits::Block, tracing::trace};
3271
3272 if matches!(tracer_type, $crate::evm::TracerType::ExecutionTracer(_)) &&
3273 !$crate::DebugSettings::is_execution_tracing_enabled::<Runtime>()
3274 {
3275 return None
3276 }
3277
3278 let mut tracer = $crate::Pallet::<Self>::evm_tracer(tracer_type);
3279 let (header, extrinsics) = block.deconstruct();
3280
3281 <$Executive>::initialize_block(&header);
3282 for (index, ext) in extrinsics.into_iter().enumerate() {
3283 if index as u32 == tx_index {
3284 let t = tracer.as_tracing();
3285 let _ = trace(t, || <$Executive>::apply_extrinsic(ext));
3286 break;
3287 } else {
3288 let _ = <$Executive>::apply_extrinsic(ext);
3289 }
3290 }
3291
3292 tracer.collect_trace()
3293 }
3294
3295 fn trace_call(
3296 tx: $crate::evm::GenericTransaction,
3297 tracer_type: $crate::evm::TracerType,
3298 ) -> Result<$crate::evm::Trace, $crate::EthTransactError> {
3299 use $crate::tracing::trace;
3300
3301 if matches!(tracer_type, $crate::evm::TracerType::ExecutionTracer(_)) &&
3302 !$crate::DebugSettings::is_execution_tracing_enabled::<Runtime>()
3303 {
3304 return Err($crate::EthTransactError::Message("Execution Tracing is disabled".into()))
3305 }
3306
3307 let mut tracer = $crate::Pallet::<Self>::evm_tracer(tracer_type.clone());
3308 let t = tracer.as_tracing();
3309
3310 t.watch_address(&tx.from.unwrap_or_default());
3311 t.watch_address(&$crate::Pallet::<Self>::block_author());
3312 let result = trace(t, || Self::eth_transact(tx));
3313
3314 if let Some(trace) = tracer.collect_trace() {
3315 Ok(trace)
3316 } else if let Err(err) = result {
3317 Err(err)
3318 } else {
3319 Ok($crate::Pallet::<Self>::evm_tracer(tracer_type).empty_trace())
3320 }
3321 }
3322
3323 fn trace_call_with_config(
3324 tx: $crate::evm::GenericTransaction,
3325 tracer_type: $crate::evm::TracerType,
3326 config: $crate::evm::TracingConfig,
3327 ) -> Result<$crate::evm::Trace, $crate::EthTransactError> {
3328 let $crate::evm::TracingConfig { state_overrides } = config;
3329
3330 if let Some(overrides) = state_overrides {
3331 $crate::state_overrides::apply_state_overrides::<Runtime>(overrides)?;
3332 }
3333
3334 Self::trace_call(tx, tracer_type)
3335 }
3336
3337 fn runtime_pallets_address() -> $crate::H160 {
3338 $crate::RUNTIME_PALLETS_ADDR
3339 }
3340
3341 fn code(address: $crate::H160) -> Vec<u8> {
3342 $crate::Pallet::<Self>::code(&address)
3343 }
3344
3345 fn account_id(address: $crate::H160) -> AccountId {
3346 use $crate::AddressMapper;
3347 <Self as $crate::Config>::AddressMapper::to_account_id(&address)
3348 }
3349
3350 fn new_balance_with_dust(balance: $crate::U256) -> Result<(Balance, u32), $crate::BalanceConversionError> {
3351 $crate::Pallet::<Self>::new_balance_with_dust(balance)
3352 }
3353 }
3354 }
3355 };
3356}