referrerpolicy=no-referrer-when-downgrade

pallet_revive/
lib.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18#![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		TYPE_EIP1559, Tracer, TracerType, block_hash::EthereumBlockBuilderIR, block_storage,
61		fees::InfoT as FeeInfo, runtime::SetWeightLimit,
62	},
63	exec::{AccountIdOf, ExecError, ReentrancyProtection, Stack as ExecStack},
64	sp_runtime::TransactionOutcome,
65	storage::{AccountType, DeletionQueueManager},
66	tracing::if_tracing,
67	vm::{CodeInfo, RuntimeCosts, pvm::extract_code_and_data},
68	weightinfo_extension::OnFinalizeBlockParts,
69};
70use alloc::{boxed::Box, format, vec};
71use codec::{Codec, Decode, Encode};
72use environmental::*;
73use frame_support::{
74	BoundedVec,
75	dispatch::{
76		DispatchErrorWithPostInfo, DispatchResult, DispatchResultWithPostInfo, GetDispatchInfo,
77		Pays, PostDispatchInfo, RawOrigin,
78	},
79	ensure,
80	pallet_prelude::DispatchClass,
81	storage::with_transaction,
82	traits::{
83		ConstU32, ConstU64, DefensiveResult, EnsureOrigin, Get, IsSubType, IsType, OnUnbalanced,
84		OriginTrait,
85		fungible::{Balanced, Credit, Inspect, Mutate, MutateHold},
86		tokens::Balance,
87	},
88	weights::WeightMeter,
89};
90use frame_system::{
91	Pallet as System, ensure_signed,
92	pallet_prelude::{BlockNumberFor, OriginFor},
93};
94use pallet_revive_types::runtime_api::*;
95use scale_info::TypeInfo;
96use sp_runtime::{
97	AccountId32, DispatchError, FixedPointNumber, FixedU128, SaturatedConversion,
98	traits::{
99		BadOrigin, Bounded, Convert, Dispatchable, Saturating, UniqueSaturatedFrom,
100		UniqueSaturatedInto, Zero,
101	},
102};
103
104pub use crate::{
105	address::{AccountId32Mapper, AddressMapper, AutoMapper, TestAccountMapper, create1, create2},
106	debug::DebugSettings,
107	deposit_payment::{Deposit, PGasDeposit},
108	evm::{
109		Address as EthAddress, Block as EthBlock, DryRunConfig, TracingConfig,
110		block_hash::ReceiptGasInfo,
111	},
112	exec::{CallResources, DelegateInfo, Executable, Key, MomentOf, Origin as ExecOrigin},
113	limits::TRANSIENT_STORAGE_BYTES as TRANSIENT_STORAGE_LIMIT,
114	metering::{
115		EthTxInfo, FrameMeter, ResourceMeter, Token as WeightToken, TransactionLimits,
116		TransactionMeter,
117	},
118	pallet::{genesis, *},
119	storage::{AccountInfo, ContractInfo},
120	transient_storage::{MeterEntry, StorageMeter as TransientStorageMeter, TransientStorage},
121	vm::{BytecodeType, ContractBlob},
122};
123pub use codec;
124use frame_support::traits::tokens::Precision;
125pub use frame_support::{self, dispatch::DispatchInfo, traits::Time, weights::Weight};
126pub use frame_system::{self, limits::BlockWeights};
127pub use primitives::*;
128pub use sp_core::{H160, H256, U256};
129pub use sp_crypto_hashing::keccak_256;
130pub use sp_runtime;
131pub use weights::WeightInfo;
132
133// Types re-export, needed to make it easier for runtimes to implement the pallet-revive runtime API
134pub extern crate pallet_revive_types;
135
136#[cfg(doc)]
137pub use crate::vm::pvm::SyscallDoc;
138
139pub type BalanceOf<T> = <T as Config>::Balance;
140pub type CreditOf<T> = Credit<<T as frame_system::Config>::AccountId, <T as Config>::Currency>;
141type TrieId = BoundedVec<u8, ConstU32<128>>;
142type ImmutableData = BoundedVec<u8, ConstU32<{ limits::IMMUTABLE_BYTES }>>;
143type CallOf<T> = <T as Config>::RuntimeCall;
144
145/// Used as a sentinel value when reading and writing contract memory.
146///
147/// It is usually used to signal `None` to a contract when only a primitive is allowed
148/// and we don't want to go through encoding a full Rust type. Using `u32::Max` is a safe
149/// sentinel because contracts are never allowed to use such a large amount of resources
150/// that this value makes sense for a memory location or length.
151const SENTINEL: u32 = u32::MAX;
152
153/// The target that is used for the log output emitted by this crate.
154///
155/// Hence you can use this target to selectively increase the log level for this crate.
156///
157/// Example: `RUST_LOG=runtime::revive=debug my_code --dev`
158const LOG_TARGET: &str = "runtime::revive";
159
160#[frame_support::pallet]
161pub mod pallet {
162	use super::*;
163	use frame_support::{pallet_prelude::*, traits::FindAuthor};
164	use frame_system::pallet_prelude::*;
165	use sp_core::U256;
166	use sp_runtime::Perbill;
167
168	/// The in-code storage version.
169	pub(crate) const STORAGE_VERSION: StorageVersion = StorageVersion::new(0);
170
171	#[pallet::pallet]
172	#[pallet::storage_version(STORAGE_VERSION)]
173	pub struct Pallet<T>(_);
174
175	#[pallet::config(with_default)]
176	pub trait Config: frame_system::Config {
177		/// The time implementation used to supply timestamps to contracts through `seal_now`.
178		type Time: Time<Moment: Into<U256>>;
179
180		/// The balance type of [`Self::Currency`].
181		///
182		/// Just added here to add additional trait bounds.
183		#[pallet::no_default]
184		type Balance: Balance
185			+ TryFrom<U256>
186			+ Into<U256>
187			+ Bounded
188			+ UniqueSaturatedInto<u64>
189			+ UniqueSaturatedFrom<u64>
190			+ UniqueSaturatedInto<u128>;
191
192		/// The fungible in which fees are paid and contract balances are held.
193		#[pallet::no_default]
194		type Currency: Inspect<Self::AccountId, Balance = Self::Balance>
195			+ Mutate<Self::AccountId>
196			+ MutateHold<Self::AccountId, Reason = Self::RuntimeHoldReason>
197			+ Balanced<Self::AccountId>;
198
199		/// Handler for burned native currency (e.g. gas rounding).
200		///
201		/// When EVM gas accounting rounds up the transaction cost, the small rounding
202		/// difference is withdrawn from the caller and forwarded to this handler.
203		/// Use this to redirect burned value to a treasury or DAP instead of silently
204		/// destroying it.
205		#[pallet::no_default_bounds]
206		type OnBurn: OnUnbalanced<CreditOf<Self>>;
207
208		/// The overarching event type.
209		#[pallet::no_default_bounds]
210		#[allow(deprecated)]
211		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
212
213		/// The overarching call type.
214		#[pallet::no_default_bounds]
215		type RuntimeCall: Parameter
216			+ Dispatchable<
217				RuntimeOrigin = OriginFor<Self>,
218				Info = DispatchInfo,
219				PostInfo = PostDispatchInfo,
220			> + IsType<<Self as frame_system::Config>::RuntimeCall>
221			+ From<Call<Self>>
222			+ IsSubType<Call<Self>>
223			+ GetDispatchInfo;
224
225		/// The overarching origin type.
226		#[pallet::no_default_bounds]
227		type RuntimeOrigin: IsType<OriginFor<Self>>
228			+ From<Origin<Self>>
229			+ Into<Result<Origin<Self>, OriginFor<Self>>>;
230
231		/// Overarching hold reason.
232		#[pallet::no_default_bounds]
233		type RuntimeHoldReason: From<HoldReason>;
234
235		/// Describes the weights of the dispatchables of this module and is also used to
236		/// construct a default cost schedule.
237		type WeightInfo: WeightInfo;
238
239		/// Type that allows the runtime authors to add new host functions for a contract to call.
240		///
241		/// Pass in a tuple of types that implement [`precompiles::Precompile`].
242		#[pallet::no_default_bounds]
243		#[allow(private_bounds)]
244		type Precompiles: precompiles::Precompiles<Self>;
245
246		/// Find the author of the current block.
247		type FindAuthor: FindAuthor<Self::AccountId>;
248
249		/// The amount of balance a caller has to pay for each byte of storage.
250		///
251		/// # Note
252		///
253		/// It is safe to change this value on a live chain as all refunds are pro rata.
254		#[pallet::constant]
255		#[pallet::no_default_bounds]
256		type DepositPerByte: Get<BalanceOf<Self>>;
257
258		/// The amount of balance a caller has to pay for each storage item.
259		///
260		/// # Note
261		///
262		/// It is safe to change this value on a live chain as all refunds are pro rata.
263		#[pallet::constant]
264		#[pallet::no_default_bounds]
265		type DepositPerItem: Get<BalanceOf<Self>>;
266
267		/// The amount of balance a caller has to pay for each child trie storage item.
268		///
269		/// Those are the items created by a contract. In Solidity each value is a single
270		/// storage item. This is why we need to set a lower value here than for the main
271		/// trie items. Otherwise the storage deposit is too high.
272		///
273		/// # Note
274		///
275		/// It is safe to change this value on a live chain as all refunds are pro rata.
276		#[pallet::constant]
277		#[pallet::no_default_bounds]
278		type DepositPerChildTrieItem: Get<BalanceOf<Self>>;
279
280		/// The percentage of the storage deposit that should be held for using a code hash.
281		/// Instantiating a contract, protects the code from being removed. In order to prevent
282		/// abuse these actions are protected with a percentage of the code deposit.
283		#[pallet::constant]
284		type CodeHashLockupDepositPercent: Get<Perbill>;
285
286		/// Use either valid type is [`address::AccountId32Mapper`] or [`address::H160Mapper`].
287		#[pallet::no_default]
288		type AddressMapper: AddressMapper<Self>;
289
290		/// Allow EVM bytecode to be uploaded and instantiated.
291		#[pallet::constant]
292		type AllowEVMBytecode: Get<bool>;
293
294		/// Origin allowed to upload code.
295		///
296		/// By default, it is safe to set this to `EnsureSigned`, allowing anyone to upload contract
297		/// code.
298		#[pallet::no_default_bounds]
299		type UploadOrigin: EnsureOrigin<OriginFor<Self>, Success = Self::AccountId>;
300
301		/// Origin allowed to instantiate code.
302		///
303		/// # Note
304		///
305		/// This is not enforced when a contract instantiates another contract. The
306		/// [`Self::UploadOrigin`] should make sure that no code is deployed that does unwanted
307		/// instantiations.
308		///
309		/// By default, it is safe to set this to `EnsureSigned`, allowing anyone to instantiate
310		/// contract code.
311		#[pallet::no_default_bounds]
312		type InstantiateOrigin: EnsureOrigin<OriginFor<Self>, Success = Self::AccountId>;
313
314		/// The amount of memory in bytes that parachain nodes a lot to the runtime.
315		///
316		/// This is used in [`Pallet::integrity_test`] to make sure that the runtime has enough
317		/// memory to support this pallet if set to the correct value.
318		type RuntimeMemory: Get<u32>;
319
320		/// The amount of memory in bytes that relay chain validators a lot to the PoV.
321		///
322		/// This is used in [`Pallet::integrity_test`] to make sure that the runtime has enough
323		/// memory to support this pallet if set to the correct value.
324		///
325		/// This value is usually higher than [`Self::RuntimeMemory`] to account for the fact
326		/// that validators have to hold all storage items in PvF memory.
327		type PVFMemory: Get<u32>;
328
329		/// The [EIP-155](https://eips.ethereum.org/EIPS/eip-155) chain ID.
330		///
331		/// This is a unique identifier assigned to each blockchain network,
332		/// preventing replay attacks.
333		#[pallet::constant]
334		type ChainId: Get<u64>;
335
336		/// The ratio between the decimal representation of the native token and the ETH token.
337		#[pallet::constant]
338		type NativeToEthRatio: Get<u32>;
339
340		/// Set to [`crate::evm::fees::Info`] for a production runtime.
341		///
342		/// For mock runtimes that do not need to interact with any eth compat functionality
343		/// the default value of `()` will suffice.
344		#[pallet::no_default_bounds]
345		type FeeInfo: FeeInfo<Self>;
346
347		/// Payment backend used to charge storage deposits.
348		/// The default `()` binding always uses the native currency.
349		#[pallet::no_default_bounds]
350		type Deposit: Deposit<Self>;
351
352		/// The fraction the maximum extrinsic weight `eth_transact` extrinsics are capped to.
353		///
354		/// This is not a security measure but a requirement due to how we map gas to `(Weight,
355		/// StorageDeposit)`. The mapping might derive a `Weight` that is too large to fit into an
356		/// extrinsic. In this case we cap it to the limit specified here.
357		///
358		/// `eth_transact` transactions that use more weight than specified will fail with an out of
359		/// gas error during execution. Larger fractions will allow more transactions to run.
360		/// Smaller values waste less block space: Choose as small as possible and as large as
361		/// necessary.
362		///
363		///  Default: `0.5`.
364		#[pallet::constant]
365		type MaxEthExtrinsicWeight: Get<FixedU128>;
366
367		/// Allows debug-mode configuration, such as enabling unlimited contract size.
368		#[pallet::constant]
369		type DebugEnabled: Get<bool>;
370
371		/// When enabled, accounts are automatically mapped on creation and unmapped on
372		/// kill via [`AutoMapper`]. This removes the need for explicit `map_account` calls.
373		///
374		/// Requires `frame_system::Config::OnNewAccount` and `OnKilledAccount` to be set
375		/// to [`AutoMapper`]. When enabled, the `map_account` and `unmap_account`
376		/// dispatchables are disabled.
377		#[pallet::constant]
378		type AutoMap: Get<bool>;
379
380		/// This determines the relative scale of our gas price and gas estimates.
381		///
382		/// By default, the gas price (in wei) is `FeeInfo::next_fee_multiplier()` multiplied by
383		/// `NativeToEthRatio`. `GasScale` allows to scale this value: the actual gas price is the
384		/// default gas price multiplied by `GasScale`.
385		///
386		/// As a consequence, gas cost (gas estimates and actual gas usage during transaction) is
387		/// scaled down by the same factor. Thus, the total transaction cost is not affected by
388		/// `GasScale` – apart from rounding differences: the transaction cost is always a multiple
389		/// of the gas price and is derived by rounded up, so that with higher `GasScales` this can
390		/// lead to higher gas cost as the rounding difference would be larger.
391		///
392		/// The main purpose of changing the `GasScale` is to tune the gas cost so that it is closer
393		/// to standard EVM gas cost and contracts will not run out of gas when tools or code
394		/// assume hard coded gas limits.
395		///
396		/// Requirement: `GasScale` must not be 0
397		#[pallet::constant]
398		#[pallet::no_default_bounds]
399		type GasScale: Get<u32>;
400	}
401
402	/// Container for different types that implement [`DefaultConfig`]` of this pallet.
403	pub mod config_preludes {
404		use super::*;
405		use frame_support::{
406			derive_impl,
407			traits::{ConstBool, ConstU32},
408		};
409		use frame_system::EnsureSigned;
410		use sp_core::parameter_types;
411
412		type Balance = u64;
413
414		pub const DOLLARS: Balance = 1_000_000_000_000;
415		pub const CENTS: Balance = DOLLARS / 100;
416		pub const MILLICENTS: Balance = CENTS / 1_000;
417
418		pub const fn deposit(items: u32, bytes: u32) -> Balance {
419			items as Balance * 20 * CENTS + (bytes as Balance) * MILLICENTS
420		}
421
422		parameter_types! {
423			pub const DepositPerItem: Balance = deposit(1, 0);
424			pub const DepositPerChildTrieItem: Balance = deposit(1, 0) / 100;
425			pub const DepositPerByte: Balance = deposit(0, 1);
426			pub const CodeHashLockupDepositPercent: Perbill = Perbill::from_percent(0);
427			pub const MaxEthExtrinsicWeight: FixedU128 = FixedU128::from_rational(9, 10);
428			pub const GasScale: u32 = 10u32;
429		}
430
431		/// A type providing default configurations for this pallet in testing environment.
432		pub struct TestDefaultConfig;
433
434		impl Time for TestDefaultConfig {
435			type Moment = u64;
436			fn now() -> Self::Moment {
437				0u64
438			}
439		}
440
441		impl<T: From<u64>> Convert<Weight, T> for TestDefaultConfig {
442			fn convert(w: Weight) -> T {
443				w.ref_time().into()
444			}
445		}
446
447		#[derive_impl(frame_system::config_preludes::TestDefaultConfig, no_aggregated_types)]
448		impl frame_system::DefaultConfig for TestDefaultConfig {}
449
450		#[frame_support::register_default_impl(TestDefaultConfig)]
451		impl DefaultConfig for TestDefaultConfig {
452			#[inject_runtime_type]
453			type RuntimeEvent = ();
454
455			#[inject_runtime_type]
456			type RuntimeHoldReason = ();
457
458			#[inject_runtime_type]
459			type RuntimeCall = ();
460
461			#[inject_runtime_type]
462			type RuntimeOrigin = ();
463
464			type Precompiles = ();
465			type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent;
466			type DepositPerByte = DepositPerByte;
467			type DepositPerItem = DepositPerItem;
468			type DepositPerChildTrieItem = DepositPerChildTrieItem;
469			type Time = Self;
470			type AllowEVMBytecode = ConstBool<true>;
471			type UploadOrigin = EnsureSigned<Self::AccountId>;
472			type InstantiateOrigin = EnsureSigned<Self::AccountId>;
473			type WeightInfo = ();
474			type RuntimeMemory = ConstU32<{ 128 * 1024 * 1024 }>;
475			type PVFMemory = ConstU32<{ 512 * 1024 * 1024 }>;
476			type ChainId = ConstU64<42>;
477			type NativeToEthRatio = ConstU32<1_000_000>;
478			type FindAuthor = ();
479			type FeeInfo = ();
480			type Deposit = ();
481			type MaxEthExtrinsicWeight = MaxEthExtrinsicWeight;
482			type DebugEnabled = ConstBool<false>;
483			type AutoMap = ConstBool<false>;
484			type GasScale = GasScale;
485			type OnBurn = ();
486		}
487	}
488
489	#[pallet::event]
490	pub enum Event<T: Config> {
491		/// A custom event emitted by the contract.
492		ContractEmitted {
493			/// The contract that emitted the event.
494			contract: H160,
495			/// Data supplied by the contract. Metadata generated during contract compilation
496			/// is needed to decode it.
497			data: Vec<u8>,
498			/// A list of topics used to index the event.
499			/// Number of topics is capped by [`limits::NUM_EVENT_TOPICS`].
500			topics: Vec<H256>,
501		},
502
503		/// Contract deployed by deployer at the specified address.
504		Instantiated { deployer: H160, contract: H160 },
505
506		/// Emitted when an Ethereum transaction reverts.
507		///
508		/// Ethereum transactions always complete successfully at the extrinsic level,
509		/// as even reverted calls must store their `ReceiptInfo`.
510		/// To distinguish reverted calls from successful ones, this event is emitted
511		/// for failed Ethereum transactions.
512		EthExtrinsicRevert { dispatch_error: DispatchError },
513	}
514
515	#[pallet::error]
516	#[repr(u8)]
517	pub enum Error<T> {
518		/// Invalid schedule supplied, e.g. with zero weight of a basic operation.
519		InvalidSchedule = 0x01,
520		/// Invalid combination of flags supplied to `seal_call` or `seal_delegate_call`.
521		InvalidCallFlags = 0x02,
522		/// The executed contract exhausted its gas limit.
523		OutOfGas = 0x03,
524		/// Performing the requested transfer failed. Probably because there isn't enough
525		/// free balance in the sender's account.
526		TransferFailed = 0x04,
527		/// Performing a call was denied because the calling depth reached the limit
528		/// of what is specified in the schedule.
529		MaxCallDepthReached = 0x05,
530		/// No contract was found at the specified address.
531		ContractNotFound = 0x06,
532		/// No code could be found at the supplied code hash.
533		CodeNotFound = 0x07,
534		/// No code info could be found at the supplied code hash.
535		CodeInfoNotFound = 0x08,
536		/// A buffer outside of sandbox memory was passed to a contract API function.
537		OutOfBounds = 0x09,
538		/// Input passed to a contract API function failed to decode as expected type.
539		DecodingFailed = 0x0A,
540		/// Contract trapped during execution.
541		ContractTrapped = 0x0B,
542		/// Event body or storage item exceeds [`limits::STORAGE_BYTES`].
543		ValueTooLarge = 0x0C,
544		/// Termination of a contract is not allowed while the contract is already
545		/// on the call stack. Can be triggered by `seal_terminate`.
546		TerminatedWhileReentrant = 0x0D,
547		/// `seal_call` forwarded this contracts input. It therefore is no longer available.
548		InputForwarded = 0x0E,
549		/// The amount of topics passed to `seal_deposit_events` exceeds the limit.
550		TooManyTopics = 0x0F,
551		/// A contract with the same AccountId already exists.
552		DuplicateContract = 0x12,
553		/// A contract self destructed in its constructor.
554		///
555		/// This can be triggered by a call to `seal_terminate`.
556		TerminatedInConstructor = 0x13,
557		/// A call tried to invoke a contract that is flagged as non-reentrant.
558		ReentranceDenied = 0x14,
559		/// A contract called into the runtime which then called back into this pallet.
560		ReenteredPallet = 0x15,
561		/// A contract attempted to invoke a state modifying API while being in read-only mode.
562		StateChangeDenied = 0x16,
563		/// Origin doesn't have enough balance to pay the required storage deposits.
564		StorageDepositNotEnoughFunds = 0x17,
565		/// More storage was created than allowed by the storage deposit limit.
566		StorageDepositLimitExhausted = 0x18,
567		/// Code removal was denied because the code is still in use by at least one contract.
568		CodeInUse = 0x19,
569		/// The contract ran to completion but decided to revert its storage changes.
570		/// Please note that this error is only returned from extrinsics. When called directly
571		/// or via RPC an `Ok` will be returned. In this case the caller needs to inspect the flags
572		/// to determine whether a reversion has taken place.
573		ContractReverted = 0x1A,
574		/// The contract failed to compile or is missing the correct entry points.
575		///
576		/// A more detailed error can be found on the node console if debug messages are enabled
577		/// by supplying `-lruntime::revive=debug`.
578		CodeRejected = 0x1B,
579		/// The code blob supplied is larger than [`limits::code::BLOB_BYTES`].
580		BlobTooLarge = 0x1C,
581		/// The contract declares too much memory (ro + rw + stack).
582		StaticMemoryTooLarge = 0x1D,
583		/// The program contains a basic block that is larger than allowed.
584		BasicBlockTooLarge = 0x1E,
585		/// The program contains an invalid instruction.
586		InvalidInstruction = 0x1F,
587		/// The contract has reached its maximum number of delegate dependencies.
588		MaxDelegateDependenciesReached = 0x20,
589		/// The dependency was not found in the contract's delegate dependencies.
590		DelegateDependencyNotFound = 0x21,
591		/// The contract already depends on the given delegate dependency.
592		DelegateDependencyAlreadyExists = 0x22,
593		/// Can not add a delegate dependency to the code hash of the contract itself.
594		CannotAddSelfAsDelegateDependency = 0x23,
595		/// Can not add more data to transient storage.
596		OutOfTransientStorage = 0x24,
597		/// The contract tried to call a syscall which does not exist (at its current api level).
598		InvalidSyscall = 0x25,
599		/// Invalid storage flags were passed to one of the storage syscalls.
600		InvalidStorageFlags = 0x26,
601		/// PolkaVM failed during code execution. Probably due to a malformed program.
602		ExecutionFailed = 0x27,
603		/// Failed to convert a U256 to a Balance.
604		BalanceConversionFailed = 0x28,
605		/// Immutable data can only be set during deploys and only be read during calls.
606		/// Additionally, it is only valid to set the data once and it must not be empty.
607		InvalidImmutableAccess = 0x2A,
608		/// An `AccountID32` account tried to interact with the pallet without having a mapping.
609		///
610		/// Call [`Pallet::map_account`] in order to create a mapping for the account.
611		AccountUnmapped = 0x2B,
612		/// Tried to map an account that is already mapped.
613		AccountAlreadyMapped = 0x2C,
614		/// The transaction used to dry-run a contract is invalid.
615		InvalidGenericTransaction = 0x2D,
616		/// The refcount of a code either over or underflowed.
617		RefcountOverOrUnderflow = 0x2E,
618		/// Unsupported precompile address.
619		UnsupportedPrecompileAddress = 0x2F,
620		/// The calldata exceeds [`limits::CALLDATA_BYTES`].
621		CallDataTooLarge = 0x30,
622		/// The return data exceeds [`limits::CALLDATA_BYTES`].
623		ReturnDataTooLarge = 0x31,
624		/// Invalid jump destination. Dynamic jumps points to invalid not jumpdest opcode.
625		InvalidJump = 0x32,
626		/// Attempting to pop a value from an empty stack.
627		StackUnderflow = 0x33,
628		/// Attempting to push a value onto a full stack.
629		StackOverflow = 0x34,
630		/// Too much deposit was drawn from the shared txfee and deposit credit.
631		///
632		/// This happens if the passed `gas` inside the ethereum transaction is too low.
633		TxFeeOverdraw = 0x35,
634		/// When calling an EVM constructor `data` has to be empty.
635		///
636		/// EVM constructors do not accept data. Their input data is part of the code blob itself.
637		EvmConstructorNonEmptyData = 0x36,
638		/// Tried to construct an EVM contract via code hash.
639		///
640		/// EVM contracts can only be instantiated via code upload as no initcode is
641		/// stored on-chain.
642		EvmConstructedFromHash = 0x37,
643		/// The contract does not have enough balance to refund the storage deposit.
644		///
645		/// This is a bug and should never happen. It means the accounting got out of sync.
646		StorageRefundNotEnoughFunds = 0x38,
647		/// This means there are locks on the contracts storage deposit that prevents refunding it.
648		///
649		/// This would be the case if the contract used its storage deposits for governance
650		/// or other pallets that allow creating locks over held balance.
651		StorageRefundLocked = 0x39,
652		/// Called a pre-compile that is not allowed to be delegate called.
653		///
654		/// Some pre-compile functions will trap the caller context if being delegate
655		/// called or if their caller was being delegate called.
656		PrecompileDelegateDenied = 0x40,
657		/// ECDSA public key recovery failed. Most probably wrong recovery id or signature.
658		EcdsaRecoveryFailed = 0x41,
659		/// Manual mapping is disabled when auto-mapping is enabled.
660		AutoMappingEnabled = 0x42,
661		/// A contract cannot be created at this address: it still has uncleared
662		/// [`NativeDepositOf`] entries from a previously terminated contract that the deletion
663		/// queue has not yet drained.
664		PendingDepositCleanup = 0x43,
665		/// Benchmarking only error.
666		#[cfg(feature = "runtime-benchmarks")]
667		BenchmarkingError = 0xFF,
668	}
669
670	/// A reason for the pallet revive placing a hold on funds.
671	#[pallet::composite_enum]
672	pub enum HoldReason {
673		/// The Pallet has reserved it for storing code on-chain.
674		CodeUploadDepositReserve,
675		/// The Pallet has reserved it for storage deposit.
676		StorageDepositReserve,
677		/// Deposit for creating an address mapping in [`OriginalAccount`].
678		AddressMapping,
679	}
680
681	/// A reason for the pallet revive placing a freeze on PGAS funds.
682	#[pallet::composite_enum]
683	pub enum FreezeReason {
684		/// Pins the PGAS existential deposit minted into a contract account so it cannot be
685		/// transferred or burned by the contract while it is alive. Without this freeze, a
686		/// contract could call the PGAS ERC20 precompile with `Preservation::Expendable` and
687		/// drain its own ED.
688		PGasMinBalance,
689	}
690
691	#[derive(
692		PartialEq, Eq, Clone, MaxEncodedLen, Encode, Decode, DecodeWithMemTracking, TypeInfo, Debug,
693	)]
694	#[pallet::origin]
695	pub enum Origin<T: Config> {
696		EthTransaction(T::AccountId),
697	}
698
699	/// A mapping from a contract's code hash to its code.
700	/// The code's size is bounded by [`crate::limits::BLOB_BYTES`] for PVM and
701	/// [`revm::primitives::eip170::MAX_CODE_SIZE`] for EVM bytecode.
702	#[pallet::storage]
703	#[pallet::unbounded]
704	pub(crate) type PristineCode<T: Config> = StorageMap<_, Identity, H256, Vec<u8>>;
705
706	/// A mapping from a contract's code hash to its code info.
707	#[pallet::storage]
708	pub(crate) type CodeInfoOf<T: Config> = StorageMap<_, Identity, H256, CodeInfo<T>>;
709
710	/// The data associated to a contract or externally owned account.
711	#[pallet::storage]
712	pub(crate) type AccountInfoOf<T: Config> = StorageMap<_, Identity, H160, AccountInfo<T>>;
713
714	/// Native currency storage deposit contributed by a user into a contract.
715	///
716	/// Bounds how much native value the user can receive back from that contract's
717	/// storage deposit.
718	///
719	/// Keys: `(holder, contributor) -> amount`
720	/// - `holder`: account on which the deposit is held (a contract, or the pallet's own account
721	///   for code-upload deposits).
722	/// - `contributor`: user that funded the deposit. Receives the native portion on refund, capped
723	///   at this entry's `amount`.
724	#[pallet::storage]
725	pub(crate) type NativeDepositOf<T: Config> = StorageDoubleMap<
726		_,
727		Identity,
728		T::AccountId,
729		Identity,
730		T::AccountId,
731		BalanceOf<T>,
732		ValueQuery,
733	>;
734
735	/// The immutable data associated with a given account.
736	#[pallet::storage]
737	pub(crate) type ImmutableDataOf<T: Config> = StorageMap<_, Identity, H160, ImmutableData>;
738
739	/// Terminated contracts that await lazy cleanup.
740	///
741	/// Each entry pairs a child trie ID with the contract account so that `on_idle` can
742	/// drain both the child trie and any [`NativeDepositOf`] entries that named the contract
743	/// as `holder`. Both can be arbitrarily large, so cleanup runs lazily in `on_idle`.
744	#[pallet::storage]
745	pub(crate) type DeletionQueue<T: Config> =
746		StorageMap<_, Twox64Concat, u32, crate::storage::DeletionQueueItem<T>>;
747
748	/// A pair of monotonic counters used to track the latest contract marked for deletion
749	/// and the latest deleted contract in queue.
750	#[pallet::storage]
751	pub(crate) type DeletionQueueCounter<T: Config> =
752		StorageValue<_, DeletionQueueManager<T>, ValueQuery>;
753
754	/// Map a Ethereum address to its original `AccountId32`.
755	///
756	/// When deriving a `H160` from an `AccountId32` we use a hash function. In order to
757	/// reconstruct the original account we need to store the reverse mapping here.
758	/// Register your `AccountId32` using [`Pallet::map_account`] in order to
759	/// use it with this pallet.
760	#[pallet::storage]
761	pub(crate) type OriginalAccount<T: Config> = StorageMap<_, Identity, H160, AccountId32>;
762
763	/// The current Ethereum block that is stored in the `on_finalize` method.
764	///
765	/// # Note
766	///
767	/// This could be further optimized into the future to store only the minimum
768	/// information needed to reconstruct the Ethereum block at the RPC level.
769	///
770	/// Since the block is convenient to have around, and the extra details are capped
771	/// by a few hashes and the vector of transaction hashes, we store the block here.
772	#[pallet::storage]
773	#[pallet::unbounded]
774	pub(crate) type EthereumBlock<T> = StorageValue<_, EthBlock, ValueQuery>;
775
776	/// Mapping for block number and hashes.
777	///
778	/// The maximum number of elements stored is capped by the block hash count `BLOCK_HASH_COUNT`.
779	#[pallet::storage]
780	pub(crate) type BlockHash<T: Config> =
781		StorageMap<_, Identity, BlockNumberFor<T>, H256, ValueQuery>;
782
783	/// The details needed to reconstruct the receipt info offchain.
784	///
785	/// This contains valuable information about the gas used by the transaction.
786	///
787	/// NOTE: The item is unbound and should therefore never be read on chain.
788	/// It could otherwise inflate the PoV size of a block.
789	#[pallet::storage]
790	#[pallet::unbounded]
791	pub(crate) type ReceiptInfoData<T: Config> = StorageValue<_, Vec<ReceiptGasInfo>, ValueQuery>;
792
793	/// Incremental ethereum block builder.
794	#[pallet::storage]
795	#[pallet::unbounded]
796	pub(crate) type EthBlockBuilderIR<T: Config> =
797		StorageValue<_, EthereumBlockBuilderIR<T>, ValueQuery>;
798
799	/// The first transaction and receipt of the ethereum block.
800	///
801	/// These values are moved out of the `EthBlockBuilderIR` to avoid serializing and
802	/// deserializing them on every transaction. Instead, they are loaded when needed.
803	#[pallet::storage]
804	#[pallet::unbounded]
805	pub(crate) type EthBlockBuilderFirstValues<T: Config> =
806		StorageValue<_, Option<(Vec<u8>, Vec<u8>)>, ValueQuery>;
807
808	/// Debugging settings that can be configured when DebugEnabled config is true.
809	#[pallet::storage]
810	pub(crate) type DebugSettingsOf<T: Config> = StorageValue<_, DebugSettings, ValueQuery>;
811
812	pub mod genesis {
813		use super::*;
814		use crate::evm::Bytes32;
815
816		/// Genesis configuration for contract-specific data.
817		#[derive(Clone, PartialEq, Debug, Default, serde::Serialize, serde::Deserialize)]
818		pub struct ContractData {
819			/// Contract code.
820			pub code: crate::evm::Bytes,
821			/// Initial storage entries as 32-byte key/value pairs.
822			pub storage: alloc::collections::BTreeMap<Bytes32, Bytes32>,
823		}
824
825		/// Genesis configuration for a contract account.
826		#[derive(PartialEq, Default, Debug, Clone, serde::Serialize, serde::Deserialize)]
827		pub struct Account<T: Config> {
828			/// Contract address.
829			pub address: H160,
830			/// Contract balance.
831			#[serde(default)]
832			pub balance: U256,
833			/// Account nonce
834			#[serde(default)]
835			pub nonce: T::Nonce,
836			/// Contract-specific data (code and storage). None for EOAs.
837			#[serde(flatten, skip_serializing_if = "Option::is_none")]
838			pub contract_data: Option<ContractData>,
839		}
840	}
841
842	#[pallet::genesis_config]
843	#[derive(Debug, PartialEq, frame_support::DefaultNoBound)]
844	pub struct GenesisConfig<T: Config> {
845		/// List of native Substrate accounts (typically `AccountId32`) to be mapped at genesis
846		/// block, enabling them to interact with smart contracts.
847		#[serde(default, skip_serializing_if = "Vec::is_empty")]
848		pub mapped_accounts: Vec<T::AccountId>,
849
850		/// Account entries (both EOAs and contracts)
851		#[serde(default, skip_serializing_if = "Vec::is_empty")]
852		pub accounts: Vec<genesis::Account<T>>,
853
854		/// Optional debugging settings applied at genesis.
855		#[serde(default, skip_serializing_if = "Option::is_none")]
856		pub debug_settings: Option<DebugSettings>,
857	}
858
859	#[pallet::genesis_build]
860	impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
861		fn build(&self) {
862			use crate::{exec::Key, vm::ContractBlob};
863			use frame_support::traits::fungible::Mutate;
864
865			if !System::<T>::account_exists(&Pallet::<T>::account_id()) {
866				let _ = T::Currency::mint_into(
867					&Pallet::<T>::account_id(),
868					T::Currency::minimum_balance(),
869				);
870			}
871
872			for id in &self.mapped_accounts {
873				if let Err(err) = T::AddressMapper::map_no_deposit_unchecked(id) {
874					log::error!(target: LOG_TARGET, "Failed to map account {id:?}: {err:?}");
875				}
876			}
877
878			let owner = Pallet::<T>::account_id();
879
880			for genesis::Account { address, balance, nonce, contract_data } in &self.accounts {
881				let account_id = T::AddressMapper::to_account_id(address);
882
883				if !System::<T>::account_exists(&account_id) {
884					let _ = T::Currency::mint_into(&account_id, T::Currency::minimum_balance());
885				}
886
887				frame_system::Account::<T>::mutate(&account_id, |info| {
888					info.nonce = (*nonce).into();
889				});
890
891				match contract_data {
892					None => {
893						AccountInfoOf::<T>::insert(
894							address,
895							AccountInfo { account_type: AccountType::EOA, dust: 0 },
896						);
897					},
898					Some(genesis::ContractData { code, storage }) => {
899						let blob = if code.0.starts_with(&polkavm_common::program::BLOB_MAGIC) {
900							ContractBlob::<T>::from_pvm_code(code.0.clone(), owner.clone())
901								.inspect_err(|err| {
902									log::error!(target: LOG_TARGET, "Failed to create PVM ContractBlob for {address:?}: {err:?}");
903								})
904						} else {
905							ContractBlob::<T>::from_evm_runtime_code(code.0.clone(), account_id)
906								.inspect_err(|err| {
907									log::error!(target: LOG_TARGET, "Failed to create EVM ContractBlob for {address:?}: {err:?}");
908								})
909						};
910
911						let Ok(blob) = blob else {
912							continue;
913						};
914
915						let code_hash = *blob.code_hash();
916						let Ok(info) = <ContractInfo<T>>::new(&address, 0u32.into(), code_hash)
917							.inspect_err(|err| {
918								log::error!(target: LOG_TARGET, "Failed to create ContractInfo for {address:?}: {err:?}");
919							})
920						else {
921							continue;
922						};
923
924						AccountInfoOf::<T>::insert(
925							address,
926							AccountInfo { account_type: info.clone().into(), dust: 0 },
927						);
928
929						<PristineCode<T>>::insert(blob.code_hash(), code.0.clone());
930						<CodeInfoOf<T>>::insert(blob.code_hash(), blob.code_info().clone());
931						for (k, v) in storage {
932							let _ = info.write(&Key::from_fixed(k.0), Some(v.0.to_vec()), None, false).inspect_err(|err| {
933								log::error!(target: LOG_TARGET, "Failed to write genesis storage for {address:?} at key {k:?}: {err:?}");
934							});
935						}
936					},
937				}
938
939				let _ = Pallet::<T>::set_evm_balance(address, *balance).inspect_err(|err| {
940					log::error!(target: LOG_TARGET, "Failed to set EVM balance for {address:?}: {err:?}");
941				});
942			}
943
944			// Build genesis block
945			block_storage::on_finalize_build_eth_block::<T>(
946				// Make sure to use the block number from storage instead of the hardcoded 0.
947				// This enables testing tools like anvil to customise the genesis block number.
948				frame_system::Pallet::<T>::block_number(),
949			);
950
951			// Set debug settings.
952			if let Some(settings) = self.debug_settings.as_ref() {
953				settings.write_to_storage::<T>()
954			}
955		}
956	}
957
958	#[pallet::hooks]
959	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
960		fn on_idle(_block: BlockNumberFor<T>, limit: Weight) -> Weight {
961			let mut meter = WeightMeter::with_limit(limit);
962			ContractInfo::<T>::process_deletion_queue_batch(&mut meter);
963			meter.consumed()
964		}
965
966		fn on_initialize(_n: BlockNumberFor<T>) -> Weight {
967			// Kill related ethereum block storage items.
968			block_storage::on_initialize::<T>();
969
970			// Warm up the pallet account.
971			System::<T>::account_exists(&Pallet::<T>::account_id());
972			// Account for the fixed part of the costs incurred in `on_finalize`.
973			<T as Config>::WeightInfo::on_finalize_block_fixed()
974		}
975
976		fn on_finalize(block_number: BlockNumberFor<T>) {
977			// Build the ethereum block and place it in storage.
978			block_storage::on_finalize_build_eth_block::<T>(block_number);
979		}
980
981		fn integrity_test() {
982			assert!(T::ChainId::get() > 0, "ChainId must be greater than 0");
983
984			assert!(T::GasScale::get() > 0u32.into(), "GasScale must not be 0");
985
986			T::FeeInfo::integrity_test();
987
988			// The memory available in the block building runtime
989			let max_runtime_mem: u64 = T::RuntimeMemory::get().into();
990
991			// We only allow 50% of the runtime memory to be utilized by the contracts call
992			// stack, keeping the rest for other facilities, such as PoV, etc.
993			const TOTAL_MEMORY_DEVIDER: u64 = 2;
994
995			// Validators are configured to be able to use more memory than block builders. This is
996			// because in addition to `max_runtime_mem` they need to hold additional data in
997			// memory: PoV in multiple copies (1x encoded + 2x decoded) and all storage which
998			// includes emitted events. The assumption is that storage/events size
999			// can be a maximum of half of the validator runtime memory - max_runtime_mem.
1000			let max_block_weight = T::BlockWeights::get()
1001				.get(DispatchClass::Normal)
1002				.max_total
1003				.unwrap_or_else(|| T::BlockWeights::get().max_block);
1004			let max_key_size: u64 =
1005				Key::try_from_var(alloc::vec![0u8; limits::STORAGE_KEY_BYTES as usize])
1006					.expect("Key of maximal size shall be created")
1007					.hash()
1008					.len()
1009					.try_into()
1010					.unwrap();
1011
1012			let max_immutable_key_size: u64 = T::AccountId::max_encoded_len().try_into().unwrap();
1013			let max_immutable_size: u64 = max_block_weight
1014				.checked_div_per_component(&<RuntimeCosts as WeightToken<T>>::weight(
1015					&RuntimeCosts::SetImmutableData(limits::IMMUTABLE_BYTES),
1016				))
1017				.unwrap()
1018				.saturating_mul(
1019					u64::from(limits::IMMUTABLE_BYTES)
1020						.saturating_add(max_immutable_key_size)
1021						.into(),
1022				);
1023
1024			let max_pvf_mem: u64 = T::PVFMemory::get().into();
1025			let storage_size_limit = max_pvf_mem.saturating_sub(max_runtime_mem) / 2;
1026
1027			// We can use storage to store events using the available block ref_time with the
1028			// `deposit_event` host function. The overhead of stored events, which is around 100B,
1029			// is not taken into account to simplify calculations, as it does not change much.
1030			let max_events_size = max_block_weight
1031				.checked_div_per_component(
1032					&(<RuntimeCosts as WeightToken<T>>::weight(&RuntimeCosts::DepositEvent {
1033						num_topic: 0,
1034						len: limits::EVENT_BYTES,
1035					})
1036					.saturating_add(<RuntimeCosts as WeightToken<T>>::weight(
1037						&RuntimeCosts::HostFn,
1038					))),
1039				)
1040				.unwrap()
1041				.saturating_mul(limits::EVENT_BYTES.into());
1042
1043			assert!(
1044				max_events_size <= storage_size_limit,
1045				"Maximal events size {} exceeds the events limit {}",
1046				max_events_size,
1047				storage_size_limit
1048			);
1049
1050			// The incremental block builder uses 3 x maximum entry size for receipts and
1051			// for transactions. Transactions are bounded to `MAX_TRANSACTION_PAYLOAD_SIZE`.
1052			//
1053			// To determine the maximum size of the receipts, we know the following:
1054			// - (I) first receipt is stored into pallet storage and not given to the hasher until
1055			//   finalization.
1056			// - (II) the hasher will not consume more memory than the receipts we are giving it.
1057			// - (III) the hasher is capped by 3 x maximum entry for 3 or more transactions.
1058			//
1059			// # Case 1. One transaction with maximum receipts
1060			//
1061			// The worst case scenario for having one single transaction is for the transaction
1062			// to emit the maximum receipt size (ie `max_events_size`). In this case,
1063			// the maximum storage (and memory) consumed is bounded by `max_events_size` (II). The
1064			// receipt is stored in pallet storage, and loaded from storage in the
1065			// `on_finalize` hook (I).
1066			//
1067			// # Case 2. Two transactions
1068			//
1069			// The sum of the receipt size of both transactions cannot exceed `max_events_size`,
1070			// otherwise one transaction will be reverted. From (II), the bytes utilized
1071			// by the builder are capped to `max_events_size`.
1072			//
1073			// # Case 3. Three or more transactions
1074			//
1075			// Similar to the above case, the sum of all receipt size is bounded to
1076			// `max_events_size`. Therefore, the bytes are capped to `max_events_size`.
1077			//
1078			// On average, a transaction could emit `max_events_size / num_tx`. The would
1079			// consume `max_events_size / num_tx * 3` bytes, which is lower than
1080			// `max_events_size` for more than 3 transactions.
1081			//
1082			// In practice, the builder will consume even lower amounts considering
1083			// it is unlikely for a transaction to utilize all the weight of the block for events.
1084			let max_eth_block_builder_bytes =
1085				block_storage::block_builder_bytes_usage(max_events_size.try_into().unwrap());
1086
1087			log::debug!(
1088				target: LOG_TARGET,
1089				"Integrity check: max_eth_block_builder_bytes={} KB using max_events_size={} KB",
1090				max_eth_block_builder_bytes / 1024,
1091				max_events_size / 1024,
1092			);
1093
1094			// Check that the configured memory limits fit into runtime memory.
1095			//
1096			// Dynamic allocations are not available, yet. Hence they are not taken into
1097			// consideration here.
1098			let memory_left = i128::from(max_runtime_mem)
1099				.saturating_div(TOTAL_MEMORY_DEVIDER.into())
1100				.saturating_sub(limits::MEMORY_REQUIRED.into())
1101				.saturating_sub(max_eth_block_builder_bytes.into());
1102
1103			log::debug!(target: LOG_TARGET, "Integrity check: memory_left={} KB", memory_left / 1024);
1104
1105			assert!(
1106				memory_left >= 0,
1107				"Runtime does not have enough memory for current limits. Additional runtime memory required: {} KB",
1108				memory_left.saturating_mul(TOTAL_MEMORY_DEVIDER.into()).abs() / 1024
1109			);
1110
1111			// We can use storage to store items using the available block ref_time with the
1112			// `set_storage` host function. A revertible cold access is the worst case.
1113			let max_storage_size = max_block_weight
1114				.checked_div_per_component(
1115					&<RuntimeCosts as WeightToken<T>>::weight(&RuntimeCosts::SetStorage {
1116						new_bytes: limits::STORAGE_BYTES,
1117						old_bytes: 0,
1118						kind: StorageAccessKind::Persistent(Warmth::Cold { revertible: true }),
1119					})
1120					.saturating_mul(u64::from(limits::STORAGE_BYTES).saturating_add(max_key_size)),
1121				)
1122				.unwrap()
1123				.saturating_add(max_immutable_size.into())
1124				.saturating_add(max_eth_block_builder_bytes.into());
1125
1126			assert!(
1127				max_storage_size <= storage_size_limit,
1128				"Maximal storage size {} exceeds the storage limit {}",
1129				max_storage_size,
1130				storage_size_limit
1131			);
1132		}
1133	}
1134
1135	#[pallet::call]
1136	impl<T: Config> Pallet<T> {
1137		/// A raw EVM transaction, typically dispatched by an Ethereum JSON-RPC server.
1138		///
1139		/// # Parameters
1140		///
1141		/// * `payload`: The encoded [`crate::evm::TransactionSigned`].
1142		///
1143		/// # Note
1144		///
1145		/// This call cannot be dispatched directly; attempting to do so will result in a failed
1146		/// transaction. It serves as a wrapper for an Ethereum transaction. When submitted, the
1147		/// runtime converts it into a [`sp_runtime::generic::CheckedExtrinsic`] by recovering the
1148		/// signer and validating the transaction.
1149		#[allow(unused_variables)]
1150		#[pallet::call_index(0)]
1151		#[pallet::weight(Weight::MAX)]
1152		pub fn eth_transact(origin: OriginFor<T>, payload: Vec<u8>) -> DispatchResultWithPostInfo {
1153			Err(frame_system::Error::CallFiltered::<T>.into())
1154		}
1155
1156		/// Makes a call to an account, optionally transferring some balance.
1157		///
1158		/// # Parameters
1159		///
1160		/// * `dest`: Address of the contract to call.
1161		/// * `value`: The balance to transfer from the `origin` to `dest`.
1162		/// * `weight_limit`: The weight limit enforced when executing the constructor.
1163		/// * `storage_deposit_limit`: The maximum amount of balance that can be charged from the
1164		///   caller to pay for the storage consumed.
1165		/// * `data`: The input data to pass to the contract.
1166		///
1167		/// * If the account is a smart-contract account, the associated code will be
1168		/// executed and any value will be transferred.
1169		/// * If the account is a regular account, any value will be transferred.
1170		/// * If no account exists and the call value is not less than `existential_deposit`,
1171		/// a regular account will be created and any value will be transferred.
1172		#[pallet::call_index(1)]
1173		#[pallet::weight(<T as Config>::WeightInfo::call().saturating_add(*weight_limit))]
1174		pub fn call(
1175			origin: OriginFor<T>,
1176			dest: H160,
1177			#[pallet::compact] value: BalanceOf<T>,
1178			weight_limit: Weight,
1179			#[pallet::compact] storage_deposit_limit: BalanceOf<T>,
1180			data: Vec<u8>,
1181		) -> DispatchResultWithPostInfo {
1182			Self::ensure_non_contract_if_signed(&origin)?;
1183			let mut output = Self::bare_call(
1184				origin,
1185				dest,
1186				Pallet::<T>::convert_native_to_evm(value),
1187				TransactionLimits::WeightAndDeposit {
1188					weight_limit,
1189					deposit_limit: storage_deposit_limit,
1190				},
1191				data,
1192				&ExecConfig::new_substrate_tx(),
1193			);
1194
1195			if let Ok(return_value) = &output.result &&
1196				return_value.did_revert()
1197			{
1198				output.result = Err(<Error<T>>::ContractReverted.into());
1199			}
1200			dispatch_result(
1201				output.result,
1202				output.weight_consumed,
1203				<T as Config>::WeightInfo::call(),
1204			)
1205		}
1206
1207		/// Instantiates a contract from a previously deployed vm binary.
1208		///
1209		/// This function is identical to [`Self::instantiate_with_code`] but without the
1210		/// code deployment step. Instead, the `code_hash` of an on-chain deployed vm binary
1211		/// must be supplied.
1212		#[pallet::call_index(2)]
1213		#[pallet::weight(
1214			<T as Config>::WeightInfo::instantiate(data.len() as u32).saturating_add(*weight_limit)
1215		)]
1216		pub fn instantiate(
1217			origin: OriginFor<T>,
1218			#[pallet::compact] value: BalanceOf<T>,
1219			weight_limit: Weight,
1220			#[pallet::compact] storage_deposit_limit: BalanceOf<T>,
1221			code_hash: sp_core::H256,
1222			data: Vec<u8>,
1223			salt: Option<[u8; 32]>,
1224		) -> DispatchResultWithPostInfo {
1225			Self::ensure_non_contract_if_signed(&origin)?;
1226			let data_len = data.len() as u32;
1227			let mut output = Self::bare_instantiate(
1228				origin,
1229				Pallet::<T>::convert_native_to_evm(value),
1230				TransactionLimits::WeightAndDeposit {
1231					weight_limit,
1232					deposit_limit: storage_deposit_limit,
1233				},
1234				Code::Existing(code_hash),
1235				data,
1236				salt,
1237				&ExecConfig::new_substrate_tx(),
1238			);
1239			if let Ok(retval) = &output.result &&
1240				retval.result.did_revert()
1241			{
1242				output.result = Err(<Error<T>>::ContractReverted.into());
1243			}
1244			dispatch_result(
1245				output.result.map(|result| result.result),
1246				output.weight_consumed,
1247				<T as Config>::WeightInfo::instantiate(data_len),
1248			)
1249		}
1250
1251		/// Instantiates a new contract from the supplied `code` optionally transferring
1252		/// some balance.
1253		///
1254		/// This dispatchable has the same effect as calling [`Self::upload_code`] +
1255		/// [`Self::instantiate`]. Bundling them together provides efficiency gains. Please
1256		/// also check the documentation of [`Self::upload_code`].
1257		///
1258		/// # Parameters
1259		///
1260		/// * `value`: The balance to transfer from the `origin` to the newly created contract.
1261		/// * `weight_limit`: The weight limit enforced when executing the constructor.
1262		/// * `storage_deposit_limit`: The maximum amount of balance that can be charged/reserved
1263		///   from the caller to pay for the storage consumed.
1264		/// * `code`: The contract code to deploy in raw bytes.
1265		/// * `data`: The input data to pass to the contract constructor.
1266		/// * `salt`: Used for the address derivation. If `Some` is supplied then `CREATE2`
1267		/// 	semantics are used. If `None` then `CRATE1` is used.
1268		///
1269		///
1270		/// Instantiation is executed as follows:
1271		///
1272		/// - The supplied `code` is deployed, and a `code_hash` is created for that code.
1273		/// - If the `code_hash` already exists on the chain the underlying `code` will be shared.
1274		/// - The destination address is computed based on the sender, code_hash and the salt.
1275		/// - The smart-contract account is created at the computed address.
1276		/// - The `value` is transferred to the new account.
1277		/// - The `deploy` function is executed in the context of the newly-created account.
1278		#[pallet::call_index(3)]
1279		#[pallet::weight(
1280			<T as Config>::WeightInfo::instantiate_with_code(code.len() as u32, data.len() as u32)
1281			.saturating_add(*weight_limit)
1282		)]
1283		pub fn instantiate_with_code(
1284			origin: OriginFor<T>,
1285			#[pallet::compact] value: BalanceOf<T>,
1286			weight_limit: Weight,
1287			#[pallet::compact] storage_deposit_limit: BalanceOf<T>,
1288			code: Vec<u8>,
1289			data: Vec<u8>,
1290			salt: Option<[u8; 32]>,
1291		) -> DispatchResultWithPostInfo {
1292			Self::ensure_non_contract_if_signed(&origin)?;
1293			let code_len = code.len() as u32;
1294			let data_len = data.len() as u32;
1295			let mut output = Self::bare_instantiate(
1296				origin,
1297				Pallet::<T>::convert_native_to_evm(value),
1298				TransactionLimits::WeightAndDeposit {
1299					weight_limit,
1300					deposit_limit: storage_deposit_limit,
1301				},
1302				Code::Upload(code),
1303				data,
1304				salt,
1305				&ExecConfig::new_substrate_tx(),
1306			);
1307			if let Ok(retval) = &output.result &&
1308				retval.result.did_revert()
1309			{
1310				output.result = Err(<Error<T>>::ContractReverted.into());
1311			}
1312			dispatch_result(
1313				output.result.map(|result| result.result),
1314				output.weight_consumed,
1315				<T as Config>::WeightInfo::instantiate_with_code(code_len, data_len),
1316			)
1317		}
1318
1319		/// Same as [`Self::instantiate_with_code`], but intended to be dispatched **only**
1320		/// by an EVM transaction through the EVM compatibility layer.
1321		///
1322		/// # Parameters
1323		///
1324		/// * `value`: The balance to transfer from the `origin` to the newly created contract.
1325		/// * `weight_limit`: The gas limit used to derive the transaction weight for transaction
1326		///   payment
1327		/// * `eth_gas_limit`: The Ethereum gas limit governing the resource usage of the execution
1328		/// * `code`: The contract code to deploy in raw bytes.
1329		/// * `data`: The input data to pass to the contract constructor.
1330		/// * `transaction_encoded`: The RLP encoding of the signed Ethereum transaction,
1331		///   represented as [crate::evm::TransactionSigned], provided by the Ethereum wallet. This
1332		///   is used for building the Ethereum transaction root.
1333		/// * effective_gas_price: the price of a unit of gas
1334		/// * encoded len: the byte code size of the `eth_transact` extrinsic
1335		///
1336		/// Calling this dispatchable ensures that the origin's nonce is bumped only once,
1337		/// via the `CheckNonce` transaction extension. In contrast, [`Self::instantiate_with_code`]
1338		/// also bumps the nonce after contract instantiation, since it may be invoked multiple
1339		/// times within a batch call transaction.
1340		#[pallet::call_index(10)]
1341		#[pallet::weight(
1342			<T as Config>::WeightInfo::eth_instantiate_with_code(code.len() as u32, data.len() as u32, Pallet::<T>::has_dust(*value).into())
1343			.saturating_add(*weight_limit)
1344			.saturating_add(T::WeightInfo::on_finalize_block_per_tx(transaction_encoded.len() as u32))
1345		)]
1346		pub fn eth_instantiate_with_code(
1347			origin: OriginFor<T>,
1348			value: U256,
1349			weight_limit: Weight,
1350			eth_gas_limit: U256,
1351			code: Vec<u8>,
1352			data: Vec<u8>,
1353			transaction_encoded: Vec<u8>,
1354			effective_gas_price: U256,
1355			encoded_len: u32,
1356		) -> DispatchResultWithPostInfo {
1357			let signer = Self::ensure_eth_signed(origin)?;
1358			let origin = OriginFor::<T>::signed(signer.clone());
1359			Self::ensure_non_contract_if_signed(&origin)?;
1360			let mut call = Call::<T>::eth_instantiate_with_code {
1361				value,
1362				weight_limit,
1363				eth_gas_limit,
1364				code: code.clone(),
1365				data: data.clone(),
1366				transaction_encoded: transaction_encoded.clone(),
1367				effective_gas_price,
1368				encoded_len,
1369			}
1370			.into();
1371			let info = T::FeeInfo::dispatch_info(&call);
1372			let base_info = T::FeeInfo::base_dispatch_info(&mut call);
1373			drop(call);
1374
1375			block_storage::with_ethereum_context::<T>(transaction_encoded, || {
1376				let extra_weight = base_info.total_weight();
1377				let output = Self::bare_instantiate(
1378					origin,
1379					value,
1380					TransactionLimits::EthereumGas {
1381						eth_gas_limit: eth_gas_limit.saturated_into(),
1382						weight_limit,
1383						eth_tx_info: EthTxInfo::new(encoded_len, extra_weight),
1384					},
1385					Code::Upload(code),
1386					data,
1387					None,
1388					&ExecConfig::new_eth_tx(effective_gas_price, encoded_len, extra_weight),
1389				);
1390
1391				block_storage::EthereumCallResult::new::<T>(
1392					signer,
1393					output.map_result(|r| r.result),
1394					base_info.call_weight,
1395					encoded_len,
1396					&info,
1397					effective_gas_price,
1398				)
1399			})
1400		}
1401
1402		/// Same as [`Self::call`], but intended to be dispatched **only**
1403		/// by an EVM transaction through the EVM compatibility layer.
1404		///
1405		/// # Parameters
1406		///
1407		/// * `dest`: The Ethereum address of the account to be called
1408		/// * `value`: The balance to transfer from the `origin` to the newly created contract.
1409		/// * `weight_limit`: The gas limit used to derive the transaction weight for transaction
1410		///   payment
1411		/// * `eth_gas_limit`: The Ethereum gas limit governing the resource usage of the execution
1412		/// * `data`: The input data to pass to the contract constructor.
1413		/// * `transaction_encoded`: The RLP encoding of the signed Ethereum transaction,
1414		///   represented as [crate::evm::TransactionSigned], provided by the Ethereum wallet. This
1415		///   is used for building the Ethereum transaction root.
1416		/// * effective_gas_price: the price of a unit of gas
1417		/// * encoded len: the byte code size of the `eth_transact` extrinsic
1418		#[pallet::call_index(11)]
1419		#[pallet::weight(
1420			T::WeightInfo::eth_call(Pallet::<T>::has_dust(*value).into())
1421			.saturating_add(*weight_limit)
1422			.saturating_add(T::WeightInfo::on_finalize_block_per_tx(transaction_encoded.len() as u32))
1423		)]
1424		pub fn eth_call(
1425			origin: OriginFor<T>,
1426			dest: H160,
1427			value: U256,
1428			weight_limit: Weight,
1429			eth_gas_limit: U256,
1430			data: Vec<u8>,
1431			transaction_encoded: Vec<u8>,
1432			effective_gas_price: U256,
1433			encoded_len: u32,
1434		) -> DispatchResultWithPostInfo {
1435			let signer = Self::ensure_eth_signed(origin)?;
1436			let origin = OriginFor::<T>::signed(signer.clone());
1437
1438			Self::ensure_non_contract_if_signed(&origin)?;
1439			let mut call = Call::<T>::eth_call {
1440				dest,
1441				value,
1442				weight_limit,
1443				eth_gas_limit,
1444				data: data.clone(),
1445				transaction_encoded: transaction_encoded.clone(),
1446				effective_gas_price,
1447				encoded_len,
1448			}
1449			.into();
1450			let info = T::FeeInfo::dispatch_info(&call);
1451			let base_info = T::FeeInfo::base_dispatch_info(&mut call);
1452			drop(call);
1453
1454			block_storage::with_ethereum_context::<T>(transaction_encoded, || {
1455				let extra_weight = base_info.total_weight();
1456				let output = Self::bare_call(
1457					origin,
1458					dest,
1459					value,
1460					TransactionLimits::EthereumGas {
1461						eth_gas_limit: eth_gas_limit.saturated_into(),
1462						weight_limit,
1463						eth_tx_info: EthTxInfo::new(encoded_len, extra_weight),
1464					},
1465					data,
1466					&ExecConfig::new_eth_tx(effective_gas_price, encoded_len, extra_weight),
1467				);
1468
1469				block_storage::EthereumCallResult::new::<T>(
1470					signer,
1471					output,
1472					base_info.call_weight,
1473					encoded_len,
1474					&info,
1475					effective_gas_price,
1476				)
1477			})
1478		}
1479
1480		/// Executes a Substrate runtime call from an Ethereum transaction.
1481		///
1482		/// This dispatchable is intended to be called **only** through the EVM compatibility
1483		/// layer. The provided call will be dispatched using `RawOrigin::Signed`.
1484		///
1485		/// # Parameters
1486		///
1487		/// * `origin`: Must be an [`Origin::EthTransaction`] origin.
1488		/// * `call`: The Substrate runtime call to execute.
1489		/// * `transaction_encoded`: The RLP encoding of the Ethereum transaction,
1490		#[pallet::call_index(12)]
1491		#[pallet::weight(
1492			T::WeightInfo::eth_substrate_call(transaction_encoded.len() as u32)
1493			.saturating_add(call.get_dispatch_info().call_weight)
1494			.saturating_add(T::WeightInfo::on_finalize_block_per_tx(transaction_encoded.len() as u32))
1495		)]
1496		pub fn eth_substrate_call(
1497			origin: OriginFor<T>,
1498			call: Box<<T as Config>::RuntimeCall>,
1499			transaction_encoded: Vec<u8>,
1500		) -> DispatchResultWithPostInfo {
1501			// Note that the inner dispatch uses `RawOrigin::Signed`, which cannot
1502			// re-enter `eth_substrate_call` (which requires `Origin::EthTransaction`).
1503			let signer = Self::ensure_eth_signed(origin)?;
1504			Self::ensure_non_contract_if_signed(&OriginFor::<T>::signed(signer.clone()))?;
1505			let tx_len = transaction_encoded.len() as u32;
1506			let weight_overhead = T::WeightInfo::eth_substrate_call(tx_len)
1507				.saturating_add(T::WeightInfo::on_finalize_block_per_tx(tx_len));
1508
1509			block_storage::with_ethereum_context::<T>(transaction_encoded, || {
1510				let call_weight = call.get_dispatch_info().call_weight;
1511				let mut call_result = call.dispatch(RawOrigin::Signed(signer).into());
1512
1513				// Add extrinsic_overhead to the actual weight in PostDispatchInfo
1514				match &mut call_result {
1515					Ok(post_info) | Err(DispatchErrorWithPostInfo { post_info, .. }) => {
1516						post_info.actual_weight = Some(
1517							post_info
1518								.actual_weight
1519								.unwrap_or_else(|| call_weight)
1520								.saturating_add(weight_overhead),
1521						);
1522					},
1523				}
1524
1525				// Return zero EVM gas (Substrate dispatch, not EVM contract call).
1526				// Actual weight is in `post_info.actual_weight`.
1527				block_storage::EthereumCallResult {
1528					receipt_gas_info: ReceiptGasInfo::default(),
1529					result: call_result,
1530				}
1531			})
1532		}
1533
1534		/// Upload new `code` without instantiating a contract from it.
1535		///
1536		/// If the code does not already exist a deposit is reserved from the caller
1537		/// The size of the reserve depends on the size of the supplied `code`.
1538		///
1539		/// # Note
1540		///
1541		/// Anyone can instantiate a contract from any uploaded code and thus prevent its removal.
1542		/// To avoid this situation a constructor could employ access control so that it can
1543		/// only be instantiated by permissioned entities. The same is true when uploading
1544		/// through [`Self::instantiate_with_code`].
1545		///
1546		/// If the refcount of the code reaches zero after terminating the last contract that
1547		/// references this code, the code will be removed automatically.
1548		#[pallet::call_index(4)]
1549		#[pallet::weight(<T as Config>::WeightInfo::upload_code(code.len() as u32))]
1550		pub fn upload_code(
1551			origin: OriginFor<T>,
1552			code: Vec<u8>,
1553			#[pallet::compact] storage_deposit_limit: BalanceOf<T>,
1554		) -> DispatchResult {
1555			Self::ensure_non_contract_if_signed(&origin)?;
1556			Self::bare_upload_code(origin, code, storage_deposit_limit).map(|_| ())
1557		}
1558
1559		/// Remove the code stored under `code_hash` and refund the deposit to its owner.
1560		///
1561		/// A code can only be removed by its original uploader (its owner) and only if it is
1562		/// not used by any contract.
1563		#[pallet::call_index(5)]
1564		#[pallet::weight(<T as Config>::WeightInfo::remove_code())]
1565		pub fn remove_code(
1566			origin: OriginFor<T>,
1567			code_hash: sp_core::H256,
1568		) -> DispatchResultWithPostInfo {
1569			let origin = ensure_signed(origin)?;
1570			<ContractBlob<T>>::remove(&origin, code_hash)?;
1571			// we waive the fee because removing unused code is beneficial
1572			Ok(Pays::No.into())
1573		}
1574
1575		/// Privileged function that changes the code of an existing contract.
1576		///
1577		/// This takes care of updating refcounts and all other necessary operations. Returns
1578		/// an error if either the `code_hash` or `dest` do not exist.
1579		///
1580		/// # Note
1581		///
1582		/// This does **not** change the address of the contract in question. This means
1583		/// that the contract address is no longer derived from its code hash after calling
1584		/// this dispatchable.
1585		#[pallet::call_index(6)]
1586		#[pallet::weight(<T as Config>::WeightInfo::set_code())]
1587		pub fn set_code(
1588			origin: OriginFor<T>,
1589			dest: H160,
1590			code_hash: sp_core::H256,
1591		) -> DispatchResult {
1592			ensure_root(origin)?;
1593			<AccountInfoOf<T>>::try_mutate(&dest, |account| {
1594				let Some(account) = account else {
1595					return Err(<Error<T>>::ContractNotFound.into());
1596				};
1597
1598				let AccountType::Contract(ref mut contract) = account.account_type else {
1599					return Err(<Error<T>>::ContractNotFound.into());
1600				};
1601
1602				<CodeInfo<T>>::increment_refcount(code_hash)?;
1603				let _ = <CodeInfo<T>>::decrement_refcount(contract.code_hash)?;
1604				contract.code_hash = code_hash;
1605
1606				Ok(())
1607			})
1608		}
1609
1610		/// Register the callers account id so that it can be used in contract interactions.
1611		///
1612		/// This will error if the origin is already mapped or is a eth native `Address20`. It will
1613		/// take a deposit that can be released by calling [`Self::unmap_account`].
1614		///
1615		/// Noop when [`Config::AutoMap`] is enabled, as accounts are automatically mapped
1616		/// on creation via [`AutoMapper`].
1617		#[pallet::call_index(7)]
1618		#[pallet::weight(<T as Config>::WeightInfo::map_account())]
1619		pub fn map_account(origin: OriginFor<T>) -> DispatchResult {
1620			#[cfg(not(feature = "runtime-benchmarks"))]
1621			if T::AutoMap::get() {
1622				return Ok(());
1623			}
1624
1625			Self::ensure_non_contract_if_signed(&origin)?;
1626			let origin = ensure_signed(origin)?;
1627			T::AddressMapper::map(&origin)
1628		}
1629
1630		/// Map many accounts and make the TX free if at least 90% were unmapped or held deposits.
1631		#[pallet::call_index(13)]
1632		#[pallet::weight(<T as Config>::WeightInfo::batch_map_accounts(accounts.len().saturated_into::<u32>()))]
1633		pub fn batch_map_accounts(
1634			origin: OriginFor<T>,
1635			accounts: Vec<T::AccountId>,
1636		) -> DispatchResultWithPostInfo {
1637			ensure_signed(origin.clone())?;
1638			Self::ensure_non_contract_if_signed(&origin)?;
1639
1640			let total: u32 = accounts.len().saturated_into();
1641			let mut mapped = 0;
1642
1643			for account_id in accounts
1644				.iter()
1645				// Eth-derived accounts are stateless mapped, nothing to do.
1646				.filter(|&a| !T::AddressMapper::is_eth_derived(a))
1647				// Skip non-existent accounts: otherwise any caller could permanently
1648				// insert mappings for arbitrary AccountIds at no cost.
1649				.filter(|&a| frame_system::Pallet::<T>::account_exists(a))
1650			{
1651				let mut useful = false;
1652
1653				match T::AddressMapper::map_no_deposit_unchecked(account_id) {
1654					Ok(()) => {
1655						useful = true;
1656					},
1657					Err(err) => log::debug!(
1658						target: LOG_TARGET,
1659						"Failed to map account {account_id:?}: {err:?}",
1660					),
1661				}
1662
1663				match T::Currency::release_all(
1664					&HoldReason::AddressMapping.into(),
1665					account_id,
1666					Precision::BestEffort,
1667				) {
1668					// `release_all` returns `Ok(0)` when there is no hold to release,
1669					// which is not useful work and must not earn a fee refund.
1670					Ok(released) if !released.is_zero() => {
1671						useful = true;
1672					},
1673					Ok(_) => {},
1674					Err(err) => log::debug!(
1675						target: LOG_TARGET,
1676						"Failed to release mapping deposit for {account_id:?}: {err:?}",
1677					),
1678				}
1679
1680				if useful {
1681					mapped = mapped.saturating_add(1);
1682				}
1683			}
1684
1685			// guard against 0 division below
1686			if total == 0 || mapped == 0 {
1687				return Ok(Pays::Yes.into());
1688			}
1689
1690			let proportion_mapped = Perbill::from_rational(mapped, total);
1691			if proportion_mapped >= Perbill::from_percent(90) {
1692				Ok(Pays::No.into())
1693			} else {
1694				Ok(Pays::Yes.into())
1695			}
1696		}
1697
1698		/// Unregister the callers account id in order to free the deposit.
1699		///
1700		/// There is no reason to ever call this function other than freeing up the deposit.
1701		/// This is only useful when the account should no longer be used.
1702		///
1703		/// Disabled when [`Config::AutoMap`] is enabled, as accounts are automatically unmapped
1704		/// on kill via [`AutoMapper`].
1705		#[pallet::call_index(8)]
1706		#[pallet::weight(<T as Config>::WeightInfo::unmap_account())]
1707		pub fn unmap_account(origin: OriginFor<T>) -> DispatchResult {
1708			#[cfg(not(feature = "runtime-benchmarks"))]
1709			ensure!(!T::AutoMap::get(), <Error<T>>::AutoMappingEnabled);
1710			let origin = ensure_signed(origin)?;
1711			T::AddressMapper::unmap(&origin)
1712		}
1713
1714		/// Dispatch an `call` with the origin set to the callers fallback address.
1715		///
1716		/// Every `AccountId32` can control its corresponding fallback account. The fallback account
1717		/// is the `AccountId20` with the last 12 bytes set to `0xEE`. This is essentially a
1718		/// recovery function in case an `AccountId20` was used without creating a mapping first.
1719		#[pallet::call_index(9)]
1720		#[pallet::weight({
1721			let dispatch_info = call.get_dispatch_info();
1722			(
1723				<T as Config>::WeightInfo::dispatch_as_fallback_account().saturating_add(dispatch_info.call_weight),
1724				dispatch_info.class
1725			)
1726		})]
1727		pub fn dispatch_as_fallback_account(
1728			mut origin: OriginFor<T>,
1729			call: Box<<T as Config>::RuntimeCall>,
1730		) -> DispatchResultWithPostInfo {
1731			Self::ensure_non_contract_if_signed(&origin)?;
1732			let account_id = origin.as_signer().ok_or(DispatchError::BadOrigin)?;
1733			let unmapped_account = T::AddressMapper::to_fallback_account_id(
1734				&T::AddressMapper::to_address(&account_id),
1735			);
1736			origin.set_caller_from(RawOrigin::Signed(unmapped_account));
1737			call.dispatch(origin)
1738		}
1739	}
1740}
1741
1742/// Create a dispatch result reflecting the amount of consumed weight.
1743fn dispatch_result<R>(
1744	result: Result<R, DispatchError>,
1745	weight_consumed: Weight,
1746	base_weight: Weight,
1747) -> DispatchResultWithPostInfo {
1748	let post_info = PostDispatchInfo {
1749		actual_weight: Some(weight_consumed.saturating_add(base_weight)),
1750		pays_fee: Default::default(),
1751	};
1752
1753	result
1754		.map(|_| post_info)
1755		.map_err(|e| DispatchErrorWithPostInfo { post_info, error: e })
1756}
1757
1758impl<T: Config> Pallet<T> {
1759	/// A generalized version of [`Self::call`].
1760	///
1761	/// Identical to [`Self::call`] but tailored towards being called by other code within the
1762	/// runtime as opposed to from an extrinsic. It returns more information and allows the
1763	/// enablement of features that are not suitable for an extrinsic (debugging, event
1764	/// collection).
1765	pub fn bare_call(
1766		origin: OriginFor<T>,
1767		dest: H160,
1768		evm_value: U256,
1769		transaction_limits: TransactionLimits<T>,
1770		data: Vec<u8>,
1771		exec_config: &ExecConfig<T>,
1772	) -> ContractResult<ExecReturnValue, BalanceOf<T>> {
1773		let mut transaction_meter = match TransactionMeter::new(transaction_limits) {
1774			Ok(transaction_meter) => transaction_meter,
1775			Err(error) => return ContractResult { result: Err(error), ..Default::default() },
1776		};
1777		let mut storage_deposit = Default::default();
1778
1779		let try_call = || {
1780			let origin = ExecOrigin::from_runtime_origin(origin)?;
1781			let result = ExecStack::<T, ContractBlob<T>>::run_call(
1782				origin.clone(),
1783				dest,
1784				&mut transaction_meter,
1785				evm_value,
1786				data,
1787				&exec_config,
1788			)?;
1789
1790			storage_deposit = transaction_meter
1791				.execute_postponed_deposits(&origin, &exec_config)
1792				.inspect_err(|err| {
1793				log::debug!(target: LOG_TARGET, "Failed to transfer deposit: {err:?}");
1794			})?;
1795
1796			Ok(result)
1797		};
1798		let result = Self::run_guarded(try_call);
1799
1800		log::trace!(target: LOG_TARGET, "Bare call ends: \
1801			result={result:?}, \
1802			weight_consumed={:?}, \
1803			weight_required={:?}, \
1804			storage_deposit={:?}, \
1805			gas_consumed={:?}, \
1806			max_storage_deposit={:?}",
1807			transaction_meter.weight_consumed(),
1808			transaction_meter.weight_required(),
1809			storage_deposit,
1810			transaction_meter.total_consumed_gas(),
1811			transaction_meter.deposit_required()
1812		);
1813
1814		ContractResult {
1815			result: result.map_err(|r| r.error),
1816			weight_consumed: transaction_meter.weight_consumed(),
1817			weight_required: transaction_meter.weight_required(),
1818			storage_deposit,
1819			gas_consumed: transaction_meter.total_consumed_gas(),
1820			max_storage_deposit: transaction_meter.deposit_required(),
1821		}
1822	}
1823
1824	/// Prepare a dry run for the given account.
1825	///
1826	///
1827	/// This function is public because it is called by the runtime API implementation
1828	/// (see `impl_runtime_apis_plus_revive`).
1829	pub fn prepare_dry_run(account: &T::AccountId) {
1830		// Bump the  nonce to simulate what would happen
1831		// `pre-dispatch` if the transaction was executed.
1832		frame_system::Pallet::<T>::inc_account_nonce(account);
1833
1834		// Map the account if it is not mapped already so we don't hit
1835		// `AccountUnmapped` from the origin when dry-running.
1836		if !T::AddressMapper::is_mapped(account) {
1837			let _ = T::AddressMapper::map_no_deposit_unchecked(account);
1838		}
1839	}
1840
1841	/// A generalized version of [`Self::instantiate`] or [`Self::instantiate_with_code`].
1842	///
1843	/// Identical to [`Self::instantiate`] or [`Self::instantiate_with_code`] but tailored towards
1844	/// being called by other code within the runtime as opposed to from an extrinsic. It returns
1845	/// more information to the caller useful to estimate the cost of the operation.
1846	pub fn bare_instantiate(
1847		origin: OriginFor<T>,
1848		evm_value: U256,
1849		transaction_limits: TransactionLimits<T>,
1850		code: Code,
1851		data: Vec<u8>,
1852		salt: Option<[u8; 32]>,
1853		exec_config: &ExecConfig<T>,
1854	) -> ContractResult<InstantiateReturnValue, BalanceOf<T>> {
1855		let mut transaction_meter = match TransactionMeter::new(transaction_limits) {
1856			Ok(transaction_meter) => transaction_meter,
1857			Err(error) => return ContractResult { result: Err(error), ..Default::default() },
1858		};
1859
1860		let mut storage_deposit = Default::default();
1861
1862		let try_instantiate = || {
1863			let instantiate_account = T::InstantiateOrigin::ensure_origin(origin.clone())?;
1864
1865			if_tracing(|t| t.instantiate_code(&code, salt.as_ref()));
1866			let executable = match code {
1867				Code::Upload(code) if code.starts_with(&polkavm_common::program::BLOB_MAGIC) => {
1868					let upload_account = T::UploadOrigin::ensure_origin(origin)?;
1869					let executable = Self::try_upload_code(
1870						upload_account,
1871						code,
1872						BytecodeType::Pvm,
1873						&mut transaction_meter,
1874						&exec_config,
1875					)?;
1876					executable
1877				},
1878				Code::Upload(code) => {
1879					if T::AllowEVMBytecode::get() {
1880						ensure!(data.is_empty(), <Error<T>>::EvmConstructorNonEmptyData);
1881						let origin = T::UploadOrigin::ensure_origin(origin)?;
1882						let executable = ContractBlob::from_evm_init_code(code, origin)?;
1883						executable
1884					} else {
1885						return Err(<Error<T>>::CodeRejected.into());
1886					}
1887				},
1888				Code::Existing(code_hash) => {
1889					let executable = ContractBlob::from_storage(code_hash, &mut transaction_meter)?;
1890					ensure!(executable.code_info().is_pvm(), <Error<T>>::EvmConstructedFromHash);
1891					executable
1892				},
1893			};
1894			let instantiate_origin = ExecOrigin::from_account_id(instantiate_account.clone());
1895			let result = ExecStack::<T, ContractBlob<T>>::run_instantiate(
1896				instantiate_account,
1897				executable,
1898				&mut transaction_meter,
1899				evm_value,
1900				data,
1901				salt.as_ref(),
1902				&exec_config,
1903			);
1904
1905			storage_deposit = transaction_meter
1906				.execute_postponed_deposits(&instantiate_origin, &exec_config)
1907				.inspect_err(|err| {
1908					log::debug!(target: LOG_TARGET, "Failed to transfer deposit: {err:?}");
1909				})?;
1910			result
1911		};
1912		let output = Self::run_guarded(try_instantiate);
1913
1914		log::trace!(target: LOG_TARGET, "Bare instantiate ends: weight_consumed={:?}\
1915			weight_required={:?} \
1916			storage_deposit={:?} \
1917			gas_consumed={:?} \
1918			max_storage_deposit={:?}",
1919			transaction_meter.weight_consumed(),
1920			transaction_meter.weight_required(),
1921			storage_deposit,
1922			transaction_meter.total_consumed_gas(),
1923			transaction_meter.deposit_required()
1924		);
1925
1926		ContractResult {
1927			result: output
1928				.map(|(addr, result)| InstantiateReturnValue { result, addr })
1929				.map_err(|e| e.error),
1930			weight_consumed: transaction_meter.weight_consumed(),
1931			weight_required: transaction_meter.weight_required(),
1932			storage_deposit,
1933			gas_consumed: transaction_meter.total_consumed_gas(),
1934			max_storage_deposit: transaction_meter.deposit_required(),
1935		}
1936	}
1937
1938	/// Estimates the amount of gas that a transactions requires.
1939	///
1940	/// This function estimates the gas of the transaction according to the same binary search
1941	/// algorithm that's implemented in Geth. It stops when with an acceptable error ratio of
1942	/// 1.5% so that the algorithm terminates early.
1943	///
1944	/// # Note
1945	///
1946	/// All calls to [`Self::dry_run_eth_transact`] need to happen inside of a [`with_transaction`]
1947	/// with state rollback to ensure that dry runs subsequent to the first one preserve the correct
1948	/// amount of storage deposits needed without any kind of caching from the previous dry runs.
1949	pub fn eth_estimate_gas(
1950		tx: GenericTransaction,
1951		config: DryRunConfig<<<T as Config>::Time as Time>::Moment>,
1952	) -> Result<U256, EthTransactError>
1953	where
1954		T::Nonce: Into<U256> + TryFrom<U256>,
1955		CallOf<T>: SetWeightLimit,
1956	{
1957		log::debug!(target: LOG_TARGET, "eth_estimate_gas: {tx:?}");
1958
1959		let mut low = U256::zero();
1960		let mut high = Self::evm_block_gas_limit();
1961
1962		log::trace!(target: LOG_TARGET, "eth_estimate_gas starting with low={low}, high={high}");
1963
1964		// If the user has specified a gas limit then this is the limit we use as the high bound for
1965		// the binary search. Also, if the user didn't specify a gas limit then we need to skip the
1966		// balance checks.
1967		let perform_balance_checks = if let Some(gas_limit) = tx.gas {
1968			high = gas_limit;
1969			log::trace!(target: LOG_TARGET, "eth_estimate_gas high limited by the gas limit high={high}");
1970			true
1971		} else {
1972			false
1973		};
1974
1975		// Cap the high bound of the binary search based on the account's balance if it can be done.
1976		let fee_cap = tx.max_fee_per_gas.or(tx.gas_price);
1977		if let (Some(fee_cap), Some(from), true) = (fee_cap, tx.from, perform_balance_checks) {
1978			let mut available_balance = Self::evm_balance(&from);
1979			if let Some(value) = tx.value {
1980				available_balance = available_balance.checked_sub(value).ok_or_else(|| {
1981					EthTransactError::Message("insufficient funds for value transfer".into())
1982				})?;
1983			}
1984			if let Some(allowance) = available_balance.checked_div(fee_cap) {
1985				if high > allowance && allowance != U256::zero() {
1986					log::trace!(target: LOG_TARGET, "eth_estimate_gas high limited by the user's allowance high={high} allowance={allowance}");
1987					high = allowance
1988				}
1989			}
1990		}
1991
1992		// Run one gas probe in a rolled-back transaction. Overrides ride along in `config` so
1993		// `dry_run_eth_transact` applies them *after* `prepare_dry_run` bumps the nonce, keeping a
1994		// nonce override at the exact value it sets.
1995		let dry_run_at = |gas: U256| {
1996			let mut transaction = tx.clone();
1997			transaction.gas = Some(gas);
1998			let dry_run_config = config.clone().with_perform_balance_checks(perform_balance_checks);
1999			with_transaction(|| {
2000				TransactionOutcome::Rollback(Ok::<_, DispatchError>(Self::dry_run_eth_transact(
2001					transaction,
2002					dry_run_config,
2003				)))
2004			})
2005			.expect("Rollback shouldn't error out")
2006		};
2007
2008		// Classify against post-override state (a code override can make the destination a
2009		// contract) in a rolled-back probe, so the overrides don't leak into the dry runs.
2010		let is_simple_transfer = with_transaction(|| {
2011			let probe = config
2012				.state_overrides
2013				.clone()
2014				.map_or(Ok(()), state_overrides::apply_state_overrides::<T>)
2015				.map(|()| Self::is_simple_transfer(&tx));
2016			TransactionOutcome::Rollback(Ok::<_, DispatchError>(probe))
2017		})
2018		.expect("Rollback shouldn't error out")?;
2019
2020		if is_simple_transfer {
2021			let dry_run_result = dry_run_at(high)?;
2022			log::trace!(
2023				target: LOG_TARGET,
2024				"eth_estimate_gas short-circuited simple transfer to {:?} with eth_gas={}",
2025				tx.to,
2026				dry_run_result.eth_gas,
2027			);
2028			return Ok(dry_run_result.eth_gas);
2029		}
2030
2031		// Perform the first dry run with the gas limit of the binary search's high bound. If it
2032		// fails then we attempt again with the max extrinsic weight in gas which we do since some
2033		// transactions fail the dry run with the highest gas limit. If both of these fail then we
2034		// return early as it means that the transaction simply can't succeed.
2035		let dry_run_results = [high, Self::evm_max_extrinsic_weight_in_gas()]
2036			.map(|gas_limit| (gas_limit, dry_run_at(gas_limit)));
2037		let (gas_limit, first_dry_run_result) = match dry_run_results {
2038			[(gas_limit1, Ok(dry_run_result1)), (gas_limit2, Ok(dry_run_result2))] => {
2039				if dry_run_result2.eth_gas >= gas_limit2 {
2040					(gas_limit1, dry_run_result1)
2041				} else {
2042					(gas_limit2, dry_run_result2)
2043				}
2044			},
2045			[(gas_limit, Ok(dry_run_result)), (_, Err(_))] |
2046			[(_, Err(_)), (gas_limit, Ok(dry_run_result))] => (gas_limit, dry_run_result),
2047			[(_, Err(err)), (_, Err(..))] => return Err(err),
2048		};
2049		log::trace!(
2050			target: LOG_TARGET,
2051			"eth_estimate_gas first dry run succeeded with gas_limit={} consumed={}",
2052			gas_limit,
2053			first_dry_run_result.eth_gas
2054		);
2055		low = first_dry_run_result.eth_gas;
2056		high = gas_limit;
2057
2058		while low + U256::one() < high {
2059			log::trace!(target: LOG_TARGET, "eth_estimate_gas estimation iteration with low={low} high={high}");
2060			let error_ratio = high
2061				.checked_sub(low)
2062				.and_then(|value| value.checked_mul(U256::from(1000)))
2063				.and_then(|value| value.checked_div(high))
2064				.ok_or_else(|| {
2065					EthTransactError::Message(
2066						"failed to calculate error ratio in gas estimation".into(),
2067					)
2068				})?;
2069			if error_ratio <= U256::from(15) {
2070				log::trace!(
2071					target: LOG_TARGET,
2072					"eth_estimate_gas finished due to error ratio being less than 1.5% high={}",
2073					high
2074				);
2075				break;
2076			}
2077
2078			let mut midpoint = high
2079				.checked_sub(low)
2080				.and_then(|value| value.checked_div(U256::from(2)))
2081				.and_then(|value| value.checked_add(low))
2082				.ok_or_else(|| {
2083					EthTransactError::Message(
2084						"failed to calculate midpoint in gas estimation".into(),
2085					)
2086				})?;
2087
2088			if let Some(other_midpoint) = low.checked_mul(U256::from(2)) {
2089				if other_midpoint != U256::zero() {
2090					midpoint = midpoint.min(other_midpoint)
2091				}
2092			};
2093
2094			let dry_run_result = dry_run_at(midpoint);
2095			log::trace!(target: LOG_TARGET, "eth_estimate_gas dry run result with midpoint={midpoint} is dry_run_result={dry_run_result:?}");
2096			match dry_run_result {
2097				Ok(..) => {
2098					log::trace!(target: LOG_TARGET, "eth_estimate_gas dry run succeeded, new high={midpoint}");
2099					high = midpoint
2100				},
2101				Err(..) => {
2102					log::trace!(target: LOG_TARGET, "eth_estimate_gas dry run failed, new low={midpoint}");
2103					low = midpoint
2104				},
2105			}
2106		}
2107
2108		log::trace!(target: LOG_TARGET, "eth_estimate_gas completed. high={high}");
2109		Ok(high)
2110	}
2111
2112	/// Returns true when `tx` is a plain value transfer that executes no code at its destination.
2113	pub(crate) fn is_simple_transfer(tx: &GenericTransaction) -> bool {
2114		tx.to
2115			.map(|to| tx.has_simple_transfer_fields() && Self::address_runs_no_code(&to))
2116			.unwrap_or(false)
2117	}
2118
2119	/// Returns true when a value transfer can target `address` without triggering any code
2120	/// execution: it is neither the runtime pallets address, a precompile, nor a contract.
2121	fn address_runs_no_code(address: &H160) -> bool {
2122		// TODO(eip-7702): also reject delegated (authorized) destinations once EIP-7702
2123		// delegations land, since a transfer to one executes the delegate's code.
2124		*address != RUNTIME_PALLETS_ADDR &&
2125			!exec::is_precompile::<T, ContractBlob<T>>(address) &&
2126			!<AccountInfo<T>>::is_contract(address)
2127	}
2128
2129	/// Return the pre-dispatch weight booked for the signed Ethereum transaction payload.
2130	///
2131	/// This matches the weight contribution that `frame_system::CheckWeight` would add for the
2132	/// transaction on an otherwise empty block:
2133	/// - the revive call's total dispatch weight, including extension weight,
2134	/// - the dispatch class base extrinsic weight,
2135	/// - and the extrinsic-length proof-size charge.
2136	pub fn eth_pre_dispatch_weight(transaction_encoded: Vec<u8>) -> Result<Weight, EthTransactError>
2137	where
2138		CallOf<T>: SetWeightLimit,
2139	{
2140		let signed_tx =
2141			crate::evm::TransactionSigned::decode(&transaction_encoded).map_err(|err| {
2142				EthTransactError::Message(format!("Failed to decode transaction: {err:?}"))
2143			})?;
2144		let signer_addr = signed_tx.recover_eth_address().map_err(|err| {
2145			EthTransactError::Message(format!("Failed to recover signer: {err:?}"))
2146		})?;
2147		let tx =
2148			GenericTransaction::from_signed(signed_tx, Self::evm_base_fee(), Some(signer_addr));
2149		let encoded_len = T::FeeInfo::encoded_len(
2150			crate::Call::<T>::eth_transact { payload: transaction_encoded.clone() }.into(),
2151		);
2152		let call_info = tx
2153			.into_call::<T>(CreateCallMode::ExtrinsicExecution(encoded_len, transaction_encoded))
2154			.map_err(|err| EthTransactError::Message(format!("Invalid call: {err:?}")))?;
2155		let info = T::FeeInfo::dispatch_info(&call_info.call);
2156
2157		Ok(frame_system::calculate_consumed_extrinsic_weight::<CallOf<T>>(
2158			&T::BlockWeights::get(),
2159			&info,
2160			call_info.encoded_len as usize,
2161		))
2162	}
2163
2164	/// Dry-run Ethereum calls.
2165	///
2166	/// # Parameters
2167	///
2168	/// - `tx`: The Ethereum transaction to simulate.
2169	pub fn dry_run_eth_transact(
2170		mut tx: GenericTransaction,
2171		mut dry_run_config: DryRunConfig<<<T as Config>::Time as Time>::Moment>,
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) = dry_run_config.state_overrides.take() {
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.into_call expects tx.gas_price to be the effective gas price
2203		tx.gas_price = Some(effective_gas_price);
2204		// we don't support priority fee for now as the tipping system in pallet-transaction-payment
2205		// works differently and the total tip needs to be known pre dispatch
2206		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		// Store values before moving the tx
2220		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		// we need to parse the weight from the transaction so that it is run
2226		// using the exact weight limit passed by the eth wallet
2227		let mut call_info = tx
2228			.into_call::<T>(CreateCallMode::DryRun)
2229			.map_err(|err| EthTransactError::Message(format!("Invalid call: {err:?}")))?;
2230
2231		// the dry-run might leave out certain fields
2232		// in those cases we skip the check that the caller has enough balance
2233		// to pay for the fees
2234		let base_info = T::FeeInfo::base_dispatch_info(&mut call_info.call);
2235		let base_weight = base_info.total_weight();
2236		let perform_balance_checks = dry_run_config.perform_balance_checks;
2237		let exec_config =
2238			ExecConfig::new_eth_tx(effective_gas_price, call_info.encoded_len, base_weight)
2239				.with_dry_run(dry_run_config);
2240
2241		// emulate transaction behavior
2242		let fees = call_info.tx_fee.saturating_add(call_info.storage_deposit);
2243		if let Some(from) = &from {
2244			let fees = if gas.is_some() && matches!(perform_balance_checks, Some(true)) {
2245				fees
2246			} else {
2247				Zero::zero()
2248			};
2249			let balance = Self::evm_balance(from);
2250			if balance < Pallet::<T>::convert_native_to_evm(fees).saturating_add(value) {
2251				return Err(EthTransactError::Message(format!(
2252					"insufficient funds for gas * price + value ({fees:?}): address {from:?} have {balance:?} (supplied gas {gas:?})",
2253				)));
2254			}
2255		}
2256
2257		// the deposit is done when the transaction is transformed from an `eth_transact`
2258		// we emulate this behavior for the dry-run here
2259		T::FeeInfo::deposit_txfee(T::Currency::issue(fees));
2260
2261		let extract_error = |err| {
2262			if err == Error::<T>::StorageDepositNotEnoughFunds.into() {
2263				Err(EthTransactError::Message(format!("Not enough gas supplied: {err:?}")))
2264			} else {
2265				Err(EthTransactError::Message(format!("failed to run contract: {err:?}")))
2266			}
2267		};
2268
2269		let transaction_limits = TransactionLimits::EthereumGas {
2270			eth_gas_limit: call_info.eth_gas_limit.saturated_into(),
2271			weight_limit: Self::evm_max_extrinsic_weight(),
2272			eth_tx_info: EthTxInfo::new(call_info.encoded_len, base_weight),
2273		};
2274
2275		// Dry run the call
2276		let mut dry_run = match to {
2277			// A contract call.
2278			Some(dest) => {
2279				if dest == RUNTIME_PALLETS_ADDR {
2280					let Ok(dispatch_call) = <CallOf<T>>::decode(&mut &input[..]) else {
2281						return Err(EthTransactError::Message(format!(
2282							"Failed to decode pallet-call {input:?}"
2283						)));
2284					};
2285
2286					if let Err(result) =
2287						dispatch_call.clone().dispatch(RawOrigin::Signed(origin).into())
2288					{
2289						return Err(EthTransactError::Message(format!(
2290							"Failed to dispatch call: {:?}",
2291							result.error,
2292						)));
2293					};
2294
2295					Default::default()
2296				} else {
2297					// Dry run the call.
2298					let result = crate::Pallet::<T>::bare_call(
2299						OriginFor::<T>::signed(origin),
2300						dest,
2301						value,
2302						transaction_limits,
2303						input.clone(),
2304						&exec_config,
2305					);
2306
2307					let data = match result.result {
2308						Ok(return_value) => {
2309							if return_value.did_revert() {
2310								return Err(EthTransactError::Data(return_value.data));
2311							}
2312							return_value.data
2313						},
2314						Err(err) => {
2315							log::debug!(target: LOG_TARGET, "Failed to execute call: {err:?}");
2316							return extract_error(err);
2317						},
2318					};
2319
2320					EthTransactInfo {
2321						weight_required: result.weight_required,
2322						storage_deposit: result.storage_deposit.charge_or_zero(),
2323						max_storage_deposit: result.max_storage_deposit.charge_or_zero(),
2324						data,
2325						eth_gas: Default::default(),
2326					}
2327				}
2328			},
2329			// A contract deployment
2330			None => {
2331				// Extract code and data from the input.
2332				let (code, data) = if input.starts_with(&polkavm_common::program::BLOB_MAGIC) {
2333					extract_code_and_data(&input).unwrap_or_else(|| (input, Default::default()))
2334				} else {
2335					(input, vec![])
2336				};
2337
2338				// Dry run the call.
2339				let result = crate::Pallet::<T>::bare_instantiate(
2340					OriginFor::<T>::signed(origin),
2341					value,
2342					transaction_limits,
2343					Code::Upload(code.clone()),
2344					data.clone(),
2345					None,
2346					&exec_config,
2347				);
2348
2349				let returned_data = match result.result {
2350					Ok(return_value) => {
2351						if return_value.result.did_revert() {
2352							return Err(EthTransactError::Data(return_value.result.data));
2353						}
2354						return_value.result.data
2355					},
2356					Err(err) => {
2357						log::debug!(target: LOG_TARGET, "Failed to instantiate: {err:?}");
2358						return extract_error(err);
2359					},
2360				};
2361
2362				EthTransactInfo {
2363					weight_required: result.weight_required,
2364					storage_deposit: result.storage_deposit.charge_or_zero(),
2365					max_storage_deposit: result.max_storage_deposit.charge_or_zero(),
2366					data: returned_data,
2367					eth_gas: Default::default(),
2368				}
2369			},
2370		};
2371
2372		// replace the weight passed in the transaction with the dry_run result
2373		call_info.call.set_weight_limit(dry_run.weight_required);
2374
2375		// we notify the wallet that the tx would not fit
2376		let total_weight = T::FeeInfo::dispatch_info(&call_info.call).total_weight();
2377		let max_weight = Self::evm_max_extrinsic_weight();
2378		if total_weight.any_gt(max_weight) {
2379			log::debug!(target: LOG_TARGET, "Transaction weight estimate exceeds extrinsic maximum: \
2380				total_weight={total_weight:?} \
2381				max_weight={max_weight:?}",
2382			);
2383
2384			Err(EthTransactError::Message(format!(
2385				"\
2386				The transaction consumes more than the allowed weight. \
2387				needed={total_weight} \
2388				allowed={max_weight} \
2389				overweight_by={}\
2390				",
2391				total_weight.saturating_sub(max_weight),
2392			)))?;
2393		}
2394
2395		// not enough gas supplied to pay for both the tx fees and the storage deposit
2396		let transaction_fee = T::FeeInfo::tx_fee(call_info.encoded_len, &call_info.call);
2397		let available_fee = T::FeeInfo::remaining_txfee();
2398		if transaction_fee > available_fee {
2399			Err(EthTransactError::Message(format!(
2400				"Not enough gas supplied: Off by: {:?}",
2401				transaction_fee.saturating_sub(available_fee),
2402			)))?;
2403		}
2404
2405		let total_cost = transaction_fee.saturating_add(dry_run.max_storage_deposit);
2406		let total_cost_wei = Pallet::<T>::convert_native_to_evm(total_cost);
2407		let (mut eth_gas, rest) = total_cost_wei.div_mod(base_fee);
2408		if !rest.is_zero() {
2409			eth_gas = eth_gas.saturating_add(1_u32.into());
2410		}
2411
2412		log::debug!(target: LOG_TARGET, "\
2413			dry_run_eth_transact finished: \
2414			weight_limit={}, \
2415			total_weight={total_weight}, \
2416			max_weight={max_weight}, \
2417			weight_left={}, \
2418			eth_gas={eth_gas}, \
2419			encoded_len={}, \
2420			tx_fee={transaction_fee:?}, \
2421			storage_deposit={:?}, \
2422			max_storage_deposit={:?}\
2423			",
2424			dry_run.weight_required,
2425			max_weight.saturating_sub(total_weight),
2426			call_info.encoded_len,
2427			dry_run.storage_deposit,
2428			dry_run.max_storage_deposit,
2429
2430		);
2431		dry_run.eth_gas = eth_gas;
2432		Ok(dry_run)
2433	}
2434
2435	/// Get the balance with EVM decimals of the given `address`.
2436	///
2437	/// Returns the spendable balance excluding the existential deposit.
2438	pub fn evm_balance(address: &H160) -> U256 {
2439		let balance = AccountInfo::<T>::balance_of((*address).into());
2440		Self::convert_native_to_evm(balance)
2441	}
2442
2443	/// Get the current Ethereum block from storage.
2444	pub fn eth_block() -> EthBlock {
2445		EthereumBlock::<T>::get()
2446	}
2447
2448	/// Convert the Ethereum block number into the Ethereum block hash.
2449	///
2450	/// # Note
2451	///
2452	/// The Ethereum block number is identical to the Substrate block number.
2453	/// If the provided block number is outside of the pruning None is returned.
2454	pub fn eth_block_hash_from_number(number: U256) -> Option<H256> {
2455		let number = BlockNumberFor::<T>::try_from(number).ok()?;
2456		let hash = <BlockHash<T>>::get(number);
2457		if hash == H256::zero() { None } else { Some(hash) }
2458	}
2459
2460	/// The details needed to reconstruct the receipt information offchain.
2461	pub fn eth_receipt_data() -> Vec<ReceiptGasInfo> {
2462		ReceiptInfoData::<T>::get()
2463	}
2464
2465	/// Set the EVM balance of an account.
2466	///
2467	/// The account's total balance becomes the EVM value plus the existential deposit,
2468	/// consistent with `evm_balance` which returns the spendable balance excluding the existential
2469	/// deposit.
2470	pub fn set_evm_balance(address: &H160, evm_value: U256) -> Result<(), Error<T>> {
2471		let (balance, dust) = Self::new_balance_with_dust(evm_value)
2472			.map_err(|_| <Error<T>>::BalanceConversionFailed)?;
2473		let account_id = T::AddressMapper::to_account_id(&address);
2474		T::Currency::set_balance(&account_id, balance);
2475		AccountInfoOf::<T>::mutate(&address, |account| {
2476			if let Some(account) = account {
2477				account.dust = dust;
2478			} else {
2479				*account = Some(AccountInfo { dust, ..Default::default() });
2480			}
2481		});
2482
2483		Ok(())
2484	}
2485
2486	/// Construct native balance from EVM balance.
2487	///
2488	/// Adds the existential deposit and returns the native balance plus the dust.
2489	pub fn new_balance_with_dust(
2490		evm_value: U256,
2491	) -> Result<(BalanceOf<T>, u32), BalanceConversionError> {
2492		let ed = T::Currency::minimum_balance();
2493		let balance_with_dust = BalanceWithDust::<BalanceOf<T>>::from_value::<T>(evm_value)?;
2494		let (value, dust) = balance_with_dust.deconstruct();
2495
2496		Ok((ed.saturating_add(value), dust))
2497	}
2498
2499	/// Get the nonce for the given `address`.
2500	pub fn evm_nonce(address: &H160) -> u32
2501	where
2502		T::Nonce: Into<u32>,
2503	{
2504		let account = T::AddressMapper::to_account_id(&address);
2505		System::<T>::account_nonce(account).into()
2506	}
2507
2508	/// Get the block gas limit.
2509	pub fn evm_block_gas_limit() -> U256 {
2510		// We just return `u64::MAX` because the gas cost of a transaction can get very large when
2511		// the transaction executes many storage deposits (in theory a contract can behave like a
2512		// factory, procedurally create code and make contract creation calls to store that as
2513		// code). It is too brittle to estimate a maximally possible amount here.
2514		// On the other hand, the data type `u64` seems to be the "common denominator" as the
2515		// typical data type tools and Ethereum implementations use to represent gas amounts.
2516		u64::MAX.into()
2517	}
2518
2519	/// Returns the maximum value of gas that can be represented in weights.
2520	pub fn evm_max_extrinsic_weight_in_gas() -> U256 {
2521		let max_extrinsic_fee = T::FeeInfo::weight_to_fee(&Self::evm_max_extrinsic_weight());
2522		let gas_scale: BalanceOf<T> = T::GasScale::get().into();
2523		(max_extrinsic_fee / gas_scale).into()
2524	}
2525
2526	/// The maximum weight an `eth_transact` is allowed to consume.
2527	pub fn evm_max_extrinsic_weight() -> Weight {
2528		let factor = <T as Config>::MaxEthExtrinsicWeight::get();
2529		let max_weight = <T as frame_system::Config>::BlockWeights::get()
2530			.get(DispatchClass::Normal)
2531			.max_extrinsic
2532			.unwrap_or_else(|| <T as frame_system::Config>::BlockWeights::get().max_block);
2533		Weight::from_parts(
2534			factor.saturating_mul_int(max_weight.ref_time()),
2535			factor.saturating_mul_int(max_weight.proof_size()),
2536		)
2537	}
2538
2539	/// Get the base gas price.
2540	pub fn evm_base_fee() -> U256 {
2541		let gas_scale = <T as Config>::GasScale::get();
2542		let multiplier = T::FeeInfo::next_fee_multiplier();
2543		multiplier
2544			.saturating_mul_int::<u128>(T::NativeToEthRatio::get().into())
2545			.saturating_mul(gas_scale.saturated_into())
2546			.into()
2547	}
2548
2549	/// Build an EVM tracer from the given tracer type.
2550	pub fn evm_tracer(tracer_type: TracerType) -> Tracer<T>
2551	where
2552		T::Nonce: Into<u32>,
2553	{
2554		match tracer_type {
2555			TracerType::CallTracer(config) => CallTracer::new(config.unwrap_or_default()).into(),
2556			TracerType::PrestateTracer(config) => {
2557				PrestateTracer::new(config.unwrap_or_default()).into()
2558			},
2559			TracerType::ExecutionTracer(config) => {
2560				ExecutionTracer::new(config.unwrap_or_default()).into()
2561			},
2562		}
2563	}
2564
2565	/// A generalized version of [`Self::upload_code`].
2566	///
2567	/// It is identical to [`Self::upload_code`] and only differs in the information it returns.
2568	pub fn bare_upload_code(
2569		origin: OriginFor<T>,
2570		code: Vec<u8>,
2571		storage_deposit_limit: BalanceOf<T>,
2572	) -> CodeUploadResult<BalanceOf<T>> {
2573		let origin = T::UploadOrigin::ensure_origin(origin)?;
2574
2575		let bytecode_type = if code.starts_with(&polkavm_common::program::BLOB_MAGIC) {
2576			BytecodeType::Pvm
2577		} else {
2578			if !T::AllowEVMBytecode::get() {
2579				return Err(<Error<T>>::CodeRejected.into());
2580			}
2581			BytecodeType::Evm
2582		};
2583
2584		let mut meter = TransactionMeter::new(TransactionLimits::WeightAndDeposit {
2585			weight_limit: Default::default(),
2586			deposit_limit: storage_deposit_limit,
2587		})?;
2588
2589		let module = Self::try_upload_code(
2590			origin,
2591			code,
2592			bytecode_type,
2593			&mut meter,
2594			&ExecConfig::new_substrate_tx(),
2595		)?;
2596		Ok(CodeUploadReturnValue {
2597			code_hash: *module.code_hash(),
2598			deposit: meter.deposit_consumed().charge_or_zero(),
2599		})
2600	}
2601
2602	/// Query storage of a specified contract under a specified key.
2603	pub fn get_storage(address: H160, key: [u8; 32]) -> GetStorageResult {
2604		let contract_info =
2605			AccountInfo::<T>::load_contract(&address).ok_or(ContractAccessError::DoesntExist)?;
2606
2607		let maybe_value = contract_info.read(&Key::from_fixed(key));
2608		Ok(maybe_value)
2609	}
2610
2611	/// Get the immutable data of a specified contract.
2612	///
2613	/// Returns `None` if the contract does not exist or has no immutable data.
2614	pub fn get_immutables(address: H160) -> Option<ImmutableData> {
2615		let immutable_data = <ImmutableDataOf<T>>::get(address);
2616		immutable_data
2617	}
2618
2619	/// Sets immutable data of a contract
2620	///
2621	/// Returns an error if the contract does not exist.
2622	///
2623	/// # Warning
2624	///
2625	/// Does not collect any storage deposit. Not safe to be called by user controlled code.
2626	pub fn set_immutables(address: H160, data: ImmutableData) -> Result<(), ContractAccessError> {
2627		AccountInfo::<T>::load_contract(&address).ok_or(ContractAccessError::DoesntExist)?;
2628		<ImmutableDataOf<T>>::insert(address, data);
2629		Ok(())
2630	}
2631
2632	/// Query storage of a specified contract under a specified variable-sized key.
2633	pub fn get_storage_var_key(address: H160, key: Vec<u8>) -> GetStorageResult {
2634		let contract_info =
2635			AccountInfo::<T>::load_contract(&address).ok_or(ContractAccessError::DoesntExist)?;
2636
2637		let maybe_value = contract_info.read(
2638			&Key::try_from_var(key)
2639				.map_err(|_| ContractAccessError::KeyDecodingFailed)?
2640				.into(),
2641		);
2642		Ok(maybe_value)
2643	}
2644
2645	/// Convert a native balance to EVM balance.
2646	pub fn convert_native_to_evm(value: impl Into<BalanceWithDust<BalanceOf<T>>>) -> U256 {
2647		let (value, dust) = value.into().deconstruct();
2648		value
2649			.into()
2650			.saturating_mul(T::NativeToEthRatio::get().into())
2651			.saturating_add(dust.into())
2652	}
2653
2654	/// Set storage of a specified contract under a specified key.
2655	///
2656	/// If the `value` is `None`, the storage entry is deleted.
2657	///
2658	/// Returns an error if the contract does not exist or if the write operation fails.
2659	///
2660	/// # Warning
2661	///
2662	/// Does not collect any storage deposit. Not safe to be called by user controlled code.
2663	pub fn set_storage(address: H160, key: [u8; 32], value: Option<Vec<u8>>) -> SetStorageResult {
2664		let contract_info =
2665			AccountInfo::<T>::load_contract(&address).ok_or(ContractAccessError::DoesntExist)?;
2666
2667		contract_info
2668			.write(&Key::from_fixed(key), value, None, false)
2669			.map_err(ContractAccessError::StorageWriteFailed)
2670	}
2671
2672	/// Set the storage of a specified contract under a specified variable-sized key.
2673	///
2674	/// If the `value` is `None`, the storage entry is deleted.
2675	///
2676	/// Returns an error if the contract does not exist, if the key decoding fails,
2677	/// or if the write operation fails.
2678	///
2679	/// # Warning
2680	///
2681	/// Does not collect any storage deposit. Not safe to be called by user controlled code.
2682	pub fn set_storage_var_key(
2683		address: H160,
2684		key: Vec<u8>,
2685		value: Option<Vec<u8>>,
2686	) -> SetStorageResult {
2687		let contract_info =
2688			AccountInfo::<T>::load_contract(&address).ok_or(ContractAccessError::DoesntExist)?;
2689
2690		contract_info
2691			.write(
2692				&Key::try_from_var(key)
2693					.map_err(|_| ContractAccessError::KeyDecodingFailed)?
2694					.into(),
2695				value,
2696				None,
2697				false,
2698			)
2699			.map_err(ContractAccessError::StorageWriteFailed)
2700	}
2701
2702	/// Pallet account, used to hold funds for contracts upload deposit.
2703	pub fn account_id() -> T::AccountId {
2704		use frame_support::PalletId;
2705		use sp_runtime::traits::AccountIdConversion;
2706		PalletId(*b"py/reviv").into_account_truncating()
2707	}
2708
2709	/// The address of the validator that produced the current block.
2710	pub fn block_author() -> H160 {
2711		use frame_support::traits::FindAuthor;
2712
2713		let digest = <frame_system::Pallet<T>>::digest();
2714		let pre_runtime_digests = digest.logs.iter().filter_map(|d| d.as_pre_runtime());
2715
2716		T::FindAuthor::find_author(pre_runtime_digests)
2717			.map(|account_id| T::AddressMapper::to_address(&account_id))
2718			.unwrap_or_default()
2719	}
2720
2721	/// Returns the code at `address`.
2722	///
2723	/// This takes pre-compiles into account.
2724	pub fn code(address: &H160) -> Vec<u8> {
2725		use precompiles::{All, Precompiles};
2726		if let Some(code) = <All<T>>::code(address.as_fixed_bytes()) {
2727			return code.into();
2728		}
2729		AccountInfo::<T>::load_contract(&address)
2730			.and_then(|contract| <PristineCode<T>>::get(contract.code_hash))
2731			.map(|code| code.into())
2732			.unwrap_or_default()
2733	}
2734
2735	/// Uploads new code and returns the Vm binary contract blob and deposit amount collected.
2736	pub fn try_upload_code(
2737		origin: T::AccountId,
2738		code: Vec<u8>,
2739		code_type: BytecodeType,
2740		meter: &mut TransactionMeter<T>,
2741		exec_config: &ExecConfig<T>,
2742	) -> Result<ContractBlob<T>, DispatchError> {
2743		let mut module = match code_type {
2744			BytecodeType::Pvm => ContractBlob::from_pvm_code(code, origin)?,
2745			BytecodeType::Evm => ContractBlob::from_evm_runtime_code(code, origin)?,
2746		};
2747		module.store_code(exec_config, meter)?;
2748		Ok(module)
2749	}
2750
2751	/// Run the supplied function `f` if no other instance of this pallet is on the stack.
2752	fn run_guarded<R, F: FnOnce() -> Result<R, ExecError>>(f: F) -> Result<R, ExecError> {
2753		executing_contract::using_once(&mut false, || {
2754			executing_contract::with(|f| {
2755				// Fail if already entered contract execution
2756				if *f {
2757					return Err(())
2758				}
2759				// We are entering contract execution
2760				*f = true;
2761				Ok(())
2762			})
2763				.expect("Returns `Ok` if called within `using_once`. It is syntactically obvious that this is the case; qed")
2764				.map_err(|_| <Error<T>>::ReenteredPallet.into())
2765				.map(|_| f())
2766				.and_then(|r| r)
2767		})
2768	}
2769
2770	/// Transfer a deposit from some account to another and place it on hold under `hold_reason`.
2771	///
2772	/// `from` is usually the transaction origin and `to` a contract or
2773	/// the pallets own account.
2774	fn charge_deposit(
2775		hold_reason: HoldReason,
2776		from: &T::AccountId,
2777		to: &T::AccountId,
2778		amount: BalanceOf<T>,
2779		exec_config: &ExecConfig<T>,
2780	) -> DispatchResult {
2781		if amount.is_zero() {
2782			return Ok(());
2783		}
2784
2785		T::Deposit::charge_and_hold(hold_reason, exec_config.funds(from), to, amount)
2786			.map_err(|_| Error::<T>::StorageDepositNotEnoughFunds)?;
2787		Ok(())
2788	}
2789
2790	/// Refund a deposit.
2791	///
2792	/// `dst` is usually the transaction origin and `from` a contract or
2793	/// the pallets own account.
2794	fn refund_deposit(
2795		hold_reason: HoldReason,
2796		from: &T::AccountId,
2797		dst: deposit_payment::Funds<T::AccountId>,
2798		amount: BalanceOf<T>,
2799	) -> Result<(), DispatchError> {
2800		if amount.is_zero() {
2801			return Ok(());
2802		}
2803
2804		let to = match &dst {
2805			deposit_payment::Funds::Balance(to) | deposit_payment::Funds::TxFee(to) => *to,
2806		};
2807		let result = T::Deposit::refund_on_hold(hold_reason, from, dst, amount);
2808
2809		result.defensive_map_err(|err| {
2810			let available = T::Deposit::total_on_hold(hold_reason, from);
2811			if available < amount {
2812				// The storage deposit accounting got out of sync with the balance: This would be a
2813				// straight up bug in this pallet.
2814				log::error!(
2815					target: LOG_TARGET,
2816					"Failed to refund storage deposit {amount:?} from contract {from:?} to origin {to:?}. Not enough deposit: {available:?}. This is a bug.",
2817				);
2818				Error::<T>::StorageRefundNotEnoughFunds.into()
2819			} else {
2820				// There are some locks preventing the refund. This could be the case if the
2821				// contract participates in government. The consequence is that if a contract votes
2822				// with its storage deposit it would no longer be possible to remove storage without first
2823				// reducing the lock.
2824				log::warn!(
2825					target: LOG_TARGET,
2826					"Failed to refund storage deposit {amount:?} from contract {from:?} to origin {to:?}: {err:?}. First remove locks (staking, governance) from the contracts account.",
2827				);
2828				Error::<T>::StorageRefundLocked.into()
2829			}
2830		})
2831	}
2832
2833	/// Returns true if the evm value carries dust.
2834	fn has_dust(value: U256) -> bool {
2835		value % U256::from(<T>::NativeToEthRatio::get()) != U256::zero()
2836	}
2837
2838	/// Returns true if the evm value carries balance.
2839	fn has_balance(value: U256) -> bool {
2840		value >= U256::from(<T>::NativeToEthRatio::get())
2841	}
2842
2843	/// Return the existential deposit of [`Config::Currency`].
2844	#[cfg(any(feature = "runtime-benchmarks", feature = "try-runtime", test))]
2845	fn min_balance() -> BalanceOf<T> {
2846		<T::Currency as Inspect<AccountIdOf<T>>>::minimum_balance()
2847	}
2848
2849	/// Deposit a pallet revive event.
2850	///
2851	/// This method will be called by the EVM to deposit events emitted by the contract.
2852	/// Therefore all events must be contract emitted events.
2853	fn deposit_event(event: Event<T>) {
2854		<frame_system::Pallet<T>>::deposit_event(<T as Config>::RuntimeEvent::from(event))
2855	}
2856
2857	// Returns Ok with the account that signed the eth transaction.
2858	fn ensure_eth_signed(origin: OriginFor<T>) -> Result<AccountIdOf<T>, DispatchError> {
2859		match <T as Config>::RuntimeOrigin::from(origin).into() {
2860			Ok(Origin::EthTransaction(signer)) => Ok(signer),
2861			_ => Err(BadOrigin.into()),
2862		}
2863	}
2864
2865	/// Ensure that the origin is neither a pre-compile nor a contract.
2866	///
2867	/// This enforces EIP-3607.
2868	fn ensure_non_contract_if_signed(origin: &OriginFor<T>) -> DispatchResult {
2869		if DebugSettings::bypass_eip_3607::<T>() {
2870			return Ok(());
2871		}
2872		let Some(address) = origin
2873			.as_system_ref()
2874			.and_then(|o| o.as_signed())
2875			.map(<T::AddressMapper as AddressMapper<T>>::to_address)
2876		else {
2877			return Ok(());
2878		};
2879		if exec::is_precompile::<T, ContractBlob<T>>(&address) ||
2880			<AccountInfo<T>>::is_contract(&address)
2881		{
2882			log::debug!(
2883				target: crate::LOG_TARGET,
2884				"EIP-3607: reject tx as pre-compile or account exist at {address:?}",
2885			);
2886			Err(DispatchError::BadOrigin)
2887		} else {
2888			Ok(())
2889		}
2890	}
2891}
2892
2893/// The address used to call the runtime's pallets dispatchables
2894///
2895/// Note:
2896/// computed with PalletId(*b"py/paddr").into_account_truncating();
2897pub const RUNTIME_PALLETS_ADDR: H160 =
2898	H160(hex_literal::hex!("6d6f646c70792f70616464720000000000000000"));
2899
2900// Set up a global reference to the boolean flag used for the re-entrancy guard.
2901environmental!(executing_contract: bool);
2902
2903sp_api::decl_runtime_apis! {
2904	/// The API used to dry-run contract interactions.
2905	#[api_version(2)]
2906	pub trait ReviveApi<AccountId, Balance, Nonce, BlockNumber, Moment> where
2907		AccountId: Codec,
2908		Balance: Codec,
2909		Nonce: Codec,
2910		BlockNumber: Codec,
2911		Moment: Codec,
2912	{
2913		/// Returns the current ETH block.
2914		///
2915		/// This is one block behind the substrate block.
2916		fn eth_block() -> EthBlock;
2917
2918		/// Returns the ETH block hash for the given block number.
2919		#[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		/// The details needed to reconstruct the receipt information offchain.
2923		///
2924		/// # Note
2925		///
2926		/// Each entry corresponds to the appropriate Ethereum transaction in the current block.
2927		#[deprecated(note = "Use the versioned equivalent `eth_receipt_data_versioned` if available on your runtime")]
2928		fn eth_receipt_data() -> Vec<ReceiptGasInfoV1>;
2929
2930		/// Returns the block gas limit.
2931		#[deprecated(note = "Use the versioned equivalent `block_gas_limit_versioned` if available on your runtime")]
2932		fn block_gas_limit() -> U256;
2933
2934		/// Returns the block gas limit as calculated from the weights.
2935		#[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		/// Returns the free balance of the given `[H160]` address, using EVM decimals.
2939		#[deprecated(note = "Use the versioned equivalent `balance_versioned` if available on your runtime")]
2940		fn balance(address: H160) -> U256;
2941
2942		/// Returns the gas price.
2943		#[deprecated(note = "Use the versioned equivalent `gas_price_versioned` if available on your runtime")]
2944		fn gas_price() -> U256;
2945
2946		/// Returns the nonce of the given `[H160]` address.
2947		#[deprecated(note = "Use the versioned equivalent `nonce_versioned` if available on your runtime")]
2948		fn nonce(address: H160) -> Nonce;
2949
2950		/// Perform a call from a specified account to a given contract.
2951		///
2952		/// See [`crate::Pallet::bare_call`].
2953		fn call(
2954			origin: AccountId,
2955			dest: H160,
2956			value: Balance,
2957			gas_limit: Option<Weight>,
2958			storage_deposit_limit: Option<Balance>,
2959			input_data: Vec<u8>,
2960		) -> ContractResult<ExecReturnValue, Balance>;
2961
2962		/// Instantiate a new contract.
2963		///
2964		/// See `[crate::Pallet::bare_instantiate]`.
2965		fn instantiate(
2966			origin: AccountId,
2967			value: Balance,
2968			gas_limit: Option<Weight>,
2969			storage_deposit_limit: Option<Balance>,
2970			code: Code,
2971			data: Vec<u8>,
2972			salt: Option<[u8; 32]>,
2973		) -> ContractResult<InstantiateReturnValue, Balance>;
2974
2975
2976		/// Perform an Ethereum call.
2977		///
2978		/// Deprecated use `v2` version instead.
2979		/// See [`crate::Pallet::dry_run_eth_transact`]
2980		fn eth_transact(tx: GenericTransaction) -> Result<EthTransactInfo<Balance>, EthTransactError>;
2981
2982		/// Perform an Ethereum call.
2983		///
2984		/// See [`crate::Pallet::dry_run_eth_transact`]
2985		fn eth_transact_with_config(
2986			tx: GenericTransaction,
2987			config: DryRunConfig<Moment>,
2988		) -> Result<EthTransactInfo<Balance>, EthTransactError>;
2989
2990		/// Estimates the amount of gas that a transactions requires.
2991		///
2992		/// This function estimates the gas of the transaction according to the same binary search
2993		/// algorithm that's implemented in Geth. It stops when with an acceptable error ratio of
2994		/// 1.5% so that the algorithm terminates early.
2995		fn eth_estimate_gas(
2996			tx: GenericTransaction,
2997			config: DryRunConfig<Moment>
2998		) -> Result<U256, EthTransactError>;
2999
3000		/// Return the pre-dispatch weight booked for the signed Ethereum transaction payload.
3001		#[deprecated(note = "Use the versioned equivalent `eth_pre_dispatch_weight_versioned` if available on your runtime")]
3002		fn eth_pre_dispatch_weight(tx: Vec<u8>) -> Result<Weight, EthTransactError>;
3003
3004		/// Upload new code without instantiating a contract from it.
3005		///
3006		/// See [`crate::Pallet::bare_upload_code`].
3007		#[deprecated(note = "Use the versioned equivalent `upload_code_versioned` if available on your runtime")]
3008		fn upload_code(
3009			origin: AccountId,
3010			code: Vec<u8>,
3011			storage_deposit_limit: Option<Balance>,
3012		) -> Result<CodeUploadReturnValueV1<Balance>, DispatchError>;
3013
3014		/// Query a given storage key in a given contract.
3015		///
3016		/// Returns `Ok(Some(Vec<u8>))` if the storage value exists under the given key in the
3017		/// specified account and `Ok(None)` if it doesn't. If the account specified by the address
3018		/// doesn't exist, or doesn't have a contract then `Err` is returned.
3019		#[deprecated(note = "Use the versioned equivalent `get_storage_versioned` if available on your runtime")]
3020		fn get_storage(
3021			address: H160,
3022			key: [u8; 32],
3023		) -> GetStorageResult;
3024
3025		/// Query a given variable-sized storage key in a given contract.
3026		///
3027		/// Returns `Ok(Some(Vec<u8>))` if the storage value exists under the given key in the
3028		/// specified account and `Ok(None)` if it doesn't. If the account specified by the address
3029		/// doesn't exist, or doesn't have a contract then `Err` is returned.
3030		#[deprecated(note = "Use the versioned equivalent `get_storage_versioned` if available on your runtime")]
3031		fn get_storage_var_key(
3032			address: H160,
3033			key: Vec<u8>,
3034		) -> GetStorageResult;
3035
3036		/// Traces the execution of an entire block and returns call traces.
3037		///
3038		/// This is intended to be called through `state_call` to replay the block from the
3039		/// parent block.
3040		///
3041		/// See eth-rpc `debug_traceBlockByNumber` for usage.
3042		#[deprecated(note = "Use the versioned equivalent `trace_block_versioned` if available on your runtime")]
3043		fn trace_block(
3044			block: Block,
3045			config: TracerTypeV1
3046		) -> Vec<(u32, TraceV1)>;
3047
3048		/// Traces the execution of a specific transaction within a block.
3049		///
3050		/// This is intended to be called through `state_call` to replay the block from the
3051		/// parent hash up to the transaction.
3052		///
3053		/// See eth-rpc `debug_traceTransaction` for usage.
3054		#[deprecated(note = "Use the versioned equivalent `trace_tx_versioned` if available on your runtime")]
3055		fn trace_tx(
3056			block: Block,
3057			tx_index: u32,
3058			config: TracerTypeV1
3059		) -> Option<TraceV1>;
3060
3061		/// Dry run and return the trace of the given call.
3062		///
3063		/// See eth-rpc `debug_traceCall` for usage.
3064		fn trace_call(tx: GenericTransaction, config: TracerTypeV1) -> Result<TraceV1, EthTransactError>;
3065
3066		/// Dry run and return the trace of the given call with additional configuration.
3067		///
3068		/// Like [`Self::trace_call`], but accepts a [`TracingConfig`] that can carry state
3069		/// overrides and future extensibility. The config must be the **last argument** for
3070		/// backwards compatibility — see [`TracingConfig`] documentation.
3071		fn trace_call_with_config(
3072			tx: GenericTransaction,
3073			tracer_type: TracerTypeV1,
3074			config: TracingConfig,
3075		) -> Result<TraceV1, EthTransactError>;
3076
3077		/// The address of the validator that produced the current block.
3078		#[deprecated(note = "Use the versioned equivalent `block_author_versioned` if available on your runtime")]
3079		fn block_author() -> H160;
3080
3081		/// Get the H160 address associated to this account id
3082		#[deprecated(note = "Use the versioned equivalent `address_versioned` if available on your runtime")]
3083		fn address(account_id: AccountId) -> H160;
3084
3085		/// Get the account id associated to this H160 address.
3086		#[deprecated(note = "Use the versioned equivalent `account_id_versioned` if available on your runtime")]
3087		fn account_id(address: H160) -> AccountId;
3088
3089		/// The address used to call the runtime's pallets dispatchables
3090		#[deprecated(note = "Use the versioned equivalent `runtime_pallets_address_versioned` if available on your runtime")]
3091		fn runtime_pallets_address() -> H160;
3092
3093		/// The code at the specified address taking pre-compiles into account.
3094		#[deprecated(note = "Use the versioned equivalent `code_versioned` if available on your runtime")]
3095		fn code(address: H160) -> Vec<u8>;
3096
3097		/// Construct the new balance and dust components of this EVM balance.
3098		#[deprecated(note = "Use the versioned equivalent `new_balance_with_dust_versioned` if available on your runtime")]
3099		fn new_balance_with_dust(balance: U256) -> Result<(Balance, u32), BalanceConversionError>;
3100
3101		/* Versioned Runtime APIs */
3102
3103		#[api_version(2)]
3104		fn version_declarations() -> ReviveRuntimeApiVersionDeclarations;
3105
3106		#[api_version(2)]
3107		fn eth_block_hash_versioned(input: BlockHashVersionedInputPayload) -> BlockHashVersionedOutputPayload;
3108
3109		#[api_version(2)]
3110		fn eth_receipt_data_versioned(input: ReceiptDataVersionedInputPayload) -> ReceiptDataVersionedOutputPayload;
3111
3112		#[api_version(2)]
3113		fn block_gas_limit_versioned(
3114			input: BlockGasLimitVersionedInputPayload
3115		) -> BlockGasLimitVersionedOutputPayload;
3116
3117		#[api_version(2)]
3118		fn max_extrinsic_weight_in_gas_versioned(
3119			input: MaxExtrinsicWeightInGasVersionedInputPayload
3120		) -> MaxExtrinsicWeightInGasVersionedOutputPayload;
3121
3122		#[api_version(2)]
3123		fn balance_versioned(input: BalanceVersionedInputPayload) -> BalanceVersionedOutputPayload;
3124
3125		#[api_version(2)]
3126		fn gas_price_versioned(input: GasPriceVersionedInputPayload) -> GasPriceVersionedOutputPayload;
3127
3128		#[api_version(2)]
3129		fn nonce_versioned(input: NonceVersionedInputPayload) -> NonceVersionedOutputPayload<Nonce>;
3130
3131		#[api_version(2)]
3132		fn eth_pre_dispatch_weight_versioned(
3133			input: PreDispatchWeightVersionedInputPayload
3134		) -> Result<PreDispatchWeightVersionedOutputPayload, EthTransactError>;
3135
3136		#[api_version(2)]
3137		fn upload_code_versioned(
3138			input: UploadCodeVersionedInputPayload<AccountId, Balance>
3139		) -> Result<UploadCodeVersionedOutputPayload<Balance>, DispatchError>;
3140
3141		#[api_version(2)]
3142		fn get_storage_versioned(
3143			input: GetStorageVersionedInputPayload
3144		) -> Result<GetStorageVersionedOutputPayload, ContractAccessError>;
3145
3146		#[api_version(2)]
3147		fn runtime_pallets_address_versioned(
3148			input: RuntimePalletsAddressVersionedInputPayload
3149		) -> RuntimePalletsAddressVersionedOutputPayload;
3150
3151		#[api_version(2)]
3152		fn code_versioned(input: CodeVersionedInputPayload) -> CodeVersionedOutputPayload;
3153
3154		#[api_version(2)]
3155		fn account_id_versioned(input: AccountIdVersionedInputPayload) -> AccountIdVersionedOutputPayload<AccountId>;
3156
3157		#[api_version(2)]
3158		fn new_balance_with_dust_versioned(
3159			input: NewBalanceWithDustVersionedInputPayload
3160		) -> Result<NewBalanceWithDustVersionedOutputPayload<Balance>, BalanceConversionError>;
3161
3162		#[api_version(2)]
3163		fn block_author_versioned(input: BlockAuthorVersionedInputPayload) -> BlockAuthorVersionedOutputPayload;
3164
3165		#[api_version(2)]
3166		fn address_versioned(input: AddressVersionedInputPayload<AccountId>) -> AddressVersionedOutputPayload;
3167
3168		#[api_version(2)]
3169		fn trace_block_versioned(input: TraceBlockVersionedInputPayload<Block>) -> TraceBlockVersionedOutputPayload;
3170
3171		#[api_version(2)]
3172		fn trace_tx_versioned(input: TraceTxVersionedInputPayload<Block>) -> TraceTxVersionedOutputPayload;
3173	}
3174}
3175
3176/// This macro wraps substrate's `impl_runtime_apis!` and implements `pallet_revive` runtime APIs
3177/// and other required traits.
3178///
3179/// # Note
3180///
3181/// This also implements [`SetWeightLimit`] for the runtime call.
3182///
3183/// # Parameters
3184/// - `$Runtime`: The runtime type to implement the APIs for.
3185/// - `$Revive`: The name under which revive is declared in `construct_runtime`.
3186/// - `$Executive`: The Executive type of the runtime.
3187/// - `$EthExtra`: Type for additional Ethereum runtime extension.
3188/// - `$($rest:tt)*`: Remaining input to be forwarded to the underlying `impl_runtime_apis!`.
3189#[macro_export]
3190macro_rules! impl_runtime_apis_plus_revive_traits {
3191	($Runtime: ty, $Revive: ident, $Executive: ty, $EthExtra: ty, $($rest:tt)*) => {
3192
3193		type __ReviveMacroMoment = <<$Runtime as $crate::Config>::Time as $crate::Time>::Moment;
3194
3195		impl $crate::evm::runtime::SetWeightLimit for RuntimeCall {
3196			fn set_weight_limit(&mut self, new_weight_limit: Weight) -> Weight {
3197				use $crate::pallet::Call as ReviveCall;
3198				match self {
3199					Self::$Revive(
3200						ReviveCall::eth_call{ weight_limit, .. } |
3201						ReviveCall::eth_instantiate_with_code{ weight_limit, .. }
3202					) => {
3203						let old = *weight_limit;
3204						*weight_limit = new_weight_limit;
3205						old
3206					},
3207					_ => Weight::default(),
3208				}
3209			}
3210		}
3211
3212		impl_runtime_apis! {
3213			$($rest)*
3214
3215			#[api_version(2)]
3216			impl pallet_revive::ReviveApi<Block, AccountId, Balance, Nonce, BlockNumber, __ReviveMacroMoment> for $Runtime
3217			{
3218				fn eth_block() -> $crate::EthBlock {
3219					$crate::Pallet::<Self>::eth_block()
3220				}
3221
3222				fn eth_block_hash(number: $crate::U256) -> Option<$crate::H256> {
3223					use $crate::pallet_revive_types::runtime_api::*;
3224
3225					let input = BlockHashVersionedInputPayload::from(BlockHashInputPayloadV1 {
3226						block_number: number
3227					});
3228					let output = Self::eth_block_hash_versioned(input);
3229					BlockHashOutputPayloadV1::try_from(output)
3230						.expect("v1 input must produce v1 output; qed")
3231						.block_hash
3232				}
3233
3234				fn eth_receipt_data() -> Vec<$crate::pallet_revive_types::runtime_api::ReceiptGasInfoV1> {
3235					use $crate::pallet_revive_types::runtime_api::*;
3236
3237					let input = ReceiptDataVersionedInputPayload::from(ReceiptDataInputPayloadV1);
3238					let output = Self::eth_receipt_data_versioned(input);
3239					ReceiptDataOutputPayloadV1::try_from(output)
3240						.expect("v1 input must produce v1 output; qed")
3241						.receipt_data
3242				}
3243
3244				fn balance(address: $crate::H160) -> $crate::U256 {
3245					use $crate::pallet_revive_types::runtime_api::*;
3246
3247					let input = BalanceVersionedInputPayload::from(BalanceInputPayloadV1 { address });
3248					let output = Self::balance_versioned(input);
3249					BalanceOutputPayloadV1::try_from(output)
3250						.expect("v1 input must produce v1 output; qed")
3251						.balance
3252				}
3253
3254				fn block_author() -> $crate::H160 {
3255					use $crate::pallet_revive_types::runtime_api::*;
3256
3257					let input = BlockAuthorVersionedInputPayload::from(BlockAuthorInputPayloadV1);
3258					let output = Self::block_author_versioned(input);
3259					BlockAuthorOutputPayloadV1::try_from(output)
3260						.expect("v1 input must produce v1 output; qed")
3261						.block_author
3262				}
3263
3264				fn block_gas_limit() -> $crate::U256 {
3265					use $crate::pallet_revive_types::runtime_api::*;
3266
3267					let input = BlockGasLimitVersionedInputPayload::from(BlockGasLimitInputPayloadV1);
3268					let output = Self::block_gas_limit_versioned(input);
3269					BlockGasLimitOutputPayloadV1::try_from(output)
3270						.expect("v1 input must produce v1 output; qed")
3271						.block_gas_limit
3272				}
3273
3274				fn max_extrinsic_weight_in_gas() -> $crate::U256 {
3275					use $crate::pallet_revive_types::runtime_api::*;
3276
3277					let input = MaxExtrinsicWeightInGasVersionedInputPayload::from(
3278						MaxExtrinsicWeightInGasInputPayloadV1
3279					);
3280					let output = Self::max_extrinsic_weight_in_gas_versioned(input);
3281					MaxExtrinsicWeightInGasOutputPayloadV1::try_from(output)
3282						.expect("v1 input must produce v1 output; qed")
3283						.max_extrinsic_weight_in_gas
3284				}
3285
3286				fn gas_price() -> $crate::U256 {
3287					use $crate::pallet_revive_types::runtime_api::*;
3288
3289					let input = GasPriceVersionedInputPayload::from(GasPriceInputPayloadV1);
3290					let output = Self::gas_price_versioned(input);
3291					GasPriceOutputPayloadV1::try_from(output)
3292						.expect("v1 input must produce v1 output; qed")
3293						.gas_price
3294				}
3295
3296				fn nonce(address: $crate::H160) -> Nonce {
3297					use $crate::pallet_revive_types::runtime_api::*;
3298
3299					let input = NonceVersionedInputPayload::from(NonceInputPayloadV1 { address });
3300					let output = Self::nonce_versioned(input);
3301					NonceOutputPayloadV1::try_from(output)
3302						.expect("v1 input must produce v1 output; qed")
3303						.nonce
3304				}
3305
3306				fn address(account_id: AccountId) -> $crate::H160 {
3307					use $crate::pallet_revive_types::runtime_api::*;
3308
3309					let input = AddressVersionedInputPayload::from(AddressInputPayloadV1 { account_id });
3310					let output = Self::address_versioned(input);
3311					AddressOutputPayloadV1::try_from(output)
3312						.expect("v1 input must produce v1 output; qed")
3313						.address
3314				}
3315
3316				fn eth_transact(
3317					tx: $crate::evm::GenericTransaction,
3318				) -> Result<$crate::EthTransactInfo<Balance>, $crate::EthTransactError> {
3319					use $crate::{
3320						codec::Encode, evm::runtime::EthExtra, frame_support::traits::Get,
3321						sp_runtime::traits::TransactionExtension,
3322						sp_runtime::traits::Block as BlockT
3323					};
3324					$crate::Pallet::<Self>::dry_run_eth_transact(tx, Default::default())
3325				}
3326
3327				fn eth_transact_with_config(
3328					tx: $crate::evm::GenericTransaction,
3329					config: $crate::DryRunConfig<__ReviveMacroMoment>,
3330				) -> Result<$crate::EthTransactInfo<Balance>, $crate::EthTransactError> {
3331					use $crate::{
3332						codec::Encode, evm::runtime::EthExtra, frame_support::traits::Get,
3333						sp_runtime::traits::TransactionExtension,
3334						sp_runtime::traits::Block as BlockT
3335					};
3336					$crate::Pallet::<Self>::dry_run_eth_transact(tx, config)
3337				}
3338
3339				fn eth_estimate_gas(
3340					tx: $crate::evm::GenericTransaction,
3341					config: $crate::DryRunConfig<__ReviveMacroMoment>,
3342				) -> Result<$crate::U256, $crate::EthTransactError>  {
3343					use $crate::{
3344						codec::Encode, evm::runtime::EthExtra, frame_support::traits::Get,
3345						sp_runtime::traits::TransactionExtension,
3346						sp_runtime::traits::Block as BlockT
3347					};
3348					$crate::Pallet::<Self>::eth_estimate_gas(tx, config)
3349				}
3350
3351				fn eth_pre_dispatch_weight(
3352					tx: Vec<u8>,
3353				) -> Result<$crate::Weight, $crate::EthTransactError> {
3354					use $crate::pallet_revive_types::runtime_api::*;
3355
3356					let input = PreDispatchWeightVersionedInputPayload::from(
3357						PreDispatchWeightInputPayloadV1 { tx }
3358					);
3359					let output = Self::eth_pre_dispatch_weight_versioned(input)?;
3360					Ok(PreDispatchWeightOutputPayloadV1::try_from(output)
3361						.expect("v1 input must produce v1 output; qed")
3362						.weight)
3363				}
3364
3365				fn call(
3366					origin: AccountId,
3367					dest: $crate::H160,
3368					value: Balance,
3369					weight_limit: Option<$crate::Weight>,
3370					storage_deposit_limit: Option<Balance>,
3371					input_data: Vec<u8>,
3372				) -> $crate::ContractResult<$crate::ExecReturnValue, Balance> {
3373					use $crate::frame_support::traits::Get;
3374					let blockweights: $crate::BlockWeights =
3375						<Self as $crate::frame_system::Config>::BlockWeights::get();
3376
3377					$crate::Pallet::<Self>::prepare_dry_run(&origin);
3378					$crate::Pallet::<Self>::bare_call(
3379						<Self as $crate::frame_system::Config>::RuntimeOrigin::signed(origin),
3380						dest,
3381						$crate::Pallet::<Self>::convert_native_to_evm(value),
3382						$crate::TransactionLimits::WeightAndDeposit {
3383							weight_limit: weight_limit.unwrap_or(blockweights.max_block),
3384							deposit_limit: storage_deposit_limit.unwrap_or(u128::MAX),
3385						},
3386						input_data,
3387						&$crate::ExecConfig::new_substrate_tx().with_dry_run(Default::default()),
3388					)
3389				}
3390
3391				fn instantiate(
3392					origin: AccountId,
3393					value: Balance,
3394					weight_limit: Option<$crate::Weight>,
3395					storage_deposit_limit: Option<Balance>,
3396					code: $crate::Code,
3397					data: Vec<u8>,
3398					salt: Option<[u8; 32]>,
3399				) -> $crate::ContractResult<$crate::InstantiateReturnValue, Balance> {
3400					use $crate::frame_support::traits::Get;
3401					let blockweights: $crate::BlockWeights =
3402						<Self as $crate::frame_system::Config>::BlockWeights::get();
3403
3404					$crate::Pallet::<Self>::prepare_dry_run(&origin);
3405					$crate::Pallet::<Self>::bare_instantiate(
3406						<Self as $crate::frame_system::Config>::RuntimeOrigin::signed(origin),
3407						$crate::Pallet::<Self>::convert_native_to_evm(value),
3408						$crate::TransactionLimits::WeightAndDeposit {
3409							weight_limit: weight_limit.unwrap_or(blockweights.max_block),
3410							deposit_limit: storage_deposit_limit.unwrap_or(u128::MAX),
3411						},
3412						code,
3413						data,
3414						salt,
3415						&$crate::ExecConfig::new_substrate_tx().with_dry_run(Default::default()),
3416					)
3417				}
3418
3419				fn upload_code(
3420					origin: AccountId,
3421					code: Vec<u8>,
3422					storage_deposit_limit: Option<Balance>,
3423				) -> Result<$crate::pallet_revive_types::runtime_api::CodeUploadReturnValueV1<Balance>, $crate::sp_runtime::DispatchError> {
3424					use $crate::pallet_revive_types::runtime_api::*;
3425
3426					let input = UploadCodeVersionedInputPayload::from(UploadCodeInputPayloadV1 {
3427						origin,
3428						code,
3429						storage_deposit_limit
3430					});
3431					let output = Self::upload_code_versioned(input)?;
3432					Ok(UploadCodeOutputPayloadV1::try_from(output)
3433						.expect("v1 input must produce v1 output; qed")
3434						.code_upload_return_value)
3435				}
3436
3437				fn get_storage_var_key(
3438					address: $crate::H160,
3439					key: Vec<u8>,
3440				) -> $crate::GetStorageResult {
3441					use $crate::pallet_revive_types::runtime_api::*;
3442
3443					let input = GetStorageVersionedInputPayload::from(GetStorageInputPayloadV1 {
3444						address,
3445						key: StorageKeyV1::Variable(key)
3446					});
3447					let output = Self::get_storage_versioned(input)?;
3448					Ok(GetStorageOutputPayloadV1::try_from(output)
3449						.expect("v1 input must produce v1 output; qed")
3450						.storage)
3451				}
3452
3453				fn get_storage(address: $crate::H160, key: [u8; 32]) -> $crate::GetStorageResult {
3454					use $crate::pallet_revive_types::runtime_api::*;
3455
3456					let input = GetStorageVersionedInputPayload::from(GetStorageInputPayloadV1 {
3457						address,
3458						key: StorageKeyV1::Fixed(key)
3459					});
3460					let output = Self::get_storage_versioned(input)?;
3461					Ok(GetStorageOutputPayloadV1::try_from(output)
3462						.expect("v1 input must produce v1 output; qed")
3463						.storage)
3464				}
3465
3466				fn trace_block(
3467					block: Block,
3468					tracer_type: $crate::pallet_revive_types::runtime_api::TracerTypeV1,
3469				) -> Vec<(u32, $crate::pallet_revive_types::runtime_api::TraceV1)> {
3470					use $crate::pallet_revive_types::runtime_api::*;
3471
3472					let input = TraceBlockVersionedInputPayload::from(TraceBlockInputPayloadV1 {
3473						block,
3474						config: tracer_type
3475					});
3476					let output = Self::trace_block_versioned(input);
3477					TraceBlockOutputPayloadV1::try_from(output)
3478						.expect("v1 input must produce v1 output; qed")
3479						.traces
3480				}
3481
3482				fn trace_tx(
3483					block: Block,
3484					tx_index: u32,
3485					tracer_type: $crate::pallet_revive_types::runtime_api::TracerTypeV1,
3486				) -> Option<$crate::pallet_revive_types::runtime_api::TraceV1> {
3487					use $crate::pallet_revive_types::runtime_api::*;
3488
3489					let input = TraceTxVersionedInputPayload::from(TraceTxInputPayloadV1 {
3490						block,
3491						tx_index,
3492						config: tracer_type
3493					});
3494					let output = Self::trace_tx_versioned(input);
3495					TraceTxOutputPayloadV1::try_from(output)
3496						.expect("v1 input must produce v1 output; qed")
3497						.trace
3498				}
3499
3500				fn trace_call(
3501					tx: $crate::evm::GenericTransaction,
3502					tracer_type: $crate::pallet_revive_types::runtime_api::TracerTypeV1,
3503				) -> Result<$crate::pallet_revive_types::runtime_api::TraceV1, $crate::EthTransactError> {
3504					use $crate::tracing::trace;
3505
3506					let tracer_type = $crate::evm::TracerType::from(tracer_type);
3507					if matches!(tracer_type, $crate::evm::TracerType::ExecutionTracer(_)) &&
3508						!$crate::DebugSettings::is_execution_tracing_enabled::<Runtime>()
3509					{
3510						return Err($crate::EthTransactError::Message("Execution Tracing is disabled".into()))
3511					}
3512
3513					let mut tracer = $crate::Pallet::<Self>::evm_tracer(tracer_type.clone());
3514					let t = tracer.as_tracing();
3515
3516					t.watch_address(&tx.from.unwrap_or_default());
3517					t.watch_address(&$crate::Pallet::<Self>::block_author());
3518					let result = trace(t, || Self::eth_transact(tx));
3519
3520					if let Some(trace) = tracer.collect_trace() {
3521						Ok(trace)
3522					} else if let Err(err) = result {
3523						Err(err)
3524					} else {
3525						Ok($crate::Pallet::<Self>::evm_tracer(tracer_type).empty_trace())
3526					}
3527					.map(Into::into)
3528				}
3529
3530				fn trace_call_with_config(
3531					tx: $crate::evm::GenericTransaction,
3532					tracer_type: $crate::pallet_revive_types::runtime_api::TracerTypeV1,
3533					config: $crate::evm::TracingConfig,
3534				) -> Result<$crate::pallet_revive_types::runtime_api::TraceV1, $crate::EthTransactError> {
3535					let $crate::evm::TracingConfig { state_overrides } = config;
3536
3537					if let Some(overrides) = state_overrides {
3538						$crate::state_overrides::apply_state_overrides::<Runtime>(overrides)?;
3539					}
3540
3541					Self::trace_call(tx, tracer_type)
3542				}
3543
3544				fn runtime_pallets_address() -> $crate::H160 {
3545					use $crate::pallet_revive_types::runtime_api::*;
3546
3547					let input = RuntimePalletsAddressVersionedInputPayload::from(
3548						RuntimePalletsAddressInputPayloadV1
3549					);
3550					let output = Self::runtime_pallets_address_versioned(input);
3551					RuntimePalletsAddressOutputPayloadV1::try_from(output)
3552						.expect("v1 input must produce v1 output; qed")
3553						.runtime_pallets_address
3554				}
3555
3556				fn code(address: $crate::H160) -> Vec<u8> {
3557					use $crate::pallet_revive_types::runtime_api::*;
3558
3559					let input = CodeVersionedInputPayload::from(CodeInputPayloadV1 { address });
3560					let output = Self::code_versioned(input);
3561					CodeOutputPayloadV1::try_from(output)
3562						.expect("v1 input must produce v1 output; qed")
3563						.code
3564				}
3565
3566				fn account_id(address: $crate::H160) -> AccountId {
3567					use $crate::pallet_revive_types::runtime_api::*;
3568
3569					let input = AccountIdVersionedInputPayload::from(AccountIdInputPayloadV1 { address });
3570					let output = Self::account_id_versioned(input);
3571					AccountIdOutputPayloadV1::try_from(output)
3572						.expect("v1 input must produce v1 output; qed")
3573						.account_id
3574				}
3575
3576				fn new_balance_with_dust(balance: $crate::U256) -> Result<(Balance, u32), $crate::BalanceConversionError> {
3577					use $crate::pallet_revive_types::runtime_api::*;
3578
3579					let input = NewBalanceWithDustVersionedInputPayload::from(
3580						NewBalanceWithDustInputPayloadV1 { balance }
3581					);
3582					let output = Self::new_balance_with_dust_versioned(input)?;
3583					let output = NewBalanceWithDustOutputPayloadV1::try_from(output)
3584						.expect("v1 input must produce v1 output; qed");
3585					Ok((output.new_balance, output.dust))
3586				}
3587
3588				/* Versioned Runtime APIs */
3589
3590				fn version_declarations()
3591					-> $crate::pallet_revive_types::runtime_api::ReviveRuntimeApiVersionDeclarations
3592				{
3593					use $crate::pallet_revive_types::runtime_api::*;
3594
3595					ReviveRuntimeApiVersionDeclarations::new()
3596						.insert("eth_block_hash_versioned", 1)
3597						.insert("eth_receipt_data_versioned", 1)
3598						.insert("block_gas_limit_versioned", 1)
3599						.insert("max_extrinsic_weight_in_gas_versioned", 1)
3600						.insert("balance_versioned", 1)
3601						.insert("gas_price_versioned", 1)
3602						.insert("nonce_versioned", 1)
3603						.insert("eth_pre_dispatch_weight_versioned", 1)
3604						.insert("upload_code_versioned", 1)
3605						.insert("get_storage_versioned", 1)
3606						.insert("runtime_pallets_address_versioned", 1)
3607						.insert("code_versioned", 1)
3608						.insert("account_id_versioned", 1)
3609						.insert("new_balance_with_dust_versioned", 1)
3610						.insert("block_author_versioned", 1)
3611						.insert("address_versioned", 1)
3612						.insert("trace_block_versioned", 2)
3613						.insert("trace_tx_versioned", 2)
3614				}
3615
3616				fn eth_block_hash_versioned(
3617					input: $crate::pallet_revive_types::runtime_api::BlockHashVersionedInputPayload
3618				) -> $crate::pallet_revive_types::runtime_api::BlockHashVersionedOutputPayload {
3619					use $crate::pallet_revive_types::runtime_api::*;
3620					use $crate::runtime_api::*;
3621					use alloc::boxed::Box;
3622
3623					let (input, output_wrapper): (
3624						_,
3625						Box<dyn Fn(BlockHashOutputPayload) -> BlockHashVersionedOutputPayload>,
3626					) = match input {
3627						BlockHashVersionedInputPayload::V1(payload) => (
3628							BlockHashInputPayload::from(payload),
3629							Box::new(|output| BlockHashVersionedOutputPayload::V1(output.into())),
3630						),
3631					};
3632
3633					let output = BlockHashOutputPayload {
3634						block_hash: $crate::Pallet::<Self>::eth_block_hash_from_number(input.block_number)
3635					};
3636					output_wrapper(output)
3637				}
3638
3639				fn eth_receipt_data_versioned(
3640					input: $crate::pallet_revive_types::runtime_api::ReceiptDataVersionedInputPayload
3641				) -> $crate::pallet_revive_types::runtime_api::ReceiptDataVersionedOutputPayload {
3642					use $crate::pallet_revive_types::runtime_api::*;
3643					use $crate::runtime_api::*;
3644					use alloc::boxed::Box;
3645
3646					let (_input, output_wrapper): (
3647						_,
3648						Box<dyn Fn(ReceiptDataOutputPayload) -> ReceiptDataVersionedOutputPayload>,
3649					) = match input {
3650						ReceiptDataVersionedInputPayload::V1(payload) => (
3651							ReceiptDataInputPayload::from(payload),
3652							Box::new(|output| ReceiptDataVersionedOutputPayload::V1(output.into())),
3653						),
3654					};
3655
3656					let output = ReceiptDataOutputPayload {
3657						receipt_data: $crate::Pallet::<Self>::eth_receipt_data()
3658					};
3659					output_wrapper(output)
3660				}
3661
3662				fn block_gas_limit_versioned(
3663					input: $crate::pallet_revive_types::runtime_api::BlockGasLimitVersionedInputPayload
3664				) -> $crate::pallet_revive_types::runtime_api::BlockGasLimitVersionedOutputPayload {
3665					use $crate::pallet_revive_types::runtime_api::*;
3666					use $crate::runtime_api::*;
3667					use alloc::boxed::Box;
3668
3669					let (_input, output_wrapper): (
3670						_,
3671						Box<dyn Fn(BlockGasLimitOutputPayload) -> BlockGasLimitVersionedOutputPayload>,
3672					) = match input {
3673						BlockGasLimitVersionedInputPayload::V1(payload) => (
3674							BlockGasLimitInputPayload::from(payload),
3675							Box::new(|output| BlockGasLimitVersionedOutputPayload::V1(output.into())),
3676						),
3677					};
3678
3679					let output = BlockGasLimitOutputPayload {
3680						block_gas_limit: $crate::Pallet::<Self>::evm_block_gas_limit()
3681					};
3682					output_wrapper(output)
3683				}
3684
3685				fn max_extrinsic_weight_in_gas_versioned(
3686					input: $crate::pallet_revive_types::runtime_api::MaxExtrinsicWeightInGasVersionedInputPayload
3687				) -> $crate::pallet_revive_types::runtime_api::MaxExtrinsicWeightInGasVersionedOutputPayload {
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(MaxExtrinsicWeightInGasOutputPayload) -> MaxExtrinsicWeightInGasVersionedOutputPayload>,
3695					) = match input {
3696						MaxExtrinsicWeightInGasVersionedInputPayload::V1(payload) => (
3697							MaxExtrinsicWeightInGasInputPayload::from(payload),
3698							Box::new(|output| MaxExtrinsicWeightInGasVersionedOutputPayload::V1(output.into())),
3699						),
3700					};
3701
3702					let output = MaxExtrinsicWeightInGasOutputPayload {
3703						max_extrinsic_weight_in_gas: $crate::Pallet::<Self>::evm_max_extrinsic_weight_in_gas()
3704					};
3705					output_wrapper(output)
3706				}
3707
3708				fn balance_versioned(
3709					input: $crate::pallet_revive_types::runtime_api::BalanceVersionedInputPayload
3710				) -> $crate::pallet_revive_types::runtime_api::BalanceVersionedOutputPayload {
3711					use $crate::pallet_revive_types::runtime_api::*;
3712					use $crate::runtime_api::*;
3713					use alloc::boxed::Box;
3714
3715					let (input, output_wrapper): (
3716						_,
3717						Box<dyn Fn(BalanceOutputPayload) -> BalanceVersionedOutputPayload>,
3718					) = match input {
3719						BalanceVersionedInputPayload::V1(payload) => (
3720							BalanceInputPayload::from(payload),
3721							Box::new(|output| BalanceVersionedOutputPayload::V1(output.into())),
3722						),
3723					};
3724
3725					let output = BalanceOutputPayload {
3726						balance: $crate::Pallet::<Self>::evm_balance(&input.address)
3727					};
3728					output_wrapper(output)
3729				}
3730
3731				fn gas_price_versioned(
3732					input: $crate::pallet_revive_types::runtime_api::GasPriceVersionedInputPayload
3733				) -> $crate::pallet_revive_types::runtime_api::GasPriceVersionedOutputPayload {
3734					use $crate::pallet_revive_types::runtime_api::*;
3735					use $crate::runtime_api::*;
3736					use alloc::boxed::Box;
3737
3738					let (_input, output_wrapper): (
3739						_,
3740						Box<dyn Fn(GasPriceOutputPayload) -> GasPriceVersionedOutputPayload>,
3741					) = match input {
3742						GasPriceVersionedInputPayload::V1(payload) => (
3743							GasPriceInputPayload::from(payload),
3744							Box::new(|output| GasPriceVersionedOutputPayload::V1(output.into())),
3745						),
3746					};
3747
3748					let output = GasPriceOutputPayload {
3749						gas_price: $crate::Pallet::<Self>::evm_base_fee()
3750					};
3751					output_wrapper(output)
3752				}
3753
3754				fn nonce_versioned(
3755					input: $crate::pallet_revive_types::runtime_api::NonceVersionedInputPayload
3756				) -> $crate::pallet_revive_types::runtime_api::NonceVersionedOutputPayload<Nonce> {
3757					use $crate::pallet_revive_types::runtime_api::*;
3758					use $crate::runtime_api::*;
3759					use $crate::AddressMapper;
3760					use alloc::boxed::Box;
3761
3762					let (input, output_wrapper): (
3763						_,
3764						Box<dyn Fn(NonceOutputPayload<Nonce>) -> NonceVersionedOutputPayload<Nonce>>,
3765					) = match input {
3766						NonceVersionedInputPayload::V1(payload) => (
3767							NonceInputPayload::from(payload),
3768							Box::new(|output| NonceVersionedOutputPayload::V1(output.into())),
3769						),
3770					};
3771
3772					let account = <Self as $crate::Config>::AddressMapper::to_account_id(&input.address);
3773					let output = NonceOutputPayload {
3774						nonce: $crate::frame_system::Pallet::<Self>::account_nonce(account)
3775					};
3776					output_wrapper(output)
3777				}
3778
3779				fn eth_pre_dispatch_weight_versioned(
3780					input: $crate::pallet_revive_types::runtime_api::PreDispatchWeightVersionedInputPayload
3781				) -> Result<
3782					$crate::pallet_revive_types::runtime_api::PreDispatchWeightVersionedOutputPayload,
3783					$crate::EthTransactError
3784				> {
3785					use $crate::pallet_revive_types::runtime_api::*;
3786					use $crate::runtime_api::*;
3787					use alloc::boxed::Box;
3788
3789					let (input, output_wrapper): (
3790						_,
3791						Box<dyn Fn(PreDispatchWeightOutputPayload) -> PreDispatchWeightVersionedOutputPayload>,
3792					) = match input {
3793						PreDispatchWeightVersionedInputPayload::V1(payload) => (
3794							PreDispatchWeightInputPayload::from(payload),
3795							Box::new(|output| PreDispatchWeightVersionedOutputPayload::V1(output.into())),
3796						),
3797					};
3798
3799					let output = PreDispatchWeightOutputPayload {
3800						weight: $crate::Pallet::<Self>::eth_pre_dispatch_weight(input.tx)?
3801					};
3802					Ok(output_wrapper(output))
3803				}
3804
3805				fn upload_code_versioned(
3806					input: $crate::pallet_revive_types::runtime_api::UploadCodeVersionedInputPayload<AccountId, Balance>
3807				) -> Result<
3808					$crate::pallet_revive_types::runtime_api::UploadCodeVersionedOutputPayload<Balance>,
3809					$crate::sp_runtime::DispatchError
3810				> {
3811					use $crate::pallet_revive_types::runtime_api::*;
3812					use $crate::runtime_api::*;
3813					use alloc::boxed::Box;
3814
3815					let (input, output_wrapper): (
3816						_,
3817						Box<dyn Fn(UploadCodeOutputPayload<Balance>) -> UploadCodeVersionedOutputPayload<Balance>>,
3818					) = match input {
3819						UploadCodeVersionedInputPayload::V1(payload) => (
3820							UploadCodeInputPayload::from(payload),
3821							Box::new(|output| UploadCodeVersionedOutputPayload::V1(output.into())),
3822						),
3823					};
3824
3825					let origin =
3826						<Self as $crate::frame_system::Config>::RuntimeOrigin::signed(input.origin);
3827					let code_upload_return_value = $crate::Pallet::<Self>::bare_upload_code(
3828						origin,
3829						input.code,
3830						input.storage_deposit_limit.unwrap_or(u128::MAX),
3831					)?;
3832					let output = UploadCodeOutputPayload { code_upload_return_value };
3833					Ok(output_wrapper(output))
3834				}
3835
3836				fn get_storage_versioned(
3837					input: $crate::pallet_revive_types::runtime_api::GetStorageVersionedInputPayload
3838				) -> Result<
3839					$crate::pallet_revive_types::runtime_api::GetStorageVersionedOutputPayload,
3840					$crate::ContractAccessError
3841				> {
3842					use $crate::pallet_revive_types::runtime_api::*;
3843					use $crate::runtime_api::*;
3844					use alloc::boxed::Box;
3845
3846					let (input, output_wrapper): (
3847						_,
3848						Box<dyn Fn(GetStorageOutputPayload) -> GetStorageVersionedOutputPayload>,
3849					) = match input {
3850						GetStorageVersionedInputPayload::V1(payload) => (
3851							GetStorageInputPayload::from(payload),
3852							Box::new(|output| GetStorageVersionedOutputPayload::V1(output.into())),
3853						),
3854					};
3855
3856					let storage = match input.key {
3857						StorageKey::Fixed(key) => $crate::Pallet::<Self>::get_storage(input.address, key)?,
3858						StorageKey::Variable(key) => $crate::Pallet::<Self>::get_storage_var_key(input.address, key)?,
3859					};
3860					let output = GetStorageOutputPayload { storage };
3861					Ok(output_wrapper(output))
3862				}
3863
3864				fn runtime_pallets_address_versioned(
3865					input: $crate::pallet_revive_types::runtime_api::RuntimePalletsAddressVersionedInputPayload
3866				) -> $crate::pallet_revive_types::runtime_api::RuntimePalletsAddressVersionedOutputPayload {
3867					use $crate::pallet_revive_types::runtime_api::*;
3868					use $crate::runtime_api::*;
3869					use alloc::boxed::Box;
3870
3871					let (_input, output_wrapper): (
3872						_,
3873						Box<dyn Fn(RuntimePalletsAddressOutputPayload) -> RuntimePalletsAddressVersionedOutputPayload>,
3874					) = match input {
3875						RuntimePalletsAddressVersionedInputPayload::V1(payload) => (
3876							RuntimePalletsAddressInputPayload::from(payload),
3877							Box::new(|output| RuntimePalletsAddressVersionedOutputPayload::V1(output.into())),
3878						),
3879					};
3880
3881					let output = RuntimePalletsAddressOutputPayload {
3882						runtime_pallets_address: $crate::RUNTIME_PALLETS_ADDR
3883					};
3884					output_wrapper(output)
3885				}
3886
3887				fn code_versioned(
3888					input: $crate::pallet_revive_types::runtime_api::CodeVersionedInputPayload
3889				) -> $crate::pallet_revive_types::runtime_api::CodeVersionedOutputPayload {
3890					use $crate::pallet_revive_types::runtime_api::*;
3891					use $crate::runtime_api::*;
3892					use alloc::boxed::Box;
3893
3894					let (input, output_wrapper): (
3895						_,
3896						Box<dyn Fn(CodeOutputPayload) -> CodeVersionedOutputPayload>,
3897					) = match input {
3898						CodeVersionedInputPayload::V1(payload) => (
3899							CodeInputPayload::from(payload),
3900							Box::new(|output| CodeVersionedOutputPayload::V1(output.into())),
3901						),
3902					};
3903
3904					let output = CodeOutputPayload {
3905						code: $crate::Pallet::<Self>::code(&input.address)
3906					};
3907					output_wrapper(output)
3908				}
3909
3910				fn account_id_versioned(
3911					input: $crate::pallet_revive_types::runtime_api::AccountIdVersionedInputPayload
3912				) -> $crate::pallet_revive_types::runtime_api::AccountIdVersionedOutputPayload<AccountId> {
3913					use $crate::pallet_revive_types::runtime_api::*;
3914					use $crate::runtime_api::*;
3915					use $crate::AddressMapper;
3916					use alloc::boxed::Box;
3917
3918					let (input, output_wrapper): (
3919						_,
3920						Box<dyn Fn(AccountIdOutputPayload<AccountId>) -> AccountIdVersionedOutputPayload<AccountId>>,
3921					) = match input {
3922						AccountIdVersionedInputPayload::V1(payload) => (
3923							AccountIdInputPayload::from(payload),
3924							Box::new(|output| AccountIdVersionedOutputPayload::V1(output.into())),
3925						),
3926					};
3927
3928					let output = AccountIdOutputPayload {
3929						account_id: <Self as $crate::Config>::AddressMapper::to_account_id(&input.address)
3930					};
3931					output_wrapper(output)
3932				}
3933
3934				fn new_balance_with_dust_versioned(
3935					input: $crate::pallet_revive_types::runtime_api::NewBalanceWithDustVersionedInputPayload
3936				) -> Result<
3937					$crate::pallet_revive_types::runtime_api::NewBalanceWithDustVersionedOutputPayload<Balance>,
3938					$crate::BalanceConversionError
3939				> {
3940					use $crate::pallet_revive_types::runtime_api::*;
3941					use $crate::runtime_api::*;
3942					use alloc::boxed::Box;
3943
3944					let (input, output_wrapper): (
3945						_,
3946						Box<
3947							dyn Fn(NewBalanceWithDustOutputPayload<Balance>) -> NewBalanceWithDustVersionedOutputPayload<Balance>,
3948						>,
3949					) = match input {
3950						NewBalanceWithDustVersionedInputPayload::V1(payload) => (
3951							NewBalanceWithDustInputPayload::from(payload),
3952							Box::new(|output| NewBalanceWithDustVersionedOutputPayload::V1(output.into())),
3953						),
3954					};
3955
3956					let (new_balance, dust) = $crate::Pallet::<Self>::new_balance_with_dust(input.balance)?;
3957					let output = NewBalanceWithDustOutputPayload { new_balance, dust };
3958					Ok(output_wrapper(output))
3959				}
3960
3961				fn block_author_versioned(
3962					input: $crate::pallet_revive_types::runtime_api::BlockAuthorVersionedInputPayload
3963				) -> $crate::pallet_revive_types::runtime_api::BlockAuthorVersionedOutputPayload {
3964					use $crate::pallet_revive_types::runtime_api::*;
3965					use $crate::runtime_api::*;
3966					use alloc::boxed::Box;
3967
3968					let (_input, output_wrapper): (
3969						_,
3970						Box<dyn Fn(BlockAuthorOutputPayload) -> BlockAuthorVersionedOutputPayload>,
3971					) = match input {
3972						BlockAuthorVersionedInputPayload::V1(payload) => (
3973							BlockAuthorInputPayload::from(payload),
3974							Box::new(|output| BlockAuthorVersionedOutputPayload::V1(output.into())),
3975						),
3976					};
3977
3978					let output = BlockAuthorOutputPayload {
3979						block_author: $crate::Pallet::<Self>::block_author()
3980					};
3981					output_wrapper(output)
3982				}
3983
3984				fn address_versioned(
3985					input: $crate::pallet_revive_types::runtime_api::AddressVersionedInputPayload<AccountId>
3986				) -> $crate::pallet_revive_types::runtime_api::AddressVersionedOutputPayload {
3987					use $crate::pallet_revive_types::runtime_api::*;
3988					use $crate::runtime_api::*;
3989					use $crate::AddressMapper;
3990					use alloc::boxed::Box;
3991
3992					let (input, output_wrapper): (
3993						_,
3994						Box<dyn Fn(AddressOutputPayload) -> AddressVersionedOutputPayload>,
3995					) = match input {
3996						AddressVersionedInputPayload::V1(payload) => (
3997							AddressInputPayload::from(payload),
3998							Box::new(|output| AddressVersionedOutputPayload::V1(output.into())),
3999						),
4000					};
4001
4002					let output = AddressOutputPayload {
4003						address: <Self as $crate::Config>::AddressMapper::to_address(&input.account_id)
4004					};
4005					output_wrapper(output)
4006				}
4007
4008				fn trace_block_versioned(
4009					input: $crate::pallet_revive_types::runtime_api::TraceBlockVersionedInputPayload<Block>
4010				) -> $crate::pallet_revive_types::runtime_api::TraceBlockVersionedOutputPayload {
4011					use $crate::{
4012						sp_runtime::traits::Block,
4013						tracing::trace,
4014						runtime_api::*,
4015						pallet_revive_types::runtime_api::*
4016					};
4017					use alloc::boxed::Box;
4018
4019					let (input, output_wrapper): (_, Box<dyn Fn(TraceBlockOutputPayload) -> TraceBlockVersionedOutputPayload>) = match input {
4020						TraceBlockVersionedInputPayload::V1(payload) => (
4021							TraceBlockInputPayload::from(payload),
4022							Box::new(|output| TraceBlockVersionedOutputPayload::V1(output.into()))
4023						),
4024						TraceBlockVersionedInputPayload::V2(payload) => (
4025							TraceBlockInputPayload::from(payload),
4026							Box::new(|output| TraceBlockVersionedOutputPayload::V2(output.into()))
4027						),
4028					};
4029
4030					if matches!(input.config, $crate::evm::TracerType::ExecutionTracer(_)) &&
4031						!$crate::DebugSettings::is_execution_tracing_enabled::<Runtime>()
4032					{
4033						return output_wrapper(Default::default())
4034					}
4035
4036					let mut traces = vec![];
4037					let (header, extrinsics) = input.block.deconstruct();
4038					<$Executive>::initialize_block(&header);
4039					for (index, ext) in extrinsics.into_iter().enumerate() {
4040						let mut tracer = $crate::Pallet::<Self>::evm_tracer(input.config.clone());
4041						let t = tracer.as_tracing();
4042						let _ = trace(t, || <$Executive>::apply_extrinsic(ext));
4043
4044						if let Some(tx_trace) = tracer.collect_trace() {
4045							traces.push((index as u32, tx_trace));
4046						}
4047					}
4048
4049					let output = TraceBlockOutputPayload { traces };
4050					output_wrapper(output)
4051				}
4052
4053				fn trace_tx_versioned(
4054					input: $crate::pallet_revive_types::runtime_api::TraceTxVersionedInputPayload<Block>
4055				) -> $crate::pallet_revive_types::runtime_api::TraceTxVersionedOutputPayload {
4056					use $crate::pallet_revive_types::runtime_api::*;
4057					use $crate::runtime_api::*;
4058					use $crate::{sp_runtime::traits::Block, tracing::trace};
4059					use alloc::boxed::Box;
4060
4061					let (input, output_wrapper): (
4062						_,
4063						Box<dyn Fn(TraceTxOutputPayload) -> TraceTxVersionedOutputPayload>,
4064					) = match input {
4065						TraceTxVersionedInputPayload::V1(payload) => (
4066							TraceTxInputPayload::from(payload),
4067							Box::new(|output| TraceTxVersionedOutputPayload::V1(output.into())),
4068						),
4069						TraceTxVersionedInputPayload::V2(payload) => (
4070							TraceTxInputPayload::from(payload),
4071							Box::new(|output| TraceTxVersionedOutputPayload::V2(output.into())),
4072						),
4073					};
4074
4075					if matches!(&input.config, $crate::evm::TracerType::ExecutionTracer(_)) &&
4076						!$crate::DebugSettings::is_execution_tracing_enabled::<Runtime>()
4077					{
4078						return output_wrapper(TraceTxOutputPayload { trace: None })
4079					}
4080
4081					let mut tracer = $crate::Pallet::<Self>::evm_tracer(input.config);
4082					let (header, extrinsics) = input.block.deconstruct();
4083
4084					<$Executive>::initialize_block(&header);
4085					for (index, ext) in extrinsics.into_iter().enumerate() {
4086						if index as u32 == input.tx_index {
4087							let t = tracer.as_tracing();
4088							let _ = trace(t, || <$Executive>::apply_extrinsic(ext));
4089							break;
4090						} else {
4091							let _ = <$Executive>::apply_extrinsic(ext);
4092						}
4093					}
4094
4095					let output = TraceTxOutputPayload {
4096						trace: tracer.collect_trace()
4097					};
4098					output_wrapper(output)
4099				}
4100			}
4101		}
4102	};
4103}