referrerpolicy=no-referrer-when-downgrade

pallet_revive/
exec.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
18use crate::{
19	AccountInfo, AccountInfoOf, BalanceOf, BalanceWithDust, Code, CodeInfo, CodeInfoOf,
20	CodeRemoved, Config, ContractInfo, Error, Event, ImmutableData, ImmutableDataOf, LOG_TARGET,
21	Pallet as Contracts, RuntimeCosts, TrieId,
22	access_list::{AccessEntry, AccessList, StorageOp, Warmth},
23	address::{self, AddressMapper},
24	deposit_payment::Deposit as _,
25	evm::{block_storage, fees::InfoT as _, transfer_with_dust},
26	limits,
27	metering::{ChargedAmount, Diff, FrameMeter, ResourceMeter, State, Token, TransactionMeter},
28	precompiles::{All as AllPrecompiles, Instance as PrecompileInstance, Precompiles},
29	primitives::{ExecConfig, ExecReturnValue, StorageDeposit},
30	runtime_decl_for_revive_api::{Decode, Encode, TypeInfo},
31	storage::{AccountIdOrAddress, WriteOutcome},
32	tracing::if_tracing,
33	transient_storage::TransientStorage,
34};
35use alloc::{
36	collections::{BTreeMap, BTreeSet},
37	vec::Vec,
38};
39use core::{cmp, fmt::Debug, marker::PhantomData, mem, ops::ControlFlow};
40use frame_support::{
41	Blake2_128Concat, BoundedVec, DebugNoBound, StorageHasher,
42	crypto::ecdsa::ECDSAExt,
43	dispatch::DispatchResult,
44	ensure,
45	storage::{TransactionOutcome, with_transaction},
46	traits::{
47		Time,
48		fungible::{Balanced as _, Inspect, Mutate},
49		tokens::Preservation,
50	},
51	weights::Weight,
52};
53use frame_system::{
54	Pallet as System, RawOrigin,
55	pallet_prelude::{BlockNumberFor, OriginFor},
56};
57use sp_core::{
58	ConstU32, Get, H160, H256, U256,
59	ecdsa::Public as ECDSAPublic,
60	sr25519::{Public as SR25519Public, Signature as SR25519Signature},
61};
62use sp_io::{crypto::secp256k1_ecdsa_recover_compressed, hashing::blake2_256};
63use sp_runtime::{
64	DispatchError, SaturatedConversion,
65	traits::{BadOrigin, Saturating, TrailingZeroInput, Zero},
66};
67
68#[cfg(test)]
69mod tests;
70
71#[cfg(test)]
72pub mod mock_ext;
73
74pub type AccountIdOf<T> = <T as frame_system::Config>::AccountId;
75pub type MomentOf<T> = <<T as Config>::Time as Time>::Moment;
76pub type ExecResult = Result<ExecReturnValue, ExecError>;
77
78/// Type for variable sized storage key. Used for transparent hashing.
79type VarSizedKey = BoundedVec<u8, ConstU32<{ limits::STORAGE_KEY_BYTES }>>;
80
81const FRAME_ALWAYS_EXISTS_ON_INSTANTIATE: &str = "The return value is only `None` if no contract exists at the specified address. This cannot happen on instantiate or delegate; qed";
82
83/// Code hash of existing account without code (keccak256 hash of empty data).
84pub const EMPTY_CODE_HASH: H256 =
85	H256(sp_core::hex2array!("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470"));
86
87/// Combined key type for both fixed and variable sized storage keys.
88#[derive(Debug)]
89pub enum Key {
90	/// Variant for fixed sized keys.
91	Fix([u8; 32]),
92	/// Variant for variable sized keys.
93	Var(VarSizedKey),
94}
95
96impl Key {
97	/// Reference to the raw unhashed key.
98	pub fn unhashed(&self) -> &[u8] {
99		match self {
100			Key::Fix(v) => v.as_ref(),
101			Key::Var(v) => v.as_ref(),
102		}
103	}
104
105	/// The hashed key that has be used as actual key to the storage trie.
106	pub fn hash(&self) -> Vec<u8> {
107		match self {
108			Key::Fix(v) => blake2_256(v.as_slice()).to_vec(),
109			Key::Var(v) => Blake2_128Concat::hash(v.as_slice()),
110		}
111	}
112
113	pub fn from_fixed(v: [u8; 32]) -> Self {
114		Self::Fix(v)
115	}
116
117	pub fn try_from_var(v: Vec<u8>) -> Result<Self, ()> {
118		VarSizedKey::try_from(v).map(Self::Var).map_err(|_| ())
119	}
120}
121
122/// Level of reentrancy protection.
123///
124/// This needs to be specifed when a contract makes a message call. This way the calling contract
125/// can specify the level of re-entrancy protection while the callee (and it's recursive callees) is
126/// executing.
127#[derive(Copy, Clone, PartialEq, Debug)]
128pub enum ReentrancyProtection {
129	/// Don't activate reentrancy protection
130	AllowReentry,
131	/// Activate strict reentrancy protection. The direct callee and none of its own recursive
132	/// callees must be the calling contract.
133	Strict,
134	/// Activate reentrancy protection where the direct callee can be the same contract as the
135	/// caller but none of the recursive callees of the callee must be the caller.
136	///
137	/// This is used for calls that transfer value but restrict gas so that the callee only has a
138	/// stipend gas amount. In Ethereum that is not sufficient for the callee to make another call.
139	/// However, due to gas scale differences that guarantee does not automatically hold in revive
140	/// and we enforce it explicitly here.
141	AllowNext,
142}
143
144/// Origin of the error.
145///
146/// Call or instantiate both called into other contracts and pass through errors happening
147/// in those to the caller. This enum is for the caller to distinguish whether the error
148/// happened during the execution of the callee or in the current execution context.
149#[derive(Copy, Clone, PartialEq, Eq, Debug, codec::Decode, codec::Encode)]
150pub enum ErrorOrigin {
151	/// Caller error origin.
152	///
153	/// The error happened in the current execution context rather than in the one
154	/// of the contract that is called into.
155	Caller,
156	/// The error happened during execution of the called contract.
157	Callee,
158}
159
160/// Error returned by contract execution.
161#[derive(Copy, Clone, PartialEq, Eq, Debug, codec::Decode, codec::Encode)]
162pub struct ExecError {
163	/// The reason why the execution failed.
164	pub error: DispatchError,
165	/// Origin of the error.
166	pub origin: ErrorOrigin,
167}
168
169impl<T: Into<DispatchError>> From<T> for ExecError {
170	fn from(error: T) -> Self {
171		Self { error: error.into(), origin: ErrorOrigin::Caller }
172	}
173}
174
175/// The type of origins supported by the revive pallet.
176#[derive(Clone, Encode, Decode, PartialEq, TypeInfo, DebugNoBound)]
177pub enum Origin<T: Config> {
178	Root,
179	Signed(T::AccountId),
180}
181
182impl<T: Config> Origin<T> {
183	/// Creates a new Signed Caller from an AccountId.
184	pub fn from_account_id(account_id: T::AccountId) -> Self {
185		Origin::Signed(account_id)
186	}
187
188	/// Creates a new Origin from a `RuntimeOrigin`.
189	pub fn from_runtime_origin(o: OriginFor<T>) -> Result<Self, DispatchError> {
190		match o.into() {
191			Ok(RawOrigin::Root) => Ok(Self::Root),
192			Ok(RawOrigin::Signed(t)) => Ok(Self::Signed(t)),
193			_ => Err(BadOrigin.into()),
194		}
195	}
196
197	/// Returns the AccountId of a Signed Origin or an error if the origin is Root.
198	pub fn account_id(&self) -> Result<&T::AccountId, DispatchError> {
199		match self {
200			Origin::Signed(id) => Ok(id),
201			Origin::Root => Err(DispatchError::RootNotAllowed),
202		}
203	}
204
205	/// Make sure that this origin is mapped.
206	///
207	/// We require an origin to be mapped in order to be used in a `Stack`. Otherwise
208	/// [`Stack::caller`] returns an address that can't be reverted to the original address.
209	fn ensure_mapped(&self) -> DispatchResult {
210		match self {
211			Self::Root => Ok(()),
212			Self::Signed(account_id) if T::AddressMapper::is_mapped(account_id) => Ok(()),
213			Self::Signed(_) => Err(<Error<T>>::AccountUnmapped.into()),
214		}
215	}
216}
217
218/// Argument passed by a contact to describe the amount of resources allocated to a cross contact
219/// call.
220#[derive(DebugNoBound)]
221pub enum CallResources<T: Config> {
222	/// Resources are not limited
223	NoLimits,
224	/// Resources encoded using their actual values.
225	WeightDeposit { weight: Weight, deposit_limit: BalanceOf<T> },
226	/// Resources encoded as unified ethereum gas.
227	Ethereum { gas: BalanceOf<T>, add_stipend: bool },
228}
229
230impl<T: Config> CallResources<T> {
231	/// Creates a new `CallResources` with weight and deposit limits.
232	pub fn from_weight_and_deposit(weight: Weight, deposit_limit: U256) -> Self {
233		Self::WeightDeposit {
234			weight,
235			deposit_limit: deposit_limit.saturated_into::<BalanceOf<T>>(),
236		}
237	}
238
239	/// Creates a new `CallResources` from Ethereum gas limits.
240	pub fn from_ethereum_gas(gas: U256, add_stipend: bool) -> Self {
241		Self::Ethereum { gas: gas.saturated_into::<BalanceOf<T>>(), add_stipend }
242	}
243}
244
245impl<T: Config> Default for CallResources<T> {
246	fn default() -> Self {
247		Self::WeightDeposit { weight: Default::default(), deposit_limit: Default::default() }
248	}
249}
250
251/// Stored inside the `Stack` for each contract that is scheduled for termination.
252struct TerminateArgs<T: Config> {
253	/// Where to send the free balance of the terminated contract.
254	beneficiary: T::AccountId,
255	/// The storage child trie of the contract that needs to be deleted.
256	trie_id: TrieId,
257	/// The code referenced by the contract. Will be deleted if refcount drops to zero.
258	code_hash: H256,
259	/// Triggered by the EVM opcode.
260	only_if_same_tx: bool,
261}
262
263/// Environment functions only available to host functions.
264pub trait Ext: PrecompileWithInfoExt {
265	/// Execute code in the current frame.
266	///
267	/// Returns the code size of the called contract.
268	fn delegate_call(
269		&mut self,
270		call_resources: &CallResources<Self::T>,
271		address: H160,
272		input_data: Vec<u8>,
273	) -> Result<(), ExecError>;
274
275	/// Register the contract for destruction at the end of the call stack.
276	///
277	/// Transfer all funds to `beneficiary`.
278	/// Contract is deleted only if it was created in the same call stack.
279	///
280	/// This function will fail if called from constructor.
281	fn terminate_if_same_tx(&mut self, beneficiary: &H160) -> Result<CodeRemoved, DispatchError>;
282
283	/// Returns the code hash of the contract being executed.
284	#[allow(dead_code)]
285	fn own_code_hash(&mut self) -> &H256;
286
287	/// This query is free as it does not need to load the immutable data from storage.
288	/// Useful when we need a constant time lookup of the length.
289	/// For foreign code (delegate call, EIP-7702 delegated EOA) returns the `IMMUTABLE_BYTES` cap.
290	fn immutable_data_len(&mut self) -> u32;
291
292	/// Returns the immutable data of the current contract.
293	///
294	/// Returns `Err(InvalidImmutableAccess)` if called from a constructor.
295	fn get_immutable_data(&mut self) -> Result<ImmutableData, DispatchError>;
296
297	/// Set the immutable data of the current contract.
298	///
299	/// Returns `Err(InvalidImmutableAccess)` if not called from a constructor.
300	///
301	/// Note: Requires &mut self to access the contract info.
302	fn set_immutable_data(&mut self, data: ImmutableData) -> Result<(), DispatchError>;
303}
304
305/// Environment functions which are available to pre-compiles with `HAS_CONTRACT_INFO = true`.
306pub trait PrecompileWithInfoExt: PrecompileExt {
307	/// Instantiate a contract from the given code.
308	///
309	/// Returns the original code size of the called contract.
310	/// The newly created account will be associated with `code`. `value` specifies the amount of
311	/// value transferred from the caller to the newly created account.
312	fn instantiate(
313		&mut self,
314		limits: &CallResources<Self::T>,
315		code: Code,
316		value: U256,
317		input_data: Vec<u8>,
318		salt: Option<&[u8; 32]>,
319	) -> Result<H160, ExecError>;
320}
321
322/// Environment functions which are available to all pre-compiles.
323pub trait PrecompileExt: sealing::Sealed {
324	type T: Config;
325
326	/// Charges the weight meter with the given weight.
327	fn charge(&mut self, weight: Weight) -> Result<ChargedAmount, DispatchError> {
328		self.frame_meter_mut().charge_weight_token(RuntimeCosts::Precompile(weight))
329	}
330
331	/// Reconcile an earlier gas charge with the actual weight consumed.
332	/// This updates the current weight meter to reflect the real cost of the token.
333	fn adjust_gas(&mut self, charged: ChargedAmount, actual_weight: Weight) {
334		self.frame_meter_mut()
335			.adjust_weight(charged, RuntimeCosts::Precompile(actual_weight));
336	}
337
338	/// Charges the weight meter with the given token or halts execution if not enough weight is
339	/// left.
340	#[inline]
341	fn charge_or_halt<Tok: Token<Self::T>>(
342		&mut self,
343		token: Tok,
344	) -> ControlFlow<crate::vm::evm::Halt, ChargedAmount> {
345		self.frame_meter_mut().charge_or_halt(token)
346	}
347
348	/// Call (possibly transferring some amount of funds) into the specified account.
349	fn call(
350		&mut self,
351		call_resources: &CallResources<Self::T>,
352		to: &H160,
353		value: U256,
354		input_data: Vec<u8>,
355		reentrancy: ReentrancyProtection,
356		read_only: bool,
357	) -> Result<(), ExecError>;
358
359	/// Returns the transient storage entry of the executing account for the given `key`.
360	///
361	/// Returns `None` if the `key` wasn't previously set by `set_transient_storage` or
362	/// was deleted.
363	fn get_transient_storage(&self, key: &Key) -> Option<Vec<u8>>;
364
365	/// Returns `Some(len)` (in bytes) if a transient storage item exists at `key`.
366	///
367	/// Returns `None` if the `key` wasn't previously set by `set_transient_storage` or
368	/// was deleted.
369	fn get_transient_storage_size(&self, key: &Key) -> Option<u32>;
370
371	/// Sets the transient storage entry for the given key to the specified value. If `value` is
372	/// `None` then the storage entry is deleted.
373	fn set_transient_storage(
374		&mut self,
375		key: &Key,
376		value: Option<Vec<u8>>,
377		take_old: bool,
378	) -> Result<WriteOutcome, DispatchError>;
379
380	/// Returns the caller.
381	fn caller(&self) -> Origin<Self::T>;
382
383	/// Returns the caller of the caller.
384	fn caller_of_caller(&self) -> Origin<Self::T>;
385
386	/// Return the origin of the whole call stack.
387	fn origin(&self) -> &Origin<Self::T>;
388
389	/// Returns the account id for the given `address`.
390	fn to_account_id(&self, address: &H160) -> AccountIdOf<Self::T>;
391
392	/// Returns the code hash of the contract for the given `address`.
393	/// If not a contract but account exists then `keccak_256([])` is returned, otherwise `zero`.
394	fn code_hash(&self, address: &H160) -> H256;
395
396	/// Returns the code size of the contract at the given `address` or zero.
397	fn code_size(&self, address: &H160) -> u64;
398
399	/// Check if the caller of the current contract is the origin of the whole call stack.
400	fn caller_is_origin(&self, use_caller_of_caller: bool) -> bool;
401
402	/// Check if the caller is origin, and this origin is root.
403	fn caller_is_root(&self, use_caller_of_caller: bool) -> bool;
404
405	/// Check if the origin of the whole call stack is root.
406	///
407	/// Unlike [`Self::caller_is_root`], this does not require the caller to be the origin: any
408	/// number of intermediate frames may sit between this contract and the original dispatch.
409	fn origin_is_root(&self) -> bool;
410
411	/// Returns a reference to the account id of the current contract.
412	fn account_id(&self) -> &AccountIdOf<Self::T>;
413
414	/// Returns a reference to the [`H160`] address of the current contract.
415	fn address(&self) -> H160 {
416		<Self::T as Config>::AddressMapper::to_address(self.account_id())
417	}
418
419	/// Returns the balance of the current contract.
420	///
421	/// The `value_transferred` is already added.
422	fn balance(&self) -> U256;
423
424	/// Returns the balance of the supplied account.
425	///
426	/// The `value_transferred` is already added.
427	fn balance_of(&self, address: &H160) -> U256;
428
429	/// Returns the value transferred along with this call.
430	fn value_transferred(&self) -> U256;
431
432	/// Returns the timestamp of the current block in seconds.
433	fn now(&self) -> U256;
434
435	/// Returns the minimum balance that is required for creating an account.
436	fn minimum_balance(&self) -> U256;
437
438	/// Deposit an event with the given topics.
439	///
440	/// There should not be any duplicates in `topics`.
441	fn deposit_event(&mut self, topics: Vec<H256>, data: Vec<u8>);
442
443	/// Returns the current block number.
444	fn block_number(&self) -> U256;
445
446	/// Returns the block hash at the given `block_number` or `None` if
447	/// `block_number` isn't within the range of the previous 256 blocks.
448	fn block_hash(&self, block_number: U256) -> Option<H256>;
449
450	/// Returns the author of the current block.
451	fn block_author(&self) -> H160;
452
453	/// Returns the block gas limit.
454	fn gas_limit(&self) -> u64;
455
456	/// Returns the chain id.
457	fn chain_id(&self) -> u64;
458
459	/// Get an immutable reference to the nested resource meter of the frame.
460	#[deprecated(note = "Renamed to `frame_meter`; this alias will be removed in future versions")]
461	fn gas_meter(&self) -> &FrameMeter<Self::T>;
462
463	/// Get a mutable reference to the nested resource meter of the frame.
464	#[deprecated(
465		note = "Renamed to `frame_meter_mut`; this alias will be removed in future versions"
466	)]
467	fn gas_meter_mut(&mut self) -> &mut FrameMeter<Self::T>;
468
469	/// Get an immutable reference to the nested resource meter of the frame.
470	fn frame_meter(&self) -> &FrameMeter<Self::T>;
471
472	/// Get a mutable reference to the nested resource meter of the frame.
473	fn frame_meter_mut(&mut self) -> &mut FrameMeter<Self::T>;
474
475	/// Recovers ECDSA compressed public key based on signature and message hash.
476	fn ecdsa_recover(&self, signature: &[u8; 65], message_hash: &[u8; 32]) -> Result<[u8; 33], ()>;
477
478	/// Verify a sr25519 signature.
479	fn sr25519_verify(&self, signature: &[u8; 64], message: &[u8], pub_key: &[u8; 32]) -> bool;
480
481	/// Returns Ethereum address from the ECDSA compressed public key.
482	fn ecdsa_to_eth_address(&self, pk: &[u8; 33]) -> Result<[u8; 20], DispatchError>;
483
484	/// Tests sometimes need to modify and inspect the contract info directly.
485	#[cfg(any(test, feature = "runtime-benchmarks"))]
486	fn contract_info(&mut self) -> &mut ContractInfo<Self::T>;
487
488	/// Get a mutable reference to the transient storage.
489	/// Useful in benchmarks when it is sometimes necessary to modify and inspect the transient
490	/// storage directly.
491	#[cfg(any(feature = "runtime-benchmarks", test))]
492	fn transient_storage(&mut self) -> &mut TransientStorage<Self::T>;
493
494	/// Check if running in read-only context.
495	fn is_read_only(&self) -> bool;
496
497	/// Check if running as a delegate call.
498	fn is_delegate_call(&self) -> bool;
499
500	/// Returns an immutable reference to the output of the last executed call frame.
501	fn last_frame_output(&self) -> &ExecReturnValue;
502
503	/// Returns a mutable reference to the output of the last executed call frame.
504	fn last_frame_output_mut(&mut self) -> &mut ExecReturnValue;
505
506	/// Copies a slice of the contract's code at `address` into the provided buffer.
507	///
508	/// EVM CODECOPY semantics:
509	/// - If `buf.len()` = 0: Nothing happens
510	/// - If `code_offset` >= code size: `len` bytes of zero are written to memory
511	/// - If `code_offset + buf.len()` extends beyond code: Available code copied, remaining bytes
512	///   are filled with zeros
513	fn copy_code_slice(&mut self, buf: &mut [u8], address: &H160, code_offset: usize);
514
515	/// Register the caller of the current contract for destruction.
516	/// Destruction happens at the end of the call stack.
517	/// This is supposed to be used by the terminate precompile.
518	///
519	/// Transfer all funds to `beneficiary`.
520	/// Contract is deleted at the end of the call stack.
521	///
522	/// This function will fail if called from constructor.
523	fn terminate_caller(&mut self, beneficiary: &H160) -> Result<(), DispatchError>;
524
525	/// Returns the effective gas price of this transaction.
526	fn effective_gas_price(&self) -> U256;
527
528	/// The amount of gas left in eth gas units.
529	fn gas_left(&self) -> u64;
530
531	/// Returns the storage entry of the executing account by the given `key`.
532	///
533	/// Returns `None` if the `key` wasn't previously set by `set_storage` or
534	/// was deleted.
535	fn get_storage(&mut self, key: &Key) -> Option<Vec<u8>>;
536
537	/// Returns `Some(len)` (in bytes) if a storage item exists at `key`.
538	///
539	/// Returns `None` if the `key` wasn't previously set by `set_storage` or
540	/// was deleted.
541	fn get_storage_size(&mut self, key: &Key) -> Option<u32>;
542
543	/// Sets the storage entry by the given key to the specified value. If `value` is `None` then
544	/// the storage entry is deleted.
545	fn set_storage(
546		&mut self,
547		key: &Key,
548		value: Option<Vec<u8>>,
549		take_old: bool,
550	) -> Result<WriteOutcome, DispatchError>;
551
552	/// Checks if the persistent storage slot `key` was already accessed in this transaction
553	/// and inserts it otherwise, so subsequent accesses to the same slot bill as hot. Returns
554	/// the slot's [`Warmth`]. `op` is the operation being performed: a write upgrades a slot
555	/// that had only paid for a read.
556	fn touch_storage_access(&mut self, key: &Key, op: StorageOp) -> Warmth;
557
558	/// Non-mutating sibling of `touch_storage_access`: reports the persistent storage
559	/// slot's warmth without warming it.
560	fn peek_storage_access(&self, key: &Key) -> Warmth;
561
562	/// Charges `diff` from the meter.
563	fn charge_storage(&mut self, diff: &Diff) -> DispatchResult;
564}
565
566/// Describes the different functions that can be exported by an [`Executable`].
567#[derive(
568	Copy,
569	Clone,
570	PartialEq,
571	Eq,
572	Debug,
573	codec::Decode,
574	codec::Encode,
575	codec::MaxEncodedLen,
576	scale_info::TypeInfo,
577)]
578pub enum ExportedFunction {
579	/// The constructor function which is executed on deployment of a contract.
580	Constructor,
581	/// The function which is executed when a contract is called.
582	Call,
583}
584
585/// A trait that represents something that can be executed.
586///
587/// In the on-chain environment this would be represented by a vm binary module. This trait exists
588/// in order to be able to mock the vm logic for testing.
589pub trait Executable<T: Config>: Sized {
590	/// Load the executable from storage.
591	///
592	/// # Note
593	/// Charges size base load weight from the weight meter.
594	fn from_storage<S: State>(
595		code_hash: H256,
596		meter: &mut ResourceMeter<T, S>,
597	) -> Result<Self, DispatchError>;
598
599	/// Load the executable from EVM bytecode
600	fn from_evm_init_code(code: Vec<u8>, owner: AccountIdOf<T>) -> Result<Self, DispatchError>;
601
602	/// Execute the specified exported function and return the result.
603	///
604	/// When the specified function is `Constructor` the executable is stored and its
605	/// refcount incremented.
606	///
607	/// # Note
608	///
609	/// This functions expects to be executed in a storage transaction that rolls back
610	/// all of its emitted storage changes.
611	fn execute<E: Ext<T = T>>(
612		self,
613		ext: &mut E,
614		function: ExportedFunction,
615		input_data: Vec<u8>,
616	) -> ExecResult;
617
618	/// The code info of the executable.
619	fn code_info(&self) -> &CodeInfo<T>;
620
621	/// The raw code of the executable.
622	fn code(&self) -> &[u8];
623
624	/// The code hash of the executable.
625	fn code_hash(&self) -> &H256;
626}
627
628/// The complete call stack of a contract execution.
629///
630/// The call stack is initiated by either a signed origin or one of the contract RPC calls.
631/// This type implements `Ext` and by that exposes the business logic of contract execution to
632/// the runtime module which interfaces with the contract (the vm contract blob) itself.
633pub struct Stack<'a, T: Config, E> {
634	/// The origin that initiated the call stack. It could either be a Signed plain account that
635	/// holds an account id or Root.
636	///
637	/// # Note
638	///
639	/// Please note that it is possible that the id of a Signed origin belongs to a contract rather
640	/// than a plain account when being called through one of the contract RPCs where the
641	/// client can freely choose the origin. This usually makes no sense but is still possible.
642	origin: Origin<T>,
643	/// The resource meter that tracks all resource usage before the first frame starts.
644	transaction_meter: &'a mut TransactionMeter<T>,
645	/// The timestamp at the point of call stack instantiation.
646	timestamp: MomentOf<T>,
647	/// The block number at the time of call stack instantiation.
648	block_number: BlockNumberFor<T>,
649	/// The actual call stack. One entry per nested contract called/instantiated.
650	/// This does **not** include the [`Self::first_frame`].
651	frames: BoundedVec<Frame<T>, ConstU32<{ limits::CALL_STACK_DEPTH }>>,
652	/// Statically guarantee that each call stack has at least one frame.
653	first_frame: Frame<T>,
654	/// Transient storage used to store data, which is kept for the duration of a transaction.
655	transient_storage: TransientStorage<T>,
656	/// Per-transaction cold/hot access list for storage slots (EIP-2929 style).
657	access_list: AccessList,
658	/// Global behavior determined by the creater of this stack.
659	exec_config: &'a ExecConfig<T>,
660	/// No executable is held by the struct but influences its behaviour.
661	_phantom: PhantomData<E>,
662}
663
664/// Represents one entry in the call stack.
665///
666/// For each nested contract call or instantiate one frame is created. It holds specific
667/// information for the said call and caches the in-storage `ContractInfo` data structure.
668struct Frame<T: Config> {
669	/// The address of the executing contract.
670	account_id: T::AccountId,
671	/// The cached in-storage data of the contract.
672	contract_info: CachedContract<T>,
673	/// The EVM balance transferred by the caller as part of the call.
674	value_transferred: U256,
675	/// Determines whether this is a call or instantiate frame.
676	entry_point: ExportedFunction,
677	/// The resource meter that tracks all resource usage of this frame.
678	frame_meter: FrameMeter<T>,
679	/// If `false` the contract enabled its defense against reentrance attacks.
680	allows_reentry: bool,
681	/// If `true` subsequent calls cannot modify storage.
682	read_only: bool,
683	/// The delegate call info of the currently executing frame which was spawned by
684	/// `delegate_call`.
685	delegate: Option<DelegateInfo<T>>,
686	/// The address where the code (and immutable data) originates from.
687	///
688	/// For regular contracts, this equals the contract's own address.
689	/// For delegated accounts (EIP-7702), this is the delegation target's address.
690	/// For explicit delegate_call, this is the callee's address.
691	code_address: H160,
692	/// The output of the last executed call frame.
693	last_frame_output: ExecReturnValue,
694	/// The set of contracts that were created during this call stack.
695	contracts_created: BTreeSet<T::AccountId>,
696	/// The set of contracts that are registered for destruction at the end of this call stack.
697	contracts_to_be_destroyed: BTreeMap<T::AccountId, TerminateArgs<T>>,
698}
699
700/// This structure is used to represent the arguments in a delegate call frame in order to
701/// distinguish who delegated the call and where it was delegated to.
702#[derive(Clone, DebugNoBound)]
703pub struct DelegateInfo<T: Config> {
704	/// The caller of the contract.
705	pub caller: Origin<T>,
706	/// The address of the contract the call was delegated to.
707	pub callee: H160,
708}
709
710/// When calling an address it can either lead to execution of contract code or a pre-compile.
711enum ExecutableOrPrecompile<T: Config, E: Executable<T>, Env> {
712	/// Contract code.
713	Executable(E),
714	/// Code inside the runtime (so called pre-compile).
715	Precompile { instance: PrecompileInstance<Env>, _phantom: PhantomData<T> },
716}
717
718impl<T: Config, E: Executable<T>, Env> ExecutableOrPrecompile<T, E, Env> {
719	fn as_executable(&self) -> Option<&E> {
720		if let Self::Executable(executable) = self { Some(executable) } else { None }
721	}
722
723	fn is_pvm(&self) -> bool {
724		match self {
725			Self::Executable(e) => e.code_info().is_pvm(),
726			_ => false,
727		}
728	}
729
730	fn as_precompile(&self) -> Option<&PrecompileInstance<Env>> {
731		if let Self::Precompile { instance, .. } = self { Some(instance) } else { None }
732	}
733
734	#[cfg(any(feature = "runtime-benchmarks", test))]
735	fn into_executable(self) -> Option<E> {
736		if let Self::Executable(executable) = self { Some(executable) } else { None }
737	}
738}
739
740/// Parameter passed in when creating a new `Frame`.
741///
742/// It determines whether the new frame is for a call or an instantiate.
743enum FrameArgs<'a, T: Config, E> {
744	Call {
745		/// The account id of the contract that is to be called.
746		dest: T::AccountId,
747		/// If `None` the contract info needs to be reloaded from storage.
748		cached_info: Option<ContractInfo<T>>,
749		/// This frame was created by `seal_delegate_call` and hence uses different code than
750		/// what is stored at [`Self::Call::dest`]. Its caller ([`DelegatedCall::caller`]) is the
751		/// account which called the caller contract
752		delegated_call: Option<DelegateInfo<T>>,
753	},
754	Instantiate {
755		/// The contract or signed origin which instantiates the new contract.
756		sender: T::AccountId,
757		/// The executable whose `deploy` function is run.
758		executable: E,
759		/// A salt used in the contract address derivation of the new contract.
760		salt: Option<&'a [u8; 32]>,
761		/// The input data is used in the contract address derivation of the new contract.
762		input_data: &'a [u8],
763	},
764}
765
766/// Describes the different states of a contract as contained in a `Frame`.
767enum CachedContract<T: Config> {
768	/// The cached contract is up to date with the in-storage value.
769	Cached(ContractInfo<T>),
770	/// A recursive call into the same contract did write to the contract info.
771	///
772	/// In this case the cached contract is stale and needs to be reloaded from storage.
773	Invalidated,
774	/// The frame is associated with pre-compile that has no contract info.
775	None,
776}
777
778impl<T: Config> Frame<T> {
779	/// Return the `contract_info` of the current contract.
780	fn contract_info(&mut self) -> &mut ContractInfo<T> {
781		self.contract_info.get(&self.account_id)
782	}
783}
784
785/// Extract the contract info after loading it from storage.
786///
787/// This assumes that `load` was executed before calling this macro.
788macro_rules! get_cached_or_panic_after_load {
789	($c:expr) => {{
790		if let CachedContract::Cached(contract) = $c {
791			contract
792		} else {
793			panic!(
794				"It is impossible to remove a contract that is on the call stack;\
795				See implementations of terminate;\
796				Therefore fetching a contract will never fail while using an account id
797				that is currently active on the call stack;\
798				qed"
799			);
800		}
801	}};
802}
803
804/// Same as [`Stack::top_frame`].
805///
806/// We need this access as a macro because sometimes hiding the lifetimes behind
807/// a function won't work out.
808macro_rules! top_frame {
809	($stack:expr) => {
810		$stack.frames.last().unwrap_or(&$stack.first_frame)
811	};
812}
813
814/// Same as [`Stack::top_frame_mut`].
815///
816/// We need this access as a macro because sometimes hiding the lifetimes behind
817/// a function won't work out.
818macro_rules! top_frame_mut {
819	($stack:expr) => {
820		$stack.frames.last_mut().unwrap_or(&mut $stack.first_frame)
821	};
822}
823
824impl<T: Config> CachedContract<T> {
825	/// Return `Some(ContractInfo)` if the contract is in cached state. `None` otherwise.
826	fn into_contract(self) -> Option<ContractInfo<T>> {
827		if let CachedContract::Cached(contract) = self { Some(contract) } else { None }
828	}
829
830	/// Return `Some(&mut ContractInfo)` if the contract is in cached state. `None` otherwise.
831	fn as_contract(&mut self) -> Option<&mut ContractInfo<T>> {
832		if let CachedContract::Cached(contract) = self { Some(contract) } else { None }
833	}
834
835	/// Load the `contract_info` from storage if necessary.
836	fn load(&mut self, account_id: &T::AccountId) {
837		if let CachedContract::Invalidated = self &&
838			let Some(contract) =
839				AccountInfo::<T>::load_contract(&T::AddressMapper::to_address(account_id))
840		{
841			*self = CachedContract::Cached(contract);
842		}
843	}
844
845	/// Return the cached contract_info.
846	fn get(&mut self, account_id: &T::AccountId) -> &mut ContractInfo<T> {
847		self.load(account_id);
848		get_cached_or_panic_after_load!(self)
849	}
850
851	/// Set the status to invalidate if is cached.
852	fn invalidate(&mut self) {
853		if matches!(self, CachedContract::Cached(_)) {
854			*self = CachedContract::Invalidated;
855		}
856	}
857}
858
859impl<'a, T, E> Stack<'a, T, E>
860where
861	T: Config,
862	E: Executable<T>,
863{
864	/// Create and run a new call stack by calling into `dest`.
865	///
866	/// # Return Value
867	///
868	/// Result<(ExecReturnValue, CodeSize), (ExecError, CodeSize)>
869	pub fn run_call(
870		origin: Origin<T>,
871		dest: H160,
872		transaction_meter: &'a mut TransactionMeter<T>,
873		value: U256,
874		input_data: Vec<u8>,
875		exec_config: &ExecConfig<T>,
876	) -> ExecResult {
877		let dest = T::AddressMapper::to_account_id(&dest);
878		if let Some((mut stack, executable)) = Stack::<'_, T, E>::new(
879			FrameArgs::Call { dest: dest.clone(), cached_info: None, delegated_call: None },
880			origin.clone(),
881			transaction_meter,
882			value,
883			exec_config,
884			&input_data,
885		)? {
886			stack.run(executable, input_data).map(|_| stack.first_frame.last_frame_output)
887		} else {
888			if_tracing(|t| {
889				t.enter_child_span(
890					origin.account_id().map(T::AddressMapper::to_address).unwrap_or_default(),
891					T::AddressMapper::to_address(&dest),
892					None,
893					false,
894					false,
895					value,
896					&input_data,
897					Default::default(),
898				);
899			});
900
901			let result = if let Some(mock_answer) =
902				exec_config.mock_handler.as_ref().and_then(|handler| {
903					handler.mock_call(T::AddressMapper::to_address(&dest), &input_data, value)
904				}) {
905				Ok(mock_answer)
906			} else {
907				Self::transfer_from_origin(
908					&origin,
909					&origin,
910					&dest,
911					value,
912					transaction_meter,
913					exec_config,
914				)
915			};
916
917			if_tracing(|t| {
918				let gas_used =
919					transaction_meter.total_consumed_gas().try_into().unwrap_or(u64::MAX);
920				let weight_consumed = transaction_meter.weight_consumed();
921				match result {
922					Ok(ref output) => t.exit_child_span(&output, gas_used, weight_consumed),
923					Err(e) => {
924						t.exit_child_span_with_error(e.error.into(), gas_used, weight_consumed)
925					},
926				}
927			});
928
929			log::trace!(target: LOG_TARGET, "call finished with: {result:?}");
930
931			result
932		}
933	}
934
935	/// Create and run a new call stack by instantiating a new contract.
936	///
937	/// # Return Value
938	///
939	/// Result<(NewContractAccountId, ExecReturnValue), ExecError)>
940	pub fn run_instantiate(
941		origin: T::AccountId,
942		executable: E,
943		transaction_meter: &'a mut TransactionMeter<T>,
944		value: U256,
945		input_data: Vec<u8>,
946		salt: Option<&[u8; 32]>,
947		exec_config: &ExecConfig<T>,
948	) -> Result<(H160, ExecReturnValue), ExecError> {
949		let deployer = T::AddressMapper::to_address(&origin);
950		let (mut stack, executable) = Stack::<'_, T, E>::new(
951			FrameArgs::Instantiate {
952				sender: origin.clone(),
953				executable,
954				salt,
955				input_data: input_data.as_ref(),
956			},
957			Origin::from_account_id(origin),
958			transaction_meter,
959			value,
960			exec_config,
961			&input_data,
962		)?
963		.expect(FRAME_ALWAYS_EXISTS_ON_INSTANTIATE);
964		let address = T::AddressMapper::to_address(&stack.top_frame().account_id);
965		let result = stack
966			.run(executable, input_data)
967			.map(|_| (address, stack.first_frame.last_frame_output));
968		if let Ok((contract, output)) = &result &&
969			!output.did_revert()
970		{
971			Contracts::<T>::deposit_event(Event::Instantiated { deployer, contract: *contract });
972		}
973		log::trace!(target: LOG_TARGET, "instantiate finished with: {result:?}");
974		result
975	}
976
977	#[cfg(any(feature = "runtime-benchmarks", test))]
978	pub fn bench_new_call(
979		dest: H160,
980		origin: Origin<T>,
981		transaction_meter: &'a mut TransactionMeter<T>,
982		value: BalanceOf<T>,
983		exec_config: &'a ExecConfig<T>,
984		read_only: bool,
985		delegate_call: bool,
986	) -> (Self, E) {
987		let call = Self::new(
988			FrameArgs::Call {
989				dest: T::AddressMapper::to_account_id(&dest),
990				cached_info: None,
991				delegated_call: None,
992			},
993			origin,
994			transaction_meter,
995			value.into(),
996			exec_config,
997			&Default::default(),
998		)
999		.unwrap()
1000		.unwrap();
1001		let mut stack = call.0;
1002		if read_only {
1003			stack.top_frame_mut().read_only = true;
1004		}
1005		if delegate_call {
1006			let frame = stack.top_frame_mut();
1007			frame.delegate = Some(DelegateInfo {
1008				caller: Origin::from_account_id(frame.account_id.clone()),
1009				callee: H160::zero(),
1010			});
1011		}
1012		(stack, call.1.into_executable().unwrap())
1013	}
1014
1015	/// Create a new call stack.
1016	///
1017	/// Returns `None` when calling a non existent contract. This is not an error case
1018	/// since this will result in a value transfer.
1019	fn new(
1020		args: FrameArgs<T, E>,
1021		origin: Origin<T>,
1022		transaction_meter: &'a mut TransactionMeter<T>,
1023		value: U256,
1024		exec_config: &'a ExecConfig<T>,
1025		input_data: &Vec<u8>,
1026	) -> Result<Option<(Self, ExecutableOrPrecompile<T, E, Self>)>, ExecError> {
1027		origin.ensure_mapped()?;
1028		let Some((first_frame, executable)) = Self::new_frame(
1029			args,
1030			value,
1031			transaction_meter,
1032			&CallResources::NoLimits,
1033			false,
1034			true,
1035			input_data,
1036			exec_config,
1037		)?
1038		else {
1039			return Ok(None);
1040		};
1041
1042		let mut timestamp = T::Time::now();
1043		let mut block_number = <frame_system::Pallet<T>>::block_number();
1044		// if dry run with timestamp override is provided we simulate the run in a `pending` block
1045		if let Some(timestamp_override) =
1046			exec_config.is_dry_run.as_ref().and_then(|cfg| cfg.timestamp_override)
1047		{
1048			block_number = block_number.saturating_add(1u32.into());
1049			// Delta is in milliseconds; increment timestamp by one second
1050			let delta = 1000u32.into();
1051			timestamp = cmp::max(timestamp.saturating_add(delta), timestamp_override);
1052		}
1053
1054		let stack = Self {
1055			origin,
1056			transaction_meter,
1057			timestamp,
1058			block_number,
1059			first_frame,
1060			frames: Default::default(),
1061			transient_storage: TransientStorage::new(limits::TRANSIENT_STORAGE_BYTES),
1062			access_list: AccessList::new(),
1063			exec_config,
1064			_phantom: Default::default(),
1065		};
1066		Ok(Some((stack, executable)))
1067	}
1068
1069	/// EIP-7702 chained delegation check for an account with no loadable code.
1070	///
1071	/// A chained delegation always surfaces with an empty snapshot: `set_delegation` only
1072	/// snapshots a `code_hash` when the target is a deployed contract, and a contract can
1073	/// never become delegated. So when `load_contract_with_delegation` returns no contract
1074	/// info but a delegation target, one read of the target decides: if the target is itself
1075	/// delegated, the spec resolves one hop, retrieves the target's indicator bytes
1076	/// `0xef0100 || ..`, and traps on the leading `0xef` invalid opcode. Otherwise the
1077	/// resolved code is genuinely empty and the call falls through to the transfer path.
1078	fn fail_if_chained_delegation(target: Option<H160>) -> Result<(), ExecError> {
1079		if let Some(target) = target &&
1080			AccountInfo::<T>::is_delegated(&target)
1081		{
1082			return Err(ExecError {
1083				error: <Error<T>>::ContractTrapped.into(),
1084				origin: ErrorOrigin::Callee,
1085			});
1086		}
1087		Ok(())
1088	}
1089
1090	/// Construct a new frame.
1091	///
1092	/// This does not take `self` because when constructing the first frame `self` is
1093	/// not initialized, yet.
1094	fn new_frame<S: State>(
1095		frame_args: FrameArgs<T, E>,
1096		value_transferred: U256,
1097		meter: &mut ResourceMeter<T, S>,
1098		call_resources: &CallResources<T>,
1099		read_only: bool,
1100		origin_is_caller: bool,
1101		input_data: &[u8],
1102		exec_config: &ExecConfig<T>,
1103	) -> Result<Option<(Frame<T>, ExecutableOrPrecompile<T, E, Self>)>, ExecError> {
1104		// `Some` once the account entry has been read: the delegation target it carried, so
1105		// `code_address` below does not decode the same entry a second time.
1106		let mut read_delegation: Option<Option<H160>> = None;
1107		// `Some` when this is a delegate call whose callee is an EIP-7702 delegated EOA: the
1108		// callee's delegation target, which is where the executed code (and therefore its
1109		// immutable data) lives.
1110		let mut delegate_code_target: Option<H160> = None;
1111
1112		let (account_id, contract_info, executable, delegate, entry_point) = match frame_args {
1113			FrameArgs::Call { dest, cached_info, delegated_call } => {
1114				let address = T::AddressMapper::to_address(&dest);
1115				let precompile = <AllPrecompiles<T>>::get(address.as_fixed_bytes());
1116
1117				// which contract info to load is unaffected by the fact if this
1118				// is a delegate call or not
1119				let mut contract = match (cached_info, &precompile) {
1120					(Some(info), _) => CachedContract::Cached(info),
1121					(None, None) => {
1122						let (info, target) =
1123							AccountInfo::<T>::load_contract_with_delegation(&address);
1124						read_delegation = Some(target);
1125						if let Some(info) = info {
1126							CachedContract::Cached(info)
1127						} else {
1128							Self::fail_if_chained_delegation(target)?;
1129							return Ok(None);
1130						}
1131					},
1132					(None, Some(precompile)) if precompile.has_contract_info() => {
1133						log::trace!(target: LOG_TARGET, "found precompile for address {address:?}");
1134						let (info, target) =
1135							AccountInfo::<T>::load_contract_with_delegation(&address);
1136						read_delegation = Some(target);
1137						if let Some(info) = info {
1138							CachedContract::Cached(info)
1139						} else {
1140							let info = ContractInfo::new(&address, 0u32.into(), H256::zero())?;
1141							CachedContract::Cached(info)
1142						}
1143					},
1144					// A precompile address can never be delegated: skip the `code_address`
1145					// delegation lookup below.
1146					(None, Some(_)) => {
1147						read_delegation = Some(None);
1148						CachedContract::None
1149					},
1150				};
1151
1152				let delegated_call = delegated_call.or_else(|| {
1153					exec_config.mock_handler.as_ref().and_then(|mock_handler| {
1154						mock_handler.mock_delegated_caller(address, input_data)
1155					})
1156				});
1157				// in case of delegate the executable is not the one at `address`
1158				let executable = if let Some(delegated_call) = &delegated_call {
1159					if let Some(precompile) =
1160						<AllPrecompiles<T>>::get(delegated_call.callee.as_fixed_bytes())
1161					{
1162						ExecutableOrPrecompile::Precompile {
1163							instance: precompile,
1164							_phantom: Default::default(),
1165						}
1166					} else {
1167						let (info, target) =
1168							AccountInfo::<T>::load_contract_with_delegation(&delegated_call.callee);
1169						let Some(info) = info else {
1170							Self::fail_if_chained_delegation(target)?;
1171							return Ok(None);
1172						};
1173						delegate_code_target = target;
1174						let executable = E::from_storage(info.code_hash, meter)?;
1175						ExecutableOrPrecompile::Executable(executable)
1176					}
1177				} else {
1178					if let Some(precompile) = precompile {
1179						ExecutableOrPrecompile::Precompile {
1180							instance: precompile,
1181							_phantom: Default::default(),
1182						}
1183					} else {
1184						let executable = E::from_storage(
1185							contract
1186								.as_contract()
1187								.expect("When not a precompile the contract was loaded above; qed")
1188								.code_hash,
1189							meter,
1190						)?;
1191						ExecutableOrPrecompile::Executable(executable)
1192					}
1193				};
1194
1195				(dest, contract, executable, delegated_call, ExportedFunction::Call)
1196			},
1197			FrameArgs::Instantiate { sender, executable, salt, input_data } => {
1198				let deployer = T::AddressMapper::to_address(&sender);
1199				let account_nonce = <System<T>>::account_nonce(&sender);
1200				let address = if let Some(salt) = salt {
1201					address::create2(&deployer, executable.code(), input_data, salt)
1202				} else {
1203					use sp_runtime::Saturating;
1204					address::create1(
1205						&deployer,
1206						// the Nonce from the origin has been incremented pre-dispatch, so we
1207						// need to subtract 1 to get the nonce at the time of the call.
1208						if origin_is_caller {
1209							account_nonce.saturating_sub(1u32.into()).saturated_into()
1210						} else {
1211							account_nonce.saturated_into()
1212						},
1213					)
1214				};
1215				let contract = ContractInfo::new(
1216					&address,
1217					<System<T>>::account_nonce(&sender),
1218					*executable.code_hash(),
1219				)?;
1220				(
1221					T::AddressMapper::to_fallback_account_id(&address),
1222					CachedContract::Cached(contract),
1223					ExecutableOrPrecompile::Executable(executable),
1224					None,
1225					ExportedFunction::Constructor,
1226				)
1227			},
1228		};
1229
1230		// Compute the code_address: the address where the code (and immutable data) comes from.
1231		// For delegate_call this is the callee — or the callee's delegation target when the
1232		// callee is itself a delegated EOA. For a call to an EIP-7702 delegated account it's
1233		// the delegation target, otherwise it's the account's own address.
1234		let address = T::AddressMapper::to_address(&account_id);
1235		let code_address = delegate
1236			.as_ref()
1237			.map(|d| delegate_code_target.unwrap_or(d.callee))
1238			.or_else(|| {
1239				// Constructors can't be delegated, skip the storage read.
1240				if entry_point == ExportedFunction::Constructor {
1241					return None;
1242				}
1243				read_delegation.unwrap_or_else(|| AccountInfo::<T>::get_delegation_target(&address))
1244			})
1245			.unwrap_or(address);
1246
1247		let frame = Frame {
1248			delegate,
1249			value_transferred,
1250			contract_info,
1251			account_id,
1252			entry_point,
1253			code_address,
1254			frame_meter: meter.new_nested(call_resources)?,
1255			allows_reentry: true,
1256			read_only,
1257			last_frame_output: Default::default(),
1258			contracts_created: Default::default(),
1259			contracts_to_be_destroyed: Default::default(),
1260		};
1261
1262		Ok(Some((frame, executable)))
1263	}
1264
1265	/// Create a subsequent nested frame.
1266	fn push_frame(
1267		&mut self,
1268		frame_args: FrameArgs<T, E>,
1269		value_transferred: U256,
1270		call_resources: &CallResources<T>,
1271		read_only: bool,
1272		input_data: &[u8],
1273	) -> Result<Option<ExecutableOrPrecompile<T, E, Self>>, ExecError> {
1274		if self.frames.len() as u32 == limits::CALL_STACK_DEPTH {
1275			return Err(Error::<T>::MaxCallDepthReached.into());
1276		}
1277
1278		// We need to make sure that changes made to the contract info are not discarded.
1279		// See the `in_memory_changes_not_discarded` test for more information.
1280		// We do not store on instantiate because we do not allow to call into a contract
1281		// from its own constructor.
1282		//
1283		// Additionally, we need to apply pending storage changes to the ContractInfo before
1284		// saving it, so that child frames can correctly calculate storage deposit refunds.
1285		// See: <https://github.com/paritytech/contract-issues/issues/213>
1286		let frame = self.top_frame();
1287		if let (CachedContract::Cached(contract), ExportedFunction::Call) =
1288			(&frame.contract_info, frame.entry_point)
1289		{
1290			let mut contract_with_pending_changes = contract.clone();
1291			frame
1292				.frame_meter
1293				.apply_pending_storage_changes(&mut contract_with_pending_changes);
1294			AccountInfo::<T>::insert_contract(
1295				&T::AddressMapper::to_address(&frame.account_id),
1296				contract_with_pending_changes,
1297			);
1298		}
1299
1300		let frame = top_frame_mut!(self);
1301		let meter = &mut frame.frame_meter;
1302		if let Some((frame, executable)) = Self::new_frame(
1303			frame_args,
1304			value_transferred,
1305			meter,
1306			call_resources,
1307			read_only,
1308			false,
1309			input_data,
1310			self.exec_config,
1311		)? {
1312			// EIP-684: an in-construction address is not in `AccountInfoOf` yet, so the
1313			// `is_contract` guard in `ContractInfo::new` misses this re-entrant collision.
1314			if frame.entry_point == ExportedFunction::Constructor &&
1315				self.frames().any(|f| {
1316					f.entry_point == ExportedFunction::Constructor &&
1317						f.account_id == frame.account_id
1318				}) {
1319				return Err(Error::<T>::DuplicateContract.into());
1320			}
1321			self.frames.try_push(frame).map_err(|_| Error::<T>::MaxCallDepthReached)?;
1322			Ok(Some(executable))
1323		} else {
1324			Ok(None)
1325		}
1326	}
1327
1328	/// Run the current (top) frame.
1329	///
1330	/// This can be either a call or an instantiate.
1331	fn run(
1332		&mut self,
1333		executable: ExecutableOrPrecompile<T, E, Self>,
1334		input_data: Vec<u8>,
1335	) -> Result<(), ExecError> {
1336		let frame = self.top_frame();
1337		let entry_point = frame.entry_point;
1338		let is_pvm = executable.is_pvm();
1339
1340		if_tracing(|tracer| {
1341			// For DELEGATECALL, `from` is the contract making the delegatecall and
1342			// `to` is the target contract whose code is being executed.
1343			let (from, to) = match frame.delegate.as_ref() {
1344				Some(delegate) => {
1345					(T::AddressMapper::to_address(&frame.account_id), delegate.callee)
1346				},
1347				None => (
1348					self.caller()
1349						.account_id()
1350						.map(T::AddressMapper::to_address)
1351						.unwrap_or_default(),
1352					T::AddressMapper::to_address(&frame.account_id),
1353				),
1354			};
1355			tracer.enter_child_span(
1356				from,
1357				to,
1358				(frame.code_address != to).then_some(frame.code_address),
1359				frame.delegate.is_some(),
1360				frame.read_only,
1361				frame.value_transferred,
1362				&input_data,
1363				frame
1364					.frame_meter
1365					.eth_gas_left()
1366					.unwrap_or_default()
1367					.try_into()
1368					.unwrap_or_default(),
1369			);
1370		});
1371		let mock_answer = self.exec_config.mock_handler.as_ref().and_then(|handler| {
1372			handler.mock_call(
1373				frame
1374					.delegate
1375					.as_ref()
1376					.map(|delegate| delegate.callee)
1377					.unwrap_or(T::AddressMapper::to_address(&frame.account_id)),
1378				&input_data,
1379				frame.value_transferred,
1380			)
1381		});
1382		// The output of the caller frame will be replaced by the output of this run.
1383		// It is also not accessible from nested frames.
1384		// Hence we drop it early to save the memory.
1385		let frames_len = self.frames.len();
1386		if let Some(caller_frame) = match frames_len {
1387			0 => None,
1388			1 => Some(&mut self.first_frame.last_frame_output),
1389			_ => self.frames.get_mut(frames_len - 2).map(|frame| &mut frame.last_frame_output),
1390		} {
1391			*caller_frame = Default::default();
1392		}
1393
1394		self.with_transient_storage_mut(|transient_storage| {
1395			transient_storage.start_transaction();
1396		});
1397		let is_first_frame = self.frames.is_empty();
1398		let access_list_checkpoints_len = self.access_list.frame_depth();
1399		// Open an access-list frame for nested CALL/CREATE. The first frame
1400		// is skipped; its touches land in the bare journal and persist
1401		// for the whole transaction.
1402		if !is_first_frame {
1403			self.access_list.enter_frame();
1404		}
1405
1406		let do_transaction = || -> ExecResult {
1407			let caller = self.caller();
1408			let bump_nonce = self.exec_config.bump_nonce;
1409			let frame = top_frame_mut!(self);
1410			let account_id = &frame.account_id.clone();
1411
1412			if u32::try_from(input_data.len())
1413				.map(|len| len > limits::CALLDATA_BYTES)
1414				.unwrap_or(true)
1415			{
1416				Err(<Error<T>>::CallDataTooLarge)?;
1417			}
1418
1419			// We need to make sure that the contract's account exists before calling its
1420			// constructor.
1421			if entry_point == ExportedFunction::Constructor {
1422				if !frame_system::Pallet::<T>::account_exists(&account_id) {
1423					T::Deposit::init_contract(account_id)?;
1424				}
1425
1426				// A consumer is added at account creation and removed it on termination, otherwise
1427				// the runtime could remove the account. As long as a contract exists its
1428				// account must exist. With the consumer, a correct runtime cannot remove the
1429				// account.
1430				<System<T>>::inc_consumers(account_id)?;
1431
1432				// Contracts nonce starts at 1
1433				<System<T>>::inc_account_nonce(account_id);
1434
1435				if bump_nonce || !is_first_frame {
1436					// Needs to be incremented before calling into the code so that it is visible
1437					// in case of recursion.
1438					<System<T>>::inc_account_nonce(caller.account_id()?);
1439				}
1440				// The incremented refcount should be visible to the constructor.
1441				if is_pvm {
1442					<CodeInfo<T>>::increment_refcount(
1443						*executable
1444							.as_executable()
1445							.expect("Precompiles cannot be instantiated; qed")
1446							.code_hash(),
1447					)?;
1448				}
1449			}
1450
1451			// Every non delegate call or instantiate also optionally transfers the balance.
1452			// If it is a delegate call, then we've already transferred tokens in the
1453			// last non-delegate frame.
1454			if frame.delegate.is_none() {
1455				Self::transfer_from_origin(
1456					&self.origin,
1457					&caller,
1458					account_id,
1459					frame.value_transferred,
1460					&mut frame.frame_meter,
1461					self.exec_config,
1462				)?;
1463			}
1464
1465			// We need to make sure that the pre-compiles contract exist before executing it.
1466			// A few more conditionals:
1467			// 	- Only contracts with extended API (has_contract_info) are guaranteed to have an
1468			//    account.
1469			//  - Only when not delegate calling we are executing in the context of the pre-compile.
1470			//    Pre-compiles itself cannot delegate call.
1471			if let Some(precompile) = executable.as_precompile() &&
1472				precompile.has_contract_info() &&
1473				frame.delegate.is_none() &&
1474				!<System<T>>::account_exists(account_id)
1475			{
1476				// prefix matching pre-compiles cannot have a contract info
1477				// hence we only mint once per pre-compile
1478				T::Currency::mint_into(account_id, T::Currency::minimum_balance())?;
1479				// make sure the pre-compile does not destroy its account by accident
1480				<System<T>>::inc_consumers(account_id)?;
1481			}
1482
1483			let mut code_deposit = executable
1484				.as_executable()
1485				.map(|exec| exec.code_info().deposit())
1486				.unwrap_or_default();
1487
1488			let mut output = match executable {
1489				ExecutableOrPrecompile::Executable(executable) => {
1490					executable.execute(self, entry_point, input_data)
1491				},
1492				ExecutableOrPrecompile::Precompile { instance, .. } => {
1493					instance.call(input_data, self)
1494				},
1495			}
1496			.and_then(|output| {
1497				if u32::try_from(output.data.len())
1498					.map(|len| len > limits::CALLDATA_BYTES)
1499					.unwrap_or(true)
1500				{
1501					Err(<Error<T>>::ReturnDataTooLarge)?;
1502				}
1503				Ok(output)
1504			})
1505			.map_err(|e| ExecError { error: e.error, origin: ErrorOrigin::Callee })?;
1506
1507			// Avoid useless work that would be reverted anyways.
1508			if output.did_revert() {
1509				return Ok(output);
1510			}
1511
1512			// The deposit we charge for a contract depends on the size of the immutable data.
1513			// Hence we need to delay charging the base deposit after execution.
1514			let frame = if entry_point == ExportedFunction::Constructor {
1515				let frame = top_frame_mut!(self);
1516				// if we are dealing with EVM bytecode
1517				// We upload the new runtime code, and update the code
1518				if !is_pvm {
1519					// Only keep return data for tracing and for dry runs.
1520					// When a dry-run simulates contract deployment, keep the execution result's
1521					// data.
1522					let data = if crate::tracing::if_tracing(|_| {}).is_none() &&
1523						self.exec_config.is_dry_run.is_none()
1524					{
1525						core::mem::replace(&mut output.data, Default::default())
1526					} else {
1527						output.data.clone()
1528					};
1529
1530					// Under Root there is no origin account to attribute the upload
1531					// deposit to: use the pallet's own account as a sentinel owner
1532					// with zero deposit so charge/refund are no-ops.
1533					let mut module = match &self.origin {
1534						Origin::Signed(o) => {
1535							crate::ContractBlob::<T>::from_evm_runtime_code(data, o.clone())?
1536						},
1537						Origin::Root => {
1538							crate::ContractBlob::<T>::from_evm_runtime_code_with_deposit(
1539								data,
1540								crate::Pallet::<T>::account_id(),
1541								Zero::zero(),
1542							)?
1543						},
1544					};
1545					module.store_code(&self.exec_config, &mut frame.frame_meter)?;
1546					code_deposit = module.code_info().deposit();
1547
1548					let contract_info = frame.contract_info();
1549					contract_info.code_hash = *module.code_hash();
1550					<CodeInfo<T>>::increment_refcount(contract_info.code_hash)?;
1551				}
1552
1553				let deposit = frame.contract_info().update_base_deposit(code_deposit);
1554				frame.frame_meter.charge_contract_deposit_and_transfer(
1555					frame.account_id.clone(),
1556					StorageDeposit::Charge(deposit),
1557				)?;
1558				frame
1559			} else {
1560				self.top_frame_mut()
1561			};
1562
1563			// The storage deposit is only charged at the end of every call stack.
1564			// To make sure that no sub call uses more than it is allowed to,
1565			// the limit is manually enforced here.
1566			let contract = frame.contract_info.as_contract();
1567			frame
1568				.frame_meter
1569				.finalize(contract)
1570				.map_err(|e| ExecError { error: e, origin: ErrorOrigin::Callee })?;
1571
1572			Ok(output)
1573		};
1574
1575		// All changes performed by the contract are executed under a storage transaction.
1576		// This allows for roll back on error. Changes to the cached contract_info are
1577		// committed or rolled back when popping the frame.
1578		//
1579		// `with_transactional` may return an error caused by a limit in the
1580		// transactional storage depth.
1581		let transaction_outcome =
1582			with_transaction(|| -> TransactionOutcome<Result<_, DispatchError>> {
1583				let output = if let Some(mock_answer) = mock_answer {
1584					Ok(mock_answer)
1585				} else {
1586					do_transaction()
1587				};
1588				match &output {
1589					Ok(result) if !result.did_revert() => {
1590						TransactionOutcome::Commit(Ok((true, output)))
1591					},
1592					_ => TransactionOutcome::Rollback(Ok((false, output))),
1593				}
1594			});
1595
1596		let (success, output) = match transaction_outcome {
1597			// `with_transactional` executed successfully, and we have the expected output.
1598			Ok((success, output)) => {
1599				if_tracing(|tracer| {
1600					let frame_meter = &top_frame!(self).frame_meter;
1601
1602					// we treat the initial frame meter differently to address
1603					// https://github.com/paritytech/polkadot-sdk/issues/8362
1604					let gas_consumed = if is_first_frame {
1605						frame_meter.total_consumed_gas()
1606					} else {
1607						frame_meter.eth_gas_consumed()
1608					};
1609
1610					let gas_consumed: u64 = gas_consumed.try_into().unwrap_or(u64::MAX);
1611					let weight_consumed = frame_meter.weight_consumed();
1612
1613					match &output {
1614						Ok(output) => {
1615							tracer.exit_child_span(&output, gas_consumed, weight_consumed)
1616						},
1617						Err(e) => tracer.exit_child_span_with_error(
1618							e.error.into(),
1619							gas_consumed,
1620							weight_consumed,
1621						),
1622					}
1623				});
1624
1625				(success, output)
1626			},
1627			// `with_transactional` returned an error, and we propagate that error and note no state
1628			// has changed.
1629			Err(error) => {
1630				if_tracing(|tracer| {
1631					let frame_meter = &top_frame!(self).frame_meter;
1632
1633					// we treat the initial frame meter differently to address
1634					// https://github.com/paritytech/polkadot-sdk/issues/8362
1635					let gas_consumed = if is_first_frame {
1636						frame_meter.total_consumed_gas()
1637					} else {
1638						frame_meter.eth_gas_consumed()
1639					};
1640
1641					let gas_consumed: u64 = gas_consumed.try_into().unwrap_or(u64::MAX);
1642					let weight_consumed = frame_meter.weight_consumed();
1643					tracer.exit_child_span_with_error(error.into(), gas_consumed, weight_consumed);
1644				});
1645
1646				(false, Err(error.into()))
1647			},
1648		};
1649		self.with_transient_storage_mut(|transient_storage| {
1650			if success {
1651				transient_storage.commit_transaction();
1652			} else {
1653				transient_storage.rollback_transaction();
1654			}
1655		});
1656		// For the first frame, only log the final metrics since it doesn't open a
1657		// checkpoint. Nested frames commit or roll back the checkpoint they opened.
1658		if is_first_frame {
1659			let m = self.access_list.metrics();
1660			log::trace!(
1661				target: LOG_TARGET,
1662				"access list metrics: size={size} cold={cold} hot={hot}",
1663				size = m.size, cold = m.cold, hot = m.hot,
1664			);
1665		} else if success {
1666			self.access_list.commit_frame();
1667		} else {
1668			self.access_list.rollback_frame();
1669		}
1670		debug_assert_eq!(
1671			self.access_list.frame_depth(),
1672			access_list_checkpoints_len,
1673			"this frame closed exactly the checkpoint it opened",
1674		);
1675		log::trace!(target: LOG_TARGET, "frame finished with: {output:?}");
1676
1677		self.pop_frame(success);
1678		output.map(|output| {
1679			self.top_frame_mut().last_frame_output = output;
1680		})
1681	}
1682
1683	/// Remove the current (top) frame from the stack.
1684	///
1685	/// This is called after running the current frame. It commits cached values to storage
1686	/// and invalidates all stale references to it that might exist further down the call stack.
1687	fn pop_frame(&mut self, persist: bool) {
1688		/// Bank the pending storage diff into the cached `ContractInfo`, then invalidate.
1689		///
1690		/// The `load` covers the case where an earlier same-contract reentry already
1691		/// invalidated this frame; without it a removal-bearing diff would be banked with
1692		/// no info and silently drop the refund pro-rata. A `None` after `load` means the
1693		/// frame is a precompile with no contract info, which has nothing to bank.
1694		fn bank_pending_changes_and_invalidate<T: Config>(f: &mut Frame<T>) {
1695			let contract = f.account_id.clone();
1696			f.contract_info.load(&f.account_id);
1697			if let Some(info) = f.contract_info.as_contract() {
1698				f.frame_meter.bank_pending_storage_changes(contract, info);
1699			}
1700			// `invalidate` drops the in-memory update `bank` made to `info`; that is safe
1701			// because storage already reflects it. Additions and `set_storage` removals leave
1702			// the frame `Cached` (write reloads the cache), so `push_frame` preview-persists
1703			// them before we get here. The only diff not yet in storage would be a removal on
1704			// an already-invalidated frame — reachable solely via `charge_storage`, which has
1705			// no contract-level caller. If that changes, persist here instead of invalidating.
1706			f.contract_info.invalidate();
1707		}
1708
1709		// Pop the current frame from the stack and return it in case it needs to interact
1710		// with duplicates that might exist on the stack.
1711		// A `None` means that we are returning from the `first_frame`.
1712		let frame = self.frames.pop();
1713
1714		// Both branches do essentially the same with the exception. The difference is that
1715		// the else branch does consume the hardcoded `first_frame`.
1716		if let Some(mut frame) = frame {
1717			let account_id = &frame.account_id;
1718			let prev = top_frame_mut!(self);
1719
1720			// Only weight counter changes are persisted in case of a failure.
1721			if !persist {
1722				prev.frame_meter.absorb_weight_meter_only(frame.frame_meter);
1723				return;
1724			}
1725
1726			// Record the storage meter changes of the nested call into the parent meter.
1727			// If the dropped frame's contract has a contract info we update the deposit
1728			// counter in its contract info. The load is necessary to pull it from storage in case
1729			// it was invalidated.
1730			frame.contract_info.load(account_id);
1731			let mut contract = frame.contract_info.into_contract();
1732			prev.frame_meter
1733				.absorb_all_meters(frame.frame_meter, account_id, contract.as_mut());
1734
1735			// only on success inherit the created and to be destroyed contracts
1736			prev.contracts_created.extend(frame.contracts_created);
1737			prev.contracts_to_be_destroyed.extend(frame.contracts_to_be_destroyed);
1738
1739			if let Some(contract) = contract {
1740				// Persist the info and invalidate the first stale cache we find.
1741				// This triggers a reload from storage on next use. Only the first
1742				// cache needs to be invalidated because that one will invalidate the next cache
1743				// when it is popped from the stack.
1744				AccountInfo::<T>::insert_contract(
1745					&T::AddressMapper::to_address(account_id),
1746					contract,
1747				);
1748				if let Some(f) = self.frames_mut().find(|f| f.account_id == *account_id) {
1749					// Bank before invalidating so finalize doesn't apply the diff a second time.
1750					bank_pending_changes_and_invalidate(f);
1751				}
1752			}
1753		} else {
1754			if !persist {
1755				self.transaction_meter
1756					.absorb_weight_meter_only(mem::take(&mut self.first_frame.frame_meter));
1757				return;
1758			}
1759
1760			let mut contract = self.first_frame.contract_info.as_contract();
1761			self.transaction_meter.absorb_all_meters(
1762				mem::take(&mut self.first_frame.frame_meter),
1763				&self.first_frame.account_id,
1764				contract.as_deref_mut(),
1765			);
1766
1767			if let Some(contract) = contract {
1768				AccountInfo::<T>::insert_contract(
1769					&T::AddressMapper::to_address(&self.first_frame.account_id),
1770					contract.clone(),
1771				);
1772			}
1773			// End of the callstack: destroy scheduled contracts in line with EVM semantics.
1774			let contracts_created = mem::take(&mut self.first_frame.contracts_created);
1775			let contracts_to_destroy = mem::take(&mut self.first_frame.contracts_to_be_destroyed);
1776			for (contract_account, args) in contracts_to_destroy {
1777				if args.only_if_same_tx && !contracts_created.contains(&contract_account) {
1778					continue;
1779				}
1780				Self::do_terminate(
1781					&mut self.transaction_meter,
1782					self.exec_config,
1783					&contract_account,
1784					&self.origin,
1785					&args,
1786				)
1787				.ok();
1788			}
1789		}
1790	}
1791
1792	/// Transfer some funds from `from` to `to`.
1793	///
1794	/// This is a no-op for zero `value`, avoiding events to be emitted for zero balance transfers.
1795	///
1796	/// If the destination account does not exist, it is pulled into existence by transferring the
1797	/// ED from `origin` to the new account. The total amount transferred to `to` will be ED +
1798	/// `value`. This makes the ED fully transparent for contracts.
1799	/// The ED transfer is executed atomically with the actual transfer, avoiding the possibility of
1800	/// the ED transfer succeeding but the actual transfer failing. In other words, if the `to` does
1801	/// not exist, the transfer does fail and nothing will be sent to `to` if either `origin` can
1802	/// not provide the ED or transferring `value` from `from` to `to` fails.
1803	/// Note: This will also fail if `origin` is root.
1804	fn transfer<S: State>(
1805		origin: &Origin<T>,
1806		from: &T::AccountId,
1807		to: &T::AccountId,
1808		value: U256,
1809		preservation: Preservation,
1810		meter: &mut ResourceMeter<T, S>,
1811		exec_config: &ExecConfig<T>,
1812	) -> DispatchResult {
1813		let value = BalanceWithDust::<BalanceOf<T>>::from_value::<T>(value)
1814			.map_err(|_| Error::<T>::BalanceConversionFailed)?;
1815		if value.is_zero() {
1816			return Ok(());
1817		}
1818
1819		if <System<T>>::account_exists(to) {
1820			return transfer_with_dust::<T>(from, to, value, preservation);
1821		}
1822
1823		let origin = origin.account_id()?;
1824		let ed = <T as Config>::Currency::minimum_balance();
1825		let is_eth_tx = exec_config.collect_deposit_from_hold.is_some();
1826		with_transaction(|| -> TransactionOutcome<DispatchResult> {
1827			// Meter the ED deposit only after the transfer succeeds: the meter is not rolled
1828			// back, so metering earlier would count an ED for an account never created.
1829			match Ok::<(), DispatchError>(())
1830				.and_then(|_| {
1831					if is_eth_tx {
1832						let credit = T::FeeInfo::withdraw_txfee(ed)
1833							.ok_or(Error::<T>::StorageDepositNotEnoughFunds)?;
1834						T::Currency::resolve(to, credit)
1835							.map_err(|_| Error::<T>::StorageDepositNotEnoughFunds)?;
1836						Ok(())
1837					} else {
1838						T::Currency::transfer(origin, to, ed, Preservation::Preserve)
1839							.map(|_| ())
1840							.map_err(|_| Error::<T>::StorageDepositNotEnoughFunds.into())
1841					}
1842				})
1843				.and_then(|_| transfer_with_dust::<T>(from, to, value, preservation))
1844				.and_then(|_| meter.charge_deposit(&StorageDeposit::Charge(ed)))
1845			{
1846				Ok(_) => TransactionOutcome::Commit(Ok(())),
1847				Err(err) => TransactionOutcome::Rollback(Err(err)),
1848			}
1849		})
1850	}
1851
1852	/// Same as `transfer` but `from` is an `Origin`.
1853	fn transfer_from_origin<S: State>(
1854		origin: &Origin<T>,
1855		from: &Origin<T>,
1856		to: &T::AccountId,
1857		value: U256,
1858		meter: &mut ResourceMeter<T, S>,
1859		exec_config: &ExecConfig<T>,
1860	) -> ExecResult {
1861		// If the from address is root there is no account to transfer from, and therefore we can't
1862		// take any `value` other than 0.
1863		let from = match from {
1864			Origin::Signed(caller) => caller,
1865			Origin::Root if value.is_zero() => return Ok(Default::default()),
1866			Origin::Root => return Err(DispatchError::RootNotAllowed.into()),
1867		};
1868		Self::transfer(origin, from, to, value, Preservation::Preserve, meter, exec_config)
1869			.map(|_| Default::default())
1870			.map_err(Into::into)
1871	}
1872
1873	/// Performs the actual deletion of a contract at the end of a call stack.
1874	fn do_terminate(
1875		transaction_meter: &mut TransactionMeter<T>,
1876		exec_config: &ExecConfig<T>,
1877		contract_account: &T::AccountId,
1878		origin: &Origin<T>,
1879		args: &TerminateArgs<T>,
1880	) -> Result<(), DispatchError> {
1881		let contract_address = T::AddressMapper::to_address(contract_account);
1882
1883		// If root created this contract we need to use the pallet account_id because root has no
1884		// account.
1885		let origin: Origin<T> = match origin {
1886			Origin::Signed(o) => Origin::Signed(o.clone()),
1887			Origin::Root => Origin::from_account_id(crate::Pallet::<T>::account_id()),
1888		};
1889
1890		let mut delete_contract = |trie_id: &TrieId, code_hash: &H256| {
1891			// deposit needs to be removed as it adds a consumer
1892			let refund =
1893				T::Deposit::refund_all(&contract_account, exec_config.funds(origin.account_id()?))?;
1894
1895			// we added this consumer manually when instantiating
1896			System::<T>::dec_consumers(&contract_account);
1897
1898			// ED was minted when the account was brought into existence; burn it now.
1899			T::Deposit::destroy_contract(contract_account)?;
1900
1901			// this is needed to:
1902			// 1) Send any balance that was send to the contract after termination.
1903			// 2) To fail termination if any locks or holds prevent to completely empty the account.
1904			let balance = <Contracts<T>>::convert_native_to_evm(<AccountInfo<T>>::total_balance(
1905				contract_address.into(),
1906			));
1907			Self::transfer(
1908				&origin,
1909				contract_account,
1910				&args.beneficiary,
1911				balance,
1912				Preservation::Expendable,
1913				transaction_meter,
1914				exec_config,
1915			)?;
1916
1917			// this deletes the code if refcount drops to zero
1918			let _code_removed = <CodeInfo<T>>::decrement_refcount(*code_hash)?;
1919
1920			// delete the contracts data last as its infallible
1921			ContractInfo::<T>::queue_for_deletion(trie_id.clone(), contract_account.clone());
1922			AccountInfoOf::<T>::remove(contract_address);
1923			ImmutableDataOf::<T>::remove(contract_address);
1924
1925			// the meter needs to discard all deposits interacting with the terminated contract
1926			// we do this last as we cannot roll this back
1927			transaction_meter.terminate(contract_account.clone(), refund);
1928
1929			Ok(())
1930		};
1931
1932		// we cannot fail here as the contract that called `SELFDESTRUCT`
1933		// is no longer on the call stack. hence we simply roll back the
1934		// termination so that nothing happened.
1935		with_transaction(|| -> TransactionOutcome<Result<_, DispatchError>> {
1936			match delete_contract(&args.trie_id, &args.code_hash) {
1937				Ok(()) => {
1938					log::trace!(target: LOG_TARGET, "Terminated {contract_address:?}");
1939					TransactionOutcome::Commit(Ok(()))
1940				},
1941				Err(e) => {
1942					log::debug!(target: LOG_TARGET, "Contract at {contract_address:?} failed to terminate: {e:?}");
1943					TransactionOutcome::Rollback(Err(e))
1944				},
1945			}
1946		})
1947	}
1948
1949	/// Reference to the current (top) frame.
1950	fn top_frame(&self) -> &Frame<T> {
1951		top_frame!(self)
1952	}
1953
1954	/// Mutable reference to the current (top) frame.
1955	fn top_frame_mut(&mut self) -> &mut Frame<T> {
1956		top_frame_mut!(self)
1957	}
1958
1959	/// Iterator over all frames.
1960	///
1961	/// The iterator starts with the top frame and ends with the root frame.
1962	fn frames(&self) -> impl Iterator<Item = &Frame<T>> {
1963		core::iter::once(&self.first_frame).chain(&self.frames).rev()
1964	}
1965
1966	/// Same as `frames` but with a mutable reference as iterator item.
1967	fn frames_mut(&mut self) -> impl Iterator<Item = &mut Frame<T>> {
1968		core::iter::once(&mut self.first_frame).chain(&mut self.frames).rev()
1969	}
1970
1971	/// Returns whether the specified contract allows to be reentered right now.
1972	fn allows_reentry(&self, id: &T::AccountId) -> bool {
1973		!self.frames().any(|f| &f.account_id == id && !f.allows_reentry)
1974	}
1975
1976	/// Returns the *free* balance of the supplied AccountId.
1977	fn account_balance(&self, who: &T::AccountId) -> U256 {
1978		let balance = AccountInfo::<T>::balance_of(AccountIdOrAddress::AccountId(who.clone()));
1979		crate::Pallet::<T>::convert_native_to_evm(balance)
1980	}
1981
1982	/// Certain APIs, e.g. `{set,get}_immutable_data` behave differently depending
1983	/// on the configured entry point. Thus, we allow setting the export manually.
1984	#[cfg(feature = "runtime-benchmarks")]
1985	pub(crate) fn override_export(&mut self, export: ExportedFunction) {
1986		self.top_frame_mut().entry_point = export;
1987	}
1988
1989	#[cfg(feature = "runtime-benchmarks")]
1990	pub(crate) fn set_block_number(&mut self, block_number: BlockNumberFor<T>) {
1991		self.block_number = block_number;
1992	}
1993
1994	fn block_hash(&self, block_number: U256) -> Option<H256> {
1995		let Ok(block_number) = BlockNumberFor::<T>::try_from(block_number) else {
1996			return None;
1997		};
1998		if block_number >= self.block_number {
1999			return None;
2000		}
2001		if block_number < self.block_number.saturating_sub(256u32.into()) {
2002			return None;
2003		}
2004
2005		// Fallback to the system block hash for older blocks
2006		// 256 entries should suffice for all use cases, this mostly ensures
2007		// our benchmarks are passing.
2008		match crate::Pallet::<T>::eth_block_hash_from_number(block_number.into()) {
2009			Some(hash) => Some(hash),
2010			None => {
2011				use codec::Decode;
2012				let block_hash = System::<T>::block_hash(&block_number);
2013				Decode::decode(&mut TrailingZeroInput::new(block_hash.as_ref())).ok()
2014			},
2015		}
2016	}
2017
2018	/// Returns true if the current context has contract info.
2019	/// This is the case if `no_precompile || precompile_with_info`.
2020	fn has_contract_info(&self) -> bool {
2021		let address = self.address();
2022		let precompile = <AllPrecompiles<T>>::get::<Stack<'_, T, E>>(address.as_fixed_bytes());
2023		if let Some(precompile) = precompile {
2024			return precompile.has_contract_info();
2025		}
2026		true
2027	}
2028
2029	fn with_transient_storage_mut<R, F: FnOnce(&mut TransientStorage<T>) -> R>(
2030		&mut self,
2031		f: F,
2032	) -> R {
2033		if let Some(transient) = &self.exec_config.test_env_transient_storage {
2034			f(&mut transient.borrow_mut())
2035		} else {
2036			f(&mut self.transient_storage)
2037		}
2038	}
2039	fn with_transient_storage<R, F: FnOnce(&TransientStorage<T>) -> R>(&self, f: F) -> R {
2040		if let Some(transient) = &self.exec_config.test_env_transient_storage {
2041			f(&transient.borrow())
2042		} else {
2043			f(&self.transient_storage)
2044		}
2045	}
2046}
2047
2048impl<'a, T, E> Ext for Stack<'a, T, E>
2049where
2050	T: Config,
2051	E: Executable<T>,
2052{
2053	fn delegate_call(
2054		&mut self,
2055		call_resources: &CallResources<T>,
2056		address: H160,
2057		input_data: Vec<u8>,
2058	) -> Result<(), ExecError> {
2059		// We reset the return data now, so it is cleared out even if no new frame was executed.
2060		// This is for example the case for unknown code hashes or creating the frame fails.
2061		*self.last_frame_output_mut() = Default::default();
2062
2063		let top_frame = self.top_frame_mut();
2064		// Clone the contract info and apply pending storage changes so that
2065		// the child frame can correctly calculate storage deposit refunds.
2066		// See: <https://github.com/paritytech/contract-issues/issues/213>
2067		let mut contract_info = top_frame.contract_info().clone();
2068		top_frame.frame_meter.apply_pending_storage_changes(&mut contract_info);
2069		let account_id = top_frame.account_id.clone();
2070		let value = top_frame.value_transferred;
2071		if let Some(executable) = self.push_frame(
2072			FrameArgs::Call {
2073				dest: account_id,
2074				cached_info: Some(contract_info),
2075				delegated_call: Some(DelegateInfo {
2076					caller: self.caller().clone(),
2077					callee: address,
2078				}),
2079			},
2080			value,
2081			call_resources,
2082			self.is_read_only(),
2083			&input_data,
2084		)? {
2085			self.run(executable, input_data)
2086		} else {
2087			// Delegate-calls to non-contract accounts are considered success.
2088			Ok(())
2089		}
2090	}
2091
2092	fn terminate_if_same_tx(&mut self, beneficiary: &H160) -> Result<CodeRemoved, DispatchError> {
2093		if_tracing(|tracer| {
2094			let addr = T::AddressMapper::to_address(self.account_id());
2095			tracer.terminate(
2096				addr,
2097				*beneficiary,
2098				self.top_frame()
2099					.frame_meter
2100					.eth_gas_left()
2101					.unwrap_or_default()
2102					.try_into()
2103					.unwrap_or_default(),
2104				crate::Pallet::<T>::evm_balance(&addr),
2105			);
2106		});
2107		let frame = top_frame_mut!(self);
2108		let info = frame.contract_info();
2109		let trie_id = info.trie_id.clone();
2110		let code_hash = info.code_hash;
2111		let contract_address = T::AddressMapper::to_address(&frame.account_id);
2112		let beneficiary = T::AddressMapper::to_account_id(beneficiary);
2113
2114		// balance transfer is immediate
2115		Self::transfer(
2116			&self.origin,
2117			&frame.account_id,
2118			&beneficiary,
2119			<Contracts<T>>::evm_balance(&contract_address),
2120			Preservation::Preserve,
2121			&mut frame.frame_meter,
2122			self.exec_config,
2123		)?;
2124
2125		// schedule for delayed deletion
2126		let account_id = frame.account_id.clone();
2127		self.top_frame_mut().contracts_to_be_destroyed.insert(
2128			account_id,
2129			TerminateArgs { beneficiary, trie_id, code_hash, only_if_same_tx: true },
2130		);
2131		Ok(CodeRemoved::Yes)
2132	}
2133
2134	fn own_code_hash(&mut self) -> &H256 {
2135		&self.top_frame_mut().contract_info().code_hash
2136	}
2137
2138	fn immutable_data_len(&mut self) -> u32 {
2139		let frame = self.top_frame_mut();
2140		if frame.code_address == T::AddressMapper::to_address(&frame.account_id) {
2141			frame.contract_info().immutable_data_len()
2142		} else {
2143			limits::IMMUTABLE_BYTES
2144		}
2145	}
2146
2147	fn get_immutable_data(&mut self) -> Result<ImmutableData, DispatchError> {
2148		if self.top_frame().entry_point == ExportedFunction::Constructor {
2149			return Err(Error::<T>::InvalidImmutableAccess.into());
2150		}
2151
2152		// Immutable data is read from the address where the code originates.
2153		// This handles regular contracts, delegated accounts (EIP-7702), and delegate_call.
2154		let address = self.top_frame().code_address;
2155		Ok(<ImmutableDataOf<T>>::get(address).ok_or_else(|| Error::<T>::InvalidImmutableAccess)?)
2156	}
2157
2158	fn set_immutable_data(&mut self, data: ImmutableData) -> Result<(), DispatchError> {
2159		let frame = self.top_frame_mut();
2160		if frame.entry_point == ExportedFunction::Call || data.is_empty() {
2161			return Err(Error::<T>::InvalidImmutableAccess.into());
2162		}
2163		frame.contract_info().set_immutable_data_len(data.len() as u32);
2164		<ImmutableDataOf<T>>::insert(T::AddressMapper::to_address(&frame.account_id), &data);
2165		Ok(())
2166	}
2167}
2168
2169impl<'a, T, E> PrecompileWithInfoExt for Stack<'a, T, E>
2170where
2171	T: Config,
2172	E: Executable<T>,
2173{
2174	fn instantiate(
2175		&mut self,
2176		call_resources: &CallResources<T>,
2177		mut code: Code,
2178		value: U256,
2179		input_data: Vec<u8>,
2180		salt: Option<&[u8; 32]>,
2181	) -> Result<H160, ExecError> {
2182		// We reset the return data now, so it is cleared out even if no new frame was executed.
2183		// This is for example the case when creating the frame fails.
2184		*self.last_frame_output_mut() = Default::default();
2185
2186		let sender = self.top_frame().account_id.clone();
2187		let executable = {
2188			let executable = match &mut code {
2189				Code::Upload(initcode) => {
2190					if !T::AllowEVMBytecode::get() {
2191						return Err(<Error<T>>::CodeRejected.into());
2192					}
2193					ensure!(input_data.is_empty(), <Error<T>>::EvmConstructorNonEmptyData);
2194					let initcode = crate::tracing::if_tracing(|_| initcode.clone())
2195						.unwrap_or_else(|| mem::take(initcode));
2196					E::from_evm_init_code(initcode, sender.clone())?
2197				},
2198				Code::Existing(hash) => {
2199					let executable = E::from_storage(*hash, self.frame_meter_mut())?;
2200					ensure!(executable.code_info().is_pvm(), <Error<T>>::EvmConstructedFromHash);
2201					executable
2202				},
2203			};
2204			self.push_frame(
2205				FrameArgs::Instantiate {
2206					sender,
2207					executable,
2208					salt,
2209					input_data: input_data.as_ref(),
2210				},
2211				value,
2212				call_resources,
2213				self.is_read_only(),
2214				&input_data,
2215			)?
2216		};
2217		let executable = executable.expect(FRAME_ALWAYS_EXISTS_ON_INSTANTIATE);
2218
2219		// Mark the contract as created in this tx.
2220		let account_id = self.top_frame().account_id.clone();
2221		self.top_frame_mut().contracts_created.insert(account_id);
2222
2223		let address = T::AddressMapper::to_address(&self.top_frame().account_id);
2224		if_tracing(|t| t.instantiate_code(&code, salt));
2225		self.run(executable, input_data).map(|_| address)
2226	}
2227}
2228
2229impl<'a, T, E> PrecompileExt for Stack<'a, T, E>
2230where
2231	T: Config,
2232	E: Executable<T>,
2233{
2234	type T = T;
2235
2236	fn call(
2237		&mut self,
2238		call_resources: &CallResources<T>,
2239		dest_addr: &H160,
2240		value: U256,
2241		input_data: Vec<u8>,
2242		allows_reentry: ReentrancyProtection,
2243		read_only: bool,
2244	) -> Result<(), ExecError> {
2245		// We reset the return data now, so it is cleared out even if no new frame was executed.
2246		// This is for example the case for balance transfers or when creating the frame fails.
2247		*self.last_frame_output_mut() = Default::default();
2248
2249		// Before pushing the new frame: Protect the caller contract against reentrancy attacks.
2250		// It is important to do this before calling `allows_reentry` so that a direct recursion
2251		// is caught by it.
2252
2253		if allows_reentry == ReentrancyProtection::Strict {
2254			self.top_frame_mut().allows_reentry = false;
2255		}
2256
2257		let try_call = || {
2258			// Enable read-only access if requested; cannot disable it if already set.
2259			let is_read_only = read_only || self.is_read_only();
2260
2261			// We can skip the stateful lookup for pre-compiles.
2262			let dest = if <AllPrecompiles<T>>::get::<Self>(dest_addr.as_fixed_bytes()).is_some() {
2263				T::AddressMapper::to_fallback_account_id(dest_addr)
2264			} else {
2265				T::AddressMapper::to_account_id(dest_addr)
2266			};
2267
2268			if !self.allows_reentry(&dest) {
2269				return Err(<Error<T>>::ReentranceDenied.into());
2270			}
2271
2272			if allows_reentry == ReentrancyProtection::AllowNext {
2273				self.top_frame_mut().allows_reentry = false;
2274			}
2275
2276			// We ignore instantiate frames in our search for a cached contract.
2277			// Otherwise it would be possible to recursively call a contract from its own
2278			// constructor: We disallow calling not fully constructed contracts.
2279			//
2280			// When cloning the cached contract, we apply pending storage changes so that
2281			// the child frame can correctly calculate storage deposit refunds.
2282			// See: <https://github.com/paritytech/contract-issues/issues/213>
2283			let cached_info = self
2284				.frames()
2285				.find(|f| f.entry_point == ExportedFunction::Call && f.account_id == dest)
2286				.and_then(|f| match &f.contract_info {
2287					CachedContract::Cached(contract) => {
2288						let mut contract_with_pending = contract.clone();
2289						f.frame_meter.apply_pending_storage_changes(&mut contract_with_pending);
2290						Some(contract_with_pending)
2291					},
2292					_ => None,
2293				});
2294
2295			if let Some(executable) = self.push_frame(
2296				FrameArgs::Call { dest: dest.clone(), cached_info, delegated_call: None },
2297				value,
2298				call_resources,
2299				is_read_only,
2300				&input_data,
2301			)? {
2302				self.run(executable, input_data)
2303			} else {
2304				if_tracing(|t| {
2305					t.enter_child_span(
2306						T::AddressMapper::to_address(self.account_id()),
2307						T::AddressMapper::to_address(&dest),
2308						None,
2309						false,
2310						is_read_only,
2311						value,
2312						&input_data,
2313						Default::default(),
2314					);
2315				});
2316
2317				let snapshot = if_tracing(|_| top_frame!(self).frame_meter.snapshot());
2318
2319				let result = if let Some(mock_answer) =
2320					self.exec_config.mock_handler.as_ref().and_then(|handler| {
2321						handler.mock_call(T::AddressMapper::to_address(&dest), &input_data, value)
2322					}) {
2323					*self.last_frame_output_mut() = mock_answer.clone();
2324					Ok(mock_answer)
2325				} else if is_read_only && value.is_zero() {
2326					Ok(Default::default())
2327				} else if is_read_only {
2328					Err(Error::<T>::StateChangeDenied.into())
2329				} else {
2330					let account_id = self.account_id().clone();
2331					let frame = top_frame_mut!(self);
2332					Self::transfer_from_origin(
2333						&self.origin,
2334						&Origin::from_account_id(account_id),
2335						&dest,
2336						value,
2337						&mut frame.frame_meter,
2338						self.exec_config,
2339					)
2340				};
2341
2342				if_tracing(|t| {
2343					let snapshot = snapshot.as_ref().expect(
2344						"snapshot is taken inside if_tracing above; tracing state cannot \
2345						 change mid-call, so it is Some whenever this closure runs; qed",
2346					);
2347					let (gas_used, weight_delta) =
2348						top_frame!(self).frame_meter.delta_since(snapshot);
2349					match result {
2350						Ok(ref output) => t.exit_child_span(&output, gas_used, weight_delta),
2351						Err(e) => {
2352							t.exit_child_span_with_error(e.error.into(), gas_used, weight_delta)
2353						},
2354					}
2355				});
2356
2357				result.map(|_| ())
2358			}
2359		};
2360
2361		// We need to make sure to reset `allows_reentry` even on failure.
2362		let result = try_call();
2363
2364		// Protection is on a per call basis.
2365		self.top_frame_mut().allows_reentry = true;
2366
2367		result
2368	}
2369
2370	fn get_transient_storage(&self, key: &Key) -> Option<Vec<u8>> {
2371		self.with_transient_storage(|transient_storage| {
2372			transient_storage.read(self.account_id(), key)
2373		})
2374	}
2375
2376	fn get_transient_storage_size(&self, key: &Key) -> Option<u32> {
2377		self.with_transient_storage(|transient_storage| {
2378			transient_storage.read(self.account_id(), key).map(|value| value.len() as _)
2379		})
2380	}
2381
2382	fn set_transient_storage(
2383		&mut self,
2384		key: &Key,
2385		value: Option<Vec<u8>>,
2386		take_old: bool,
2387	) -> Result<WriteOutcome, DispatchError> {
2388		let account_id = self.account_id().clone();
2389		self.with_transient_storage_mut(|transient_storage| {
2390			transient_storage.write(&account_id, key, value, take_old)
2391		})
2392	}
2393
2394	fn account_id(&self) -> &T::AccountId {
2395		&self.top_frame().account_id
2396	}
2397
2398	fn caller(&self) -> Origin<T> {
2399		if let Some(Ok(mock_caller)) = self
2400			.exec_config
2401			.mock_handler
2402			.as_ref()
2403			.and_then(|mock_handler| mock_handler.mock_caller(self.frames.len()))
2404			.map(|mock_caller| Origin::<T>::from_runtime_origin(mock_caller))
2405		{
2406			return mock_caller;
2407		}
2408
2409		if let Some(DelegateInfo { caller, .. }) = &self.top_frame().delegate {
2410			caller.clone()
2411		} else {
2412			self.frames()
2413				.nth(1)
2414				.map(|f| Origin::from_account_id(f.account_id.clone()))
2415				.unwrap_or(self.origin.clone())
2416		}
2417	}
2418
2419	fn caller_of_caller(&self) -> Origin<T> {
2420		// fetch top frame of top frame
2421		let caller_of_caller_frame = match self.frames().nth(2) {
2422			None => return self.origin.clone(),
2423			Some(frame) => frame,
2424		};
2425		if let Some(DelegateInfo { caller, .. }) = &caller_of_caller_frame.delegate {
2426			caller.clone()
2427		} else {
2428			Origin::from_account_id(caller_of_caller_frame.account_id.clone())
2429		}
2430	}
2431
2432	fn origin(&self) -> &Origin<T> {
2433		if let Some(mock_origin) = self
2434			.exec_config
2435			.mock_handler
2436			.as_ref()
2437			.and_then(|mock_handler| mock_handler.mock_origin())
2438		{
2439			return mock_origin;
2440		}
2441
2442		&self.origin
2443	}
2444
2445	fn to_account_id(&self, address: &H160) -> T::AccountId {
2446		T::AddressMapper::to_account_id(address)
2447	}
2448
2449	fn code_hash(&self, address: &H160) -> H256 {
2450		if let Some(code) = <AllPrecompiles<T>>::code(address.as_fixed_bytes()).or_else(|| {
2451			self.exec_config
2452				.mock_handler
2453				.as_ref()
2454				.and_then(|handler| handler.mocked_code(*address))
2455		}) {
2456			return sp_io::hashing::keccak_256(code).into();
2457		}
2458
2459		// EIP-7702: delegated EOAs return keccak256(0xef0100 || target). This is the
2460		// EXTCODEHASH path; CODEHASH (self) uses the separate `own_code_hash` host
2461		// function and is therefore unaffected.
2462		if let Some(target) = <AccountInfo<T>>::get_delegation_target(address) {
2463			let indicator = <AccountInfo<T>>::delegation_indicator(&target);
2464			return sp_io::hashing::keccak_256(&indicator).into();
2465		}
2466
2467		<AccountInfo<T>>::load_contract(&address)
2468			.map(|contract| contract.code_hash)
2469			.unwrap_or_else(|| {
2470				if System::<T>::account_exists(&T::AddressMapper::to_account_id(address)) {
2471					return EMPTY_CODE_HASH;
2472				}
2473				H256::zero()
2474			})
2475	}
2476
2477	fn code_size(&self, address: &H160) -> u64 {
2478		if let Some(code) = <AllPrecompiles<T>>::code(address.as_fixed_bytes()).or_else(|| {
2479			self.exec_config
2480				.mock_handler
2481				.as_ref()
2482				.and_then(|handler| handler.mocked_code(*address))
2483		}) {
2484			return code.len() as u64;
2485		}
2486
2487		// EIP-7702: delegated EOAs return the delegation indicator size (23 bytes).
2488		//
2489		// PVM caveat: on PolkaVM, EXTCODESIZE and CODESIZE both lower to this
2490		// host function, so this branch is reached for both. It is spec-correct
2491		// for EXTCODESIZE but wrong for CODESIZE inside a delegated EOA's
2492		// execution — the executing code there is the target's PVM blob, whose
2493		// size is not 23. Spec-correct CODESIZE requires a separate host
2494		// function and a matching resolc change; tracked as a follow-up.
2495		if <AccountInfo<T>>::is_delegated(address) {
2496			return 23;
2497		}
2498
2499		<AccountInfo<T>>::load_contract(&address)
2500			.and_then(|contract| CodeInfoOf::<T>::get(contract.code_hash))
2501			.map(|info| info.code_len())
2502			.unwrap_or_default()
2503	}
2504
2505	fn caller_is_origin(&self, use_caller_of_caller: bool) -> bool {
2506		let caller = if use_caller_of_caller { self.caller_of_caller() } else { self.caller() };
2507		self.origin == caller
2508	}
2509
2510	fn caller_is_root(&self, use_caller_of_caller: bool) -> bool {
2511		// if the caller isn't origin, then it can't be root.
2512		self.caller_is_origin(use_caller_of_caller) && self.origin == Origin::Root
2513	}
2514
2515	fn origin_is_root(&self) -> bool {
2516		self.origin == Origin::Root
2517	}
2518
2519	fn balance(&self) -> U256 {
2520		self.account_balance(&self.top_frame().account_id)
2521	}
2522
2523	fn balance_of(&self, address: &H160) -> U256 {
2524		let balance =
2525			self.account_balance(&<Self::T as Config>::AddressMapper::to_account_id(address));
2526		if_tracing(|tracer| {
2527			tracer.balance_read(address, balance);
2528		});
2529		balance
2530	}
2531
2532	fn value_transferred(&self) -> U256 {
2533		self.top_frame().value_transferred.into()
2534	}
2535
2536	fn now(&self) -> U256 {
2537		(self.timestamp / 1000u32.into()).into()
2538	}
2539
2540	fn minimum_balance(&self) -> U256 {
2541		let min = T::Currency::minimum_balance();
2542		crate::Pallet::<T>::convert_native_to_evm(min)
2543	}
2544
2545	fn deposit_event(&mut self, topics: Vec<H256>, data: Vec<u8>) {
2546		let contract = T::AddressMapper::to_address(self.account_id());
2547		if_tracing(|tracer| {
2548			let log_index = frame_system::Pallet::<Self::T>::event_count();
2549			tracer.log_event(contract, &topics, &data, log_index);
2550		});
2551
2552		// Capture the log only if it is generated by an Ethereum transaction.
2553		block_storage::capture_ethereum_log(&contract, &data, &topics);
2554
2555		Contracts::<Self::T>::deposit_event(Event::ContractEmitted { contract, data, topics });
2556	}
2557
2558	fn block_number(&self) -> U256 {
2559		self.block_number.into()
2560	}
2561
2562	fn block_hash(&self, block_number: U256) -> Option<H256> {
2563		self.block_hash(block_number)
2564	}
2565
2566	fn block_author(&self) -> H160 {
2567		Contracts::<Self::T>::block_author()
2568	}
2569
2570	fn gas_limit(&self) -> u64 {
2571		<Contracts<T>>::evm_block_gas_limit().saturated_into()
2572	}
2573
2574	fn chain_id(&self) -> u64 {
2575		<T as Config>::ChainId::get()
2576	}
2577
2578	fn gas_meter(&self) -> &FrameMeter<Self::T> {
2579		&self.top_frame().frame_meter
2580	}
2581
2582	#[inline]
2583	fn gas_meter_mut(&mut self) -> &mut FrameMeter<Self::T> {
2584		&mut self.top_frame_mut().frame_meter
2585	}
2586
2587	fn frame_meter(&self) -> &FrameMeter<Self::T> {
2588		&self.top_frame().frame_meter
2589	}
2590
2591	#[inline]
2592	fn frame_meter_mut(&mut self) -> &mut FrameMeter<Self::T> {
2593		&mut self.top_frame_mut().frame_meter
2594	}
2595
2596	fn ecdsa_recover(&self, signature: &[u8; 65], message_hash: &[u8; 32]) -> Result<[u8; 33], ()> {
2597		secp256k1_ecdsa_recover_compressed(signature, message_hash).map_err(|_| ())
2598	}
2599
2600	fn sr25519_verify(&self, signature: &[u8; 64], message: &[u8], pub_key: &[u8; 32]) -> bool {
2601		sp_io::crypto::sr25519_verify(
2602			&SR25519Signature::from(*signature),
2603			message,
2604			&SR25519Public::from(*pub_key),
2605		)
2606	}
2607
2608	fn ecdsa_to_eth_address(&self, pk: &[u8; 33]) -> Result<[u8; 20], DispatchError> {
2609		Ok(ECDSAPublic::from(*pk)
2610			.to_eth_address()
2611			.or_else(|()| Err(Error::<T>::EcdsaRecoveryFailed))?)
2612	}
2613
2614	#[cfg(any(test, feature = "runtime-benchmarks"))]
2615	fn contract_info(&mut self) -> &mut ContractInfo<Self::T> {
2616		self.top_frame_mut().contract_info()
2617	}
2618
2619	#[cfg(any(feature = "runtime-benchmarks", test))]
2620	fn transient_storage(&mut self) -> &mut TransientStorage<Self::T> {
2621		&mut self.transient_storage
2622	}
2623
2624	fn is_read_only(&self) -> bool {
2625		self.top_frame().read_only
2626	}
2627
2628	fn is_delegate_call(&self) -> bool {
2629		self.top_frame().delegate.is_some()
2630	}
2631
2632	fn last_frame_output(&self) -> &ExecReturnValue {
2633		&self.top_frame().last_frame_output
2634	}
2635
2636	fn last_frame_output_mut(&mut self) -> &mut ExecReturnValue {
2637		&mut self.top_frame_mut().last_frame_output
2638	}
2639
2640	fn copy_code_slice(&mut self, buf: &mut [u8], address: &H160, code_offset: usize) {
2641		let len = buf.len();
2642		if len == 0 {
2643			return;
2644		}
2645
2646		let code = if let Some(code) =
2647			<AllPrecompiles<T>>::code(address.as_fixed_bytes()).or_else(|| {
2648				self.exec_config
2649					.mock_handler
2650					.as_ref()
2651					.and_then(|handler| handler.mocked_code(*address))
2652			}) {
2653			code.to_vec()
2654		} else if let Some(target) = <AccountInfo<T>>::get_delegation_target(address) {
2655			// EIP-7702: delegated EOAs return 0xef0100 || target as their code.
2656			//
2657			// PVM caveat: on PolkaVM, EXTCODECOPY and CODECOPY both lower to this
2658			// host function, so this branch is reached for both. It is spec-correct
2659			// for EXTCODECOPY but wrong for CODECOPY inside a delegated EOA's
2660			// execution — the executing code there is the target's PVM blob, not
2661			// the 23-byte indicator. Spec-correct CODECOPY requires a separate
2662			// host function and a matching resolc change; tracked as a follow-up.
2663			<AccountInfo<T>>::delegation_indicator(&target).to_vec()
2664		} else {
2665			let code_hash = self.code_hash(address);
2666			crate::PristineCode::<T>::get(&code_hash).unwrap_or_default()
2667		};
2668
2669		let copy_len = len.min(code.len().saturating_sub(code_offset));
2670		if copy_len > 0 {
2671			buf[..copy_len].copy_from_slice(&code[code_offset..code_offset + copy_len]);
2672		}
2673		buf[copy_len..].fill(0);
2674	}
2675
2676	fn terminate_caller(&mut self, beneficiary: &H160) -> Result<(), DispatchError> {
2677		ensure!(self.top_frame().delegate.is_none(), Error::<T>::PrecompileDelegateDenied);
2678		let parent = self.frames_mut().nth(1).ok_or_else(|| Error::<T>::ContractNotFound)?;
2679		ensure!(parent.entry_point == ExportedFunction::Call, Error::<T>::TerminatedInConstructor);
2680		ensure!(parent.delegate.is_none(), Error::<T>::PrecompileDelegateDenied);
2681
2682		let contract_address = T::AddressMapper::to_address(&parent.account_id);
2683
2684		// EIP-7702: delegated EOAs cannot be destroyed via the system precompile.
2685		ensure!(
2686			!AccountInfo::<T>::is_delegated(&contract_address),
2687			Error::<T>::CannotTerminateDelegatedAccount,
2688		);
2689
2690		let info = parent.contract_info();
2691		let trie_id = info.trie_id.clone();
2692		let code_hash = info.code_hash;
2693		let beneficiary = T::AddressMapper::to_account_id(beneficiary);
2694
2695		let parent_account_id = parent.account_id.clone();
2696
2697		// balance transfer is immediate
2698		Self::transfer(
2699			&self.origin,
2700			&parent_account_id,
2701			&beneficiary,
2702			<Contracts<T>>::evm_balance(&contract_address),
2703			Preservation::Preserve,
2704			&mut top_frame_mut!(self).frame_meter,
2705			&self.exec_config,
2706		)?;
2707
2708		// schedule for delayed deletion
2709		let args = TerminateArgs { beneficiary, trie_id, code_hash, only_if_same_tx: false };
2710		self.top_frame_mut().contracts_to_be_destroyed.insert(parent_account_id, args);
2711
2712		Ok(())
2713	}
2714
2715	fn effective_gas_price(&self) -> U256 {
2716		self.exec_config
2717			.effective_gas_price
2718			.unwrap_or_else(|| <Contracts<T>>::evm_base_fee())
2719	}
2720
2721	fn gas_left(&self) -> u64 {
2722		let frame = self.top_frame();
2723
2724		frame.frame_meter.eth_gas_left().unwrap_or_default().saturated_into::<u64>()
2725	}
2726
2727	fn get_storage(&mut self, key: &Key) -> Option<Vec<u8>> {
2728		assert!(self.has_contract_info());
2729		self.top_frame_mut().contract_info().read(key)
2730	}
2731
2732	fn get_storage_size(&mut self, key: &Key) -> Option<u32> {
2733		assert!(self.has_contract_info());
2734		self.top_frame_mut().contract_info().size(key.into())
2735	}
2736
2737	fn set_storage(
2738		&mut self,
2739		key: &Key,
2740		value: Option<Vec<u8>>,
2741		take_old: bool,
2742	) -> Result<WriteOutcome, DispatchError> {
2743		assert!(self.has_contract_info());
2744		let frame = self.top_frame_mut();
2745		frame.contract_info.get(&frame.account_id).write(
2746			key.into(),
2747			value,
2748			Some(&mut frame.frame_meter),
2749			take_old,
2750		)
2751	}
2752
2753	fn touch_storage_access(&mut self, key: &Key, op: StorageOp) -> Warmth {
2754		let address = self.address();
2755		self.access_list.touch(AccessEntry { address, slot: key.into() }, op)
2756	}
2757
2758	fn peek_storage_access(&self, key: &Key) -> Warmth {
2759		let address = self.address();
2760		self.access_list.peek(&AccessEntry { address, slot: key.into() })
2761	}
2762
2763	fn charge_storage(&mut self, diff: &Diff) -> DispatchResult {
2764		assert!(self.has_contract_info());
2765		self.top_frame_mut().frame_meter.record_contract_storage_changes(diff)
2766	}
2767}
2768
2769/// Returns true if the address has a precompile contract, else false.
2770pub fn is_precompile<T: Config, E: Executable<T>>(address: &H160) -> bool {
2771	<AllPrecompiles<T>>::get::<Stack<'_, T, E>>(address.as_fixed_bytes()).is_some()
2772}
2773
2774#[cfg(feature = "runtime-benchmarks")]
2775pub fn bench_do_terminate<T: Config>(
2776	transaction_meter: &mut TransactionMeter<T>,
2777	exec_config: &ExecConfig<T>,
2778	contract_account: &T::AccountId,
2779	origin: &Origin<T>,
2780	beneficiary: T::AccountId,
2781	trie_id: TrieId,
2782	code_hash: H256,
2783	only_if_same_tx: bool,
2784) -> Result<(), DispatchError> {
2785	Stack::<T, crate::ContractBlob<T>>::do_terminate(
2786		transaction_meter,
2787		exec_config,
2788		contract_account,
2789		origin,
2790		&TerminateArgs { beneficiary, trie_id, code_hash, only_if_same_tx },
2791	)
2792}
2793
2794mod sealing {
2795	use super::*;
2796
2797	pub trait Sealed {}
2798	impl<'a, T: Config, E> Sealed for Stack<'a, T, E> {}
2799
2800	#[cfg(test)]
2801	impl<T: Config> sealing::Sealed for mock_ext::MockExt<T> {}
2802}