1use 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
79type 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
84pub const EMPTY_CODE_HASH: H256 =
86 H256(sp_core::hex2array!("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470"));
87
88#[derive(Debug)]
90pub enum Key {
91 Fix([u8; 32]),
93 Var(VarSizedKey),
95}
96
97impl Key {
98 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 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#[derive(Copy, Clone, PartialEq, Debug)]
129pub enum ReentrancyProtection {
130 AllowReentry,
132 Strict,
135 AllowNext,
143}
144
145#[derive(Copy, Clone, PartialEq, Eq, Debug, codec::Decode, codec::Encode)]
151pub enum ErrorOrigin {
152 Caller,
157 Callee,
159}
160
161#[derive(Copy, Clone, PartialEq, Eq, Debug, codec::Decode, codec::Encode)]
163pub struct ExecError {
164 pub error: DispatchError,
166 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#[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 pub fn from_account_id(account_id: T::AccountId) -> Self {
186 Origin::Signed(account_id)
187 }
188
189 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 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 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#[derive(DebugNoBound)]
222pub enum CallResources<T: Config> {
223 NoLimits,
226 WeightDeposit { weight: Weight, deposit_limit: BalanceOf<T> },
228 Ethereum { gas: BalanceOf<T>, add_stipend: bool },
230}
231
232impl<T: Config> CallResources<T> {
233 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 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
253pub trait Ext: PrecompileWithInfoExt {
255 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 fn terminate_if_same_tx(&mut self, beneficiary: &H160) -> Result<CodeRemoved, DispatchError>;
272
273 #[allow(dead_code)]
275 fn own_code_hash(&mut self) -> &H256;
276
277 fn immutable_data_len(&mut self) -> u32;
281
282 fn get_immutable_data(&mut self) -> Result<ImmutableData, DispatchError>;
286
287 fn set_immutable_data(&mut self, data: ImmutableData) -> Result<(), DispatchError>;
293}
294
295pub trait PrecompileWithInfoExt: PrecompileExt {
297 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
312pub trait PrecompileExt: sealing::Sealed {
314 type T: Config;
315
316 fn charge(&mut self, weight: Weight) -> Result<ChargedAmount, DispatchError> {
318 self.frame_meter_mut().charge_weight_token(RuntimeCosts::Precompile(weight))
319 }
320
321 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 #[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 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 fn get_transient_storage(&self, key: &Key) -> Option<Vec<u8>>;
354
355 fn get_transient_storage_size(&self, key: &Key) -> Option<u32>;
360
361 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 fn caller(&self) -> Origin<Self::T>;
372
373 fn caller_of_caller(&self) -> Origin<Self::T>;
375
376 fn origin(&self) -> &Origin<Self::T>;
378
379 fn to_account_id(&self, address: &H160) -> AccountIdOf<Self::T>;
381
382 fn code_hash(&self, address: &H160) -> H256;
385
386 fn code_size(&self, address: &H160) -> u64;
388
389 fn caller_is_origin(&self, use_caller_of_caller: bool) -> bool;
391
392 fn caller_is_root(&self, use_caller_of_caller: bool) -> bool;
394
395 fn origin_is_root(&self) -> bool;
400
401 fn account_id(&self) -> &AccountIdOf<Self::T>;
403
404 fn address(&self) -> H160 {
406 <Self::T as Config>::AddressMapper::to_address(self.account_id())
407 }
408
409 fn balance(&self) -> U256;
413
414 fn balance_of(&self, address: &H160) -> U256;
418
419 fn value_transferred(&self) -> U256;
421
422 fn now(&self) -> U256;
424
425 fn minimum_balance(&self) -> U256;
427
428 fn deposit_event(
439 &mut self,
440 topics: ContractLogTopics,
441 data: Vec<u8>,
442 ) -> Result<(), DispatchError>;
443
444 fn block_number(&self) -> U256;
446
447 fn block_hash(&self, block_number: U256) -> Option<H256>;
450
451 fn block_author(&self) -> H160;
453
454 fn gas_limit(&self) -> u64;
456
457 fn chain_id(&self) -> u64;
459
460 #[deprecated(note = "Renamed to `frame_meter`; this alias will be removed in future versions")]
462 fn gas_meter(&self) -> &FrameMeter<Self::T>;
463
464 #[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 fn frame_meter(&self) -> &FrameMeter<Self::T>;
472
473 fn frame_meter_mut(&mut self) -> &mut FrameMeter<Self::T>;
475
476 fn ecdsa_recover(&self, signature: &[u8; 65], message_hash: &[u8; 32]) -> Result<[u8; 33], ()>;
478
479 fn sr25519_verify(&self, signature: &[u8; 64], message: &[u8], pub_key: &[u8; 32]) -> bool;
481
482 fn ecdsa_to_eth_address(&self, pk: &[u8; 33]) -> Result<[u8; 20], DispatchError>;
484
485 #[cfg(any(test, feature = "runtime-benchmarks"))]
487 fn contract_info(&mut self) -> &mut ContractInfo<Self::T>;
488
489 #[cfg(any(feature = "runtime-benchmarks", test))]
493 fn transient_storage(&mut self) -> &mut TransientStorage<Self::T>;
494
495 fn is_read_only(&self) -> bool;
497
498 fn is_delegate_call(&self) -> bool;
500
501 fn last_frame_output(&self) -> &ExecReturnValue;
503
504 fn last_frame_output_mut(&mut self) -> &mut ExecReturnValue;
506
507 fn copy_code_slice(&mut self, buf: &mut [u8], address: &H160, code_offset: usize);
515
516 fn terminate_caller(&mut self, beneficiary: &H160) -> Result<(), DispatchError>;
525
526 fn effective_gas_price(&self) -> U256;
528
529 fn gas_left(&self) -> u64;
531
532 fn get_storage(&mut self, key: &Key) -> Option<Vec<u8>>;
537
538 fn get_storage_size(&mut self, key: &Key) -> Option<u32>;
543
544 fn set_storage(
547 &mut self,
548 key: &Key,
549 value: Option<Vec<u8>>,
550 take_old: bool,
551 ) -> Result<WriteOutcome, DispatchError>;
552
553 fn touch_storage_access(&mut self, key: &Key, op: StorageOp) -> Warmth;
558
559 fn peek_storage_access(&self, key: &Key) -> Warmth;
562
563 fn charge_storage(&mut self, diff: &Diff) -> DispatchResult;
565}
566
567#[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 Constructor,
582 Call,
584}
585
586pub trait Executable<T: Config>: Sized {
591 fn from_storage<S: State>(
596 code_hash: H256,
597 meter: &mut ResourceMeter<T, S>,
598 ) -> Result<Self, DispatchError>;
599
600 fn from_evm_init_code(code: Vec<u8>, owner: AccountIdOf<T>) -> Result<Self, DispatchError>;
602
603 fn execute<E: Ext<T = T>>(
613 self,
614 ext: &mut E,
615 function: ExportedFunction,
616 input_data: Vec<u8>,
617 ) -> ExecResult;
618
619 fn code_info(&self) -> &CodeInfo<T>;
621
622 fn code(&self) -> &[u8];
624
625 fn code_hash(&self) -> &H256;
627}
628
629pub struct Stack<'a, T: Config, E> {
635 origin: Origin<T>,
644 transaction_meter: &'a mut TransactionMeter<T>,
646 timestamp: MomentOf<T>,
648 block_number: BlockNumberFor<T>,
650 frames: BoundedVec<Frame<T>, ConstU32<{ limits::CALL_STACK_DEPTH }>>,
653 first_frame: Frame<T>,
655 transient_storage: TransientStorage<T>,
657 access_list: AccessList,
659 exec_config: &'a ExecConfig<T>,
661 _phantom: PhantomData<E>,
663}
664
665struct Frame<T: Config> {
670 account_id: T::AccountId,
672 contract_info: CachedContract<T>,
674 value_transferred: U256,
676 entry_point: ExportedFunction,
678 frame_meter: FrameMeter<T>,
680 allows_reentry: bool,
682 read_only: bool,
684 delegate: Option<DelegateInfo<T>>,
687 code_address: H160,
693 last_frame_output: ExecReturnValue,
695 contracts_created: BTreeSet<T::AccountId>,
697 contracts_to_be_destroyed: BTreeMap<T::AccountId, T::AccountId>,
699}
700
701#[derive(Clone, DebugNoBound)]
704pub struct DelegateInfo<T: Config> {
705 pub caller: Origin<T>,
707 pub callee: H160,
709}
710
711enum ExecutableOrPrecompile<T: Config, E: Executable<T>, Env> {
713 Executable(E),
715 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
741enum FrameArgs<'a, T: Config, E> {
745 Call {
746 dest: T::AccountId,
748 cached_info: Option<ContractInfo<T>>,
750 delegated_call: Option<DelegateInfo<T>>,
754 },
755 Instantiate {
756 sender: T::AccountId,
758 executable: E,
760 salt: Option<&'a [u8; 32]>,
762 input_data: &'a [u8],
764 },
765}
766
767enum CachedContract<T: Config> {
769 Cached(ContractInfo<T>),
771 Invalidated,
775 None,
777}
778
779impl<T: Config> Frame<T> {
780 fn contract_info(&mut self) -> &mut ContractInfo<T> {
782 self.contract_info.get(&self.account_id)
783 }
784}
785
786macro_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
805macro_rules! top_frame {
810 ($stack:expr) => {
811 $stack.frames.last().unwrap_or(&$stack.first_frame)
812 };
813}
814
815macro_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 fn into_contract(self) -> Option<ContractInfo<T>> {
828 if let CachedContract::Cached(contract) = self { Some(contract) } else { None }
829 }
830
831 fn as_contract(&mut self) -> Option<&mut ContractInfo<T>> {
833 if let CachedContract::Cached(contract) = self { Some(contract) } else { None }
834 }
835
836 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 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 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 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 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 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 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 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 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 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 let mut read_delegation: Option<Option<H160>> = None;
1108 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 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 (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 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 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 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 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 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 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 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 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 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 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 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 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 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 <System<T>>::inc_consumers(account_id)?;
1444
1445 <System<T>>::inc_account_nonce(account_id);
1447
1448 if bump_nonce || !is_first_frame {
1449 <System<T>>::inc_account_nonce(caller.account_id()?);
1452 }
1453 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 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 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 T::Currency::mint_into(account_id, T::Currency::minimum_balance())?;
1492 <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 if output.did_revert() {
1522 return Ok(output);
1523 }
1524
1525 let frame = if entry_point == ExportedFunction::Constructor {
1528 let frame = top_frame_mut!(self);
1529 if !is_pvm {
1532 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 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 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 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 block_storage::ensure_receipt_within_limit::<T>()
1594 .map_err(|e| ExecError { error: e, origin: ErrorOrigin::Callee })?;
1595
1596 Ok(output)
1597 };
1598
1599 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 Ok((success, output)) => {
1623 if_tracing(|tracer| {
1624 let frame_meter = &top_frame!(self).frame_meter;
1625
1626 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 Err(error) => {
1654 if_tracing(|tracer| {
1655 let frame_meter = &top_frame!(self).frame_meter;
1656
1657 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 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 fn pop_frame(&mut self, persist: bool) {
1712 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 f.contract_info.invalidate();
1731 }
1732
1733 let frame = self.frames.pop();
1737
1738 if let Some(mut frame) = frame {
1741 let account_id = &frame.account_id;
1742 let prev = top_frame_mut!(self);
1743
1744 if !persist {
1746 prev.frame_meter.absorb_weight_meter_only(frame.frame_meter);
1747 return;
1748 }
1749
1750 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 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 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_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 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 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 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 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 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 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 let account_info = AccountInfoOf::<T>::get(contract_address).unwrap_or_default();
1911
1912 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 System::<T>::dec_consumers(contract_account);
1921
1922 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 let dust = AccountInfoOf::<T>::get(contract_address)
1949 .map(|info| info.dust)
1950 .unwrap_or_default();
1951
1952 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 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 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 transaction_meter.terminate(contract_account.clone(), refund);
1987
1988 log::trace!(target: LOG_TARGET, "Terminated {contract_address:?}");
1989 }
1990
1991 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 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 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 fn top_frame(&self) -> &Frame<T> {
2040 top_frame!(self)
2041 }
2042
2043 fn top_frame_mut(&mut self) -> &mut Frame<T> {
2045 top_frame_mut!(self)
2046 }
2047
2048 fn frames(&self) -> impl Iterator<Item = &Frame<T>> {
2052 core::iter::once(&self.first_frame).chain(&self.frames).rev()
2053 }
2054
2055 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 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 fn allows_reentry(&self, id: &T::AccountId) -> bool {
2079 !self.frames().any(|f| &f.account_id == id && !f.allows_reentry)
2080 }
2081
2082 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 #[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 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 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 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 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
2184enum CodeSource<'a> {
2186 Virtual(&'a [u8]),
2188 Indicator([u8; 23]),
2190 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 *self.last_frame_output_mut() = Default::default();
2208
2209 let top_frame = self.top_frame_mut();
2210 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 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 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 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 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 *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 *self.last_frame_output_mut() = Default::default();
2384
2385 if allows_reentry == ReentrancyProtection::Strict {
2390 self.top_frame_mut().allows_reentry = false;
2391 }
2392
2393 let try_call = || {
2394 let is_read_only = read_only || self.is_read_only();
2396
2397 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 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 let result = try_call();
2499
2500 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 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 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 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 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
2850pub 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#[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}