Skip to main content

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