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