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 access_list;
26mod address;
27mod benchmarking;
28#[cfg(any(feature = "runtime-benchmarks", test))]
29pub mod call_builder;
30mod debug;
31mod deposit_payment;
32mod exec;
33mod impl_fungibles;
34mod limits;
35mod metering;
36mod primitives;
37#[doc(hidden)]
38pub mod runtime_api;
39#[doc(hidden)]
40pub mod state_overrides;
41mod storage;
42#[cfg(test)]
43mod tests;
44mod transient_storage;
45mod vm;
46mod weightinfo_extension;
47
48pub mod evm;
49pub mod migrations;
50pub mod mock;
51pub mod precompiles;
52pub mod test_utils;
53pub mod tracing;
54pub mod weights;
55
56use crate::{
57 access_list::{StorageAccessKind, Warmth},
58 evm::{
59 CallTracer, CreateCallMode, ExecutionTracer, GenericTransaction, PrestateTracer,
60 StateOverrideSet, TYPE_EIP1559, Tracer, TracerType,
61 block_hash::{CommittedReceiptLogs, EthereumBlockBuilderIR},
62 block_storage,
63 fees::InfoT as FeeInfo,
64 runtime::SetWeightLimit,
65 },
66 exec::{AccountIdOf, ExecError, Stack as ExecStack},
67 sp_runtime::TransactionOutcome,
68 storage::{AccountType, DeletionQueueManager},
69 tracing::if_tracing,
70 vm::{CodeInfo, RuntimeCosts, pvm::extract_code_and_data},
71 weightinfo_extension::OnFinalizeBlockParts,
72};
73use alloc::{boxed::Box, format, vec};
74use codec::{Codec, Decode, Encode};
75use environmental::*;
76use frame_support::{
77 BoundedVec,
78 dispatch::{
79 DispatchErrorWithPostInfo, DispatchResult, DispatchResultWithPostInfo, GetDispatchInfo,
80 Pays, PostDispatchInfo, RawOrigin,
81 },
82 ensure,
83 pallet_prelude::DispatchClass,
84 storage::with_transaction,
85 traits::{
86 ConstU32, ConstU64, DefensiveResult, EnsureOrigin, Get, IsSubType, IsType, OnUnbalanced,
87 OriginTrait,
88 fungible::{Balanced, Credit, Inspect, Mutate, MutateHold},
89 tokens::Balance,
90 },
91 weights::WeightMeter,
92};
93use frame_system::{
94 Pallet as System, ensure_signed,
95 pallet_prelude::{BlockNumberFor, OriginFor},
96};
97use pallet_revive_types::runtime_api::*;
98use scale_info::TypeInfo;
99use sp_runtime::{
100 AccountId32, DispatchError, FixedPointNumber, FixedU128, SaturatedConversion,
101 traits::{
102 BadOrigin, Bounded, Convert, Dispatchable, Saturating, UniqueSaturatedFrom,
103 UniqueSaturatedInto, Zero,
104 },
105};
106
107pub use crate::{
108 address::{AccountId32Mapper, AddressMapper, AutoMapper, TestAccountMapper, create1, create2},
109 debug::DebugSettings,
110 deposit_payment::{Deposit, PGasDeposit},
111 evm::{Address as EthAddress, Block as EthBlock, block_hash::ReceiptGasInfo},
112 exec::{
113 CallResources, DelegateInfo, Executable, Key, MomentOf, Origin as ExecOrigin,
114 ReentrancyProtection,
115 },
116 limits::TRANSIENT_STORAGE_BYTES as TRANSIENT_STORAGE_LIMIT,
117 metering::{
118 EthTxInfo, FrameMeter, ResourceMeter, Token as WeightToken, TransactionLimits,
119 TransactionMeter,
120 },
121 pallet::{genesis, *},
122 storage::{AccountInfo, ContractInfo},
123 transient_storage::{MeterEntry, StorageMeter as TransientStorageMeter, TransientStorage},
124 vm::{BytecodeType, ContractBlob},
125};
126pub use codec;
127use frame_support::traits::tokens::Precision;
128pub use frame_support::{self, dispatch::DispatchInfo, traits::Time, weights::Weight};
129pub use frame_system::{self, limits::BlockWeights};
130pub use primitives::*;
131pub use sp_core::{H160, H256, U256};
132pub use sp_crypto_hashing::keccak_256;
133pub use sp_runtime;
134pub use weights::WeightInfo;
135
136pub extern crate pallet_revive_types;
138
139#[cfg(doc)]
140pub use crate::vm::pvm::SyscallDoc;
141
142pub type BalanceOf<T> = <T as Config>::Balance;
143pub type CreditOf<T> = Credit<<T as frame_system::Config>::AccountId, <T as Config>::Currency>;
144type TrieId = BoundedVec<u8, ConstU32<128>>;
145type ImmutableData = BoundedVec<u8, ConstU32<{ limits::IMMUTABLE_BYTES }>>;
146type CallOf<T> = <T as Config>::RuntimeCall;
147
148const SENTINEL: u32 = u32::MAX;
155
156const LOG_TARGET: &str = "runtime::revive";
162
163#[frame_support::pallet]
164pub mod pallet {
165 use super::*;
166 use frame_support::{pallet_prelude::*, traits::FindAuthor};
167 use frame_system::pallet_prelude::*;
168 use sp_core::U256;
169 use sp_runtime::Perbill;
170
171 pub(crate) const STORAGE_VERSION: StorageVersion = StorageVersion::new(0);
173
174 #[pallet::pallet]
175 #[pallet::storage_version(STORAGE_VERSION)]
176 pub struct Pallet<T>(_);
177
178 #[pallet::config(with_default)]
179 pub trait Config: frame_system::Config {
180 type Time: Time<Moment: Into<U256>>;
182
183 #[pallet::no_default]
187 type Balance: Balance
188 + TryFrom<U256>
189 + Into<U256>
190 + Bounded
191 + UniqueSaturatedInto<u64>
192 + UniqueSaturatedFrom<u64>
193 + UniqueSaturatedInto<u128>;
194
195 #[pallet::no_default]
197 type Currency: Inspect<Self::AccountId, Balance = Self::Balance>
198 + Mutate<Self::AccountId>
199 + MutateHold<Self::AccountId, Reason = Self::RuntimeHoldReason>
200 + Balanced<Self::AccountId>;
201
202 #[pallet::no_default_bounds]
209 type OnBurn: OnUnbalanced<CreditOf<Self>>;
210
211 #[pallet::no_default_bounds]
213 #[allow(deprecated)]
214 type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
215
216 #[pallet::no_default_bounds]
218 type RuntimeCall: Parameter
219 + Dispatchable<
220 RuntimeOrigin = OriginFor<Self>,
221 Info = DispatchInfo,
222 PostInfo = PostDispatchInfo,
223 > + IsType<<Self as frame_system::Config>::RuntimeCall>
224 + From<Call<Self>>
225 + IsSubType<Call<Self>>
226 + GetDispatchInfo;
227
228 #[pallet::no_default_bounds]
230 type RuntimeOrigin: IsType<OriginFor<Self>>
231 + From<Origin<Self>>
232 + Into<Result<Origin<Self>, OriginFor<Self>>>;
233
234 #[pallet::no_default_bounds]
236 type RuntimeHoldReason: From<HoldReason>;
237
238 type WeightInfo: WeightInfo;
241
242 #[pallet::no_default_bounds]
246 #[allow(private_bounds)]
247 type Precompiles: precompiles::Precompiles<Self>;
248
249 type FindAuthor: FindAuthor<Self::AccountId>;
251
252 #[pallet::constant]
258 #[pallet::no_default_bounds]
259 type DepositPerByte: Get<BalanceOf<Self>>;
260
261 #[pallet::constant]
267 #[pallet::no_default_bounds]
268 type DepositPerItem: Get<BalanceOf<Self>>;
269
270 #[pallet::constant]
280 #[pallet::no_default_bounds]
281 type DepositPerChildTrieItem: Get<BalanceOf<Self>>;
282
283 #[pallet::constant]
287 type CodeHashLockupDepositPercent: Get<Perbill>;
288
289 #[pallet::no_default]
291 type AddressMapper: AddressMapper<Self>;
292
293 #[pallet::constant]
295 type AllowEVMBytecode: Get<bool>;
296
297 #[pallet::no_default_bounds]
302 type UploadOrigin: EnsureOrigin<OriginFor<Self>, Success = Self::AccountId>;
303
304 #[pallet::no_default_bounds]
315 type InstantiateOrigin: EnsureOrigin<OriginFor<Self>, Success = Self::AccountId>;
316
317 type RuntimeMemory: Get<u32>;
322
323 type PVFMemory: Get<u32>;
331
332 #[pallet::constant]
337 type ChainId: Get<u64>;
338
339 #[pallet::constant]
341 type NativeToEthRatio: Get<u32>;
342
343 #[pallet::no_default_bounds]
348 type FeeInfo: FeeInfo<Self>;
349
350 #[pallet::no_default_bounds]
353 type Deposit: Deposit<Self>;
354
355 #[pallet::constant]
368 type MaxEthExtrinsicWeight: Get<FixedU128>;
369
370 #[pallet::constant]
372 type DebugEnabled: Get<bool>;
373
374 #[pallet::constant]
381 type AutoMap: Get<bool>;
382
383 #[pallet::constant]
401 #[pallet::no_default_bounds]
402 type GasScale: Get<u32>;
403 }
404
405 pub mod config_preludes {
407 use super::*;
408 use frame_support::{
409 derive_impl,
410 traits::{ConstBool, ConstU32},
411 };
412 use frame_system::EnsureSigned;
413 use sp_core::parameter_types;
414
415 type Balance = u64;
416
417 pub const DOLLARS: Balance = 1_000_000_000_000;
418 pub const CENTS: Balance = DOLLARS / 100;
419 pub const MILLICENTS: Balance = CENTS / 1_000;
420
421 pub const fn deposit(items: u32, bytes: u32) -> Balance {
422 items as Balance * 20 * CENTS + (bytes as Balance) * MILLICENTS
423 }
424
425 parameter_types! {
426 pub const DepositPerItem: Balance = deposit(1, 0);
427 pub const DepositPerChildTrieItem: Balance = deposit(1, 0) / 100;
428 pub const DepositPerByte: Balance = deposit(0, 1);
429 pub const CodeHashLockupDepositPercent: Perbill = Perbill::from_percent(0);
430 pub const MaxEthExtrinsicWeight: FixedU128 = FixedU128::from_rational(9, 10);
431 pub const GasScale: u32 = 10u32;
432 }
433
434 pub struct TestDefaultConfig;
436
437 impl Time for TestDefaultConfig {
438 type Moment = u64;
439 fn now() -> Self::Moment {
440 0u64
441 }
442 }
443
444 impl<T: From<u64>> Convert<Weight, T> for TestDefaultConfig {
445 fn convert(w: Weight) -> T {
446 w.ref_time().into()
447 }
448 }
449
450 #[derive_impl(frame_system::config_preludes::TestDefaultConfig, no_aggregated_types)]
451 impl frame_system::DefaultConfig for TestDefaultConfig {}
452
453 #[frame_support::register_default_impl(TestDefaultConfig)]
454 impl DefaultConfig for TestDefaultConfig {
455 #[inject_runtime_type]
456 type RuntimeEvent = ();
457
458 #[inject_runtime_type]
459 type RuntimeHoldReason = ();
460
461 #[inject_runtime_type]
462 type RuntimeCall = ();
463
464 #[inject_runtime_type]
465 type RuntimeOrigin = ();
466
467 type Precompiles = ();
468 type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent;
469 type DepositPerByte = DepositPerByte;
470 type DepositPerItem = DepositPerItem;
471 type DepositPerChildTrieItem = DepositPerChildTrieItem;
472 type Time = Self;
473 type AllowEVMBytecode = ConstBool<true>;
474 type UploadOrigin = EnsureSigned<Self::AccountId>;
475 type InstantiateOrigin = EnsureSigned<Self::AccountId>;
476 type WeightInfo = ();
477 type RuntimeMemory = ConstU32<{ 128 * 1024 * 1024 }>;
478 type PVFMemory = ConstU32<{ 512 * 1024 * 1024 }>;
479 type ChainId = ConstU64<42>;
480 type NativeToEthRatio = ConstU32<1_000_000>;
481 type FindAuthor = ();
482 type FeeInfo = ();
483 type Deposit = ();
484 type MaxEthExtrinsicWeight = MaxEthExtrinsicWeight;
485 type DebugEnabled = ConstBool<false>;
486 type AutoMap = ConstBool<false>;
487 type GasScale = GasScale;
488 type OnBurn = ();
489 }
490 }
491
492 #[pallet::event]
493 pub enum Event<T: Config> {
494 ContractEmitted {
496 contract: H160,
498 data: Vec<u8>,
501 topics: Vec<H256>,
504 },
505
506 Instantiated { deployer: H160, contract: H160 },
508
509 EthExtrinsicRevert { dispatch_error: DispatchError },
516 }
517
518 #[pallet::error]
519 #[repr(u8)]
520 pub enum Error<T> {
521 InvalidSchedule = 0x01,
523 InvalidCallFlags = 0x02,
525 OutOfGas = 0x03,
527 TransferFailed = 0x04,
530 MaxCallDepthReached = 0x05,
533 ContractNotFound = 0x06,
535 CodeNotFound = 0x07,
537 CodeInfoNotFound = 0x08,
539 OutOfBounds = 0x09,
541 DecodingFailed = 0x0A,
543 ContractTrapped = 0x0B,
545 ValueTooLarge = 0x0C,
547 TerminatedWhileReentrant = 0x0D,
550 InputForwarded = 0x0E,
552 TooManyTopics = 0x0F,
554 DuplicateContract = 0x12,
556 TerminatedInConstructor = 0x13,
560 ReentranceDenied = 0x14,
562 ReenteredPallet = 0x15,
564 StateChangeDenied = 0x16,
566 StorageDepositNotEnoughFunds = 0x17,
568 StorageDepositLimitExhausted = 0x18,
570 CodeInUse = 0x19,
572 ContractReverted = 0x1A,
577 CodeRejected = 0x1B,
582 BlobTooLarge = 0x1C,
584 StaticMemoryTooLarge = 0x1D,
586 BasicBlockTooLarge = 0x1E,
588 InvalidInstruction = 0x1F,
590 MaxDelegateDependenciesReached = 0x20,
592 DelegateDependencyNotFound = 0x21,
594 DelegateDependencyAlreadyExists = 0x22,
596 CannotAddSelfAsDelegateDependency = 0x23,
598 OutOfTransientStorage = 0x24,
600 InvalidSyscall = 0x25,
602 InvalidStorageFlags = 0x26,
604 ExecutionFailed = 0x27,
606 BalanceConversionFailed = 0x28,
608 InvalidImmutableAccess = 0x2A,
611 AccountUnmapped = 0x2B,
615 AccountAlreadyMapped = 0x2C,
617 InvalidGenericTransaction = 0x2D,
619 RefcountOverOrUnderflow = 0x2E,
621 UnsupportedPrecompileAddress = 0x2F,
623 CallDataTooLarge = 0x30,
625 ReturnDataTooLarge = 0x31,
627 InvalidJump = 0x32,
629 StackUnderflow = 0x33,
631 StackOverflow = 0x34,
633 TxFeeOverdraw = 0x35,
637 EvmConstructorNonEmptyData = 0x36,
641 EvmConstructedFromHash = 0x37,
646 StorageRefundNotEnoughFunds = 0x38,
650 StorageRefundLocked = 0x39,
655 PrecompileDelegateDenied = 0x40,
660 EcdsaRecoveryFailed = 0x41,
662 AutoMappingEnabled = 0x42,
664 PendingDepositCleanup = 0x43,
668 ReceiptTooLarge = 0x45,
671 #[cfg(feature = "runtime-benchmarks")]
673 BenchmarkingError = 0xFF,
674 }
675
676 #[pallet::composite_enum]
678 pub enum HoldReason {
679 CodeUploadDepositReserve,
681 StorageDepositReserve,
683 AddressMapping,
685 }
686
687 #[pallet::composite_enum]
689 pub enum FreezeReason {
690 PGasMinBalance,
695 }
696
697 #[derive(
698 PartialEq, Eq, Clone, MaxEncodedLen, Encode, Decode, DecodeWithMemTracking, TypeInfo, Debug,
699 )]
700 #[pallet::origin]
701 pub enum Origin<T: Config> {
702 EthTransaction(T::AccountId),
703 }
704
705 #[pallet::storage]
709 #[pallet::unbounded]
710 pub(crate) type PristineCode<T: Config> = StorageMap<_, Identity, H256, Vec<u8>>;
711
712 #[pallet::storage]
714 pub(crate) type CodeInfoOf<T: Config> = StorageMap<_, Identity, H256, CodeInfo<T>>;
715
716 #[pallet::storage]
718 pub(crate) type AccountInfoOf<T: Config> = StorageMap<_, Identity, H160, AccountInfo<T>>;
719
720 #[pallet::storage]
731 pub(crate) type NativeDepositOf<T: Config> = StorageDoubleMap<
732 _,
733 Identity,
734 T::AccountId,
735 Identity,
736 T::AccountId,
737 BalanceOf<T>,
738 ValueQuery,
739 >;
740
741 #[pallet::storage]
743 pub(crate) type ImmutableDataOf<T: Config> = StorageMap<_, Identity, H160, ImmutableData>;
744
745 #[pallet::storage]
751 pub(crate) type DeletionQueue<T: Config> =
752 StorageMap<_, Twox64Concat, u32, crate::storage::DeletionQueueItem<T>>;
753
754 #[pallet::storage]
757 pub(crate) type DeletionQueueCounter<T: Config> =
758 StorageValue<_, DeletionQueueManager<T>, ValueQuery>;
759
760 #[pallet::storage]
767 pub(crate) type OriginalAccount<T: Config> = StorageMap<_, Identity, H160, AccountId32>;
768
769 #[pallet::storage]
779 #[pallet::unbounded]
780 pub(crate) type EthereumBlock<T> = StorageValue<_, EthBlock, ValueQuery>;
781
782 #[pallet::storage]
786 pub(crate) type BlockHash<T: Config> =
787 StorageMap<_, Identity, BlockNumberFor<T>, H256, ValueQuery>;
788
789 #[pallet::storage]
796 #[pallet::unbounded]
797 pub(crate) type ReceiptInfoData<T: Config> = StorageValue<_, Vec<ReceiptGasInfo>, ValueQuery>;
798
799 #[pallet::storage]
813 #[pallet::whitelist_storage]
814 pub(crate) type ReceiptLogsCommitted<T: Config> =
815 StorageValue<_, CommittedReceiptLogs, ValueQuery>;
816
817 #[pallet::storage]
819 #[pallet::unbounded]
820 pub(crate) type EthBlockBuilderIR<T: Config> =
821 StorageValue<_, EthereumBlockBuilderIR<T>, ValueQuery>;
822
823 #[pallet::storage]
828 #[pallet::unbounded]
829 pub(crate) type EthBlockBuilderFirstValues<T: Config> =
830 StorageValue<_, Option<(Vec<u8>, Vec<u8>)>, ValueQuery>;
831
832 #[pallet::storage]
834 pub(crate) type DebugSettingsOf<T: Config> = StorageValue<_, DebugSettings, ValueQuery>;
835
836 pub mod genesis {
837 use super::*;
838 use crate::evm::Bytes32;
839
840 #[derive(Clone, PartialEq, Debug, Default, serde::Serialize, serde::Deserialize)]
842 pub struct ContractData {
843 pub code: crate::evm::Bytes,
845 pub storage: alloc::collections::BTreeMap<Bytes32, Bytes32>,
847 }
848
849 #[derive(PartialEq, Default, Debug, Clone, serde::Serialize, serde::Deserialize)]
851 pub struct Account<T: Config> {
852 pub address: H160,
854 #[serde(default)]
856 pub balance: U256,
857 #[serde(default)]
859 pub nonce: T::Nonce,
860 #[serde(flatten, skip_serializing_if = "Option::is_none")]
862 pub contract_data: Option<ContractData>,
863 }
864 }
865
866 #[pallet::genesis_config]
867 #[derive(Debug, PartialEq, frame_support::DefaultNoBound)]
868 pub struct GenesisConfig<T: Config> {
869 #[serde(default, skip_serializing_if = "Vec::is_empty")]
872 pub mapped_accounts: Vec<T::AccountId>,
873
874 #[serde(default, skip_serializing_if = "Vec::is_empty")]
876 pub accounts: Vec<genesis::Account<T>>,
877
878 #[serde(default, skip_serializing_if = "Option::is_none")]
880 pub debug_settings: Option<DebugSettings>,
881 }
882
883 #[pallet::genesis_build]
884 impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
885 fn build(&self) {
886 use crate::{exec::Key, vm::ContractBlob};
887 use frame_support::traits::fungible::Mutate;
888
889 if !System::<T>::account_exists(&Pallet::<T>::account_id()) {
890 let _ = T::Currency::mint_into(
891 &Pallet::<T>::account_id(),
892 T::Currency::minimum_balance(),
893 );
894 }
895
896 for id in &self.mapped_accounts {
897 if let Err(err) = T::AddressMapper::map_no_deposit_unchecked(id) {
898 log::error!(target: LOG_TARGET, "Failed to map account {id:?}: {err:?}");
899 }
900 }
901
902 let owner = Pallet::<T>::account_id();
903
904 for genesis::Account { address, balance, nonce, contract_data } in &self.accounts {
905 let account_id = T::AddressMapper::to_account_id(address);
906
907 if !System::<T>::account_exists(&account_id) {
908 let _ = T::Currency::mint_into(&account_id, T::Currency::minimum_balance());
909 }
910
911 frame_system::Account::<T>::mutate(&account_id, |info| {
912 info.nonce = (*nonce).into();
913 });
914
915 match contract_data {
916 None => {
917 AccountInfoOf::<T>::insert(
918 address,
919 AccountInfo { account_type: AccountType::EOA, dust: 0 },
920 );
921 },
922 Some(genesis::ContractData { code, storage }) => {
923 let blob = if code.0.starts_with(&polkavm_common::program::BLOB_MAGIC) {
924 ContractBlob::<T>::from_pvm_code(code.0.clone(), owner.clone())
925 .inspect_err(|err| {
926 log::error!(target: LOG_TARGET, "Failed to create PVM ContractBlob for {address:?}: {err:?}");
927 })
928 } else {
929 ContractBlob::<T>::from_evm_runtime_code(code.0.clone(), account_id)
930 .inspect_err(|err| {
931 log::error!(target: LOG_TARGET, "Failed to create EVM ContractBlob for {address:?}: {err:?}");
932 })
933 };
934
935 let Ok(blob) = blob else {
936 continue;
937 };
938
939 let code_hash = *blob.code_hash();
940 let Ok(info) = <ContractInfo<T>>::new(&address, 0u32.into(), code_hash)
941 .inspect_err(|err| {
942 log::error!(target: LOG_TARGET, "Failed to create ContractInfo for {address:?}: {err:?}");
943 })
944 else {
945 continue;
946 };
947
948 AccountInfoOf::<T>::insert(
949 address,
950 AccountInfo { account_type: info.clone().into(), dust: 0 },
951 );
952
953 <PristineCode<T>>::insert(blob.code_hash(), code.0.clone());
954 <CodeInfoOf<T>>::insert(blob.code_hash(), blob.code_info().clone());
955 for (k, v) in storage {
956 let _ = info.write(&Key::from_fixed(k.0), Some(v.0.to_vec()), None, false).inspect_err(|err| {
957 log::error!(target: LOG_TARGET, "Failed to write genesis storage for {address:?} at key {k:?}: {err:?}");
958 });
959 }
960 },
961 }
962
963 let _ = Pallet::<T>::set_evm_balance(address, *balance).inspect_err(|err| {
964 log::error!(target: LOG_TARGET, "Failed to set EVM balance for {address:?}: {err:?}");
965 });
966 }
967
968 block_storage::on_finalize_build_eth_block::<T>(
970 frame_system::Pallet::<T>::block_number(),
973 );
974
975 if let Some(settings) = self.debug_settings.as_ref() {
977 settings.write_to_storage::<T>()
978 }
979 }
980 }
981
982 #[pallet::hooks]
983 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
984 fn on_idle(_block: BlockNumberFor<T>, limit: Weight) -> Weight {
985 let mut meter = WeightMeter::with_limit(limit);
986 ContractInfo::<T>::process_deletion_queue_batch(&mut meter);
987 meter.consumed()
988 }
989
990 fn on_initialize(_n: BlockNumberFor<T>) -> Weight {
991 block_storage::on_initialize::<T>();
993
994 System::<T>::account_exists(&Pallet::<T>::account_id());
996 <T as Config>::WeightInfo::on_finalize_block_fixed()
998 }
999
1000 fn on_finalize(block_number: BlockNumberFor<T>) {
1001 block_storage::on_finalize_build_eth_block::<T>(block_number);
1003 }
1004
1005 fn integrity_test() {
1006 assert!(T::ChainId::get() > 0, "ChainId must be greater than 0");
1007
1008 assert!(T::GasScale::get() > 0u32.into(), "GasScale must not be 0");
1009
1010 T::FeeInfo::integrity_test();
1011
1012 let max_runtime_mem: u64 = T::RuntimeMemory::get().into();
1014
1015 const TOTAL_MEMORY_DEVIDER: u64 = 2;
1018
1019 let max_block_weight = T::BlockWeights::get()
1025 .get(DispatchClass::Normal)
1026 .max_total
1027 .unwrap_or_else(|| T::BlockWeights::get().max_block);
1028 let max_key_size: u64 =
1029 Key::try_from_var(alloc::vec![0u8; limits::STORAGE_KEY_BYTES as usize])
1030 .expect("Key of maximal size shall be created")
1031 .hash()
1032 .len()
1033 .try_into()
1034 .unwrap();
1035
1036 let max_immutable_key_size: u64 = T::AccountId::max_encoded_len().try_into().unwrap();
1037 let max_immutable_size: u64 = max_block_weight
1038 .checked_div_per_component(&<RuntimeCosts as WeightToken<T>>::weight(
1039 &RuntimeCosts::SetImmutableData(limits::IMMUTABLE_BYTES),
1040 ))
1041 .unwrap()
1042 .saturating_mul(
1043 u64::from(limits::IMMUTABLE_BYTES)
1044 .saturating_add(max_immutable_key_size)
1045 .into(),
1046 );
1047
1048 let max_pvf_mem: u64 = T::PVFMemory::get().into();
1049 let storage_size_limit = max_pvf_mem.saturating_sub(max_runtime_mem) / 2;
1050
1051 let max_events_size = max_block_weight
1055 .checked_div_per_component(
1056 &(<RuntimeCosts as WeightToken<T>>::weight(&RuntimeCosts::DepositEvent {
1057 num_topic: 0,
1058 len: limits::EVENT_BYTES,
1059 })
1060 .saturating_add(<RuntimeCosts as WeightToken<T>>::weight(
1061 &RuntimeCosts::HostFn,
1062 ))),
1063 )
1064 .unwrap()
1065 .saturating_mul(limits::EVENT_BYTES.into());
1066
1067 assert!(
1068 max_events_size <= storage_size_limit,
1069 "Maximal events size {} exceeds the events limit {}",
1070 max_events_size,
1071 storage_size_limit
1072 );
1073
1074 let max_eth_block_builder_bytes = block_storage::BLOCK_BUILDER_BYTES;
1078
1079 log::debug!(
1080 target: LOG_TARGET,
1081 "Integrity check: max_events_size={} KB, max_eth_block_builder_bytes={} KB",
1082 max_events_size / 1024,
1083 max_eth_block_builder_bytes / 1024,
1084 );
1085
1086 let memory_left = i128::from(max_runtime_mem)
1091 .saturating_div(TOTAL_MEMORY_DEVIDER.into())
1092 .saturating_sub(limits::MEMORY_REQUIRED.into())
1093 .saturating_sub(max_eth_block_builder_bytes.into());
1094
1095 log::debug!(target: LOG_TARGET, "Integrity check: memory_left={} KB", memory_left / 1024);
1096
1097 assert!(
1098 memory_left >= 0,
1099 "Runtime does not have enough memory for current limits. Additional runtime memory required: {} KB",
1100 memory_left.saturating_mul(TOTAL_MEMORY_DEVIDER.into()).abs() / 1024
1101 );
1102
1103 let max_storage_size = max_block_weight
1106 .checked_div_per_component(
1107 &<RuntimeCosts as WeightToken<T>>::weight(&RuntimeCosts::SetStorage {
1108 new_bytes: limits::STORAGE_BYTES,
1109 old_bytes: 0,
1110 kind: StorageAccessKind::Persistent(Warmth::Cold { revertible: true }),
1111 })
1112 .saturating_mul(u64::from(limits::STORAGE_BYTES).saturating_add(max_key_size)),
1113 )
1114 .unwrap()
1115 .saturating_add(max_immutable_size.into())
1116 .saturating_add(max_eth_block_builder_bytes.into());
1117
1118 assert!(
1119 max_storage_size <= storage_size_limit,
1120 "Maximal storage size {} exceeds the storage limit {}",
1121 max_storage_size,
1122 storage_size_limit
1123 );
1124 }
1125 }
1126
1127 #[pallet::call]
1128 impl<T: Config> Pallet<T> {
1129 #[allow(unused_variables)]
1142 #[pallet::call_index(0)]
1143 #[pallet::weight(Weight::MAX)]
1144 pub fn eth_transact(origin: OriginFor<T>, payload: Vec<u8>) -> DispatchResultWithPostInfo {
1145 Err(frame_system::Error::CallFiltered::<T>.into())
1146 }
1147
1148 #[pallet::call_index(1)]
1165 #[pallet::weight(<T as Config>::WeightInfo::call().saturating_add(*weight_limit))]
1166 pub fn call(
1167 origin: OriginFor<T>,
1168 dest: H160,
1169 #[pallet::compact] value: BalanceOf<T>,
1170 weight_limit: Weight,
1171 #[pallet::compact] storage_deposit_limit: BalanceOf<T>,
1172 data: Vec<u8>,
1173 ) -> DispatchResultWithPostInfo {
1174 Self::ensure_non_contract_if_signed(&origin)?;
1175 let mut output = Self::bare_call(
1176 origin,
1177 dest,
1178 Pallet::<T>::convert_native_to_evm(value),
1179 TransactionLimits::WeightAndDeposit {
1180 weight_limit,
1181 deposit_limit: storage_deposit_limit,
1182 },
1183 data,
1184 &ExecConfig::new_substrate_tx(),
1185 );
1186
1187 if let Ok(return_value) = &output.result &&
1188 return_value.did_revert()
1189 {
1190 output.result = Err(<Error<T>>::ContractReverted.into());
1191 }
1192 dispatch_result(
1193 output.result,
1194 output.weight_consumed,
1195 <T as Config>::WeightInfo::call(),
1196 )
1197 }
1198
1199 #[pallet::call_index(2)]
1205 #[pallet::weight(
1206 <T as Config>::WeightInfo::instantiate(data.len() as u32).saturating_add(*weight_limit)
1207 )]
1208 pub fn instantiate(
1209 origin: OriginFor<T>,
1210 #[pallet::compact] value: BalanceOf<T>,
1211 weight_limit: Weight,
1212 #[pallet::compact] storage_deposit_limit: BalanceOf<T>,
1213 code_hash: sp_core::H256,
1214 data: Vec<u8>,
1215 salt: Option<[u8; 32]>,
1216 ) -> DispatchResultWithPostInfo {
1217 Self::ensure_non_contract_if_signed(&origin)?;
1218 let data_len = data.len() as u32;
1219 let mut output = Self::bare_instantiate(
1220 origin,
1221 Pallet::<T>::convert_native_to_evm(value),
1222 TransactionLimits::WeightAndDeposit {
1223 weight_limit,
1224 deposit_limit: storage_deposit_limit,
1225 },
1226 Code::Existing(code_hash),
1227 data,
1228 salt,
1229 &ExecConfig::new_substrate_tx(),
1230 );
1231 if let Ok(retval) = &output.result &&
1232 retval.result.did_revert()
1233 {
1234 output.result = Err(<Error<T>>::ContractReverted.into());
1235 }
1236 dispatch_result(
1237 output.result.map(|result| result.result),
1238 output.weight_consumed,
1239 <T as Config>::WeightInfo::instantiate(data_len),
1240 )
1241 }
1242
1243 #[pallet::call_index(3)]
1271 #[pallet::weight(
1272 <T as Config>::WeightInfo::instantiate_with_code(code.len() as u32, data.len() as u32)
1273 .saturating_add(*weight_limit)
1274 )]
1275 pub fn instantiate_with_code(
1276 origin: OriginFor<T>,
1277 #[pallet::compact] value: BalanceOf<T>,
1278 weight_limit: Weight,
1279 #[pallet::compact] storage_deposit_limit: BalanceOf<T>,
1280 code: Vec<u8>,
1281 data: Vec<u8>,
1282 salt: Option<[u8; 32]>,
1283 ) -> DispatchResultWithPostInfo {
1284 Self::ensure_non_contract_if_signed(&origin)?;
1285 let code_len = code.len() as u32;
1286 let data_len = data.len() as u32;
1287 let mut output = Self::bare_instantiate(
1288 origin,
1289 Pallet::<T>::convert_native_to_evm(value),
1290 TransactionLimits::WeightAndDeposit {
1291 weight_limit,
1292 deposit_limit: storage_deposit_limit,
1293 },
1294 Code::Upload(code),
1295 data,
1296 salt,
1297 &ExecConfig::new_substrate_tx(),
1298 );
1299 if let Ok(retval) = &output.result &&
1300 retval.result.did_revert()
1301 {
1302 output.result = Err(<Error<T>>::ContractReverted.into());
1303 }
1304 dispatch_result(
1305 output.result.map(|result| result.result),
1306 output.weight_consumed,
1307 <T as Config>::WeightInfo::instantiate_with_code(code_len, data_len),
1308 )
1309 }
1310
1311 #[pallet::call_index(10)]
1333 #[pallet::weight(
1334 <T as Config>::WeightInfo::eth_instantiate_with_code(code.len() as u32, data.len() as u32, Pallet::<T>::has_dust(*value).into())
1335 .saturating_add(*weight_limit)
1336 .saturating_add(T::WeightInfo::on_finalize_block_per_tx(transaction_encoded.len() as u32))
1337 )]
1338 pub fn eth_instantiate_with_code(
1339 origin: OriginFor<T>,
1340 value: U256,
1341 weight_limit: Weight,
1342 eth_gas_limit: U256,
1343 code: Vec<u8>,
1344 data: Vec<u8>,
1345 transaction_encoded: Vec<u8>,
1346 effective_gas_price: U256,
1347 encoded_len: u32,
1348 ) -> DispatchResultWithPostInfo {
1349 let signer = Self::ensure_eth_signed(origin)?;
1350 let origin = OriginFor::<T>::signed(signer.clone());
1351 Self::ensure_non_contract_if_signed(&origin)?;
1352 let mut call = Call::<T>::eth_instantiate_with_code {
1353 value,
1354 weight_limit,
1355 eth_gas_limit,
1356 code: code.clone(),
1357 data: data.clone(),
1358 transaction_encoded: transaction_encoded.clone(),
1359 effective_gas_price,
1360 encoded_len,
1361 }
1362 .into();
1363 let info = T::FeeInfo::dispatch_info(&call);
1364 let base_info = T::FeeInfo::base_dispatch_info(&mut call);
1365 drop(call);
1366
1367 block_storage::with_ethereum_context::<T>(transaction_encoded, || {
1368 let extra_weight = base_info.total_weight();
1369 let output = Self::bare_instantiate(
1370 origin,
1371 value,
1372 TransactionLimits::EthereumGas {
1373 eth_gas_limit: eth_gas_limit.saturated_into(),
1374 weight_limit,
1375 eth_tx_info: EthTxInfo::new(encoded_len, extra_weight),
1376 },
1377 Code::Upload(code),
1378 data,
1379 None,
1380 &ExecConfig::new_eth_tx(effective_gas_price, encoded_len, extra_weight),
1381 );
1382
1383 block_storage::EthereumCallResult::new::<T>(
1384 signer,
1385 output.map_result(|r| r.result),
1386 base_info.call_weight,
1387 encoded_len,
1388 &info,
1389 effective_gas_price,
1390 )
1391 })
1392 }
1393
1394 #[pallet::call_index(11)]
1411 #[pallet::weight(
1412 T::WeightInfo::eth_call(Pallet::<T>::has_dust(*value).into())
1413 .saturating_add(*weight_limit)
1414 .saturating_add(T::WeightInfo::on_finalize_block_per_tx(transaction_encoded.len() as u32))
1415 )]
1416 pub fn eth_call(
1417 origin: OriginFor<T>,
1418 dest: H160,
1419 value: U256,
1420 weight_limit: Weight,
1421 eth_gas_limit: U256,
1422 data: Vec<u8>,
1423 transaction_encoded: Vec<u8>,
1424 effective_gas_price: U256,
1425 encoded_len: u32,
1426 ) -> DispatchResultWithPostInfo {
1427 let signer = Self::ensure_eth_signed(origin)?;
1428 let origin = OriginFor::<T>::signed(signer.clone());
1429
1430 Self::ensure_non_contract_if_signed(&origin)?;
1431 let mut call = Call::<T>::eth_call {
1432 dest,
1433 value,
1434 weight_limit,
1435 eth_gas_limit,
1436 data: data.clone(),
1437 transaction_encoded: transaction_encoded.clone(),
1438 effective_gas_price,
1439 encoded_len,
1440 }
1441 .into();
1442 let info = T::FeeInfo::dispatch_info(&call);
1443 let base_info = T::FeeInfo::base_dispatch_info(&mut call);
1444 drop(call);
1445
1446 block_storage::with_ethereum_context::<T>(transaction_encoded, || {
1447 let extra_weight = base_info.total_weight();
1448 let output = Self::bare_call(
1449 origin,
1450 dest,
1451 value,
1452 TransactionLimits::EthereumGas {
1453 eth_gas_limit: eth_gas_limit.saturated_into(),
1454 weight_limit,
1455 eth_tx_info: EthTxInfo::new(encoded_len, extra_weight),
1456 },
1457 data,
1458 &ExecConfig::new_eth_tx(effective_gas_price, encoded_len, extra_weight),
1459 );
1460
1461 block_storage::EthereumCallResult::new::<T>(
1462 signer,
1463 output,
1464 base_info.call_weight,
1465 encoded_len,
1466 &info,
1467 effective_gas_price,
1468 )
1469 })
1470 }
1471
1472 #[pallet::call_index(12)]
1483 #[pallet::weight(
1484 T::WeightInfo::eth_substrate_call(transaction_encoded.len() as u32)
1485 .saturating_add(call.get_dispatch_info().call_weight)
1486 .saturating_add(T::WeightInfo::on_finalize_block_per_tx(transaction_encoded.len() as u32))
1487 )]
1488 pub fn eth_substrate_call(
1489 origin: OriginFor<T>,
1490 call: Box<<T as Config>::RuntimeCall>,
1491 transaction_encoded: Vec<u8>,
1492 ) -> DispatchResultWithPostInfo {
1493 let signer = Self::ensure_eth_signed(origin)?;
1496 Self::ensure_non_contract_if_signed(&OriginFor::<T>::signed(signer.clone()))?;
1497 let tx_len = transaction_encoded.len() as u32;
1498 let weight_overhead = T::WeightInfo::eth_substrate_call(tx_len)
1499 .saturating_add(T::WeightInfo::on_finalize_block_per_tx(tx_len));
1500
1501 block_storage::with_ethereum_context::<T>(transaction_encoded, || {
1502 let call_weight = call.get_dispatch_info().call_weight;
1503 let mut call_result = call.dispatch(RawOrigin::Signed(signer).into());
1504
1505 match &mut call_result {
1507 Ok(post_info) | Err(DispatchErrorWithPostInfo { post_info, .. }) => {
1508 post_info.actual_weight = Some(
1509 post_info
1510 .actual_weight
1511 .unwrap_or_else(|| call_weight)
1512 .saturating_add(weight_overhead),
1513 );
1514 },
1515 }
1516
1517 block_storage::EthereumCallResult {
1520 receipt_gas_info: ReceiptGasInfo::default(),
1521 result: call_result,
1522 }
1523 })
1524 }
1525
1526 #[pallet::call_index(4)]
1541 #[pallet::weight(<T as Config>::WeightInfo::upload_code(code.len() as u32))]
1542 pub fn upload_code(
1543 origin: OriginFor<T>,
1544 code: Vec<u8>,
1545 #[pallet::compact] storage_deposit_limit: BalanceOf<T>,
1546 ) -> DispatchResult {
1547 Self::ensure_non_contract_if_signed(&origin)?;
1548 Self::bare_upload_code(origin, code, storage_deposit_limit).map(|_| ())
1549 }
1550
1551 #[pallet::call_index(5)]
1556 #[pallet::weight(<T as Config>::WeightInfo::remove_code())]
1557 pub fn remove_code(
1558 origin: OriginFor<T>,
1559 code_hash: sp_core::H256,
1560 ) -> DispatchResultWithPostInfo {
1561 let origin = ensure_signed(origin)?;
1562 <ContractBlob<T>>::remove(&origin, code_hash)?;
1563 Ok(Pays::No.into())
1565 }
1566
1567 #[pallet::call_index(6)]
1578 #[pallet::weight(<T as Config>::WeightInfo::set_code())]
1579 pub fn set_code(
1580 origin: OriginFor<T>,
1581 dest: H160,
1582 code_hash: sp_core::H256,
1583 ) -> DispatchResult {
1584 ensure_root(origin)?;
1585 <AccountInfoOf<T>>::try_mutate(&dest, |account| {
1586 let Some(account) = account else {
1587 return Err(<Error<T>>::ContractNotFound.into());
1588 };
1589
1590 let AccountType::Contract(ref mut contract) = account.account_type else {
1591 return Err(<Error<T>>::ContractNotFound.into());
1592 };
1593
1594 <CodeInfo<T>>::increment_refcount(code_hash)?;
1595 let _ = <CodeInfo<T>>::decrement_refcount(contract.code_hash)?;
1596 contract.code_hash = code_hash;
1597
1598 Ok(())
1599 })
1600 }
1601
1602 #[pallet::call_index(7)]
1610 #[pallet::weight(<T as Config>::WeightInfo::map_account())]
1611 pub fn map_account(origin: OriginFor<T>) -> DispatchResult {
1612 #[cfg(not(feature = "runtime-benchmarks"))]
1613 if T::AutoMap::get() {
1614 return Ok(());
1615 }
1616
1617 Self::ensure_non_contract_if_signed(&origin)?;
1618 let origin = ensure_signed(origin)?;
1619 T::AddressMapper::map(&origin)
1620 }
1621
1622 #[pallet::call_index(13)]
1624 #[pallet::weight(<T as Config>::WeightInfo::batch_map_accounts(accounts.len().saturated_into::<u32>()))]
1625 pub fn batch_map_accounts(
1626 origin: OriginFor<T>,
1627 accounts: Vec<T::AccountId>,
1628 ) -> DispatchResultWithPostInfo {
1629 ensure_signed(origin.clone())?;
1630 Self::ensure_non_contract_if_signed(&origin)?;
1631
1632 let total: u32 = accounts.len().saturated_into();
1633 let mut mapped = 0;
1634
1635 for account_id in accounts
1636 .iter()
1637 .filter(|&a| !T::AddressMapper::is_eth_derived(a))
1639 .filter(|&a| frame_system::Pallet::<T>::account_exists(a))
1642 {
1643 let mut useful = false;
1644
1645 match T::AddressMapper::map_no_deposit_unchecked(account_id) {
1646 Ok(()) => {
1647 useful = true;
1648 },
1649 Err(err) => log::debug!(
1650 target: LOG_TARGET,
1651 "Failed to map account {account_id:?}: {err:?}",
1652 ),
1653 }
1654
1655 match T::Currency::release_all(
1656 &HoldReason::AddressMapping.into(),
1657 account_id,
1658 Precision::BestEffort,
1659 ) {
1660 Ok(released) if !released.is_zero() => {
1663 useful = true;
1664 },
1665 Ok(_) => {},
1666 Err(err) => log::debug!(
1667 target: LOG_TARGET,
1668 "Failed to release mapping deposit for {account_id:?}: {err:?}",
1669 ),
1670 }
1671
1672 if useful {
1673 mapped = mapped.saturating_add(1);
1674 }
1675 }
1676
1677 if total == 0 || mapped == 0 {
1679 return Ok(Pays::Yes.into());
1680 }
1681
1682 let proportion_mapped = Perbill::from_rational(mapped, total);
1683 if proportion_mapped >= Perbill::from_percent(90) {
1684 Ok(Pays::No.into())
1685 } else {
1686 Ok(Pays::Yes.into())
1687 }
1688 }
1689
1690 #[pallet::call_index(8)]
1698 #[pallet::weight(<T as Config>::WeightInfo::unmap_account())]
1699 pub fn unmap_account(origin: OriginFor<T>) -> DispatchResult {
1700 #[cfg(not(feature = "runtime-benchmarks"))]
1701 ensure!(!T::AutoMap::get(), <Error<T>>::AutoMappingEnabled);
1702 let origin = ensure_signed(origin)?;
1703 T::AddressMapper::unmap(&origin)
1704 }
1705
1706 #[pallet::call_index(9)]
1712 #[pallet::weight({
1713 let dispatch_info = call.get_dispatch_info();
1714 (
1715 <T as Config>::WeightInfo::dispatch_as_fallback_account().saturating_add(dispatch_info.call_weight),
1716 dispatch_info.class
1717 )
1718 })]
1719 pub fn dispatch_as_fallback_account(
1720 mut origin: OriginFor<T>,
1721 call: Box<<T as Config>::RuntimeCall>,
1722 ) -> DispatchResultWithPostInfo {
1723 Self::ensure_non_contract_if_signed(&origin)?;
1724 let account_id = origin.as_signer().ok_or(DispatchError::BadOrigin)?;
1725 let unmapped_account = T::AddressMapper::to_fallback_account_id(
1726 &T::AddressMapper::to_address(&account_id),
1727 );
1728 origin.set_caller_from(RawOrigin::Signed(unmapped_account));
1729 call.dispatch(origin)
1730 }
1731 }
1732}
1733
1734fn dispatch_result<R>(
1736 result: Result<R, DispatchError>,
1737 weight_consumed: Weight,
1738 base_weight: Weight,
1739) -> DispatchResultWithPostInfo {
1740 let post_info = PostDispatchInfo {
1741 actual_weight: Some(weight_consumed.saturating_add(base_weight)),
1742 pays_fee: Default::default(),
1743 };
1744
1745 result
1746 .map(|_| post_info)
1747 .map_err(|e| DispatchErrorWithPostInfo { post_info, error: e })
1748}
1749
1750impl<T: Config> Pallet<T> {
1751 pub fn bare_call(
1758 origin: OriginFor<T>,
1759 dest: H160,
1760 evm_value: U256,
1761 transaction_limits: TransactionLimits<T>,
1762 data: Vec<u8>,
1763 exec_config: &ExecConfig<T>,
1764 ) -> ContractResult<ExecReturnValue, BalanceOf<T>> {
1765 let mut transaction_meter = match TransactionMeter::new(transaction_limits) {
1766 Ok(transaction_meter) => transaction_meter,
1767 Err(error) => return ContractResult { result: Err(error), ..Default::default() },
1768 };
1769 let mut storage_deposit = Default::default();
1770
1771 let try_call = || {
1772 let origin = ExecOrigin::from_runtime_origin(origin)?;
1773 let result = ExecStack::<T, ContractBlob<T>>::run_call(
1774 origin.clone(),
1775 dest,
1776 &mut transaction_meter,
1777 evm_value,
1778 data,
1779 &exec_config,
1780 )?;
1781
1782 storage_deposit = transaction_meter
1783 .execute_postponed_deposits(&origin, &exec_config)
1784 .inspect_err(|err| {
1785 log::debug!(target: LOG_TARGET, "Failed to transfer deposit: {err:?}");
1786 })?;
1787
1788 Ok(result)
1789 };
1790 let result = Self::run_guarded(try_call);
1791
1792 log::trace!(target: LOG_TARGET, "Bare call ends: \
1793 result={result:?}, \
1794 weight_consumed={:?}, \
1795 weight_required={:?}, \
1796 storage_deposit={:?}, \
1797 gas_consumed={:?}, \
1798 max_storage_deposit={:?}",
1799 transaction_meter.weight_consumed(),
1800 transaction_meter.weight_required(),
1801 storage_deposit,
1802 transaction_meter.total_consumed_gas(),
1803 transaction_meter.deposit_required()
1804 );
1805
1806 ContractResult {
1807 result: result.map_err(|r| r.error),
1808 weight_consumed: transaction_meter.weight_consumed(),
1809 weight_required: transaction_meter.weight_required(),
1810 storage_deposit,
1811 gas_consumed: transaction_meter.total_consumed_gas(),
1812 max_storage_deposit: transaction_meter.deposit_required(),
1813 }
1814 }
1815
1816 pub fn prepare_dry_run(account: &T::AccountId) {
1822 frame_system::Pallet::<T>::inc_account_nonce(account);
1825
1826 if !T::AddressMapper::is_mapped(account) {
1829 let _ = T::AddressMapper::map_no_deposit_unchecked(account);
1830 }
1831 }
1832
1833 pub fn bare_instantiate(
1839 origin: OriginFor<T>,
1840 evm_value: U256,
1841 transaction_limits: TransactionLimits<T>,
1842 code: Code,
1843 data: Vec<u8>,
1844 salt: Option<[u8; 32]>,
1845 exec_config: &ExecConfig<T>,
1846 ) -> ContractResult<InstantiateReturnValue, BalanceOf<T>> {
1847 let mut transaction_meter = match TransactionMeter::new(transaction_limits) {
1848 Ok(transaction_meter) => transaction_meter,
1849 Err(error) => return ContractResult { result: Err(error), ..Default::default() },
1850 };
1851
1852 let mut storage_deposit = Default::default();
1853
1854 let try_instantiate = || {
1855 let instantiate_account = T::InstantiateOrigin::ensure_origin(origin.clone())?;
1856
1857 if_tracing(|t| t.instantiate_code(&code, salt.as_ref()));
1858 let executable = match code {
1859 Code::Upload(code) if code.starts_with(&polkavm_common::program::BLOB_MAGIC) => {
1860 let upload_account = T::UploadOrigin::ensure_origin(origin)?;
1861 let executable = Self::try_upload_code(
1862 upload_account,
1863 code,
1864 BytecodeType::Pvm,
1865 &mut transaction_meter,
1866 &exec_config,
1867 )?;
1868 executable
1869 },
1870 Code::Upload(code) => {
1871 if T::AllowEVMBytecode::get() {
1872 ensure!(data.is_empty(), <Error<T>>::EvmConstructorNonEmptyData);
1873 let origin = T::UploadOrigin::ensure_origin(origin)?;
1874 let executable = ContractBlob::from_evm_init_code(code, origin)?;
1875 executable
1876 } else {
1877 return Err(<Error<T>>::CodeRejected.into());
1878 }
1879 },
1880 Code::Existing(code_hash) => {
1881 let executable = ContractBlob::from_storage(code_hash, &mut transaction_meter)?;
1882 ensure!(executable.code_info().is_pvm(), <Error<T>>::EvmConstructedFromHash);
1883 executable
1884 },
1885 };
1886 let instantiate_origin = ExecOrigin::from_account_id(instantiate_account.clone());
1887 let result = ExecStack::<T, ContractBlob<T>>::run_instantiate(
1888 instantiate_account,
1889 executable,
1890 &mut transaction_meter,
1891 evm_value,
1892 data,
1893 salt.as_ref(),
1894 &exec_config,
1895 );
1896
1897 storage_deposit = transaction_meter
1898 .execute_postponed_deposits(&instantiate_origin, &exec_config)
1899 .inspect_err(|err| {
1900 log::debug!(target: LOG_TARGET, "Failed to transfer deposit: {err:?}");
1901 })?;
1902 result
1903 };
1904 let output = Self::run_guarded(try_instantiate);
1905
1906 log::trace!(target: LOG_TARGET, "Bare instantiate ends: weight_consumed={:?}\
1907 weight_required={:?} \
1908 storage_deposit={:?} \
1909 gas_consumed={:?} \
1910 max_storage_deposit={:?}",
1911 transaction_meter.weight_consumed(),
1912 transaction_meter.weight_required(),
1913 storage_deposit,
1914 transaction_meter.total_consumed_gas(),
1915 transaction_meter.deposit_required()
1916 );
1917
1918 ContractResult {
1919 result: output
1920 .map(|(addr, result)| InstantiateReturnValue { result, addr })
1921 .map_err(|e| e.error),
1922 weight_consumed: transaction_meter.weight_consumed(),
1923 weight_required: transaction_meter.weight_required(),
1924 storage_deposit,
1925 gas_consumed: transaction_meter.total_consumed_gas(),
1926 max_storage_deposit: transaction_meter.deposit_required(),
1927 }
1928 }
1929
1930 pub fn eth_estimate_gas(
1942 tx: GenericTransaction,
1943 timestamp_override: Option<MomentOf<T>>,
1944 state_overrides: Option<StateOverrideSet>,
1945 ) -> Result<U256, EthTransactError>
1946 where
1947 T::Nonce: Into<U256> + TryFrom<U256>,
1948 CallOf<T>: SetWeightLimit,
1949 {
1950 log::debug!(target: LOG_TARGET, "eth_estimate_gas: {tx:?}");
1951
1952 let mut low = U256::zero();
1953 let mut high = Self::evm_block_gas_limit();
1954
1955 log::trace!(target: LOG_TARGET, "eth_estimate_gas starting with low={low}, high={high}");
1956
1957 let perform_balance_checks = if let Some(gas_limit) = tx.gas {
1961 high = gas_limit;
1962 log::trace!(target: LOG_TARGET, "eth_estimate_gas high limited by the gas limit high={high}");
1963 true
1964 } else {
1965 false
1966 };
1967
1968 let fee_cap = tx.max_fee_per_gas.or(tx.gas_price);
1970 if let (Some(fee_cap), Some(from), true) = (fee_cap, tx.from, perform_balance_checks) {
1971 let mut available_balance = Self::evm_balance(&from);
1972 if let Some(value) = tx.value {
1973 available_balance = available_balance.checked_sub(value).ok_or_else(|| {
1974 EthTransactError::Message("insufficient funds for value transfer".into())
1975 })?;
1976 }
1977 if let Some(allowance) = available_balance.checked_div(fee_cap) {
1978 if high > allowance && allowance != U256::zero() {
1979 log::trace!(target: LOG_TARGET, "eth_estimate_gas high limited by the user's allowance high={high} allowance={allowance}");
1980 high = allowance
1981 }
1982 }
1983 }
1984
1985 let dry_run_at = |gas: U256| {
1989 let mut transaction = tx.clone();
1990 transaction.gas = Some(gas);
1991 with_transaction(|| {
1992 TransactionOutcome::Rollback(Ok::<_, DispatchError>(Self::dry_run_eth_transact(
1993 transaction,
1994 timestamp_override,
1995 perform_balance_checks,
1996 state_overrides.clone(),
1997 )))
1998 })
1999 .expect("Rollback shouldn't error out")
2000 };
2001
2002 let is_simple_transfer = with_transaction(|| {
2005 let probe = state_overrides
2006 .clone()
2007 .map_or(Ok(()), state_overrides::apply_state_overrides::<T>)
2008 .map(|()| Self::is_simple_transfer(&tx));
2009 TransactionOutcome::Rollback(Ok::<_, DispatchError>(probe))
2010 })
2011 .expect("Rollback shouldn't error out")?;
2012
2013 if is_simple_transfer {
2014 let dry_run_result = dry_run_at(high)?;
2015 log::trace!(
2016 target: LOG_TARGET,
2017 "eth_estimate_gas short-circuited simple transfer to {:?} with eth_gas={}",
2018 tx.to,
2019 dry_run_result.eth_gas,
2020 );
2021 return Ok(dry_run_result.eth_gas);
2022 }
2023
2024 let dry_run_results = [high, Self::evm_max_extrinsic_weight_in_gas()]
2029 .map(|gas_limit| (gas_limit, dry_run_at(gas_limit)));
2030 let (gas_limit, first_dry_run_result) = match dry_run_results {
2031 [(gas_limit1, Ok(dry_run_result1)), (gas_limit2, Ok(dry_run_result2))] => {
2032 if dry_run_result2.eth_gas >= gas_limit2 {
2033 (gas_limit1, dry_run_result1)
2034 } else {
2035 (gas_limit2, dry_run_result2)
2036 }
2037 },
2038 [(gas_limit, Ok(dry_run_result)), (_, Err(_))] |
2039 [(_, Err(_)), (gas_limit, Ok(dry_run_result))] => (gas_limit, dry_run_result),
2040 [(_, Err(err)), (_, Err(..))] => return Err(err),
2041 };
2042 log::trace!(
2043 target: LOG_TARGET,
2044 "eth_estimate_gas first dry run succeeded with gas_limit={} consumed={}",
2045 gas_limit,
2046 first_dry_run_result.eth_gas
2047 );
2048 low = first_dry_run_result.eth_gas;
2049 high = gas_limit;
2050
2051 while low + U256::one() < high {
2052 log::trace!(target: LOG_TARGET, "eth_estimate_gas estimation iteration with low={low} high={high}");
2053 let error_ratio = high
2054 .checked_sub(low)
2055 .and_then(|value| value.checked_mul(U256::from(1000)))
2056 .and_then(|value| value.checked_div(high))
2057 .ok_or_else(|| {
2058 EthTransactError::Message(
2059 "failed to calculate error ratio in gas estimation".into(),
2060 )
2061 })?;
2062 if error_ratio <= U256::from(15) {
2063 log::trace!(
2064 target: LOG_TARGET,
2065 "eth_estimate_gas finished due to error ratio being less than 1.5% high={}",
2066 high
2067 );
2068 break;
2069 }
2070
2071 let mut midpoint = high
2072 .checked_sub(low)
2073 .and_then(|value| value.checked_div(U256::from(2)))
2074 .and_then(|value| value.checked_add(low))
2075 .ok_or_else(|| {
2076 EthTransactError::Message(
2077 "failed to calculate midpoint in gas estimation".into(),
2078 )
2079 })?;
2080
2081 if let Some(other_midpoint) = low.checked_mul(U256::from(2)) {
2082 if other_midpoint != U256::zero() {
2083 midpoint = midpoint.min(other_midpoint)
2084 }
2085 };
2086
2087 let dry_run_result = dry_run_at(midpoint);
2088 log::trace!(target: LOG_TARGET, "eth_estimate_gas dry run result with midpoint={midpoint} is dry_run_result={dry_run_result:?}");
2089 match dry_run_result {
2090 Ok(..) => {
2091 log::trace!(target: LOG_TARGET, "eth_estimate_gas dry run succeeded, new high={midpoint}");
2092 high = midpoint
2093 },
2094 Err(..) => {
2095 log::trace!(target: LOG_TARGET, "eth_estimate_gas dry run failed, new low={midpoint}");
2096 low = midpoint
2097 },
2098 }
2099 }
2100
2101 log::trace!(target: LOG_TARGET, "eth_estimate_gas completed. high={high}");
2102 Ok(high)
2103 }
2104
2105 pub(crate) fn is_simple_transfer(tx: &GenericTransaction) -> bool {
2107 tx.to
2108 .map(|to| tx.has_simple_transfer_fields() && Self::address_runs_no_code(&to))
2109 .unwrap_or(false)
2110 }
2111
2112 fn address_runs_no_code(address: &H160) -> bool {
2115 *address != RUNTIME_PALLETS_ADDR &&
2118 !exec::is_precompile::<T, ContractBlob<T>>(address) &&
2119 !<AccountInfo<T>>::is_contract(address)
2120 }
2121
2122 pub fn eth_pre_dispatch_weight(transaction_encoded: Vec<u8>) -> Result<Weight, EthTransactError>
2130 where
2131 CallOf<T>: SetWeightLimit,
2132 {
2133 let signed_tx =
2134 crate::evm::TransactionSigned::decode(&transaction_encoded).map_err(|err| {
2135 EthTransactError::Message(format!("Failed to decode transaction: {err:?}"))
2136 })?;
2137 let signer_addr = signed_tx.recover_eth_address().map_err(|err| {
2138 EthTransactError::Message(format!("Failed to recover signer: {err:?}"))
2139 })?;
2140 let tx =
2141 GenericTransaction::from_signed(signed_tx, Self::evm_base_fee(), Some(signer_addr));
2142 let encoded_len = T::FeeInfo::encoded_len(
2143 crate::Call::<T>::eth_transact { payload: transaction_encoded.clone() }.into(),
2144 );
2145 let call_info = tx
2146 .into_call::<T>(CreateCallMode::ExtrinsicExecution(encoded_len, transaction_encoded))
2147 .map_err(|err| EthTransactError::Message(format!("Invalid call: {err:?}")))?;
2148 let info = T::FeeInfo::dispatch_info(&call_info.call);
2149
2150 Ok(frame_system::calculate_consumed_extrinsic_weight::<CallOf<T>>(
2151 &T::BlockWeights::get(),
2152 &info,
2153 call_info.encoded_len as usize,
2154 ))
2155 }
2156
2157 pub fn dry_run_eth_transact(
2168 mut tx: GenericTransaction,
2169 timestamp_override: Option<MomentOf<T>>,
2170 perform_balance_checks: bool,
2171 state_overrides: Option<StateOverrideSet>,
2172 ) -> Result<EthTransactInfo<BalanceOf<T>>, EthTransactError>
2173 where
2174 T::Nonce: Into<U256> + TryFrom<U256>,
2175 CallOf<T>: SetWeightLimit,
2176 {
2177 log::debug!(target: LOG_TARGET, "dry_run_eth_transact: {tx:?}");
2178
2179 let origin = T::AddressMapper::to_account_id(&tx.from.unwrap_or_default());
2180 Self::prepare_dry_run(&origin);
2181
2182 if let Some(overrides) = state_overrides {
2183 state_overrides::apply_state_overrides::<T>(overrides)?;
2184 }
2185
2186 let base_fee = Self::evm_base_fee();
2187 let effective_gas_price = tx.effective_gas_price(base_fee).unwrap_or(base_fee);
2188
2189 if effective_gas_price < base_fee {
2190 Err(EthTransactError::Message(format!(
2191 "Effective gas price {effective_gas_price:?} lower than base fee {base_fee:?}"
2192 )))?;
2193 }
2194
2195 if tx.nonce.is_none() {
2196 tx.nonce = Some(<System<T>>::account_nonce(&origin).into());
2197 }
2198 if tx.chain_id.is_none() {
2199 tx.chain_id = Some(T::ChainId::get().into());
2200 }
2201
2202 tx.gas_price = Some(effective_gas_price);
2204 tx.max_priority_fee_per_gas = Some(0.into());
2207 if tx.max_fee_per_gas.is_none() {
2208 tx.max_fee_per_gas = Some(effective_gas_price);
2209 }
2210
2211 let gas = tx.gas;
2212 if tx.gas.is_none() {
2213 tx.gas = Some(Self::evm_block_gas_limit());
2214 }
2215 if tx.r#type.is_none() {
2216 tx.r#type = Some(TYPE_EIP1559.into());
2217 }
2218
2219 let value = tx.value.unwrap_or_default();
2221 let input = tx.input.clone().to_vec();
2222 let from = tx.from;
2223 let to = tx.to;
2224
2225 let mut call_info = tx
2228 .into_call::<T>(CreateCallMode::DryRun)
2229 .map_err(|err| EthTransactError::Message(format!("Invalid call: {err:?}")))?;
2230
2231 let base_info = T::FeeInfo::base_dispatch_info(&mut call_info.call);
2235 let base_weight = base_info.total_weight();
2236 let exec_config =
2237 ExecConfig::new_eth_tx(effective_gas_price, call_info.encoded_len, base_weight)
2238 .with_dry_run(timestamp_override);
2239
2240 let fees = call_info.tx_fee.saturating_add(call_info.storage_deposit);
2242 if let Some(from) = &from {
2243 let fees = if gas.is_some() && perform_balance_checks { fees } else { Zero::zero() };
2244 let balance = Self::evm_balance(from);
2245 if balance < Pallet::<T>::convert_native_to_evm(fees).saturating_add(value) {
2246 return Err(EthTransactError::Message(format!(
2247 "insufficient funds for gas * price + value ({fees:?}): address {from:?} have {balance:?} (supplied gas {gas:?})",
2248 )));
2249 }
2250 }
2251
2252 T::FeeInfo::deposit_txfee(T::Currency::issue(fees));
2255
2256 let extract_error = |err| {
2257 if err == Error::<T>::StorageDepositNotEnoughFunds.into() {
2258 Err(EthTransactError::Message(format!("Not enough gas supplied: {err:?}")))
2259 } else {
2260 Err(EthTransactError::Message(format!("failed to run contract: {err:?}")))
2261 }
2262 };
2263
2264 let transaction_limits = TransactionLimits::EthereumGas {
2265 eth_gas_limit: call_info.eth_gas_limit.saturated_into(),
2266 weight_limit: Self::evm_max_extrinsic_weight(),
2267 eth_tx_info: EthTxInfo::new(call_info.encoded_len, base_weight),
2268 };
2269
2270 let mut dry_run = block_storage::with_receipt_scope::<T, _>(|| {
2273 let dry_run = match to {
2274 Some(dest) => {
2276 if dest == RUNTIME_PALLETS_ADDR {
2277 let Ok(dispatch_call) = <CallOf<T>>::decode(&mut &input[..]) else {
2278 return Err(EthTransactError::Message(format!(
2279 "Failed to decode pallet-call {input:?}"
2280 )));
2281 };
2282
2283 if let Err(result) =
2284 dispatch_call.clone().dispatch(RawOrigin::Signed(origin).into())
2285 {
2286 return Err(EthTransactError::Message(format!(
2287 "Failed to dispatch call: {:?}",
2288 result.error,
2289 )));
2290 };
2291
2292 Default::default()
2293 } else {
2294 let result = crate::Pallet::<T>::bare_call(
2296 OriginFor::<T>::signed(origin),
2297 dest,
2298 value,
2299 transaction_limits,
2300 input.clone(),
2301 &exec_config,
2302 );
2303
2304 let data = match result.result {
2305 Ok(return_value) => {
2306 if return_value.did_revert() {
2307 return Err(EthTransactError::Data(return_value.data));
2308 }
2309 return_value.data
2310 },
2311 Err(err) => {
2312 log::debug!(target: LOG_TARGET, "Failed to execute call: {err:?}");
2313 return extract_error(err);
2314 },
2315 };
2316
2317 EthTransactInfo {
2318 weight_required: result.weight_required,
2319 storage_deposit: result.storage_deposit.charge_or_zero(),
2320 max_storage_deposit: result.max_storage_deposit.charge_or_zero(),
2321 data,
2322 eth_gas: Default::default(),
2323 }
2324 }
2325 },
2326 None => {
2328 let (code, data) = if input.starts_with(&polkavm_common::program::BLOB_MAGIC) {
2330 extract_code_and_data(&input).unwrap_or_else(|| (input, Default::default()))
2331 } else {
2332 (input, vec![])
2333 };
2334
2335 let result = crate::Pallet::<T>::bare_instantiate(
2337 OriginFor::<T>::signed(origin),
2338 value,
2339 transaction_limits,
2340 Code::Upload(code.clone()),
2341 data.clone(),
2342 None,
2343 &exec_config,
2344 );
2345
2346 let returned_data = match result.result {
2347 Ok(return_value) => {
2348 if return_value.result.did_revert() {
2349 return Err(EthTransactError::Data(return_value.result.data));
2350 }
2351 return_value.result.data
2352 },
2353 Err(err) => {
2354 log::debug!(target: LOG_TARGET, "Failed to instantiate: {err:?}");
2355 return extract_error(err);
2356 },
2357 };
2358
2359 EthTransactInfo {
2360 weight_required: result.weight_required,
2361 storage_deposit: result.storage_deposit.charge_or_zero(),
2362 max_storage_deposit: result.max_storage_deposit.charge_or_zero(),
2363 data: returned_data,
2364 eth_gas: Default::default(),
2365 }
2366 },
2367 };
2368 Ok(dry_run)
2369 })?;
2370
2371 call_info.call.set_weight_limit(dry_run.weight_required);
2373
2374 let total_weight = T::FeeInfo::dispatch_info(&call_info.call).total_weight();
2376 let max_weight = Self::evm_max_extrinsic_weight();
2377 if total_weight.any_gt(max_weight) {
2378 log::debug!(target: LOG_TARGET, "Transaction weight estimate exceeds extrinsic maximum: \
2379 total_weight={total_weight:?} \
2380 max_weight={max_weight:?}",
2381 );
2382
2383 Err(EthTransactError::Message(format!(
2384 "\
2385 The transaction consumes more than the allowed weight. \
2386 needed={total_weight} \
2387 allowed={max_weight} \
2388 overweight_by={}\
2389 ",
2390 total_weight.saturating_sub(max_weight),
2391 )))?;
2392 }
2393
2394 let transaction_fee = T::FeeInfo::tx_fee(call_info.encoded_len, &call_info.call);
2396 let available_fee = T::FeeInfo::remaining_txfee();
2397 if transaction_fee > available_fee {
2398 Err(EthTransactError::Message(format!(
2399 "Not enough gas supplied: Off by: {:?}",
2400 transaction_fee.saturating_sub(available_fee),
2401 )))?;
2402 }
2403
2404 let total_cost = transaction_fee.saturating_add(dry_run.max_storage_deposit);
2405 let total_cost_wei = Pallet::<T>::convert_native_to_evm(total_cost);
2406 let (mut eth_gas, rest) = total_cost_wei.div_mod(base_fee);
2407 if !rest.is_zero() {
2408 eth_gas = eth_gas.saturating_add(1_u32.into());
2409 }
2410
2411 log::debug!(target: LOG_TARGET, "\
2412 dry_run_eth_transact finished: \
2413 weight_limit={}, \
2414 total_weight={total_weight}, \
2415 max_weight={max_weight}, \
2416 weight_left={}, \
2417 eth_gas={eth_gas}, \
2418 encoded_len={}, \
2419 tx_fee={transaction_fee:?}, \
2420 storage_deposit={:?}, \
2421 max_storage_deposit={:?}\
2422 ",
2423 dry_run.weight_required,
2424 max_weight.saturating_sub(total_weight),
2425 call_info.encoded_len,
2426 dry_run.storage_deposit,
2427 dry_run.max_storage_deposit,
2428
2429 );
2430 dry_run.eth_gas = eth_gas;
2431 Ok(dry_run)
2432 }
2433
2434 pub fn evm_balance(address: &H160) -> U256 {
2438 let balance = AccountInfo::<T>::balance_of((*address).into());
2439 Self::convert_native_to_evm(balance)
2440 }
2441
2442 pub fn eth_block() -> EthBlock {
2444 EthereumBlock::<T>::get()
2445 }
2446
2447 pub fn eth_block_hash_from_number(number: U256) -> Option<H256> {
2454 let number = BlockNumberFor::<T>::try_from(number).ok()?;
2455 let hash = <BlockHash<T>>::get(number);
2456 if hash == H256::zero() { None } else { Some(hash) }
2457 }
2458
2459 pub fn eth_receipt_data() -> Vec<ReceiptGasInfo> {
2461 ReceiptInfoData::<T>::get()
2462 }
2463
2464 pub fn set_evm_balance(address: &H160, evm_value: U256) -> Result<(), Error<T>> {
2470 let (balance, dust) = Self::new_balance_with_dust(evm_value)
2471 .map_err(|_| <Error<T>>::BalanceConversionFailed)?;
2472 let account_id = T::AddressMapper::to_account_id(&address);
2473 T::Currency::set_balance(&account_id, balance);
2474 AccountInfoOf::<T>::mutate(&address, |account| {
2475 if let Some(account) = account {
2476 account.dust = dust;
2477 } else {
2478 *account = Some(AccountInfo { dust, ..Default::default() });
2479 }
2480 });
2481
2482 Ok(())
2483 }
2484
2485 pub fn new_balance_with_dust(
2489 evm_value: U256,
2490 ) -> Result<(BalanceOf<T>, u32), BalanceConversionError> {
2491 let ed = T::Currency::minimum_balance();
2492 let balance_with_dust = BalanceWithDust::<BalanceOf<T>>::from_value::<T>(evm_value)?;
2493 let (value, dust) = balance_with_dust.deconstruct();
2494
2495 Ok((ed.saturating_add(value), dust))
2496 }
2497
2498 pub fn evm_nonce(address: &H160) -> u32
2500 where
2501 T::Nonce: Into<u32>,
2502 {
2503 let account = T::AddressMapper::to_account_id(&address);
2504 System::<T>::account_nonce(account).into()
2505 }
2506
2507 pub fn evm_block_gas_limit() -> U256 {
2509 u64::MAX.into()
2516 }
2517
2518 pub fn evm_max_extrinsic_weight_in_gas() -> U256 {
2520 let max_extrinsic_fee = T::FeeInfo::weight_to_fee(&Self::evm_max_extrinsic_weight());
2521 let gas_scale: BalanceOf<T> = T::GasScale::get().into();
2522 (max_extrinsic_fee / gas_scale).into()
2523 }
2524
2525 pub fn evm_max_extrinsic_weight() -> Weight {
2527 let factor = <T as Config>::MaxEthExtrinsicWeight::get();
2528 let max_weight = <T as frame_system::Config>::BlockWeights::get()
2529 .get(DispatchClass::Normal)
2530 .max_extrinsic
2531 .unwrap_or_else(|| <T as frame_system::Config>::BlockWeights::get().max_block);
2532 Weight::from_parts(
2533 factor.saturating_mul_int(max_weight.ref_time()),
2534 factor.saturating_mul_int(max_weight.proof_size()),
2535 )
2536 }
2537
2538 pub fn evm_base_fee() -> U256 {
2540 let gas_scale = <T as Config>::GasScale::get();
2541 let multiplier = T::FeeInfo::next_fee_multiplier();
2542 multiplier
2543 .saturating_mul_int::<u128>(T::NativeToEthRatio::get().into())
2544 .saturating_mul(gas_scale.saturated_into())
2545 .into()
2546 }
2547
2548 pub fn evm_tracer(tracer_type: TracerType) -> Tracer<T>
2550 where
2551 T::Nonce: Into<u32>,
2552 {
2553 match tracer_type {
2554 TracerType::CallTracer(config) => CallTracer::new(config.unwrap_or_default()).into(),
2555 TracerType::PrestateTracer(config) => {
2556 PrestateTracer::new(config.unwrap_or_default()).into()
2557 },
2558 TracerType::ExecutionTracer(config) => {
2559 ExecutionTracer::new(config.unwrap_or_default()).into()
2560 },
2561 }
2562 }
2563
2564 pub fn bare_upload_code(
2568 origin: OriginFor<T>,
2569 code: Vec<u8>,
2570 storage_deposit_limit: BalanceOf<T>,
2571 ) -> CodeUploadResult<BalanceOf<T>> {
2572 let origin = T::UploadOrigin::ensure_origin(origin)?;
2573
2574 let bytecode_type = if code.starts_with(&polkavm_common::program::BLOB_MAGIC) {
2575 BytecodeType::Pvm
2576 } else {
2577 if !T::AllowEVMBytecode::get() {
2578 return Err(<Error<T>>::CodeRejected.into());
2579 }
2580 BytecodeType::Evm
2581 };
2582
2583 let mut meter = TransactionMeter::new(TransactionLimits::WeightAndDeposit {
2584 weight_limit: Default::default(),
2585 deposit_limit: storage_deposit_limit,
2586 })?;
2587
2588 let module = Self::try_upload_code(
2589 origin,
2590 code,
2591 bytecode_type,
2592 &mut meter,
2593 &ExecConfig::new_substrate_tx(),
2594 )?;
2595 Ok(CodeUploadReturnValue {
2596 code_hash: *module.code_hash(),
2597 deposit: meter.deposit_consumed().charge_or_zero(),
2598 })
2599 }
2600
2601 pub fn get_storage(address: H160, key: [u8; 32]) -> GetStorageResult {
2603 let contract_info =
2604 AccountInfo::<T>::load_contract(&address).ok_or(ContractAccessError::DoesntExist)?;
2605
2606 let maybe_value = contract_info.read(&Key::from_fixed(key));
2607 Ok(maybe_value)
2608 }
2609
2610 pub fn get_immutables(address: H160) -> Option<ImmutableData> {
2614 let immutable_data = <ImmutableDataOf<T>>::get(address);
2615 immutable_data
2616 }
2617
2618 pub fn set_immutables(address: H160, data: ImmutableData) -> Result<(), ContractAccessError> {
2626 AccountInfo::<T>::load_contract(&address).ok_or(ContractAccessError::DoesntExist)?;
2627 <ImmutableDataOf<T>>::insert(address, data);
2628 Ok(())
2629 }
2630
2631 pub fn get_storage_var_key(address: H160, key: Vec<u8>) -> GetStorageResult {
2633 let contract_info =
2634 AccountInfo::<T>::load_contract(&address).ok_or(ContractAccessError::DoesntExist)?;
2635
2636 let maybe_value = contract_info.read(
2637 &Key::try_from_var(key)
2638 .map_err(|_| ContractAccessError::KeyDecodingFailed)?
2639 .into(),
2640 );
2641 Ok(maybe_value)
2642 }
2643
2644 pub fn convert_native_to_evm(value: impl Into<BalanceWithDust<BalanceOf<T>>>) -> U256 {
2646 let (value, dust) = value.into().deconstruct();
2647 value
2648 .into()
2649 .saturating_mul(T::NativeToEthRatio::get().into())
2650 .saturating_add(dust.into())
2651 }
2652
2653 pub fn set_storage(address: H160, key: [u8; 32], value: Option<Vec<u8>>) -> SetStorageResult {
2663 let contract_info =
2664 AccountInfo::<T>::load_contract(&address).ok_or(ContractAccessError::DoesntExist)?;
2665
2666 contract_info
2667 .write(&Key::from_fixed(key), value, None, false)
2668 .map_err(ContractAccessError::StorageWriteFailed)
2669 }
2670
2671 pub fn set_storage_var_key(
2682 address: H160,
2683 key: Vec<u8>,
2684 value: Option<Vec<u8>>,
2685 ) -> SetStorageResult {
2686 let contract_info =
2687 AccountInfo::<T>::load_contract(&address).ok_or(ContractAccessError::DoesntExist)?;
2688
2689 contract_info
2690 .write(
2691 &Key::try_from_var(key)
2692 .map_err(|_| ContractAccessError::KeyDecodingFailed)?
2693 .into(),
2694 value,
2695 None,
2696 false,
2697 )
2698 .map_err(ContractAccessError::StorageWriteFailed)
2699 }
2700
2701 pub fn account_id() -> T::AccountId {
2703 use frame_support::PalletId;
2704 use sp_runtime::traits::AccountIdConversion;
2705 PalletId(*b"py/reviv").into_account_truncating()
2706 }
2707
2708 pub fn block_author() -> H160 {
2710 use frame_support::traits::FindAuthor;
2711
2712 let digest = <frame_system::Pallet<T>>::digest();
2713 let pre_runtime_digests = digest.logs.iter().filter_map(|d| d.as_pre_runtime());
2714
2715 T::FindAuthor::find_author(pre_runtime_digests)
2716 .map(|account_id| T::AddressMapper::to_address(&account_id))
2717 .unwrap_or_default()
2718 }
2719
2720 pub fn code(address: &H160) -> Vec<u8> {
2724 use precompiles::{All, Precompiles};
2725 if let Some(code) = <All<T>>::code(address.as_fixed_bytes()) {
2726 return code.into();
2727 }
2728 AccountInfo::<T>::load_contract(&address)
2729 .and_then(|contract| <PristineCode<T>>::get(contract.code_hash))
2730 .map(|code| code.into())
2731 .unwrap_or_default()
2732 }
2733
2734 pub fn try_upload_code(
2736 origin: T::AccountId,
2737 code: Vec<u8>,
2738 code_type: BytecodeType,
2739 meter: &mut TransactionMeter<T>,
2740 exec_config: &ExecConfig<T>,
2741 ) -> Result<ContractBlob<T>, DispatchError> {
2742 let mut module = match code_type {
2743 BytecodeType::Pvm => ContractBlob::from_pvm_code(code, origin)?,
2744 BytecodeType::Evm => ContractBlob::from_evm_runtime_code(code, origin)?,
2745 };
2746 module.store_code(exec_config, meter)?;
2747 Ok(module)
2748 }
2749
2750 fn run_guarded<R, F: FnOnce() -> Result<R, ExecError>>(f: F) -> Result<R, ExecError> {
2752 executing_contract::using_once(&mut false, || {
2753 executing_contract::with(|f| {
2754 if *f {
2756 return Err(())
2757 }
2758 *f = true;
2760 Ok(())
2761 })
2762 .expect("Returns `Ok` if called within `using_once`. It is syntactically obvious that this is the case; qed")
2763 .map_err(|_| <Error<T>>::ReenteredPallet.into())
2764 .map(|_| f())
2765 .and_then(|r| r)
2766 })
2767 }
2768
2769 fn charge_deposit(
2774 hold_reason: HoldReason,
2775 from: &T::AccountId,
2776 to: &T::AccountId,
2777 amount: BalanceOf<T>,
2778 exec_config: &ExecConfig<T>,
2779 ) -> DispatchResult {
2780 if amount.is_zero() {
2781 return Ok(());
2782 }
2783
2784 T::Deposit::charge_and_hold(hold_reason, exec_config.funds(from), to, amount)
2785 .map_err(|_| Error::<T>::StorageDepositNotEnoughFunds)?;
2786 Ok(())
2787 }
2788
2789 fn refund_deposit(
2794 hold_reason: HoldReason,
2795 from: &T::AccountId,
2796 dst: deposit_payment::Funds<T::AccountId>,
2797 amount: BalanceOf<T>,
2798 ) -> Result<(), DispatchError> {
2799 if amount.is_zero() {
2800 return Ok(());
2801 }
2802
2803 let to = match &dst {
2804 deposit_payment::Funds::Balance(to) | deposit_payment::Funds::TxFee(to) => *to,
2805 };
2806 let result = T::Deposit::refund_on_hold(hold_reason, from, dst, amount);
2807
2808 result.defensive_map_err(|err| {
2809 let available = T::Deposit::total_on_hold(hold_reason, from);
2810 if available < amount {
2811 log::error!(
2814 target: LOG_TARGET,
2815 "Failed to refund storage deposit {amount:?} from contract {from:?} to origin {to:?}. Not enough deposit: {available:?}. This is a bug.",
2816 );
2817 Error::<T>::StorageRefundNotEnoughFunds.into()
2818 } else {
2819 log::warn!(
2824 target: LOG_TARGET,
2825 "Failed to refund storage deposit {amount:?} from contract {from:?} to origin {to:?}: {err:?}. First remove locks (staking, governance) from the contracts account.",
2826 );
2827 Error::<T>::StorageRefundLocked.into()
2828 }
2829 })
2830 }
2831
2832 fn has_dust(value: U256) -> bool {
2834 value % U256::from(<T>::NativeToEthRatio::get()) != U256::zero()
2835 }
2836
2837 fn has_balance(value: U256) -> bool {
2839 value >= U256::from(<T>::NativeToEthRatio::get())
2840 }
2841
2842 #[cfg(any(feature = "runtime-benchmarks", feature = "try-runtime", test))]
2844 fn min_balance() -> BalanceOf<T> {
2845 <T::Currency as Inspect<AccountIdOf<T>>>::minimum_balance()
2846 }
2847
2848 fn deposit_event(event: Event<T>) {
2853 <frame_system::Pallet<T>>::deposit_event(<T as Config>::RuntimeEvent::from(event))
2854 }
2855
2856 fn ensure_eth_signed(origin: OriginFor<T>) -> Result<AccountIdOf<T>, DispatchError> {
2858 match <T as Config>::RuntimeOrigin::from(origin).into() {
2859 Ok(Origin::EthTransaction(signer)) => Ok(signer),
2860 _ => Err(BadOrigin.into()),
2861 }
2862 }
2863
2864 fn ensure_non_contract_if_signed(origin: &OriginFor<T>) -> DispatchResult {
2868 if DebugSettings::bypass_eip_3607::<T>() {
2869 return Ok(());
2870 }
2871 let Some(address) = origin
2872 .as_system_ref()
2873 .and_then(|o| o.as_signed())
2874 .map(<T::AddressMapper as AddressMapper<T>>::to_address)
2875 else {
2876 return Ok(());
2877 };
2878 if exec::is_precompile::<T, ContractBlob<T>>(&address) ||
2879 <AccountInfo<T>>::is_contract(&address)
2880 {
2881 log::debug!(
2882 target: crate::LOG_TARGET,
2883 "EIP-3607: reject tx as pre-compile or account exist at {address:?}",
2884 );
2885 Err(DispatchError::BadOrigin)
2886 } else {
2887 Ok(())
2888 }
2889 }
2890}
2891
2892pub const RUNTIME_PALLETS_ADDR: H160 =
2897 H160(hex_literal::hex!("6d6f646c70792f70616464720000000000000000"));
2898
2899environmental!(executing_contract: bool);
2901
2902sp_api::decl_runtime_apis! {
2903 #[api_version(2)]
2905 pub trait ReviveApi<AccountId, Balance, Nonce, BlockNumber, Moment> where
2906 AccountId: Codec,
2907 Balance: Codec,
2908 Nonce: Codec,
2909 BlockNumber: Codec,
2910 Moment: Codec,
2911 {
2912 #[deprecated(note = "Use the versioned equivalent `eth_block_versioned` if available on your runtime")]
2916 fn eth_block() -> BlockV1;
2917
2918 #[deprecated(note = "Use the versioned equivalent `eth_block_hash_versioned` if available on your runtime")]
2920 fn eth_block_hash(number: U256) -> Option<H256>;
2921
2922 #[deprecated(note = "Use the versioned equivalent `eth_receipt_data_versioned` if available on your runtime")]
2928 fn eth_receipt_data() -> Vec<ReceiptGasInfoV1>;
2929
2930 #[deprecated(note = "Use the versioned equivalent `block_gas_limit_versioned` if available on your runtime")]
2932 fn block_gas_limit() -> U256;
2933
2934 #[deprecated(note = "Use the versioned equivalent `max_extrinsic_weight_in_gas_versioned` if available on your runtime")]
2936 fn max_extrinsic_weight_in_gas() -> U256;
2937
2938 #[deprecated(note = "Use the versioned equivalent `balance_versioned` if available on your runtime")]
2940 fn balance(address: H160) -> U256;
2941
2942 #[deprecated(note = "Use the versioned equivalent `gas_price_versioned` if available on your runtime")]
2944 fn gas_price() -> U256;
2945
2946 #[deprecated(note = "Use the versioned equivalent `nonce_versioned` if available on your runtime")]
2948 fn nonce(address: H160) -> Nonce;
2949
2950 #[deprecated(note = "Use the versioned equivalent `call_versioned` if available on your runtime")]
2954 fn call(
2955 origin: AccountId,
2956 dest: H160,
2957 value: Balance,
2958 gas_limit: Option<Weight>,
2959 storage_deposit_limit: Option<Balance>,
2960 input_data: Vec<u8>,
2961 ) -> ContractResultV1<ExecReturnValueV1, Balance>;
2962
2963 #[deprecated(note = "Use the versioned equivalent `instantiate_versioned` if available on your runtime")]
2967 fn instantiate(
2968 origin: AccountId,
2969 value: Balance,
2970 gas_limit: Option<Weight>,
2971 storage_deposit_limit: Option<Balance>,
2972 code: CodeV1,
2973 data: Vec<u8>,
2974 salt: Option<[u8; 32]>,
2975 ) -> ContractResultV1<InstantiateReturnValueV1, Balance>;
2976
2977
2978 #[deprecated(note = "Use the versioned equivalent `eth_transact_versioned` if available on your runtime")]
2982 fn eth_transact(tx: GenericTransactionV1) -> Result<EthTransactInfoV1<Balance>, EthTransactError>;
2983
2984 #[deprecated(note = "Use the versioned equivalent `eth_transact_versioned` if available on your runtime")]
2988 fn eth_transact_with_config(
2989 tx: GenericTransactionV1,
2990 config: DryRunConfigV1<Moment>,
2991 ) -> Result<EthTransactInfoV1<Balance>, EthTransactError>;
2992
2993 #[deprecated(note = "Use the versioned equivalent `eth_estimate_gas_versioned` if available on your runtime")]
2999 fn eth_estimate_gas(
3000 tx: GenericTransactionV1,
3001 config: DryRunConfigV1<Moment>
3002 ) -> Result<U256, EthTransactError>;
3003
3004 #[deprecated(note = "Use the versioned equivalent `eth_pre_dispatch_weight_versioned` if available on your runtime")]
3006 fn eth_pre_dispatch_weight(tx: Vec<u8>) -> Result<Weight, EthTransactError>;
3007
3008 #[deprecated(note = "Use the versioned equivalent `upload_code_versioned` if available on your runtime")]
3012 fn upload_code(
3013 origin: AccountId,
3014 code: Vec<u8>,
3015 storage_deposit_limit: Option<Balance>,
3016 ) -> Result<CodeUploadReturnValueV1<Balance>, DispatchError>;
3017
3018 #[deprecated(note = "Use the versioned equivalent `get_storage_versioned` if available on your runtime")]
3024 fn get_storage(
3025 address: H160,
3026 key: [u8; 32],
3027 ) -> GetStorageResult;
3028
3029 #[deprecated(note = "Use the versioned equivalent `get_storage_versioned` if available on your runtime")]
3035 fn get_storage_var_key(
3036 address: H160,
3037 key: Vec<u8>,
3038 ) -> GetStorageResult;
3039
3040 #[deprecated(note = "Use the versioned equivalent `trace_block_versioned` if available on your runtime")]
3047 fn trace_block(
3048 block: Block,
3049 config: TracerTypeV1
3050 ) -> Vec<(u32, TraceV1)>;
3051
3052 #[deprecated(note = "Use the versioned equivalent `trace_tx_versioned` if available on your runtime")]
3059 fn trace_tx(
3060 block: Block,
3061 tx_index: u32,
3062 config: TracerTypeV1
3063 ) -> Option<TraceV1>;
3064
3065 #[deprecated(note = "Use the versioned equivalent `trace_call_versioned` if available on your runtime")]
3069 fn trace_call(tx: GenericTransactionV1, config: TracerTypeV1) -> Result<TraceV1, EthTransactError>;
3070
3071 #[deprecated(note = "Use the versioned equivalent `trace_call_versioned` if available on your runtime")]
3076 fn trace_call_with_config(
3077 tx: GenericTransactionV1,
3078 tracer_type: TracerTypeV1,
3079 config: TracingConfigV1,
3080 ) -> Result<TraceV1, EthTransactError>;
3081
3082 #[deprecated(note = "Use the versioned equivalent `block_author_versioned` if available on your runtime")]
3084 fn block_author() -> H160;
3085
3086 #[deprecated(note = "Use the versioned equivalent `address_versioned` if available on your runtime")]
3088 fn address(account_id: AccountId) -> H160;
3089
3090 #[deprecated(note = "Use the versioned equivalent `account_id_versioned` if available on your runtime")]
3092 fn account_id(address: H160) -> AccountId;
3093
3094 #[deprecated(note = "Use the versioned equivalent `runtime_pallets_address_versioned` if available on your runtime")]
3096 fn runtime_pallets_address() -> H160;
3097
3098 #[deprecated(note = "Use the versioned equivalent `code_versioned` if available on your runtime")]
3100 fn code(address: H160) -> Vec<u8>;
3101
3102 #[deprecated(note = "Use the versioned equivalent `new_balance_with_dust_versioned` if available on your runtime")]
3104 fn new_balance_with_dust(balance: U256) -> Result<(Balance, u32), BalanceConversionError>;
3105
3106 #[api_version(2)]
3109 fn version_declarations() -> ReviveRuntimeApiVersionDeclarations;
3110
3111 #[api_version(2)]
3112 fn eth_block_versioned(input: BlockVersionedInputPayload) -> BlockVersionedOutputPayload;
3113
3114 #[api_version(2)]
3115 fn eth_block_hash_versioned(input: BlockHashVersionedInputPayload) -> BlockHashVersionedOutputPayload;
3116
3117 #[api_version(2)]
3118 fn eth_receipt_data_versioned(input: ReceiptDataVersionedInputPayload) -> ReceiptDataVersionedOutputPayload;
3119
3120 #[api_version(2)]
3121 fn block_gas_limit_versioned(
3122 input: BlockGasLimitVersionedInputPayload
3123 ) -> BlockGasLimitVersionedOutputPayload;
3124
3125 #[api_version(2)]
3126 fn max_extrinsic_weight_in_gas_versioned(
3127 input: MaxExtrinsicWeightInGasVersionedInputPayload
3128 ) -> MaxExtrinsicWeightInGasVersionedOutputPayload;
3129
3130 #[api_version(2)]
3131 fn balance_versioned(input: BalanceVersionedInputPayload) -> BalanceVersionedOutputPayload;
3132
3133 #[api_version(2)]
3134 fn gas_price_versioned(input: GasPriceVersionedInputPayload) -> GasPriceVersionedOutputPayload;
3135
3136 #[api_version(2)]
3137 fn nonce_versioned(input: NonceVersionedInputPayload) -> NonceVersionedOutputPayload<Nonce>;
3138
3139 #[api_version(2)]
3140 fn call_versioned(
3141 input: CallVersionedInputPayload<AccountId, Balance>
3142 ) -> CallVersionedOutputPayload<Balance>;
3143
3144 #[api_version(2)]
3145 fn instantiate_versioned(
3146 input: InstantiateVersionedInputPayload<AccountId, Balance>
3147 ) -> InstantiateVersionedOutputPayload<Balance>;
3148
3149 #[api_version(2)]
3150 fn eth_transact_versioned(
3151 input: TransactVersionedInputPayload<Moment>
3152 ) -> Result<TransactVersionedOutputPayload<Balance>, EthTransactError>;
3153
3154 #[api_version(2)]
3155 fn eth_estimate_gas_versioned(
3156 input: EstimateGasVersionedInputPayload<Moment>
3157 ) -> Result<EstimateGasVersionedOutputPayload, EthTransactError>;
3158
3159 #[api_version(2)]
3160 fn eth_pre_dispatch_weight_versioned(
3161 input: PreDispatchWeightVersionedInputPayload
3162 ) -> Result<PreDispatchWeightVersionedOutputPayload, EthTransactError>;
3163
3164 #[api_version(2)]
3165 fn upload_code_versioned(
3166 input: UploadCodeVersionedInputPayload<AccountId, Balance>
3167 ) -> Result<UploadCodeVersionedOutputPayload<Balance>, DispatchError>;
3168
3169 #[api_version(2)]
3170 fn get_storage_versioned(
3171 input: GetStorageVersionedInputPayload
3172 ) -> Result<GetStorageVersionedOutputPayload, ContractAccessError>;
3173
3174 #[api_version(2)]
3175 fn runtime_pallets_address_versioned(
3176 input: RuntimePalletsAddressVersionedInputPayload
3177 ) -> RuntimePalletsAddressVersionedOutputPayload;
3178
3179 #[api_version(2)]
3180 fn code_versioned(input: CodeVersionedInputPayload) -> CodeVersionedOutputPayload;
3181
3182 #[api_version(2)]
3183 fn account_id_versioned(input: AccountIdVersionedInputPayload) -> AccountIdVersionedOutputPayload<AccountId>;
3184
3185 #[api_version(2)]
3186 fn new_balance_with_dust_versioned(
3187 input: NewBalanceWithDustVersionedInputPayload
3188 ) -> Result<NewBalanceWithDustVersionedOutputPayload<Balance>, BalanceConversionError>;
3189
3190 #[api_version(2)]
3191 fn block_author_versioned(input: BlockAuthorVersionedInputPayload) -> BlockAuthorVersionedOutputPayload;
3192
3193 #[api_version(2)]
3194 fn address_versioned(input: AddressVersionedInputPayload<AccountId>) -> AddressVersionedOutputPayload;
3195
3196 #[api_version(2)]
3197 fn trace_block_versioned(input: TraceBlockVersionedInputPayload<Block>) -> TraceBlockVersionedOutputPayload;
3198
3199 #[api_version(2)]
3200 fn trace_tx_versioned(input: TraceTxVersionedInputPayload<Block>) -> TraceTxVersionedOutputPayload;
3201
3202 #[api_version(2)]
3203 fn trace_call_versioned(
3204 input: TraceCallVersionedInputPayload
3205 ) -> Result<TraceCallVersionedOutputPayload, EthTransactError>;
3206 }
3207}
3208
3209#[macro_export]
3223macro_rules! impl_runtime_apis_plus_revive_traits {
3224 ($Runtime: ty, $Revive: ident, $Executive: ty, $EthExtra: ty, $($rest:tt)*) => {
3225
3226 type __ReviveMacroMoment = $crate::MomentOf<$Runtime>;
3227
3228 impl $crate::evm::runtime::SetWeightLimit for RuntimeCall {
3229 fn set_weight_limit(&mut self, new_weight_limit: Weight) -> Weight {
3230 use $crate::pallet::Call as ReviveCall;
3231 match self {
3232 Self::$Revive(
3233 ReviveCall::eth_call{ weight_limit, .. } |
3234 ReviveCall::eth_instantiate_with_code{ weight_limit, .. }
3235 ) => {
3236 let old = *weight_limit;
3237 *weight_limit = new_weight_limit;
3238 old
3239 },
3240 _ => Weight::default(),
3241 }
3242 }
3243 }
3244
3245 impl_runtime_apis! {
3246 $($rest)*
3247
3248 #[api_version(2)]
3249 impl pallet_revive::ReviveApi<Block, AccountId, Balance, Nonce, BlockNumber, __ReviveMacroMoment> for $Runtime
3250 {
3251 fn eth_block() -> $crate::pallet_revive_types::runtime_api::BlockV1 {
3252 use $crate::pallet_revive_types::runtime_api::*;
3253
3254 let input = BlockVersionedInputPayload::from(BlockInputPayloadV1);
3255 let output = Self::eth_block_versioned(input);
3256 BlockOutputPayloadV1::try_from(output)
3257 .expect("v1 input must produce v1 output; qed")
3258 .block
3259 }
3260
3261 fn eth_block_hash(number: $crate::U256) -> Option<$crate::H256> {
3262 use $crate::pallet_revive_types::runtime_api::*;
3263
3264 let input = BlockHashVersionedInputPayload::from(BlockHashInputPayloadV1 {
3265 block_number: number
3266 });
3267 let output = Self::eth_block_hash_versioned(input);
3268 BlockHashOutputPayloadV1::try_from(output)
3269 .expect("v1 input must produce v1 output; qed")
3270 .block_hash
3271 }
3272
3273 fn eth_receipt_data() -> Vec<$crate::pallet_revive_types::runtime_api::ReceiptGasInfoV1> {
3274 use $crate::pallet_revive_types::runtime_api::*;
3275
3276 let input = ReceiptDataVersionedInputPayload::from(ReceiptDataInputPayloadV1);
3277 let output = Self::eth_receipt_data_versioned(input);
3278 ReceiptDataOutputPayloadV1::try_from(output)
3279 .expect("v1 input must produce v1 output; qed")
3280 .receipt_data
3281 }
3282
3283 fn balance(address: $crate::H160) -> $crate::U256 {
3284 use $crate::pallet_revive_types::runtime_api::*;
3285
3286 let input = BalanceVersionedInputPayload::from(BalanceInputPayloadV1 { address });
3287 let output = Self::balance_versioned(input);
3288 BalanceOutputPayloadV1::try_from(output)
3289 .expect("v1 input must produce v1 output; qed")
3290 .balance
3291 }
3292
3293 fn block_author() -> $crate::H160 {
3294 use $crate::pallet_revive_types::runtime_api::*;
3295
3296 let input = BlockAuthorVersionedInputPayload::from(BlockAuthorInputPayloadV1);
3297 let output = Self::block_author_versioned(input);
3298 BlockAuthorOutputPayloadV1::try_from(output)
3299 .expect("v1 input must produce v1 output; qed")
3300 .block_author
3301 }
3302
3303 fn block_gas_limit() -> $crate::U256 {
3304 use $crate::pallet_revive_types::runtime_api::*;
3305
3306 let input = BlockGasLimitVersionedInputPayload::from(BlockGasLimitInputPayloadV1);
3307 let output = Self::block_gas_limit_versioned(input);
3308 BlockGasLimitOutputPayloadV1::try_from(output)
3309 .expect("v1 input must produce v1 output; qed")
3310 .block_gas_limit
3311 }
3312
3313 fn max_extrinsic_weight_in_gas() -> $crate::U256 {
3314 use $crate::pallet_revive_types::runtime_api::*;
3315
3316 let input = MaxExtrinsicWeightInGasVersionedInputPayload::from(
3317 MaxExtrinsicWeightInGasInputPayloadV1
3318 );
3319 let output = Self::max_extrinsic_weight_in_gas_versioned(input);
3320 MaxExtrinsicWeightInGasOutputPayloadV1::try_from(output)
3321 .expect("v1 input must produce v1 output; qed")
3322 .max_extrinsic_weight_in_gas
3323 }
3324
3325 fn gas_price() -> $crate::U256 {
3326 use $crate::pallet_revive_types::runtime_api::*;
3327
3328 let input = GasPriceVersionedInputPayload::from(GasPriceInputPayloadV1);
3329 let output = Self::gas_price_versioned(input);
3330 GasPriceOutputPayloadV1::try_from(output)
3331 .expect("v1 input must produce v1 output; qed")
3332 .gas_price
3333 }
3334
3335 fn nonce(address: $crate::H160) -> Nonce {
3336 use $crate::pallet_revive_types::runtime_api::*;
3337
3338 let input = NonceVersionedInputPayload::from(NonceInputPayloadV1 { address });
3339 let output = Self::nonce_versioned(input);
3340 NonceOutputPayloadV1::try_from(output)
3341 .expect("v1 input must produce v1 output; qed")
3342 .nonce
3343 }
3344
3345 fn address(account_id: AccountId) -> $crate::H160 {
3346 use $crate::pallet_revive_types::runtime_api::*;
3347
3348 let input = AddressVersionedInputPayload::from(AddressInputPayloadV1 { account_id });
3349 let output = Self::address_versioned(input);
3350 AddressOutputPayloadV1::try_from(output)
3351 .expect("v1 input must produce v1 output; qed")
3352 .address
3353 }
3354
3355 fn eth_transact(
3356 tx: $crate::pallet_revive_types::runtime_api::GenericTransactionV1,
3357 ) -> Result<
3358 $crate::pallet_revive_types::runtime_api::EthTransactInfoV1<Balance>,
3359 $crate::EthTransactError
3360 > {
3361 use $crate::pallet_revive_types::runtime_api::*;
3362
3363 let input = TransactVersionedInputPayload::from(TransactInputPayloadV1 {
3364 tx,
3365 timestamp_override: None,
3366 perform_balance_checks: true,
3367 state_overrides: None
3368 });
3369 let output = Self::eth_transact_versioned(input)?;
3370 Ok(TransactOutputPayloadV1::try_from(output)
3371 .expect("v1 input must produce v1 output; qed")
3372 .transact_info)
3373 }
3374
3375 fn eth_transact_with_config(
3376 tx: $crate::pallet_revive_types::runtime_api::GenericTransactionV1,
3377 config: $crate::pallet_revive_types::runtime_api::DryRunConfigV1<__ReviveMacroMoment>,
3378 ) -> Result<
3379 $crate::pallet_revive_types::runtime_api::EthTransactInfoV1<Balance>,
3380 $crate::EthTransactError
3381 > {
3382 use $crate::pallet_revive_types::runtime_api::*;
3383
3384 let DryRunConfigV1 { timestamp_override, perform_balance_checks, state_overrides } =
3385 config;
3386
3387 let input = TransactVersionedInputPayload::from(TransactInputPayloadV1 {
3388 tx,
3389 timestamp_override,
3390 perform_balance_checks: perform_balance_checks.unwrap_or(false),
3391 state_overrides
3392 });
3393 let output = Self::eth_transact_versioned(input)?;
3394 Ok(TransactOutputPayloadV1::try_from(output)
3395 .expect("v1 input must produce v1 output; qed")
3396 .transact_info)
3397 }
3398
3399 fn eth_estimate_gas(
3400 tx: $crate::pallet_revive_types::runtime_api::GenericTransactionV1,
3401 config: $crate::pallet_revive_types::runtime_api::DryRunConfigV1<__ReviveMacroMoment>,
3402 ) -> Result<$crate::U256, $crate::EthTransactError> {
3403 use $crate::pallet_revive_types::runtime_api::*;
3404
3405 let DryRunConfigV1 { timestamp_override, perform_balance_checks: _, state_overrides } =
3406 config;
3407
3408 let input = EstimateGasVersionedInputPayload::from(EstimateGasInputPayloadV1 {
3409 tx,
3410 timestamp_override,
3411 state_overrides
3412 });
3413 let output = Self::eth_estimate_gas_versioned(input)?;
3414 Ok(EstimateGasOutputPayloadV1::try_from(output)
3415 .expect("v1 input must produce v1 output; qed")
3416 .gas_estimate)
3417 }
3418
3419 fn eth_pre_dispatch_weight(
3420 tx: Vec<u8>,
3421 ) -> Result<$crate::Weight, $crate::EthTransactError> {
3422 use $crate::pallet_revive_types::runtime_api::*;
3423
3424 let input = PreDispatchWeightVersionedInputPayload::from(
3425 PreDispatchWeightInputPayloadV1 { tx }
3426 );
3427 let output = Self::eth_pre_dispatch_weight_versioned(input)?;
3428 Ok(PreDispatchWeightOutputPayloadV1::try_from(output)
3429 .expect("v1 input must produce v1 output; qed")
3430 .weight)
3431 }
3432
3433 fn call(
3434 origin: AccountId,
3435 dest: $crate::H160,
3436 value: Balance,
3437 weight_limit: Option<$crate::Weight>,
3438 storage_deposit_limit: Option<Balance>,
3439 input_data: Vec<u8>,
3440 ) -> $crate::pallet_revive_types::runtime_api::ContractResultV1<
3441 $crate::pallet_revive_types::runtime_api::ExecReturnValueV1,
3442 Balance
3443 > {
3444 use $crate::pallet_revive_types::runtime_api::*;
3445
3446 let input = CallVersionedInputPayload::from(CallInputPayloadV1 {
3447 origin,
3448 dest,
3449 value,
3450 gas_limit: weight_limit,
3451 storage_deposit_limit,
3452 input_data
3453 });
3454 let output = Self::call_versioned(input);
3455 CallOutputPayloadV1::try_from(output)
3456 .expect("v1 input must produce v1 output; qed")
3457 .contract_result
3458 }
3459
3460 fn instantiate(
3461 origin: AccountId,
3462 value: Balance,
3463 weight_limit: Option<$crate::Weight>,
3464 storage_deposit_limit: Option<Balance>,
3465 code: $crate::pallet_revive_types::runtime_api::CodeV1,
3466 data: Vec<u8>,
3467 salt: Option<[u8; 32]>,
3468 ) -> $crate::pallet_revive_types::runtime_api::ContractResultV1<
3469 $crate::pallet_revive_types::runtime_api::InstantiateReturnValueV1,
3470 Balance
3471 > {
3472 use $crate::pallet_revive_types::runtime_api::*;
3473
3474 let input = InstantiateVersionedInputPayload::from(InstantiateInputPayloadV1 {
3475 origin,
3476 value,
3477 gas_limit: weight_limit,
3478 storage_deposit_limit,
3479 code,
3480 data,
3481 salt
3482 });
3483 let output = Self::instantiate_versioned(input);
3484 InstantiateOutputPayloadV1::try_from(output)
3485 .expect("v1 input must produce v1 output; qed")
3486 .contract_result
3487 }
3488
3489 fn upload_code(
3490 origin: AccountId,
3491 code: Vec<u8>,
3492 storage_deposit_limit: Option<Balance>,
3493 ) -> Result<$crate::pallet_revive_types::runtime_api::CodeUploadReturnValueV1<Balance>, $crate::sp_runtime::DispatchError> {
3494 use $crate::pallet_revive_types::runtime_api::*;
3495
3496 let input = UploadCodeVersionedInputPayload::from(UploadCodeInputPayloadV1 {
3497 origin,
3498 code,
3499 storage_deposit_limit
3500 });
3501 let output = Self::upload_code_versioned(input)?;
3502 Ok(UploadCodeOutputPayloadV1::try_from(output)
3503 .expect("v1 input must produce v1 output; qed")
3504 .code_upload_return_value)
3505 }
3506
3507 fn get_storage_var_key(
3508 address: $crate::H160,
3509 key: Vec<u8>,
3510 ) -> $crate::GetStorageResult {
3511 use $crate::pallet_revive_types::runtime_api::*;
3512
3513 let input = GetStorageVersionedInputPayload::from(GetStorageInputPayloadV1 {
3514 address,
3515 key: StorageKeyV1::Variable(key)
3516 });
3517 let output = Self::get_storage_versioned(input)?;
3518 Ok(GetStorageOutputPayloadV1::try_from(output)
3519 .expect("v1 input must produce v1 output; qed")
3520 .storage)
3521 }
3522
3523 fn get_storage(address: $crate::H160, key: [u8; 32]) -> $crate::GetStorageResult {
3524 use $crate::pallet_revive_types::runtime_api::*;
3525
3526 let input = GetStorageVersionedInputPayload::from(GetStorageInputPayloadV1 {
3527 address,
3528 key: StorageKeyV1::Fixed(key)
3529 });
3530 let output = Self::get_storage_versioned(input)?;
3531 Ok(GetStorageOutputPayloadV1::try_from(output)
3532 .expect("v1 input must produce v1 output; qed")
3533 .storage)
3534 }
3535
3536 fn trace_block(
3537 block: Block,
3538 tracer_type: $crate::pallet_revive_types::runtime_api::TracerTypeV1,
3539 ) -> Vec<(u32, $crate::pallet_revive_types::runtime_api::TraceV1)> {
3540 use $crate::pallet_revive_types::runtime_api::*;
3541
3542 let input = TraceBlockVersionedInputPayload::from(TraceBlockInputPayloadV1 {
3543 block,
3544 config: tracer_type
3545 });
3546 let output = Self::trace_block_versioned(input);
3547 TraceBlockOutputPayloadV1::try_from(output)
3548 .expect("v1 input must produce v1 output; qed")
3549 .traces
3550 }
3551
3552 fn trace_tx(
3553 block: Block,
3554 tx_index: u32,
3555 tracer_type: $crate::pallet_revive_types::runtime_api::TracerTypeV1,
3556 ) -> Option<$crate::pallet_revive_types::runtime_api::TraceV1> {
3557 use $crate::pallet_revive_types::runtime_api::*;
3558
3559 let input = TraceTxVersionedInputPayload::from(TraceTxInputPayloadV1 {
3560 block,
3561 tx_index,
3562 config: tracer_type
3563 });
3564 let output = Self::trace_tx_versioned(input);
3565 TraceTxOutputPayloadV1::try_from(output)
3566 .expect("v1 input must produce v1 output; qed")
3567 .trace
3568 }
3569
3570 fn trace_call(
3571 tx: $crate::pallet_revive_types::runtime_api::GenericTransactionV1,
3572 tracer_type: $crate::pallet_revive_types::runtime_api::TracerTypeV1,
3573 ) -> Result<$crate::pallet_revive_types::runtime_api::TraceV1, $crate::EthTransactError> {
3574 use $crate::pallet_revive_types::runtime_api::*;
3575
3576 let input = TraceCallVersionedInputPayload::from(TraceCallInputPayloadV1 {
3577 tx,
3578 config: tracer_type,
3579 state_overrides: None
3580 });
3581 let output = Self::trace_call_versioned(input)?;
3582 Ok(TraceCallOutputPayloadV1::try_from(output)
3583 .expect("v1 input must produce v1 output; qed")
3584 .trace)
3585 }
3586
3587 fn trace_call_with_config(
3588 tx: $crate::pallet_revive_types::runtime_api::GenericTransactionV1,
3589 tracer_type: $crate::pallet_revive_types::runtime_api::TracerTypeV1,
3590 config: $crate::pallet_revive_types::runtime_api::TracingConfigV1,
3591 ) -> Result<$crate::pallet_revive_types::runtime_api::TraceV1, $crate::EthTransactError> {
3592 use $crate::pallet_revive_types::runtime_api::*;
3593
3594 let TracingConfigV1 { state_overrides } = config;
3595
3596 let input = TraceCallVersionedInputPayload::from(TraceCallInputPayloadV1 {
3597 tx,
3598 config: tracer_type,
3599 state_overrides
3600 });
3601 let output = Self::trace_call_versioned(input)?;
3602 Ok(TraceCallOutputPayloadV1::try_from(output)
3603 .expect("v1 input must produce v1 output; qed")
3604 .trace)
3605 }
3606
3607 fn runtime_pallets_address() -> $crate::H160 {
3608 use $crate::pallet_revive_types::runtime_api::*;
3609
3610 let input = RuntimePalletsAddressVersionedInputPayload::from(
3611 RuntimePalletsAddressInputPayloadV1
3612 );
3613 let output = Self::runtime_pallets_address_versioned(input);
3614 RuntimePalletsAddressOutputPayloadV1::try_from(output)
3615 .expect("v1 input must produce v1 output; qed")
3616 .runtime_pallets_address
3617 }
3618
3619 fn code(address: $crate::H160) -> Vec<u8> {
3620 use $crate::pallet_revive_types::runtime_api::*;
3621
3622 let input = CodeVersionedInputPayload::from(CodeInputPayloadV1 { address });
3623 let output = Self::code_versioned(input);
3624 CodeOutputPayloadV1::try_from(output)
3625 .expect("v1 input must produce v1 output; qed")
3626 .code
3627 }
3628
3629 fn account_id(address: $crate::H160) -> AccountId {
3630 use $crate::pallet_revive_types::runtime_api::*;
3631
3632 let input = AccountIdVersionedInputPayload::from(AccountIdInputPayloadV1 { address });
3633 let output = Self::account_id_versioned(input);
3634 AccountIdOutputPayloadV1::try_from(output)
3635 .expect("v1 input must produce v1 output; qed")
3636 .account_id
3637 }
3638
3639 fn new_balance_with_dust(balance: $crate::U256) -> Result<(Balance, u32), $crate::BalanceConversionError> {
3640 use $crate::pallet_revive_types::runtime_api::*;
3641
3642 let input = NewBalanceWithDustVersionedInputPayload::from(
3643 NewBalanceWithDustInputPayloadV1 { balance }
3644 );
3645 let output = Self::new_balance_with_dust_versioned(input)?;
3646 let output = NewBalanceWithDustOutputPayloadV1::try_from(output)
3647 .expect("v1 input must produce v1 output; qed");
3648 Ok((output.new_balance, output.dust))
3649 }
3650
3651 fn version_declarations()
3654 -> $crate::pallet_revive_types::runtime_api::ReviveRuntimeApiVersionDeclarations
3655 {
3656 use $crate::pallet_revive_types::runtime_api::*;
3657
3658 ReviveRuntimeApiVersionDeclarations::new()
3659 .insert("eth_block_versioned", 1)
3660 .insert("eth_block_hash_versioned", 1)
3661 .insert("eth_receipt_data_versioned", 1)
3662 .insert("block_gas_limit_versioned", 1)
3663 .insert("max_extrinsic_weight_in_gas_versioned", 1)
3664 .insert("balance_versioned", 1)
3665 .insert("gas_price_versioned", 1)
3666 .insert("nonce_versioned", 1)
3667 .insert("call_versioned", 1)
3668 .insert("instantiate_versioned", 1)
3669 .insert("eth_transact_versioned", 1)
3670 .insert("eth_estimate_gas_versioned", 1)
3671 .insert("eth_pre_dispatch_weight_versioned", 1)
3672 .insert("upload_code_versioned", 1)
3673 .insert("get_storage_versioned", 1)
3674 .insert("runtime_pallets_address_versioned", 1)
3675 .insert("code_versioned", 1)
3676 .insert("account_id_versioned", 1)
3677 .insert("new_balance_with_dust_versioned", 1)
3678 .insert("block_author_versioned", 1)
3679 .insert("address_versioned", 1)
3680 .insert("trace_block_versioned", 2)
3681 .insert("trace_tx_versioned", 2)
3682 .insert("trace_call_versioned", 2)
3683 }
3684
3685 fn eth_block_versioned(
3686 input: $crate::pallet_revive_types::runtime_api::BlockVersionedInputPayload
3687 ) -> $crate::pallet_revive_types::runtime_api::BlockVersionedOutputPayload {
3688 use $crate::pallet_revive_types::runtime_api::*;
3689 use $crate::runtime_api::*;
3690 use alloc::boxed::Box;
3691
3692 let (_input, output_wrapper): (
3693 _,
3694 Box<dyn Fn(BlockOutputPayload) -> BlockVersionedOutputPayload>,
3695 ) = match input {
3696 BlockVersionedInputPayload::V1(payload) => (
3697 BlockInputPayload::from(payload),
3698 Box::new(|output| BlockVersionedOutputPayload::V1(output.into())),
3699 ),
3700 };
3701
3702 let output = BlockOutputPayload { block: $crate::Pallet::<Self>::eth_block() };
3703 output_wrapper(output)
3704 }
3705
3706 fn eth_block_hash_versioned(
3707 input: $crate::pallet_revive_types::runtime_api::BlockHashVersionedInputPayload
3708 ) -> $crate::pallet_revive_types::runtime_api::BlockHashVersionedOutputPayload {
3709 use $crate::pallet_revive_types::runtime_api::*;
3710 use $crate::runtime_api::*;
3711 use alloc::boxed::Box;
3712
3713 let (input, output_wrapper): (
3714 _,
3715 Box<dyn Fn(BlockHashOutputPayload) -> BlockHashVersionedOutputPayload>,
3716 ) = match input {
3717 BlockHashVersionedInputPayload::V1(payload) => (
3718 BlockHashInputPayload::from(payload),
3719 Box::new(|output| BlockHashVersionedOutputPayload::V1(output.into())),
3720 ),
3721 };
3722
3723 let output = BlockHashOutputPayload {
3724 block_hash: $crate::Pallet::<Self>::eth_block_hash_from_number(input.block_number)
3725 };
3726 output_wrapper(output)
3727 }
3728
3729 fn eth_receipt_data_versioned(
3730 input: $crate::pallet_revive_types::runtime_api::ReceiptDataVersionedInputPayload
3731 ) -> $crate::pallet_revive_types::runtime_api::ReceiptDataVersionedOutputPayload {
3732 use $crate::pallet_revive_types::runtime_api::*;
3733 use $crate::runtime_api::*;
3734 use alloc::boxed::Box;
3735
3736 let (_input, output_wrapper): (
3737 _,
3738 Box<dyn Fn(ReceiptDataOutputPayload) -> ReceiptDataVersionedOutputPayload>,
3739 ) = match input {
3740 ReceiptDataVersionedInputPayload::V1(payload) => (
3741 ReceiptDataInputPayload::from(payload),
3742 Box::new(|output| ReceiptDataVersionedOutputPayload::V1(output.into())),
3743 ),
3744 };
3745
3746 let output = ReceiptDataOutputPayload {
3747 receipt_data: $crate::Pallet::<Self>::eth_receipt_data()
3748 };
3749 output_wrapper(output)
3750 }
3751
3752 fn block_gas_limit_versioned(
3753 input: $crate::pallet_revive_types::runtime_api::BlockGasLimitVersionedInputPayload
3754 ) -> $crate::pallet_revive_types::runtime_api::BlockGasLimitVersionedOutputPayload {
3755 use $crate::pallet_revive_types::runtime_api::*;
3756 use $crate::runtime_api::*;
3757 use alloc::boxed::Box;
3758
3759 let (_input, output_wrapper): (
3760 _,
3761 Box<dyn Fn(BlockGasLimitOutputPayload) -> BlockGasLimitVersionedOutputPayload>,
3762 ) = match input {
3763 BlockGasLimitVersionedInputPayload::V1(payload) => (
3764 BlockGasLimitInputPayload::from(payload),
3765 Box::new(|output| BlockGasLimitVersionedOutputPayload::V1(output.into())),
3766 ),
3767 };
3768
3769 let output = BlockGasLimitOutputPayload {
3770 block_gas_limit: $crate::Pallet::<Self>::evm_block_gas_limit()
3771 };
3772 output_wrapper(output)
3773 }
3774
3775 fn max_extrinsic_weight_in_gas_versioned(
3776 input: $crate::pallet_revive_types::runtime_api::MaxExtrinsicWeightInGasVersionedInputPayload
3777 ) -> $crate::pallet_revive_types::runtime_api::MaxExtrinsicWeightInGasVersionedOutputPayload {
3778 use $crate::pallet_revive_types::runtime_api::*;
3779 use $crate::runtime_api::*;
3780 use alloc::boxed::Box;
3781
3782 let (_input, output_wrapper): (
3783 _,
3784 Box<dyn Fn(MaxExtrinsicWeightInGasOutputPayload) -> MaxExtrinsicWeightInGasVersionedOutputPayload>,
3785 ) = match input {
3786 MaxExtrinsicWeightInGasVersionedInputPayload::V1(payload) => (
3787 MaxExtrinsicWeightInGasInputPayload::from(payload),
3788 Box::new(|output| MaxExtrinsicWeightInGasVersionedOutputPayload::V1(output.into())),
3789 ),
3790 };
3791
3792 let output = MaxExtrinsicWeightInGasOutputPayload {
3793 max_extrinsic_weight_in_gas: $crate::Pallet::<Self>::evm_max_extrinsic_weight_in_gas()
3794 };
3795 output_wrapper(output)
3796 }
3797
3798 fn balance_versioned(
3799 input: $crate::pallet_revive_types::runtime_api::BalanceVersionedInputPayload
3800 ) -> $crate::pallet_revive_types::runtime_api::BalanceVersionedOutputPayload {
3801 use $crate::pallet_revive_types::runtime_api::*;
3802 use $crate::runtime_api::*;
3803 use alloc::boxed::Box;
3804
3805 let (input, output_wrapper): (
3806 _,
3807 Box<dyn Fn(BalanceOutputPayload) -> BalanceVersionedOutputPayload>,
3808 ) = match input {
3809 BalanceVersionedInputPayload::V1(payload) => (
3810 BalanceInputPayload::from(payload),
3811 Box::new(|output| BalanceVersionedOutputPayload::V1(output.into())),
3812 ),
3813 };
3814
3815 let output = BalanceOutputPayload {
3816 balance: $crate::Pallet::<Self>::evm_balance(&input.address)
3817 };
3818 output_wrapper(output)
3819 }
3820
3821 fn gas_price_versioned(
3822 input: $crate::pallet_revive_types::runtime_api::GasPriceVersionedInputPayload
3823 ) -> $crate::pallet_revive_types::runtime_api::GasPriceVersionedOutputPayload {
3824 use $crate::pallet_revive_types::runtime_api::*;
3825 use $crate::runtime_api::*;
3826 use alloc::boxed::Box;
3827
3828 let (_input, output_wrapper): (
3829 _,
3830 Box<dyn Fn(GasPriceOutputPayload) -> GasPriceVersionedOutputPayload>,
3831 ) = match input {
3832 GasPriceVersionedInputPayload::V1(payload) => (
3833 GasPriceInputPayload::from(payload),
3834 Box::new(|output| GasPriceVersionedOutputPayload::V1(output.into())),
3835 ),
3836 };
3837
3838 let output = GasPriceOutputPayload {
3839 gas_price: $crate::Pallet::<Self>::evm_base_fee()
3840 };
3841 output_wrapper(output)
3842 }
3843
3844 fn nonce_versioned(
3845 input: $crate::pallet_revive_types::runtime_api::NonceVersionedInputPayload
3846 ) -> $crate::pallet_revive_types::runtime_api::NonceVersionedOutputPayload<Nonce> {
3847 use $crate::pallet_revive_types::runtime_api::*;
3848 use $crate::runtime_api::*;
3849 use $crate::AddressMapper;
3850 use alloc::boxed::Box;
3851
3852 let (input, output_wrapper): (
3853 _,
3854 Box<dyn Fn(NonceOutputPayload<Nonce>) -> NonceVersionedOutputPayload<Nonce>>,
3855 ) = match input {
3856 NonceVersionedInputPayload::V1(payload) => (
3857 NonceInputPayload::from(payload),
3858 Box::new(|output| NonceVersionedOutputPayload::V1(output.into())),
3859 ),
3860 };
3861
3862 let account = <Self as $crate::Config>::AddressMapper::to_account_id(&input.address);
3863 let output = NonceOutputPayload {
3864 nonce: $crate::frame_system::Pallet::<Self>::account_nonce(account)
3865 };
3866 output_wrapper(output)
3867 }
3868
3869 fn call_versioned(
3870 input: $crate::pallet_revive_types::runtime_api::CallVersionedInputPayload<AccountId, Balance>
3871 ) -> $crate::pallet_revive_types::runtime_api::CallVersionedOutputPayload<Balance> {
3872 use $crate::pallet_revive_types::runtime_api::*;
3873 use $crate::runtime_api::*;
3874 use $crate::frame_support::traits::Get;
3875 use alloc::boxed::Box;
3876
3877 let (input, output_wrapper): (
3878 _,
3879 Box<dyn Fn(CallOutputPayload<Balance>) -> CallVersionedOutputPayload<Balance>>,
3880 ) = match input {
3881 CallVersionedInputPayload::V1(payload) => (
3882 CallInputPayload::from(payload),
3883 Box::new(|output| CallVersionedOutputPayload::V1(output.into())),
3884 ),
3885 };
3886
3887 let blockweights: $crate::BlockWeights =
3888 <Self as $crate::frame_system::Config>::BlockWeights::get();
3889
3890 $crate::Pallet::<Self>::prepare_dry_run(&input.origin);
3891 let contract_result = $crate::Pallet::<Self>::bare_call(
3892 <Self as $crate::frame_system::Config>::RuntimeOrigin::signed(input.origin),
3893 input.dest,
3894 $crate::Pallet::<Self>::convert_native_to_evm(input.value),
3895 $crate::TransactionLimits::WeightAndDeposit {
3896 weight_limit: input.gas_limit.unwrap_or(blockweights.max_block),
3897 deposit_limit: input.storage_deposit_limit.unwrap_or(u128::MAX),
3898 },
3899 input.input_data,
3900 &$crate::ExecConfig::new_substrate_tx().with_dry_run(None),
3901 );
3902
3903 let output = CallOutputPayload { contract_result };
3904 output_wrapper(output)
3905 }
3906
3907 fn instantiate_versioned(
3908 input: $crate::pallet_revive_types::runtime_api::InstantiateVersionedInputPayload<AccountId, Balance>
3909 ) -> $crate::pallet_revive_types::runtime_api::InstantiateVersionedOutputPayload<Balance> {
3910 use $crate::pallet_revive_types::runtime_api::*;
3911 use $crate::runtime_api::*;
3912 use $crate::frame_support::traits::Get;
3913 use alloc::boxed::Box;
3914
3915 let (input, output_wrapper): (
3916 _,
3917 Box<dyn Fn(InstantiateOutputPayload<Balance>) -> InstantiateVersionedOutputPayload<Balance>>,
3918 ) = match input {
3919 InstantiateVersionedInputPayload::V1(payload) => (
3920 InstantiateInputPayload::from(payload),
3921 Box::new(|output| InstantiateVersionedOutputPayload::V1(output.into())),
3922 ),
3923 };
3924
3925 let blockweights: $crate::BlockWeights =
3926 <Self as $crate::frame_system::Config>::BlockWeights::get();
3927
3928 $crate::Pallet::<Self>::prepare_dry_run(&input.origin);
3929 let contract_result = $crate::Pallet::<Self>::bare_instantiate(
3930 <Self as $crate::frame_system::Config>::RuntimeOrigin::signed(input.origin),
3931 $crate::Pallet::<Self>::convert_native_to_evm(input.value),
3932 $crate::TransactionLimits::WeightAndDeposit {
3933 weight_limit: input.gas_limit.unwrap_or(blockweights.max_block),
3934 deposit_limit: input.storage_deposit_limit.unwrap_or(u128::MAX),
3935 },
3936 input.code,
3937 input.data,
3938 input.salt,
3939 &$crate::ExecConfig::new_substrate_tx().with_dry_run(None),
3940 );
3941
3942 let output = InstantiateOutputPayload { contract_result };
3943 output_wrapper(output)
3944 }
3945
3946 fn eth_transact_versioned(
3947 input: $crate::pallet_revive_types::runtime_api::TransactVersionedInputPayload<__ReviveMacroMoment>
3948 ) -> Result<
3949 $crate::pallet_revive_types::runtime_api::TransactVersionedOutputPayload<Balance>,
3950 $crate::EthTransactError
3951 > {
3952 use $crate::pallet_revive_types::runtime_api::*;
3953 use $crate::runtime_api::*;
3954 use $crate::{
3955 codec::Encode, evm::runtime::EthExtra, frame_support::traits::Get,
3956 sp_runtime::traits::TransactionExtension,
3957 sp_runtime::traits::Block as BlockT
3958 };
3959 use alloc::boxed::Box;
3960
3961 let (input, output_wrapper): (
3962 _,
3963 Box<dyn Fn(TransactOutputPayload<Balance>) -> TransactVersionedOutputPayload<Balance>>,
3964 ) = match input {
3965 TransactVersionedInputPayload::V1(payload) => (
3966 TransactInputPayload::from(payload),
3967 Box::new(|output| TransactVersionedOutputPayload::V1(output.into())),
3968 ),
3969 };
3970
3971 let transact_info = $crate::Pallet::<Self>::dry_run_eth_transact(
3972 input.tx,
3973 input.timestamp_override,
3974 input.perform_balance_checks,
3975 input.state_overrides,
3976 )?;
3977 let output = TransactOutputPayload { transact_info };
3978 Ok(output_wrapper(output))
3979 }
3980
3981 fn eth_estimate_gas_versioned(
3982 input: $crate::pallet_revive_types::runtime_api::EstimateGasVersionedInputPayload<__ReviveMacroMoment>
3983 ) -> Result<
3984 $crate::pallet_revive_types::runtime_api::EstimateGasVersionedOutputPayload,
3985 $crate::EthTransactError
3986 > {
3987 use $crate::pallet_revive_types::runtime_api::*;
3988 use $crate::runtime_api::*;
3989 use $crate::{
3990 codec::Encode, evm::runtime::EthExtra, frame_support::traits::Get,
3991 sp_runtime::traits::TransactionExtension,
3992 sp_runtime::traits::Block as BlockT
3993 };
3994 use alloc::boxed::Box;
3995
3996 let (input, output_wrapper): (
3997 _,
3998 Box<dyn Fn(EstimateGasOutputPayload) -> EstimateGasVersionedOutputPayload>,
3999 ) = match input {
4000 EstimateGasVersionedInputPayload::V1(payload) => (
4001 EstimateGasInputPayload::from(payload),
4002 Box::new(|output| EstimateGasVersionedOutputPayload::V1(output.into())),
4003 ),
4004 };
4005
4006 let gas_estimate = $crate::Pallet::<Self>::eth_estimate_gas(
4007 input.tx,
4008 input.timestamp_override,
4009 input.state_overrides,
4010 )?;
4011 let output = EstimateGasOutputPayload { gas_estimate };
4012 Ok(output_wrapper(output))
4013 }
4014
4015 fn eth_pre_dispatch_weight_versioned(
4016 input: $crate::pallet_revive_types::runtime_api::PreDispatchWeightVersionedInputPayload
4017 ) -> Result<
4018 $crate::pallet_revive_types::runtime_api::PreDispatchWeightVersionedOutputPayload,
4019 $crate::EthTransactError
4020 > {
4021 use $crate::pallet_revive_types::runtime_api::*;
4022 use $crate::runtime_api::*;
4023 use alloc::boxed::Box;
4024
4025 let (input, output_wrapper): (
4026 _,
4027 Box<dyn Fn(PreDispatchWeightOutputPayload) -> PreDispatchWeightVersionedOutputPayload>,
4028 ) = match input {
4029 PreDispatchWeightVersionedInputPayload::V1(payload) => (
4030 PreDispatchWeightInputPayload::from(payload),
4031 Box::new(|output| PreDispatchWeightVersionedOutputPayload::V1(output.into())),
4032 ),
4033 };
4034
4035 let output = PreDispatchWeightOutputPayload {
4036 weight: $crate::Pallet::<Self>::eth_pre_dispatch_weight(input.tx)?
4037 };
4038 Ok(output_wrapper(output))
4039 }
4040
4041 fn upload_code_versioned(
4042 input: $crate::pallet_revive_types::runtime_api::UploadCodeVersionedInputPayload<AccountId, Balance>
4043 ) -> Result<
4044 $crate::pallet_revive_types::runtime_api::UploadCodeVersionedOutputPayload<Balance>,
4045 $crate::sp_runtime::DispatchError
4046 > {
4047 use $crate::pallet_revive_types::runtime_api::*;
4048 use $crate::runtime_api::*;
4049 use alloc::boxed::Box;
4050
4051 let (input, output_wrapper): (
4052 _,
4053 Box<dyn Fn(UploadCodeOutputPayload<Balance>) -> UploadCodeVersionedOutputPayload<Balance>>,
4054 ) = match input {
4055 UploadCodeVersionedInputPayload::V1(payload) => (
4056 UploadCodeInputPayload::from(payload),
4057 Box::new(|output| UploadCodeVersionedOutputPayload::V1(output.into())),
4058 ),
4059 };
4060
4061 let origin =
4062 <Self as $crate::frame_system::Config>::RuntimeOrigin::signed(input.origin);
4063 let code_upload_return_value = $crate::Pallet::<Self>::bare_upload_code(
4064 origin,
4065 input.code,
4066 input.storage_deposit_limit.unwrap_or(u128::MAX),
4067 )?;
4068 let output = UploadCodeOutputPayload { code_upload_return_value };
4069 Ok(output_wrapper(output))
4070 }
4071
4072 fn get_storage_versioned(
4073 input: $crate::pallet_revive_types::runtime_api::GetStorageVersionedInputPayload
4074 ) -> Result<
4075 $crate::pallet_revive_types::runtime_api::GetStorageVersionedOutputPayload,
4076 $crate::ContractAccessError
4077 > {
4078 use $crate::pallet_revive_types::runtime_api::*;
4079 use $crate::runtime_api::*;
4080 use alloc::boxed::Box;
4081
4082 let (input, output_wrapper): (
4083 _,
4084 Box<dyn Fn(GetStorageOutputPayload) -> GetStorageVersionedOutputPayload>,
4085 ) = match input {
4086 GetStorageVersionedInputPayload::V1(payload) => (
4087 GetStorageInputPayload::from(payload),
4088 Box::new(|output| GetStorageVersionedOutputPayload::V1(output.into())),
4089 ),
4090 };
4091
4092 let storage = match input.key {
4093 StorageKey::Fixed(key) => $crate::Pallet::<Self>::get_storage(input.address, key)?,
4094 StorageKey::Variable(key) => $crate::Pallet::<Self>::get_storage_var_key(input.address, key)?,
4095 };
4096 let output = GetStorageOutputPayload { storage };
4097 Ok(output_wrapper(output))
4098 }
4099
4100 fn runtime_pallets_address_versioned(
4101 input: $crate::pallet_revive_types::runtime_api::RuntimePalletsAddressVersionedInputPayload
4102 ) -> $crate::pallet_revive_types::runtime_api::RuntimePalletsAddressVersionedOutputPayload {
4103 use $crate::pallet_revive_types::runtime_api::*;
4104 use $crate::runtime_api::*;
4105 use alloc::boxed::Box;
4106
4107 let (_input, output_wrapper): (
4108 _,
4109 Box<dyn Fn(RuntimePalletsAddressOutputPayload) -> RuntimePalletsAddressVersionedOutputPayload>,
4110 ) = match input {
4111 RuntimePalletsAddressVersionedInputPayload::V1(payload) => (
4112 RuntimePalletsAddressInputPayload::from(payload),
4113 Box::new(|output| RuntimePalletsAddressVersionedOutputPayload::V1(output.into())),
4114 ),
4115 };
4116
4117 let output = RuntimePalletsAddressOutputPayload {
4118 runtime_pallets_address: $crate::RUNTIME_PALLETS_ADDR
4119 };
4120 output_wrapper(output)
4121 }
4122
4123 fn code_versioned(
4124 input: $crate::pallet_revive_types::runtime_api::CodeVersionedInputPayload
4125 ) -> $crate::pallet_revive_types::runtime_api::CodeVersionedOutputPayload {
4126 use $crate::pallet_revive_types::runtime_api::*;
4127 use $crate::runtime_api::*;
4128 use alloc::boxed::Box;
4129
4130 let (input, output_wrapper): (
4131 _,
4132 Box<dyn Fn(CodeOutputPayload) -> CodeVersionedOutputPayload>,
4133 ) = match input {
4134 CodeVersionedInputPayload::V1(payload) => (
4135 CodeInputPayload::from(payload),
4136 Box::new(|output| CodeVersionedOutputPayload::V1(output.into())),
4137 ),
4138 };
4139
4140 let output = CodeOutputPayload {
4141 code: $crate::Pallet::<Self>::code(&input.address)
4142 };
4143 output_wrapper(output)
4144 }
4145
4146 fn account_id_versioned(
4147 input: $crate::pallet_revive_types::runtime_api::AccountIdVersionedInputPayload
4148 ) -> $crate::pallet_revive_types::runtime_api::AccountIdVersionedOutputPayload<AccountId> {
4149 use $crate::pallet_revive_types::runtime_api::*;
4150 use $crate::runtime_api::*;
4151 use $crate::AddressMapper;
4152 use alloc::boxed::Box;
4153
4154 let (input, output_wrapper): (
4155 _,
4156 Box<dyn Fn(AccountIdOutputPayload<AccountId>) -> AccountIdVersionedOutputPayload<AccountId>>,
4157 ) = match input {
4158 AccountIdVersionedInputPayload::V1(payload) => (
4159 AccountIdInputPayload::from(payload),
4160 Box::new(|output| AccountIdVersionedOutputPayload::V1(output.into())),
4161 ),
4162 };
4163
4164 let output = AccountIdOutputPayload {
4165 account_id: <Self as $crate::Config>::AddressMapper::to_account_id(&input.address)
4166 };
4167 output_wrapper(output)
4168 }
4169
4170 fn new_balance_with_dust_versioned(
4171 input: $crate::pallet_revive_types::runtime_api::NewBalanceWithDustVersionedInputPayload
4172 ) -> Result<
4173 $crate::pallet_revive_types::runtime_api::NewBalanceWithDustVersionedOutputPayload<Balance>,
4174 $crate::BalanceConversionError
4175 > {
4176 use $crate::pallet_revive_types::runtime_api::*;
4177 use $crate::runtime_api::*;
4178 use alloc::boxed::Box;
4179
4180 let (input, output_wrapper): (
4181 _,
4182 Box<
4183 dyn Fn(NewBalanceWithDustOutputPayload<Balance>) -> NewBalanceWithDustVersionedOutputPayload<Balance>,
4184 >,
4185 ) = match input {
4186 NewBalanceWithDustVersionedInputPayload::V1(payload) => (
4187 NewBalanceWithDustInputPayload::from(payload),
4188 Box::new(|output| NewBalanceWithDustVersionedOutputPayload::V1(output.into())),
4189 ),
4190 };
4191
4192 let (new_balance, dust) = $crate::Pallet::<Self>::new_balance_with_dust(input.balance)?;
4193 let output = NewBalanceWithDustOutputPayload { new_balance, dust };
4194 Ok(output_wrapper(output))
4195 }
4196
4197 fn block_author_versioned(
4198 input: $crate::pallet_revive_types::runtime_api::BlockAuthorVersionedInputPayload
4199 ) -> $crate::pallet_revive_types::runtime_api::BlockAuthorVersionedOutputPayload {
4200 use $crate::pallet_revive_types::runtime_api::*;
4201 use $crate::runtime_api::*;
4202 use alloc::boxed::Box;
4203
4204 let (_input, output_wrapper): (
4205 _,
4206 Box<dyn Fn(BlockAuthorOutputPayload) -> BlockAuthorVersionedOutputPayload>,
4207 ) = match input {
4208 BlockAuthorVersionedInputPayload::V1(payload) => (
4209 BlockAuthorInputPayload::from(payload),
4210 Box::new(|output| BlockAuthorVersionedOutputPayload::V1(output.into())),
4211 ),
4212 };
4213
4214 let output = BlockAuthorOutputPayload {
4215 block_author: $crate::Pallet::<Self>::block_author()
4216 };
4217 output_wrapper(output)
4218 }
4219
4220 fn address_versioned(
4221 input: $crate::pallet_revive_types::runtime_api::AddressVersionedInputPayload<AccountId>
4222 ) -> $crate::pallet_revive_types::runtime_api::AddressVersionedOutputPayload {
4223 use $crate::pallet_revive_types::runtime_api::*;
4224 use $crate::runtime_api::*;
4225 use $crate::AddressMapper;
4226 use alloc::boxed::Box;
4227
4228 let (input, output_wrapper): (
4229 _,
4230 Box<dyn Fn(AddressOutputPayload) -> AddressVersionedOutputPayload>,
4231 ) = match input {
4232 AddressVersionedInputPayload::V1(payload) => (
4233 AddressInputPayload::from(payload),
4234 Box::new(|output| AddressVersionedOutputPayload::V1(output.into())),
4235 ),
4236 };
4237
4238 let output = AddressOutputPayload {
4239 address: <Self as $crate::Config>::AddressMapper::to_address(&input.account_id)
4240 };
4241 output_wrapper(output)
4242 }
4243
4244 fn trace_block_versioned(
4245 input: $crate::pallet_revive_types::runtime_api::TraceBlockVersionedInputPayload<Block>
4246 ) -> $crate::pallet_revive_types::runtime_api::TraceBlockVersionedOutputPayload {
4247 use $crate::{
4248 sp_runtime::traits::Block,
4249 tracing::trace,
4250 evm::TraceEntry,
4251 runtime_api::*,
4252 pallet_revive_types::runtime_api::*
4253 };
4254 use alloc::boxed::Box;
4255
4256 let (input, output_wrapper): (_, Box<dyn Fn(TraceBlockOutputPayload) -> TraceBlockVersionedOutputPayload>) = match input {
4257 TraceBlockVersionedInputPayload::V1(payload) => (
4258 TraceBlockInputPayload::from(payload),
4259 Box::new(|output| TraceBlockVersionedOutputPayload::V1(output.into()))
4260 ),
4261 TraceBlockVersionedInputPayload::V2(payload) => (
4262 TraceBlockInputPayload::from(payload),
4263 Box::new(|output| TraceBlockVersionedOutputPayload::V2(output.into()))
4264 ),
4265 };
4266
4267 if matches!(input.config, $crate::evm::TracerType::ExecutionTracer(_)) &&
4268 !$crate::DebugSettings::is_execution_tracing_enabled::<Runtime>()
4269 {
4270 return output_wrapper(Default::default())
4271 }
4272
4273 let mut entries = vec![];
4277 let (header, extrinsics) = input.block.deconstruct();
4278 <$Executive>::initialize_block(&header);
4279 for (index, ext) in extrinsics.into_iter().enumerate() {
4280 let mut tracer = $crate::Pallet::<Self>::evm_tracer(input.config.clone());
4281 let t = tracer.as_tracing();
4282 let result = trace(t, || <$Executive>::apply_extrinsic(ext));
4283
4284 if let Some(tx_trace) = tracer.collect_trace() {
4285 entries.push((index as u32, TraceEntry::Traced(tx_trace)));
4286 } else if let Some(entry) = TraceEntry::for_untraced(&result) {
4287 entries.push((index as u32, entry));
4288 }
4289 }
4290
4291 let output = TraceBlockOutputPayload { entries };
4292 output_wrapper(output)
4293 }
4294
4295 fn trace_tx_versioned(
4296 input: $crate::pallet_revive_types::runtime_api::TraceTxVersionedInputPayload<Block>
4297 ) -> $crate::pallet_revive_types::runtime_api::TraceTxVersionedOutputPayload {
4298 use $crate::pallet_revive_types::runtime_api::*;
4299 use $crate::runtime_api::*;
4300 use $crate::{evm::TraceEntry, sp_runtime::traits::Block, tracing::trace};
4301 use alloc::boxed::Box;
4302
4303 let (input, output_wrapper): (
4304 _,
4305 Box<dyn Fn(TraceTxOutputPayload) -> TraceTxVersionedOutputPayload>,
4306 ) = match input {
4307 TraceTxVersionedInputPayload::V1(payload) => (
4308 TraceTxInputPayload::from(payload),
4309 Box::new(|output| TraceTxVersionedOutputPayload::V1(output.into())),
4310 ),
4311 TraceTxVersionedInputPayload::V2(payload) => (
4312 TraceTxInputPayload::from(payload),
4313 Box::new(|output| TraceTxVersionedOutputPayload::V2(output.into())),
4314 ),
4315 };
4316
4317 if matches!(&input.config, $crate::evm::TracerType::ExecutionTracer(_)) &&
4318 !$crate::DebugSettings::is_execution_tracing_enabled::<Runtime>()
4319 {
4320 return output_wrapper(TraceTxOutputPayload { entry: None })
4321 }
4322
4323 let mut tracer = $crate::Pallet::<Self>::evm_tracer(input.config);
4327 let (header, extrinsics) = input.block.deconstruct();
4328
4329 <$Executive>::initialize_block(&header);
4330 let mut entry = None;
4331 for (index, ext) in extrinsics.into_iter().enumerate() {
4332 if index as u32 == input.tx_index {
4333 let t = tracer.as_tracing();
4334 let result = trace(t, || <$Executive>::apply_extrinsic(ext));
4335 entry = match tracer.collect_trace() {
4336 Some(tx_trace) => Some(TraceEntry::Traced(tx_trace)),
4337 None => TraceEntry::for_untraced(&result),
4338 };
4339 break;
4340 } else {
4341 let _ = <$Executive>::apply_extrinsic(ext);
4342 }
4343 }
4344
4345 let output = TraceTxOutputPayload { entry };
4346 output_wrapper(output)
4347 }
4348
4349 fn trace_call_versioned(
4350 input: $crate::pallet_revive_types::runtime_api::TraceCallVersionedInputPayload
4351 ) -> Result<
4352 $crate::pallet_revive_types::runtime_api::TraceCallVersionedOutputPayload,
4353 $crate::EthTransactError
4354 > {
4355 use $crate::pallet_revive_types::runtime_api::*;
4356 use $crate::runtime_api::*;
4357 use $crate::tracing::trace;
4358 use alloc::boxed::Box;
4359
4360 let (input, output_wrapper): (
4361 _,
4362 Box<dyn Fn(TraceCallOutputPayload) -> TraceCallVersionedOutputPayload>,
4363 ) = match input {
4364 TraceCallVersionedInputPayload::V1(payload) => (
4365 TraceCallInputPayload::from(payload),
4366 Box::new(|output| TraceCallVersionedOutputPayload::V1(output.into())),
4367 ),
4368 TraceCallVersionedInputPayload::V2(payload) => (
4369 TraceCallInputPayload::from(payload),
4370 Box::new(|output| TraceCallVersionedOutputPayload::V2(output.into())),
4371 ),
4372 };
4373
4374 if let Some(overrides) = input.state_overrides {
4375 $crate::state_overrides::apply_state_overrides::<Runtime>(overrides)?;
4376 }
4377
4378 if matches!(input.config, $crate::evm::TracerType::ExecutionTracer(_)) &&
4379 !$crate::DebugSettings::is_execution_tracing_enabled::<Runtime>()
4380 {
4381 return Err($crate::EthTransactError::Message("Execution Tracing is disabled".into()))
4382 }
4383
4384 let mut tracer = $crate::Pallet::<Self>::evm_tracer(input.config.clone());
4385 let t = tracer.as_tracing();
4386
4387 t.watch_address(&input.tx.from.unwrap_or_default());
4388 t.watch_address(&$crate::Pallet::<Self>::block_author());
4389 let result = trace(t, || {
4390 $crate::Pallet::<Self>::dry_run_eth_transact(input.tx, None, true, None)
4391 });
4392
4393 let trace = if let Some(trace) = tracer.collect_trace() {
4394 Ok(trace)
4395 } else if let Err(err) = result {
4396 Err(err)
4397 } else {
4398 Ok($crate::Pallet::<Self>::evm_tracer(input.config).empty_trace())
4399 }?;
4400
4401 let output = TraceCallOutputPayload { trace };
4402 Ok(output_wrapper(output))
4403 }
4404 }
4405 }
4406 };
4407}