referrerpolicy=no-referrer-when-downgrade

pallet_revive/
lib.rs

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