1#![doc = include_str!("../README.md")]
19#![allow(rustdoc::private_intra_doc_links)]
20#![cfg_attr(not(feature = "std"), no_std)]
21#![cfg_attr(feature = "runtime-benchmarks", recursion_limit = "1024")]
22
23extern crate alloc;
24
25mod access_list;
26mod address;
27mod benchmarking;
28#[cfg(any(feature = "runtime-benchmarks", test))]
29pub mod call_builder;
30mod debug;
31mod deposit_payment;
32mod exec;
33mod impl_fungibles;
34mod limits;
35mod metering;
36mod primitives;
37#[doc(hidden)]
38pub mod runtime_api;
39#[doc(hidden)]
40pub mod state_overrides;
41mod storage;
42#[cfg(test)]
43mod tests;
44mod transient_storage;
45mod vm;
46mod weightinfo_extension;
47
48pub mod evm;
49pub mod migrations;
50pub mod mock;
51pub mod precompiles;
52pub mod test_utils;
53pub mod tracing;
54pub mod weights;
55
56use crate::{
57 access_list::Warmth,
58 evm::{
59 CallTracer, CreateCallMode, ExecutionTracer, GenericTransaction, PrestateTracer,
60 StateOverrideSet, TYPE_EIP1559, TYPE_EIP7702, Tracer, TracerType,
61 block_hash::{CommittedReceiptLogs, EthereumBlockBuilderIR},
62 block_storage,
63 fees::InfoT as FeeInfo,
64 runtime::SetWeightLimit,
65 },
66 exec::{AccountIdOf, ExecError, Stack as ExecStack},
67 sp_runtime::TransactionOutcome,
68 storage::{AccountType, DeletionQueueManager},
69 tracing::if_tracing,
70 vm::{CodeInfo, RuntimeCosts, StorageAccessKind, evm::EvmDispatch, pvm::extract_code_and_data},
71 weightinfo_extension::OnFinalizeBlockParts,
72};
73use alloc::{boxed::Box, format, vec};
74use codec::{Codec, Decode, Encode, MaxEncodedLen};
75use environmental::*;
76use frame_support::{
77 BoundedVec,
78 dispatch::{
79 DispatchErrorWithPostInfo, DispatchResult, DispatchResultWithPostInfo, GetDispatchInfo,
80 Pays, PostDispatchInfo, RawOrigin,
81 },
82 ensure,
83 pallet_prelude::DispatchClass,
84 storage::with_transaction,
85 traits::{
86 ConstU32, ConstU64, DefensiveResult, EnsureOrigin, Get, IsSubType, IsType, OnUnbalanced,
87 OriginTrait,
88 fungible::{Balanced, Credit, Inspect, Mutate, MutateHold},
89 tokens::Balance,
90 },
91 weights::WeightMeter,
92};
93use frame_system::{
94 Pallet as System, ensure_signed,
95 pallet_prelude::{BlockNumberFor, OriginFor},
96};
97use pallet_revive_types::runtime_api::*;
98use scale_info::TypeInfo;
99use sp_runtime::{
100 AccountId32, DispatchError, FixedPointNumber, FixedU128, SaturatedConversion,
101 traits::{
102 BadOrigin, Bounded, Convert, Dispatchable, Saturating, UniqueSaturatedFrom,
103 UniqueSaturatedInto, Zero,
104 },
105};
106
107pub use crate::{
108 address::{AccountId32Mapper, AddressMapper, AutoMapper, TestAccountMapper, create1, create2},
109 debug::DebugSettings,
110 deposit_payment::{Deposit, PGasDeposit},
111 evm::{
112 Address as EthAddress, Block as EthBlock,
113 block_hash::{OutsideFrameLog, ReceiptGasInfo, SyntheticTransactionInfo},
114 },
115 exec::{
116 CallResources, DelegateInfo, Executable, Key, MomentOf, Origin as ExecOrigin,
117 ReentrancyProtection,
118 },
119 limits::{
120 TRANSIENT_STORAGE_BYTES as TRANSIENT_STORAGE_LIMIT,
121 code::{CodeRejection, check_pvm_code},
122 },
123 metering::{
124 EthTxInfo, FrameMeter, ResourceMeter, Token as WeightToken, TransactionLimits,
125 TransactionMeter,
126 },
127 pallet::{genesis, *},
128 storage::{AccountInfo, ContractInfo},
129 transient_storage::{MeterEntry, StorageMeter as TransientStorageMeter, TransientStorage},
130 vm::{BytecodeType, ContractBlob},
131};
132pub use codec;
133use frame_support::traits::tokens::Precision;
134pub use frame_support::{self, dispatch::DispatchInfo, traits::Time, weights::Weight};
135pub use frame_system::{self, limits::BlockWeights};
136pub use primitives::*;
137pub use sp_core::{H160, H256, U256};
138pub use sp_crypto_hashing::keccak_256;
139pub use sp_runtime;
140pub use weights::WeightInfo;
141
142pub extern crate pallet_revive_types;
144
145#[cfg(doc)]
146pub use crate::vm::pvm::SyscallDoc;
147
148pub type BalanceOf<T> = <T as Config>::Balance;
149pub type CreditOf<T> = Credit<<T as frame_system::Config>::AccountId, <T as Config>::Currency>;
150type TrieId = BoundedVec<u8, ConstU32<128>>;
151type ImmutableData = BoundedVec<u8, ConstU32<{ limits::IMMUTABLE_BYTES }>>;
152type CallOf<T> = <T as Config>::RuntimeCall;
153
154pub type ContractLogTopics = BoundedVec<H256, ConstU32<{ limits::NUM_EVENT_TOPICS }>>;
156pub type ContractLogData = BoundedVec<u8, ConstU32<{ limits::EVENT_BYTES }>>;
158
159const SENTINEL: u32 = u32::MAX;
166
167const LOG_TARGET: &str = "runtime::revive";
173
174#[frame_support::pallet]
175pub mod pallet {
176 use super::*;
177 use frame_support::{pallet_prelude::*, traits::FindAuthor};
178 use frame_system::pallet_prelude::*;
179 use sp_core::U256;
180 use sp_runtime::Perbill;
181
182 pub(crate) const STORAGE_VERSION: StorageVersion = StorageVersion::new(0);
184
185 #[pallet::pallet]
186 #[pallet::storage_version(STORAGE_VERSION)]
187 pub struct Pallet<T>(_);
188
189 #[pallet::config(with_default)]
190 pub trait Config: frame_system::Config {
191 type Time: Time<Moment: Into<U256>>;
193
194 #[pallet::no_default]
198 type Balance: Balance
199 + TryFrom<U256>
200 + Into<U256>
201 + Bounded
202 + UniqueSaturatedInto<u64>
203 + UniqueSaturatedFrom<u64>
204 + UniqueSaturatedInto<u128>;
205
206 #[pallet::no_default]
208 type Currency: Inspect<Self::AccountId, Balance = Self::Balance>
209 + Mutate<Self::AccountId>
210 + MutateHold<Self::AccountId, Reason = Self::RuntimeHoldReason>
211 + Balanced<Self::AccountId>;
212
213 #[pallet::no_default_bounds]
220 type OnBurn: OnUnbalanced<CreditOf<Self>>;
221
222 #[pallet::no_default_bounds]
224 #[allow(deprecated)]
225 type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
226
227 #[pallet::no_default_bounds]
229 type RuntimeCall: Parameter
230 + Dispatchable<
231 RuntimeOrigin = OriginFor<Self>,
232 Info = DispatchInfo,
233 PostInfo = PostDispatchInfo,
234 > + IsType<<Self as frame_system::Config>::RuntimeCall>
235 + From<Call<Self>>
236 + IsSubType<Call<Self>>
237 + GetDispatchInfo;
238
239 #[pallet::no_default_bounds]
241 type RuntimeOrigin: IsType<OriginFor<Self>>
242 + From<Origin<Self>>
243 + Into<Result<Origin<Self>, OriginFor<Self>>>;
244
245 #[pallet::no_default_bounds]
247 type RuntimeHoldReason: From<HoldReason>;
248
249 type WeightInfo: WeightInfo;
252
253 #[pallet::no_default_bounds]
257 #[allow(private_bounds)]
258 type Precompiles: precompiles::Precompiles<Self>;
259
260 type FindAuthor: FindAuthor<Self::AccountId>;
262
263 #[pallet::constant]
269 #[pallet::no_default_bounds]
270 type DepositPerByte: Get<BalanceOf<Self>>;
271
272 #[pallet::constant]
278 #[pallet::no_default_bounds]
279 type DepositPerItem: Get<BalanceOf<Self>>;
280
281 #[pallet::constant]
291 #[pallet::no_default_bounds]
292 type DepositPerChildTrieItem: Get<BalanceOf<Self>>;
293
294 #[pallet::constant]
298 type CodeHashLockupDepositPercent: Get<Perbill>;
299
300 #[pallet::no_default]
302 type AddressMapper: AddressMapper<Self>;
303
304 #[pallet::constant]
306 type AllowEVMBytecode: Get<bool>;
307
308 #[pallet::no_default_bounds]
313 type UploadOrigin: EnsureOrigin<OriginFor<Self>, Success = Self::AccountId>;
314
315 #[pallet::no_default_bounds]
326 type InstantiateOrigin: EnsureOrigin<OriginFor<Self>, Success = Self::AccountId>;
327
328 type RuntimeMemory: Get<u32>;
333
334 type PVFMemory: Get<u32>;
342
343 #[pallet::constant]
348 type ChainId: Get<u64>;
349
350 #[pallet::constant]
352 type NativeToEthRatio: Get<u32>;
353
354 #[pallet::no_default_bounds]
359 type FeeInfo: FeeInfo<Self>;
360
361 #[pallet::no_default_bounds]
364 type Deposit: Deposit<Self>;
365
366 #[pallet::constant]
379 type MaxEthExtrinsicWeight: Get<FixedU128>;
380
381 #[pallet::constant]
383 type DebugEnabled: Get<bool>;
384
385 #[pallet::constant]
392 type AutoMap: Get<bool>;
393
394 #[pallet::constant]
412 #[pallet::no_default_bounds]
413 type GasScale: Get<u32>;
414
415 #[pallet::constant]
422 type MaxOutsideFrameLogs: Get<u32>;
423 }
424
425 pub mod config_preludes {
427 use super::*;
428 use frame_support::{
429 derive_impl,
430 traits::{ConstBool, ConstU32},
431 };
432 use frame_system::EnsureSigned;
433 use sp_core::parameter_types;
434
435 type Balance = u64;
436
437 pub const DOLLARS: Balance = 1_000_000_000_000;
438 pub const CENTS: Balance = DOLLARS / 100;
439 pub const MILLICENTS: Balance = CENTS / 1_000;
440
441 pub const fn deposit(items: u32, bytes: u32) -> Balance {
442 items as Balance * 20 * CENTS + (bytes as Balance) * MILLICENTS
443 }
444
445 parameter_types! {
446 pub const DepositPerItem: Balance = deposit(1, 0);
447 pub const DepositPerChildTrieItem: Balance = deposit(1, 0) / 100;
448 pub const DepositPerByte: Balance = deposit(0, 1);
449 pub const CodeHashLockupDepositPercent: Perbill = Perbill::from_percent(0);
450 pub const MaxEthExtrinsicWeight: FixedU128 = FixedU128::from_rational(9, 10);
451 pub const GasScale: u32 = 10u32;
452 }
453
454 pub struct TestDefaultConfig;
456
457 impl Time for TestDefaultConfig {
458 type Moment = u64;
459 fn now() -> Self::Moment {
460 0u64
461 }
462 }
463
464 impl<T: From<u64>> Convert<Weight, T> for TestDefaultConfig {
465 fn convert(w: Weight) -> T {
466 w.ref_time().into()
467 }
468 }
469
470 #[derive_impl(frame_system::config_preludes::TestDefaultConfig, no_aggregated_types)]
471 impl frame_system::DefaultConfig for TestDefaultConfig {}
472
473 #[frame_support::register_default_impl(TestDefaultConfig)]
474 impl DefaultConfig for TestDefaultConfig {
475 #[inject_runtime_type]
476 type RuntimeEvent = ();
477
478 #[inject_runtime_type]
479 type RuntimeHoldReason = ();
480
481 #[inject_runtime_type]
482 type RuntimeCall = ();
483
484 #[inject_runtime_type]
485 type RuntimeOrigin = ();
486
487 type Precompiles = ();
488 type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent;
489 type DepositPerByte = DepositPerByte;
490 type DepositPerItem = DepositPerItem;
491 type DepositPerChildTrieItem = DepositPerChildTrieItem;
492 type Time = Self;
493 type AllowEVMBytecode = ConstBool<true>;
494 type UploadOrigin = EnsureSigned<Self::AccountId>;
495 type InstantiateOrigin = EnsureSigned<Self::AccountId>;
496 type WeightInfo = ();
497 type RuntimeMemory = ConstU32<{ 128 * 1024 * 1024 }>;
498 type PVFMemory = ConstU32<{ 512 * 1024 * 1024 }>;
499 type ChainId = ConstU64<42>;
500 type NativeToEthRatio = ConstU32<1_000_000>;
501 type FindAuthor = ();
502 type FeeInfo = ();
503 type Deposit = ();
504 type MaxEthExtrinsicWeight = MaxEthExtrinsicWeight;
505 type DebugEnabled = ConstBool<false>;
506 type AutoMap = ConstBool<false>;
507 type GasScale = GasScale;
508 type OnBurn = ();
509 type MaxOutsideFrameLogs = ConstU32<1024>;
510 }
511 }
512
513 #[pallet::event]
514 pub enum Event<T: Config> {
515 ContractEmitted {
517 contract: H160,
519 data: Vec<u8>,
522 topics: Vec<H256>,
525 },
526
527 Instantiated { deployer: H160, contract: H160 },
529
530 EthExtrinsicRevert { dispatch_error: DispatchError },
537 }
538
539 #[pallet::error]
540 #[repr(u8)]
541 pub enum Error<T> {
542 InvalidSchedule = 0x01,
544 InvalidCallFlags = 0x02,
546 OutOfGas = 0x03,
548 TransferFailed = 0x04,
551 MaxCallDepthReached = 0x05,
554 ContractNotFound = 0x06,
556 CodeNotFound = 0x07,
558 CodeInfoNotFound = 0x08,
560 OutOfBounds = 0x09,
562 DecodingFailed = 0x0A,
564 ContractTrapped = 0x0B,
566 ValueTooLarge = 0x0C,
568 TerminatedWhileReentrant = 0x0D,
571 InputForwarded = 0x0E,
573 TooManyTopics = 0x0F,
575 DuplicateContract = 0x12,
577 TerminatedInConstructor = 0x13,
581 ReentranceDenied = 0x14,
583 ReenteredPallet = 0x15,
585 StateChangeDenied = 0x16,
587 StorageDepositNotEnoughFunds = 0x17,
589 StorageDepositLimitExhausted = 0x18,
591 CodeInUse = 0x19,
593 ContractReverted = 0x1A,
598 CodeRejected = 0x1B,
603 BlobTooLarge = 0x1C,
605 StaticMemoryTooLarge = 0x1D,
607 BasicBlockTooLarge = 0x1E,
609 InvalidInstruction = 0x1F,
611 MaxDelegateDependenciesReached = 0x20,
613 DelegateDependencyNotFound = 0x21,
615 DelegateDependencyAlreadyExists = 0x22,
617 CannotAddSelfAsDelegateDependency = 0x23,
619 OutOfTransientStorage = 0x24,
621 InvalidSyscall = 0x25,
623 InvalidStorageFlags = 0x26,
625 ExecutionFailed = 0x27,
627 BalanceConversionFailed = 0x28,
629 InvalidImmutableAccess = 0x2A,
632 AccountUnmapped = 0x2B,
636 AccountAlreadyMapped = 0x2C,
638 InvalidGenericTransaction = 0x2D,
640 RefcountOverOrUnderflow = 0x2E,
642 UnsupportedPrecompileAddress = 0x2F,
644 CallDataTooLarge = 0x30,
646 ReturnDataTooLarge = 0x31,
648 InvalidJump = 0x32,
650 StackUnderflow = 0x33,
652 StackOverflow = 0x34,
654 TxFeeOverdraw = 0x35,
658 EvmConstructorNonEmptyData = 0x36,
662 EvmConstructedFromHash = 0x37,
667 StorageRefundNotEnoughFunds = 0x38,
671 StorageRefundLocked = 0x39,
676 PrecompileDelegateDenied = 0x40,
681 EcdsaRecoveryFailed = 0x41,
683 AutoMappingEnabled = 0x42,
685 PendingDepositCleanup = 0x43,
689 CannotTerminateDelegatedAccount = 0x44,
692 ReceiptTooLarge = 0x45,
695 #[cfg(feature = "runtime-benchmarks")]
697 BenchmarkingError = 0xFF,
698 }
699
700 #[pallet::composite_enum]
702 pub enum HoldReason {
703 CodeUploadDepositReserve,
705 StorageDepositReserve,
707 AddressMapping,
709 }
710
711 #[pallet::composite_enum]
713 pub enum FreezeReason {
714 PGasMinBalance,
719 }
720
721 #[derive(
722 PartialEq, Eq, Clone, MaxEncodedLen, Encode, Decode, DecodeWithMemTracking, TypeInfo, Debug,
723 )]
724 #[pallet::origin]
725 pub enum Origin<T: Config> {
726 EthTransaction(T::AccountId),
727 }
728
729 #[pallet::storage]
733 #[pallet::unbounded]
734 pub(crate) type PristineCode<T: Config> = StorageMap<_, Identity, H256, Vec<u8>>;
735
736 #[pallet::storage]
738 pub(crate) type CodeInfoOf<T: Config> = StorageMap<_, Identity, H256, CodeInfo<T>>;
739
740 #[pallet::storage]
742 pub(crate) type AccountInfoOf<T: Config> = StorageMap<_, Identity, H160, AccountInfo<T>>;
743
744 #[pallet::storage]
755 pub(crate) type NativeDepositOf<T: Config> = StorageDoubleMap<
756 _,
757 Identity,
758 T::AccountId,
759 Identity,
760 T::AccountId,
761 BalanceOf<T>,
762 ValueQuery,
763 >;
764
765 #[pallet::storage]
767 pub(crate) type ImmutableDataOf<T: Config> = StorageMap<_, Identity, H160, ImmutableData>;
768
769 #[pallet::storage]
775 pub(crate) type DeletionQueue<T: Config> =
776 StorageMap<_, Twox64Concat, u32, crate::storage::DeletionQueueItem<T>>;
777
778 #[pallet::storage]
785 pub(crate) type DeletionQueueCounter<T: Config> =
786 StorageValue<_, DeletionQueueManager<T>, ValueQuery>;
787
788 #[pallet::storage]
795 pub(crate) type OriginalAccount<T: Config> = StorageMap<_, Identity, H160, AccountId32>;
796
797 #[pallet::storage]
807 #[pallet::unbounded]
808 pub(crate) type EthereumBlock<T> = StorageValue<_, EthBlock, ValueQuery>;
809
810 #[pallet::storage]
814 pub(crate) type BlockHash<T: Config> =
815 StorageMap<_, Identity, BlockNumberFor<T>, H256, ValueQuery>;
816
817 #[pallet::storage]
824 #[pallet::unbounded]
825 pub(crate) type ReceiptInfoData<T: Config> = StorageValue<_, Vec<ReceiptGasInfo>, ValueQuery>;
826
827 #[pallet::storage]
833 #[pallet::unbounded]
834 type SyntheticReceiptInfo<T: Config> = StorageValue<_, SyntheticTransactionInfo, OptionQuery>;
835
836 #[pallet::storage]
853 #[pallet::whitelist_storage]
854 pub(crate) type ReceiptLogsCommitted<T: Config> =
855 StorageValue<_, CommittedReceiptLogs, ValueQuery>;
856
857 #[pallet::storage]
859 #[pallet::unbounded]
860 pub(crate) type EthBlockBuilderIR<T: Config> =
861 StorageValue<_, EthereumBlockBuilderIR<T>, ValueQuery>;
862
863 #[pallet::storage]
868 #[pallet::unbounded]
869 pub(crate) type EthBlockBuilderFirstValues<T: Config> =
870 StorageValue<_, Option<(Vec<u8>, Vec<u8>)>, ValueQuery>;
871
872 #[pallet::storage]
888 #[pallet::unbounded]
889 #[pallet::whitelist_storage]
890 type OutsideFrameLogs<T: Config> = StorageValue<_, Vec<OutsideFrameLog>, ValueQuery>;
891
892 #[pallet::storage]
897 #[pallet::whitelist_storage]
898 type OutsideFrameLogsBytes<T: Config> = StorageValue<_, u32, ValueQuery>;
899
900 #[pallet::storage]
902 pub(crate) type DebugSettingsOf<T: Config> = StorageValue<_, DebugSettings, ValueQuery>;
903
904 pub mod genesis {
905 use super::*;
906 use crate::evm::Bytes32;
907
908 #[derive(Clone, PartialEq, Debug, Default, serde::Serialize, serde::Deserialize)]
910 pub struct ContractData {
911 pub code: crate::evm::Bytes,
913 pub storage: alloc::collections::BTreeMap<Bytes32, Bytes32>,
915 }
916
917 #[derive(PartialEq, Default, Debug, Clone, serde::Serialize, serde::Deserialize)]
919 pub struct Account<T: Config> {
920 pub address: H160,
922 #[serde(default)]
924 pub balance: U256,
925 #[serde(default)]
927 pub nonce: T::Nonce,
928 #[serde(flatten, skip_serializing_if = "Option::is_none")]
930 pub contract_data: Option<ContractData>,
931 }
932 }
933
934 #[pallet::genesis_config]
935 #[derive(Debug, PartialEq, frame_support::DefaultNoBound)]
936 pub struct GenesisConfig<T: Config> {
937 #[serde(default, skip_serializing_if = "Vec::is_empty")]
940 pub mapped_accounts: Vec<T::AccountId>,
941
942 #[serde(default, skip_serializing_if = "Vec::is_empty")]
944 pub accounts: Vec<genesis::Account<T>>,
945
946 #[serde(default, skip_serializing_if = "Option::is_none")]
948 pub debug_settings: Option<DebugSettings>,
949 }
950
951 #[pallet::genesis_build]
952 impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
953 fn build(&self) {
954 use crate::{exec::Key, vm::ContractBlob};
955 use frame_support::traits::fungible::Mutate;
956
957 if !System::<T>::account_exists(&Pallet::<T>::account_id()) {
958 let _ = T::Currency::mint_into(
959 &Pallet::<T>::account_id(),
960 T::Currency::minimum_balance(),
961 );
962 }
963
964 for id in &self.mapped_accounts {
965 if let Err(err) = T::AddressMapper::map_no_deposit_unchecked(id) {
966 log::error!(target: LOG_TARGET, "Failed to map account {id:?}: {err:?}");
967 }
968 }
969
970 let owner = Pallet::<T>::account_id();
971
972 for genesis::Account { address, balance, nonce, contract_data } in &self.accounts {
973 let account_id = T::AddressMapper::to_account_id(address);
974
975 if !System::<T>::account_exists(&account_id) {
976 let _ = T::Currency::mint_into(&account_id, T::Currency::minimum_balance());
977 }
978
979 frame_system::Account::<T>::mutate(&account_id, |info| {
980 info.nonce = (*nonce).into();
981 });
982
983 match contract_data {
984 None => {
985 AccountInfoOf::<T>::insert(
986 address,
987 AccountInfo { account_type: AccountType::EOA, dust: 0 },
988 );
989 },
990 Some(genesis::ContractData { code, storage }) => {
991 let blob = if code.0.starts_with(&polkavm_common::program::BLOB_MAGIC) {
992 ContractBlob::<T>::from_pvm_code(code.0.clone(), owner.clone())
993 .inspect_err(|err| {
994 log::error!(target: LOG_TARGET, "Failed to create PVM ContractBlob for {address:?}: {err:?}");
995 })
996 } else {
997 ContractBlob::<T>::from_evm_runtime_code(code.0.clone(), account_id)
998 .inspect_err(|err| {
999 log::error!(target: LOG_TARGET, "Failed to create EVM ContractBlob for {address:?}: {err:?}");
1000 })
1001 };
1002
1003 let Ok(blob) = blob else {
1004 continue;
1005 };
1006
1007 let code_hash = *blob.code_hash();
1008 let Ok(info) = <ContractInfo<T>>::new(&address, 0u32.into(), code_hash)
1009 .inspect_err(|err| {
1010 log::error!(target: LOG_TARGET, "Failed to create ContractInfo for {address:?}: {err:?}");
1011 })
1012 else {
1013 continue;
1014 };
1015
1016 AccountInfoOf::<T>::insert(
1017 address,
1018 AccountInfo { account_type: info.clone().into(), dust: 0 },
1019 );
1020
1021 <PristineCode<T>>::insert(blob.code_hash(), code.0.clone());
1022 <CodeInfoOf<T>>::insert(blob.code_hash(), blob.code_info().clone());
1023 for (k, v) in storage {
1024 let _ = info.write(&Key::from_fixed(k.0), Some(v.0.to_vec()), None, false).inspect_err(|err| {
1025 log::error!(target: LOG_TARGET, "Failed to write genesis storage for {address:?} at key {k:?}: {err:?}");
1026 });
1027 }
1028 },
1029 }
1030
1031 let _ = Pallet::<T>::set_evm_balance(address, *balance).inspect_err(|err| {
1032 log::error!(target: LOG_TARGET, "Failed to set EVM balance for {address:?}: {err:?}");
1033 });
1034 }
1035
1036 Pallet::<T>::finalize_eth_block(
1038 frame_system::Pallet::<T>::block_number(),
1041 );
1042
1043 if let Some(settings) = self.debug_settings.as_ref() {
1045 settings.write_to_storage::<T>()
1046 }
1047 }
1048 }
1049
1050 impl<T: Config> Pallet<T> {
1051 pub fn eth_synthetic_transaction() -> Option<SyntheticTransactionInfo> {
1053 SyntheticReceiptInfo::<T>::get()
1054 }
1055
1056 pub fn emit_contract_log_outside_frame(
1080 contract: H160,
1081 topics: ContractLogTopics,
1082 data: ContractLogData,
1083 ) {
1084 match block_storage::capture_into_receipt::<T>(&contract, &data, &topics) {
1085 Some(Ok(())) => {},
1086 None => Self::buffer_outside_frame_log(&contract, &topics, &data),
1087 Some(Err(_)) => return,
1091 }
1092
1093 if_tracing(|tracer| {
1094 let log_index = frame_system::Pallet::<T>::event_count();
1095 tracer.log_event_outside_frame(contract, &topics, &data, log_index);
1096 });
1097
1098 Self::deposit_event(Event::ContractEmitted {
1099 contract,
1100 data: data.into_inner(),
1101 topics: topics.into_inner(),
1102 });
1103 }
1104
1105 #[cfg(feature = "runtime-benchmarks")]
1108 pub fn clear_outside_frame_logs() {
1109 OutsideFrameLogs::<T>::kill();
1110 OutsideFrameLogsBytes::<T>::kill();
1111 }
1112
1113 #[cfg(feature = "runtime-benchmarks")]
1119 pub fn bench_buffer_outside_frame_log(contract: H160, topics: Vec<H256>, data: Vec<u8>) {
1120 OutsideFrameLogs::<T>::append(OutsideFrameLog {
1121 event_index: frame_system::Pallet::<T>::event_count(),
1122 contract,
1123 topics,
1124 data,
1125 });
1126 }
1127
1128 fn buffer_outside_frame_log(contract: &H160, topics: &[H256], data: &[u8]) {
1133 let cap = T::MaxOutsideFrameLogs::get();
1134 if cap.is_zero() {
1135 return;
1136 }
1137 let index = OutsideFrameLogs::<T>::decode_len().unwrap_or(0) as u32;
1138 if index >= cap {
1139 log::warn!(
1141 target: LOG_TARGET,
1142 "outside-of-frame log buffer full ({index} logs); log for {contract:?} stays substrate-only",
1143 );
1144 return;
1145 }
1146
1147 if index.is_zero() &&
1154 BlockHash::<T>::contains_key(frame_system::Pallet::<T>::block_number())
1155 {
1156 log::warn!(
1157 target: LOG_TARGET,
1158 "outside-of-frame log for {contract:?} emitted after the block's drain stays substrate-only",
1159 );
1160 return;
1161 }
1162
1163 let buffered_bytes = OutsideFrameLogsBytes::<T>::get().saturating_add(
1164 evm::block_hash::AccumulateReceipt::encoded_log_len(contract, data, topics)
1165 .saturated_into(),
1166 );
1167 if buffered_bytes > limits::MAX_RECEIPT_LOGS_BYTES {
1168 log::warn!(
1169 target: LOG_TARGET,
1170 "outside-of-frame logs reached the receipt size limit; log for {contract:?} stays substrate-only",
1171 );
1172 return;
1173 }
1174 OutsideFrameLogsBytes::<T>::put(buffered_bytes);
1175
1176 let entry = OutsideFrameLog {
1179 event_index: frame_system::Pallet::<T>::event_count(),
1180 contract: *contract,
1181 topics: topics.to_vec(),
1182 data: data.to_vec(),
1183 };
1184 let entry_bytes = Weight::from_parts(0, entry.encoded_size() as u64);
1185 OutsideFrameLogs::<T>::append(entry);
1186
1187 frame_system::Pallet::<T>::register_extra_weight_unchecked(
1198 T::WeightInfo::per_outside_frame_log(
1199 topics.len().saturated_into(),
1200 data.len().saturated_into(),
1201 )
1202 .max(entry_bytes),
1203 DispatchClass::Normal,
1204 );
1205
1206 if index.is_zero() {
1211 frame_system::Pallet::<T>::register_extra_weight_unchecked(
1212 T::WeightInfo::on_finalize_block_per_tx(
1213 block_storage::SYNTHETIC_LOG_TX_MAX_LEN,
1214 ),
1215 DispatchClass::Normal,
1216 );
1217 }
1218 }
1219
1220 fn finalize_eth_block(block_number: BlockNumberFor<T>) {
1223 let outside_frame_logs = OutsideFrameLogs::<T>::take();
1224 OutsideFrameLogsBytes::<T>::kill();
1225 if let Some(synthetic) =
1226 block_storage::on_finalize_build_eth_block::<T>(block_number, outside_frame_logs)
1227 {
1228 SyntheticReceiptInfo::<T>::put(synthetic);
1231 }
1232 }
1233 }
1234
1235 #[pallet::hooks]
1236 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
1237 fn on_idle(_block: BlockNumberFor<T>, limit: Weight) -> Weight {
1238 let mut meter = WeightMeter::with_limit(limit);
1239 ContractInfo::<T>::process_deletion_queue_batch(&mut meter);
1240 meter.consumed()
1241 }
1242
1243 fn on_initialize(_n: BlockNumberFor<T>) -> Weight {
1244 block_storage::on_initialize::<T>();
1246 SyntheticReceiptInfo::<T>::kill();
1247
1248 System::<T>::account_exists(&Pallet::<T>::account_id());
1250 <T as Config>::WeightInfo::on_finalize_block_fixed()
1255 }
1256
1257 fn on_finalize(block_number: BlockNumberFor<T>) {
1258 Self::finalize_eth_block(block_number);
1259 }
1260
1261 fn integrity_test() {
1262 assert!(T::ChainId::get() > 0, "ChainId must be greater than 0");
1263
1264 assert!(T::GasScale::get() > 0u32.into(), "GasScale must not be 0");
1265
1266 assert!(
1267 crate::metering::EngineMeter::<T>::ref_time_per_fuel() > 0,
1268 "The ref time per PolkaVM gas derived from the weights must not be 0"
1269 );
1270
1271 let compilation_cost =
1272 crate::metering::EngineMeter::<T>::interpreter_compilation_cost();
1273 assert!(
1274 compilation_cost.per_block > 0,
1275 "The interpreter compile weight per block must exceed per instruction plus one gas"
1276 );
1277 assert!(
1278 compilation_cost.per_instruction_millis > 0,
1279 "The interpreter compile weight per instruction must not be 0"
1280 );
1281 assert!(
1282 compilation_cost.per_code_byte_millis > 0,
1283 "The interpreter code map weight per byte must not be 0"
1284 );
1285 let ref_time_slope =
1286 |weight: fn(u32) -> Weight| crate::metering::slope(weight, 1).ref_time();
1287 assert!(
1288 ref_time_slope(T::WeightInfo::call_with_pvm_code_per_byte) >=
1289 ref_time_slope(T::WeightInfo::interpreter_code_map_per_byte),
1290 "The PVM code load weight per byte must be at least the code map weight per byte"
1291 );
1292
1293 T::FeeInfo::integrity_test();
1294
1295 EvmDispatch::integrity_test::<T>();
1296
1297 let max_runtime_mem: u64 = T::RuntimeMemory::get().into();
1299
1300 const TOTAL_MEMORY_DEVIDER: u64 = 2;
1303
1304 let max_block_weight = T::BlockWeights::get()
1310 .get(DispatchClass::Normal)
1311 .max_total
1312 .unwrap_or_else(|| T::BlockWeights::get().max_block);
1313 let max_key_size: u64 =
1314 Key::try_from_var(alloc::vec![0u8; limits::STORAGE_KEY_BYTES as usize])
1315 .expect("Key of maximal size shall be created")
1316 .hash()
1317 .len()
1318 .try_into()
1319 .unwrap();
1320
1321 let max_immutable_key_size: u64 = T::AccountId::max_encoded_len().try_into().unwrap();
1322 let max_immutable_size: u64 = max_block_weight
1323 .checked_div_per_component(&<RuntimeCosts as WeightToken<T>>::weight(
1324 &RuntimeCosts::SetImmutableData(limits::IMMUTABLE_BYTES),
1325 ))
1326 .unwrap()
1327 .saturating_mul(
1328 u64::from(limits::IMMUTABLE_BYTES)
1329 .saturating_add(max_immutable_key_size)
1330 .into(),
1331 );
1332
1333 let max_pvf_mem: u64 = T::PVFMemory::get().into();
1334 let storage_size_limit = max_pvf_mem.saturating_sub(max_runtime_mem) / 2;
1335
1336 let max_event_bytes = u64::from(limits::NUM_EVENT_TOPICS)
1341 .saturating_mul(H256::len_bytes() as u64)
1342 .saturating_add(limits::EVENT_BYTES.into());
1343 let max_events_size = max_block_weight
1344 .checked_div_per_component(
1345 &(<RuntimeCosts as WeightToken<T>>::weight(&RuntimeCosts::DepositEvent {
1346 num_topic: limits::NUM_EVENT_TOPICS,
1347 len: limits::EVENT_BYTES,
1348 })
1349 .saturating_add(<RuntimeCosts as WeightToken<T>>::weight(
1350 &RuntimeCosts::HostFn,
1351 ))),
1352 )
1353 .unwrap()
1354 .saturating_mul(max_event_bytes);
1355
1356 assert!(
1357 max_events_size <= storage_size_limit,
1358 "Maximal events size {} exceeds the events limit {}",
1359 max_events_size,
1360 storage_size_limit
1361 );
1362
1363 let max_eth_block_builder_bytes = block_storage::BLOCK_BUILDER_BYTES;
1367
1368 log::debug!(
1369 target: LOG_TARGET,
1370 "Integrity check: max_events_size={} KB, max_eth_block_builder_bytes={} KB",
1371 max_events_size / 1024,
1372 max_eth_block_builder_bytes / 1024,
1373 );
1374
1375 let memory_left = i128::from(max_runtime_mem)
1380 .saturating_div(TOTAL_MEMORY_DEVIDER.into())
1381 .saturating_sub(limits::MEMORY_REQUIRED.into())
1382 .saturating_sub(max_eth_block_builder_bytes.into());
1383
1384 log::debug!(target: LOG_TARGET, "Integrity check: memory_left={} KB", memory_left / 1024);
1385
1386 assert!(
1387 memory_left >= 0,
1388 "Runtime does not have enough memory for current limits. Additional runtime memory required: {} KB",
1389 memory_left.saturating_mul(TOTAL_MEMORY_DEVIDER.into()).abs() / 1024
1390 );
1391
1392 let max_storage_size = max_block_weight
1395 .checked_div_per_component(
1396 &<RuntimeCosts as WeightToken<T>>::weight(&RuntimeCosts::SetStorage {
1397 new_bytes: limits::STORAGE_BYTES,
1398 old_bytes: 0,
1399 kind: StorageAccessKind::Persistent(Warmth::Cold { revertible: true }),
1400 })
1401 .saturating_mul(u64::from(limits::STORAGE_BYTES).saturating_add(max_key_size)),
1402 )
1403 .unwrap()
1404 .saturating_add(max_immutable_size.into())
1405 .saturating_add(max_eth_block_builder_bytes.into());
1406
1407 assert!(
1408 max_storage_size <= storage_size_limit,
1409 "Maximal storage size {} exceeds the storage limit {}",
1410 max_storage_size,
1411 storage_size_limit
1412 );
1413 }
1414 }
1415
1416 #[pallet::call]
1417 impl<T: Config> Pallet<T> {
1418 #[allow(unused_variables)]
1431 #[pallet::call_index(0)]
1432 #[pallet::weight(Weight::MAX)]
1433 pub fn eth_transact(origin: OriginFor<T>, payload: Vec<u8>) -> DispatchResultWithPostInfo {
1434 Err(frame_system::Error::CallFiltered::<T>.into())
1435 }
1436
1437 #[pallet::call_index(1)]
1454 #[pallet::weight(<T as Config>::WeightInfo::call().saturating_add(*weight_limit))]
1455 pub fn call(
1456 origin: OriginFor<T>,
1457 dest: H160,
1458 #[pallet::compact] value: BalanceOf<T>,
1459 weight_limit: Weight,
1460 #[pallet::compact] storage_deposit_limit: BalanceOf<T>,
1461 data: Vec<u8>,
1462 ) -> DispatchResultWithPostInfo {
1463 Self::ensure_non_contract_if_signed(&origin)?;
1464 let mut output = Self::bare_call(
1465 origin,
1466 dest,
1467 Pallet::<T>::convert_native_to_evm(value),
1468 TransactionLimits::WeightAndDeposit {
1469 weight_limit,
1470 deposit_limit: storage_deposit_limit,
1471 },
1472 data,
1473 &ExecConfig::new_substrate_tx(),
1474 );
1475
1476 if let Ok(return_value) = &output.result &&
1477 return_value.did_revert()
1478 {
1479 output.result = Err(<Error<T>>::ContractReverted.into());
1480 }
1481 dispatch_result(
1482 output.result,
1483 output.weight_consumed,
1484 <T as Config>::WeightInfo::call(),
1485 )
1486 }
1487
1488 #[pallet::call_index(2)]
1494 #[pallet::weight(
1495 <T as Config>::WeightInfo::instantiate(data.len() as u32).saturating_add(*weight_limit)
1496 )]
1497 pub fn instantiate(
1498 origin: OriginFor<T>,
1499 #[pallet::compact] value: BalanceOf<T>,
1500 weight_limit: Weight,
1501 #[pallet::compact] storage_deposit_limit: BalanceOf<T>,
1502 code_hash: sp_core::H256,
1503 data: Vec<u8>,
1504 salt: Option<[u8; 32]>,
1505 ) -> DispatchResultWithPostInfo {
1506 Self::ensure_non_contract_if_signed(&origin)?;
1507 let data_len = data.len() as u32;
1508 let mut output = Self::bare_instantiate(
1509 origin,
1510 Pallet::<T>::convert_native_to_evm(value),
1511 TransactionLimits::WeightAndDeposit {
1512 weight_limit,
1513 deposit_limit: storage_deposit_limit,
1514 },
1515 Code::Existing(code_hash),
1516 data,
1517 salt,
1518 &ExecConfig::new_substrate_tx(),
1519 );
1520 if let Ok(retval) = &output.result &&
1521 retval.result.did_revert()
1522 {
1523 output.result = Err(<Error<T>>::ContractReverted.into());
1524 }
1525 dispatch_result(
1526 output.result.map(|result| result.result),
1527 output.weight_consumed,
1528 <T as Config>::WeightInfo::instantiate(data_len),
1529 )
1530 }
1531
1532 #[pallet::call_index(3)]
1560 #[pallet::weight(
1561 <T as Config>::WeightInfo::instantiate_with_code(code.len() as u32, data.len() as u32)
1562 .saturating_add(*weight_limit)
1563 )]
1564 pub fn instantiate_with_code(
1565 origin: OriginFor<T>,
1566 #[pallet::compact] value: BalanceOf<T>,
1567 weight_limit: Weight,
1568 #[pallet::compact] storage_deposit_limit: BalanceOf<T>,
1569 code: Vec<u8>,
1570 data: Vec<u8>,
1571 salt: Option<[u8; 32]>,
1572 ) -> DispatchResultWithPostInfo {
1573 Self::ensure_non_contract_if_signed(&origin)?;
1574 let code_len = code.len() as u32;
1575 let data_len = data.len() as u32;
1576 let mut output = Self::bare_instantiate(
1577 origin,
1578 Pallet::<T>::convert_native_to_evm(value),
1579 TransactionLimits::WeightAndDeposit {
1580 weight_limit,
1581 deposit_limit: storage_deposit_limit,
1582 },
1583 Code::Upload(code),
1584 data,
1585 salt,
1586 &ExecConfig::new_substrate_tx(),
1587 );
1588 if let Ok(retval) = &output.result &&
1589 retval.result.did_revert()
1590 {
1591 output.result = Err(<Error<T>>::ContractReverted.into());
1592 }
1593 dispatch_result(
1594 output.result.map(|result| result.result),
1595 output.weight_consumed,
1596 <T as Config>::WeightInfo::instantiate_with_code(code_len, data_len),
1597 )
1598 }
1599
1600 #[pallet::call_index(10)]
1622 #[pallet::weight(
1623 <T as Config>::WeightInfo::eth_instantiate_with_code(code.len() as u32, data.len() as u32, Pallet::<T>::has_dust(*value).into())
1624 .saturating_add(*weight_limit)
1625 .saturating_add(T::WeightInfo::on_finalize_block_per_tx(transaction_encoded.len() as u32))
1626 )]
1627 pub fn eth_instantiate_with_code(
1628 origin: OriginFor<T>,
1629 value: U256,
1630 weight_limit: Weight,
1631 eth_gas_limit: U256,
1632 code: Vec<u8>,
1633 data: Vec<u8>,
1634 transaction_encoded: Vec<u8>,
1635 effective_gas_price: U256,
1636 encoded_len: u32,
1637 ) -> DispatchResultWithPostInfo {
1638 let signer = Self::ensure_eth_signed(origin)?;
1639 let origin = OriginFor::<T>::signed(signer.clone());
1640 Self::ensure_non_contract_if_signed(&origin)?;
1641 let mut call = Call::<T>::eth_instantiate_with_code {
1642 value,
1643 weight_limit,
1644 eth_gas_limit,
1645 code: code.clone(),
1646 data: data.clone(),
1647 transaction_encoded: transaction_encoded.clone(),
1648 effective_gas_price,
1649 encoded_len,
1650 }
1651 .into();
1652 let info = T::FeeInfo::dispatch_info(&call);
1653 let base_info = T::FeeInfo::base_dispatch_info(&mut call);
1654 drop(call);
1655
1656 block_storage::with_ethereum_context::<T>(transaction_encoded, || {
1657 let extra_weight = base_info.total_weight();
1658 let output = Self::bare_instantiate(
1659 origin,
1660 value,
1661 TransactionLimits::EthereumGas {
1662 eth_gas_limit: eth_gas_limit.saturated_into(),
1663 weight_limit,
1664 eth_tx_info: EthTxInfo::new(encoded_len, extra_weight),
1665 authorization_deposit: Default::default(),
1666 },
1667 Code::Upload(code),
1668 data,
1669 None,
1670 &ExecConfig::new_eth_tx(effective_gas_price, encoded_len, extra_weight),
1671 );
1672
1673 block_storage::EthereumCallResult::new::<T>(
1674 signer,
1675 output.map_result(|r| r.result),
1676 base_info.call_weight,
1677 encoded_len,
1678 &info,
1679 effective_gas_price,
1680 )
1681 })
1682 }
1683
1684 #[pallet::call_index(11)]
1702 #[pallet::weight(
1703 T::WeightInfo::eth_call(Pallet::<T>::has_dust(*value).into())
1704 .saturating_add(*weight_limit)
1705 .saturating_add(T::WeightInfo::on_finalize_block_per_tx(transaction_encoded.len() as u32))
1706 .saturating_add(evm::eip7702::worst_case_authorization_weight::<T>(authorization_list.len() as u32))
1707 )]
1708 pub fn eth_call(
1709 origin: OriginFor<T>,
1710 dest: H160,
1711 value: U256,
1712 weight_limit: Weight,
1713 eth_gas_limit: U256,
1714 data: Vec<u8>,
1715 transaction_encoded: Vec<u8>,
1716 effective_gas_price: U256,
1717 encoded_len: u32,
1718 authorization_list: Vec<evm::AuthorizationListEntry>,
1719 ) -> DispatchResultWithPostInfo {
1720 let signer = Self::ensure_eth_signed(origin)?;
1721 let origin = OriginFor::<T>::signed(signer.clone());
1722
1723 Self::ensure_non_contract_if_signed(&origin)?;
1724 let mut call = Call::<T>::eth_call {
1725 dest,
1726 value,
1727 weight_limit,
1728 eth_gas_limit,
1729 data: data.clone(),
1730 transaction_encoded: transaction_encoded.clone(),
1731 effective_gas_price,
1732 encoded_len,
1733 authorization_list: authorization_list.clone(),
1734 }
1735 .into();
1736 let info = T::FeeInfo::dispatch_info(&call);
1737 let base_info = T::FeeInfo::base_dispatch_info(&mut call);
1738 drop(call);
1739
1740 let exec_config =
1741 ExecConfig::new_eth_tx(effective_gas_price, encoded_len, base_info.total_weight());
1742 let auth_result = evm::eip7702::process_authorizations::<T>(
1743 &authorization_list,
1744 &signer,
1745 &exec_config,
1746 );
1747 let extra_weight = base_info.total_weight().saturating_sub(auth_result.weight_refund);
1748 let base_call_weight = base_info.call_weight.saturating_sub(auth_result.weight_refund);
1749
1750 block_storage::with_ethereum_context::<T>(transaction_encoded, || {
1751 let output = Self::bare_call(
1752 origin,
1753 dest,
1754 value,
1755 TransactionLimits::EthereumGas {
1756 eth_gas_limit: eth_gas_limit.saturated_into(),
1757 weight_limit,
1758 eth_tx_info: EthTxInfo::new(encoded_len, extra_weight),
1759 authorization_deposit: auth_result.deposit,
1760 },
1761 data,
1762 &ExecConfig::new_eth_tx(effective_gas_price, encoded_len, extra_weight),
1763 );
1764
1765 block_storage::EthereumCallResult::new::<T>(
1766 signer,
1767 output,
1768 base_call_weight,
1769 encoded_len,
1770 &info,
1771 effective_gas_price,
1772 )
1773 })
1774 }
1775
1776 #[pallet::call_index(12)]
1787 #[pallet::weight(
1788 T::WeightInfo::eth_substrate_call(transaction_encoded.len() as u32)
1789 .saturating_add(call.get_dispatch_info().call_weight)
1790 .saturating_add(T::WeightInfo::on_finalize_block_per_tx(transaction_encoded.len() as u32))
1791 )]
1792 pub fn eth_substrate_call(
1793 origin: OriginFor<T>,
1794 call: Box<<T as Config>::RuntimeCall>,
1795 transaction_encoded: Vec<u8>,
1796 ) -> DispatchResultWithPostInfo {
1797 let signer = Self::ensure_eth_signed(origin)?;
1800 Self::ensure_non_contract_if_signed(&OriginFor::<T>::signed(signer.clone()))?;
1801 let tx_len = transaction_encoded.len() as u32;
1802 let weight_overhead = T::WeightInfo::eth_substrate_call(tx_len)
1803 .saturating_add(T::WeightInfo::on_finalize_block_per_tx(tx_len));
1804
1805 block_storage::with_ethereum_context::<T>(transaction_encoded, || {
1806 let call_weight = call.get_dispatch_info().call_weight;
1807 let mut call_result =
1808 call.dispatch(RawOrigin::Signed(signer).into()).and_then(|post_info| {
1809 match block_storage::ensure_receipt_within_limit::<T>() {
1810 Ok(()) => Ok(post_info),
1811 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),
1812 }
1813 });
1814
1815 match &mut call_result {
1817 Ok(post_info) | Err(DispatchErrorWithPostInfo { post_info, .. }) => {
1818 post_info.actual_weight = Some(
1819 post_info
1820 .actual_weight
1821 .unwrap_or_else(|| call_weight)
1822 .saturating_add(weight_overhead),
1823 );
1824 },
1825 }
1826
1827 block_storage::EthereumCallResult {
1830 receipt_gas_info: ReceiptGasInfo::default(),
1831 result: call_result,
1832 }
1833 })
1834 }
1835
1836 #[pallet::call_index(4)]
1851 #[pallet::weight(<T as Config>::WeightInfo::upload_code(code.len() as u32))]
1852 pub fn upload_code(
1853 origin: OriginFor<T>,
1854 code: Vec<u8>,
1855 #[pallet::compact] storage_deposit_limit: BalanceOf<T>,
1856 ) -> DispatchResult {
1857 Self::ensure_non_contract_if_signed(&origin)?;
1858 Self::bare_upload_code(origin, code, storage_deposit_limit).map(|_| ())
1859 }
1860
1861 #[pallet::call_index(5)]
1866 #[pallet::weight(<T as Config>::WeightInfo::remove_code())]
1867 pub fn remove_code(
1868 origin: OriginFor<T>,
1869 code_hash: sp_core::H256,
1870 ) -> DispatchResultWithPostInfo {
1871 let origin = ensure_signed(origin)?;
1872 <ContractBlob<T>>::remove(&origin, code_hash)?;
1873 Ok(Pays::No.into())
1875 }
1876
1877 #[pallet::call_index(6)]
1888 #[pallet::weight(<T as Config>::WeightInfo::set_code())]
1889 pub fn set_code(
1890 origin: OriginFor<T>,
1891 dest: H160,
1892 code_hash: sp_core::H256,
1893 ) -> DispatchResult {
1894 ensure_root(origin)?;
1895 <AccountInfoOf<T>>::try_mutate(&dest, |account| {
1896 let Some(account) = account else {
1897 return Err(<Error<T>>::ContractNotFound.into());
1898 };
1899
1900 let AccountType::Contract(ref mut contract) = account.account_type else {
1901 return Err(<Error<T>>::ContractNotFound.into());
1902 };
1903
1904 <CodeInfo<T>>::increment_refcount(code_hash)?;
1905 let _ = <CodeInfo<T>>::decrement_refcount(contract.code_hash)?;
1906 contract.code_hash = code_hash;
1907
1908 Ok(())
1909 })
1910 }
1911
1912 #[pallet::call_index(7)]
1920 #[pallet::weight(<T as Config>::WeightInfo::map_account())]
1921 pub fn map_account(origin: OriginFor<T>) -> DispatchResult {
1922 #[cfg(not(feature = "runtime-benchmarks"))]
1923 if T::AutoMap::get() {
1924 return Ok(());
1925 }
1926
1927 Self::ensure_non_contract_if_signed(&origin)?;
1928 let origin = ensure_signed(origin)?;
1929 T::AddressMapper::map(&origin)
1930 }
1931
1932 #[pallet::call_index(13)]
1934 #[pallet::weight(<T as Config>::WeightInfo::batch_map_accounts(accounts.len().saturated_into::<u32>()))]
1935 pub fn batch_map_accounts(
1936 origin: OriginFor<T>,
1937 accounts: Vec<T::AccountId>,
1938 ) -> DispatchResultWithPostInfo {
1939 ensure_signed(origin.clone())?;
1940 Self::ensure_non_contract_if_signed(&origin)?;
1941
1942 let total: u32 = accounts.len().saturated_into();
1943 let mut mapped = 0;
1944
1945 for account_id in accounts
1946 .iter()
1947 .filter(|&a| !T::AddressMapper::is_eth_derived(a))
1949 .filter(|&a| frame_system::Pallet::<T>::account_exists(a))
1952 {
1953 let mut useful = false;
1954
1955 match T::AddressMapper::map_no_deposit_unchecked(account_id) {
1956 Ok(()) => {
1957 useful = true;
1958 },
1959 Err(err) => log::debug!(
1960 target: LOG_TARGET,
1961 "Failed to map account {account_id:?}: {err:?}",
1962 ),
1963 }
1964
1965 match T::Currency::release_all(
1966 &HoldReason::AddressMapping.into(),
1967 account_id,
1968 Precision::BestEffort,
1969 ) {
1970 Ok(released) if !released.is_zero() => {
1973 useful = true;
1974 },
1975 Ok(_) => {},
1976 Err(err) => log::debug!(
1977 target: LOG_TARGET,
1978 "Failed to release mapping deposit for {account_id:?}: {err:?}",
1979 ),
1980 }
1981
1982 if useful {
1983 mapped = mapped.saturating_add(1);
1984 }
1985 }
1986
1987 if total == 0 || mapped == 0 {
1989 return Ok(Pays::Yes.into());
1990 }
1991
1992 let proportion_mapped = Perbill::from_rational(mapped, total);
1993 if proportion_mapped >= Perbill::from_percent(90) {
1994 Ok(Pays::No.into())
1995 } else {
1996 Ok(Pays::Yes.into())
1997 }
1998 }
1999
2000 #[pallet::call_index(8)]
2008 #[pallet::weight(<T as Config>::WeightInfo::unmap_account())]
2009 pub fn unmap_account(origin: OriginFor<T>) -> DispatchResult {
2010 #[cfg(not(feature = "runtime-benchmarks"))]
2011 ensure!(!T::AutoMap::get(), <Error<T>>::AutoMappingEnabled);
2012 let origin = ensure_signed(origin)?;
2013 T::AddressMapper::unmap(&origin)
2014 }
2015
2016 #[pallet::call_index(9)]
2022 #[pallet::weight({
2023 let dispatch_info = call.get_dispatch_info();
2024 (
2025 <T as Config>::WeightInfo::dispatch_as_fallback_account().saturating_add(dispatch_info.call_weight),
2026 dispatch_info.class
2027 )
2028 })]
2029 pub fn dispatch_as_fallback_account(
2030 mut origin: OriginFor<T>,
2031 call: Box<<T as Config>::RuntimeCall>,
2032 ) -> DispatchResultWithPostInfo {
2033 Self::ensure_non_contract_if_signed(&origin)?;
2034 let account_id = origin.as_signer().ok_or(DispatchError::BadOrigin)?;
2035 let unmapped_account = T::AddressMapper::to_fallback_account_id(
2036 &T::AddressMapper::to_address(&account_id),
2037 );
2038 origin.set_caller_from(RawOrigin::Signed(unmapped_account));
2039 call.dispatch(origin)
2040 }
2041 }
2042}
2043
2044fn dispatch_result<R>(
2046 result: Result<R, DispatchError>,
2047 weight_consumed: Weight,
2048 base_weight: Weight,
2049) -> DispatchResultWithPostInfo {
2050 let post_info = PostDispatchInfo {
2051 actual_weight: Some(weight_consumed.saturating_add(base_weight)),
2052 pays_fee: Default::default(),
2053 };
2054
2055 result
2056 .map(|_| post_info)
2057 .map_err(|e| DispatchErrorWithPostInfo { post_info, error: e })
2058}
2059
2060impl<T: Config> Pallet<T> {
2061 pub fn bare_call(
2068 origin: OriginFor<T>,
2069 dest: H160,
2070 evm_value: U256,
2071 transaction_limits: TransactionLimits<T>,
2072 data: Vec<u8>,
2073 exec_config: &ExecConfig<T>,
2074 ) -> ContractResult<ExecReturnValue, BalanceOf<T>> {
2075 let mut transaction_meter = match TransactionMeter::new(transaction_limits) {
2076 Ok(transaction_meter) => transaction_meter,
2077 Err(error) => return ContractResult { result: Err(error), ..Default::default() },
2078 };
2079 let mut storage_deposit = Default::default();
2080
2081 let try_call = || {
2082 let origin = ExecOrigin::from_runtime_origin(origin)?;
2083 let result = ExecStack::<T, ContractBlob<T>>::run_call(
2084 origin.clone(),
2085 dest,
2086 &mut transaction_meter,
2087 evm_value,
2088 data,
2089 &exec_config,
2090 )?;
2091
2092 let deposit = transaction_meter
2093 .execute_postponed_deposits(&origin, &exec_config)
2094 .inspect_err(|err| {
2095 log::debug!(target: LOG_TARGET, "Failed to transfer deposit: {err:?}");
2096 })?;
2097 block_storage::ensure_receipt_within_limit::<T>()?;
2099 storage_deposit = deposit;
2100
2101 Ok(result)
2102 };
2103 let result = Self::run_guarded(try_call);
2104
2105 log::trace!(target: LOG_TARGET, "Bare call ends: \
2106 result={result:?}, \
2107 weight_consumed={:?}, \
2108 weight_required={:?}, \
2109 storage_deposit={:?}, \
2110 gas_consumed={:?}, \
2111 max_storage_deposit={:?}",
2112 transaction_meter.weight_consumed(),
2113 transaction_meter.weight_required(),
2114 storage_deposit,
2115 transaction_meter.total_consumed_gas(),
2116 transaction_meter.deposit_required()
2117 );
2118
2119 ContractResult {
2120 result: result.map_err(|r| r.error),
2121 weight_consumed: transaction_meter.weight_consumed(),
2122 weight_required: transaction_meter.weight_required(),
2123 storage_deposit,
2124 gas_consumed: transaction_meter.total_consumed_gas(),
2125 max_storage_deposit: transaction_meter.deposit_required(),
2126 }
2127 }
2128
2129 pub fn prepare_dry_run(account: &T::AccountId) {
2135 frame_system::Pallet::<T>::inc_account_nonce(account);
2138
2139 if !T::AddressMapper::is_mapped(account) {
2142 let _ = T::AddressMapper::map_no_deposit_unchecked(account);
2143 }
2144 }
2145
2146 pub fn bare_instantiate(
2152 origin: OriginFor<T>,
2153 evm_value: U256,
2154 transaction_limits: TransactionLimits<T>,
2155 code: Code,
2156 data: Vec<u8>,
2157 salt: Option<[u8; 32]>,
2158 exec_config: &ExecConfig<T>,
2159 ) -> ContractResult<InstantiateReturnValue, BalanceOf<T>> {
2160 let mut transaction_meter = match TransactionMeter::new(transaction_limits) {
2161 Ok(transaction_meter) => transaction_meter,
2162 Err(error) => return ContractResult { result: Err(error), ..Default::default() },
2163 };
2164
2165 let mut storage_deposit = Default::default();
2166
2167 let try_instantiate = || {
2168 let instantiate_account = T::InstantiateOrigin::ensure_origin(origin.clone())?;
2169
2170 if_tracing(|t| t.instantiate_code(&code, salt.as_ref()));
2171 let executable = match code {
2172 Code::Upload(code) if code.starts_with(&polkavm_common::program::BLOB_MAGIC) => {
2173 let upload_account = T::UploadOrigin::ensure_origin(origin)?;
2174 let executable = Self::try_upload_code(
2175 upload_account,
2176 code,
2177 BytecodeType::Pvm,
2178 &mut transaction_meter,
2179 &exec_config,
2180 )?;
2181 executable
2182 },
2183 Code::Upload(code) => {
2184 if T::AllowEVMBytecode::get() {
2185 ensure!(data.is_empty(), <Error<T>>::EvmConstructorNonEmptyData);
2186 let origin = T::UploadOrigin::ensure_origin(origin)?;
2187 let executable = ContractBlob::from_evm_init_code(code, origin)?;
2188 executable
2189 } else {
2190 return Err(<Error<T>>::CodeRejected.into());
2191 }
2192 },
2193 Code::Existing(code_hash) => {
2194 let executable = ContractBlob::from_storage(code_hash, &mut transaction_meter)?;
2195 ensure!(executable.code_info().is_pvm(), <Error<T>>::EvmConstructedFromHash);
2196 executable
2197 },
2198 };
2199 let instantiate_origin = ExecOrigin::from_account_id(instantiate_account.clone());
2200 let result = ExecStack::<T, ContractBlob<T>>::run_instantiate(
2201 instantiate_account,
2202 executable,
2203 &mut transaction_meter,
2204 evm_value,
2205 data,
2206 salt.as_ref(),
2207 &exec_config,
2208 );
2209
2210 let deposit = transaction_meter
2211 .execute_postponed_deposits(&instantiate_origin, &exec_config)
2212 .inspect_err(|err| {
2213 log::debug!(target: LOG_TARGET, "Failed to transfer deposit: {err:?}");
2214 })?;
2215 if result.is_ok() {
2217 block_storage::ensure_receipt_within_limit::<T>()?;
2218 }
2219 storage_deposit = deposit;
2220 result
2221 };
2222 let output = Self::run_guarded(try_instantiate);
2223
2224 log::trace!(target: LOG_TARGET, "Bare instantiate ends: weight_consumed={:?}\
2225 weight_required={:?} \
2226 storage_deposit={:?} \
2227 gas_consumed={:?} \
2228 max_storage_deposit={:?}",
2229 transaction_meter.weight_consumed(),
2230 transaction_meter.weight_required(),
2231 storage_deposit,
2232 transaction_meter.total_consumed_gas(),
2233 transaction_meter.deposit_required()
2234 );
2235
2236 ContractResult {
2237 result: output
2238 .map(|(addr, result)| InstantiateReturnValue { result, addr })
2239 .map_err(|e| e.error),
2240 weight_consumed: transaction_meter.weight_consumed(),
2241 weight_required: transaction_meter.weight_required(),
2242 storage_deposit,
2243 gas_consumed: transaction_meter.total_consumed_gas(),
2244 max_storage_deposit: transaction_meter.deposit_required(),
2245 }
2246 }
2247
2248 pub fn eth_estimate_gas(
2260 tx: GenericTransaction,
2261 timestamp_override: Option<MomentOf<T>>,
2262 state_overrides: Option<StateOverrideSet>,
2263 ) -> Result<U256, EthTransactError>
2264 where
2265 T::Nonce: Into<U256> + TryFrom<U256>,
2266 CallOf<T>: SetWeightLimit,
2267 {
2268 log::debug!(target: LOG_TARGET, "eth_estimate_gas: {tx:?}");
2269
2270 let mut low = U256::zero();
2271 let mut high = Self::evm_block_gas_limit();
2272
2273 log::trace!(target: LOG_TARGET, "eth_estimate_gas starting with low={low}, high={high}");
2274
2275 let perform_balance_checks = if let Some(gas_limit) = tx.gas {
2279 high = gas_limit;
2280 log::trace!(target: LOG_TARGET, "eth_estimate_gas high limited by the gas limit high={high}");
2281 true
2282 } else {
2283 false
2284 };
2285
2286 let fee_cap = tx.max_fee_per_gas.or(tx.gas_price);
2288 if let (Some(fee_cap), Some(from), true) = (fee_cap, tx.from, perform_balance_checks) {
2289 let mut available_balance = Self::evm_balance(&from);
2290 if let Some(value) = tx.value {
2291 available_balance = available_balance.checked_sub(value).ok_or_else(|| {
2292 EthTransactError::Message("insufficient funds for value transfer".into())
2293 })?;
2294 }
2295 if let Some(allowance) = available_balance.checked_div(fee_cap) {
2296 if high > allowance && allowance != U256::zero() {
2297 log::trace!(target: LOG_TARGET, "eth_estimate_gas high limited by the user's allowance high={high} allowance={allowance}");
2298 high = allowance
2299 }
2300 }
2301 }
2302
2303 let dry_run_at = |gas: U256| {
2307 let mut transaction = tx.clone();
2308 transaction.gas = Some(gas);
2309 with_transaction(|| {
2310 TransactionOutcome::Rollback(Ok::<_, DispatchError>(Self::dry_run_eth_transact(
2311 transaction,
2312 timestamp_override,
2313 perform_balance_checks,
2314 state_overrides.clone(),
2315 )))
2316 })
2317 .expect("Rollback shouldn't error out")
2318 };
2319
2320 let is_simple_transfer = with_transaction(|| {
2323 let probe = state_overrides
2324 .clone()
2325 .map_or(Ok(()), state_overrides::apply_state_overrides::<T>)
2326 .map(|()| Self::is_simple_transfer(&tx));
2327 TransactionOutcome::Rollback(Ok::<_, DispatchError>(probe))
2328 })
2329 .expect("Rollback shouldn't error out")?;
2330
2331 if is_simple_transfer {
2332 let dry_run_result = dry_run_at(high)?;
2333 log::trace!(
2334 target: LOG_TARGET,
2335 "eth_estimate_gas short-circuited simple transfer to {:?} with eth_gas={}",
2336 tx.to,
2337 dry_run_result.eth_gas,
2338 );
2339 return Ok(dry_run_result.eth_gas);
2340 }
2341
2342 let dry_run_results = [high, Self::evm_max_extrinsic_weight_in_gas()]
2347 .map(|gas_limit| (gas_limit, dry_run_at(gas_limit)));
2348 let (gas_limit, first_dry_run_result) = match dry_run_results {
2349 [(gas_limit1, Ok(dry_run_result1)), (gas_limit2, Ok(dry_run_result2))] => {
2350 if dry_run_result2.eth_gas >= gas_limit2 {
2351 (gas_limit1, dry_run_result1)
2352 } else {
2353 (gas_limit2, dry_run_result2)
2354 }
2355 },
2356 [(gas_limit, Ok(dry_run_result)), (_, Err(_))] |
2357 [(_, Err(_)), (gas_limit, Ok(dry_run_result))] => (gas_limit, dry_run_result),
2358 [(_, Err(err)), (_, Err(..))] => return Err(err),
2359 };
2360 log::trace!(
2361 target: LOG_TARGET,
2362 "eth_estimate_gas first dry run succeeded with gas_limit={} consumed={}",
2363 gas_limit,
2364 first_dry_run_result.eth_gas
2365 );
2366 low = first_dry_run_result.eth_gas;
2367 high = gas_limit;
2368
2369 while low + U256::one() < high {
2374 log::trace!(target: LOG_TARGET, "eth_estimate_gas estimation iteration with low={low} high={high}");
2375 let error_ratio = high
2376 .checked_sub(low)
2377 .and_then(|value| value.checked_mul(U256::from(1000)))
2378 .and_then(|value| value.checked_div(high))
2379 .ok_or_else(|| {
2380 EthTransactError::Message(
2381 "failed to calculate error ratio in gas estimation".into(),
2382 )
2383 })?;
2384 if error_ratio <= U256::from(15) {
2385 log::trace!(
2386 target: LOG_TARGET,
2387 "eth_estimate_gas finished due to error ratio being less than 1.5% high={}",
2388 high
2389 );
2390 break;
2391 }
2392
2393 let mut midpoint = high
2394 .checked_sub(low)
2395 .and_then(|value| value.checked_div(U256::from(2)))
2396 .and_then(|value| value.checked_add(low))
2397 .ok_or_else(|| {
2398 EthTransactError::Message(
2399 "failed to calculate midpoint in gas estimation".into(),
2400 )
2401 })?;
2402
2403 if let Some(other_midpoint) = low.checked_mul(U256::from(2)) {
2404 if other_midpoint != U256::zero() {
2405 midpoint = midpoint.min(other_midpoint)
2406 }
2407 };
2408
2409 let dry_run_result = dry_run_at(midpoint);
2410 log::trace!(target: LOG_TARGET, "eth_estimate_gas dry run result with midpoint={midpoint} is dry_run_result={dry_run_result:?}");
2411 match dry_run_result {
2412 Ok(..) => {
2413 log::trace!(target: LOG_TARGET, "eth_estimate_gas dry run succeeded, new high={midpoint}");
2414 high = midpoint
2415 },
2416 Err(..) => {
2417 log::trace!(target: LOG_TARGET, "eth_estimate_gas dry run failed, new low={midpoint}");
2418 low = midpoint
2419 },
2420 }
2421 }
2422
2423 log::trace!(target: LOG_TARGET, "eth_estimate_gas completed. high={high}");
2424 Ok(high)
2425 }
2426
2427 pub(crate) fn is_simple_transfer(tx: &GenericTransaction) -> bool {
2429 tx.to
2430 .map(|to| tx.has_simple_transfer_fields() && Self::address_runs_no_code(&to))
2431 .unwrap_or(false)
2432 }
2433
2434 fn address_runs_no_code(address: &H160) -> bool {
2438 *address != RUNTIME_PALLETS_ADDR &&
2439 !exec::is_precompile::<T, ContractBlob<T>>(address) &&
2440 !<AccountInfo<T>>::is_contract(address) &&
2441 !<AccountInfo<T>>::is_delegated(address)
2442 }
2443
2444 pub fn eth_pre_dispatch_weight(transaction_encoded: Vec<u8>) -> Result<Weight, EthTransactError>
2452 where
2453 CallOf<T>: SetWeightLimit,
2454 {
2455 let signed_tx =
2456 crate::evm::TransactionSigned::decode(&transaction_encoded).map_err(|err| {
2457 EthTransactError::Message(format!("Failed to decode transaction: {err:?}"))
2458 })?;
2459 let signer_addr = signed_tx.recover_eth_address().map_err(|err| {
2460 EthTransactError::Message(format!("Failed to recover signer: {err:?}"))
2461 })?;
2462 let tx =
2463 GenericTransaction::from_signed(signed_tx, Self::evm_base_fee(), Some(signer_addr));
2464 let encoded_len = T::FeeInfo::encoded_len(
2465 crate::Call::<T>::eth_transact { payload: transaction_encoded.clone() }.into(),
2466 );
2467 let call_info = tx
2468 .into_call::<T>(CreateCallMode::ExtrinsicExecution(encoded_len, transaction_encoded))
2469 .map_err(|err| EthTransactError::Message(format!("Invalid call: {err:?}")))?;
2470 let info = T::FeeInfo::dispatch_info(&call_info.call);
2471
2472 Ok(frame_system::calculate_consumed_extrinsic_weight::<CallOf<T>>(
2473 &T::BlockWeights::get(),
2474 &info,
2475 call_info.encoded_len as usize,
2476 ))
2477 }
2478
2479 pub fn dry_run_eth_transact(
2491 mut tx: GenericTransaction,
2492 timestamp_override: Option<MomentOf<T>>,
2493 perform_balance_checks: bool,
2494 state_overrides: Option<StateOverrideSet>,
2495 ) -> Result<EthTransactInfo<BalanceOf<T>>, EthTransactError>
2496 where
2497 T::Nonce: Into<U256> + TryFrom<U256>,
2498 CallOf<T>: SetWeightLimit,
2499 {
2500 log::debug!(target: LOG_TARGET, "dry_run_eth_transact: {tx:?}");
2501
2502 if !tx.authorization_list.is_empty() && tx.from.is_none() {
2506 return Err(EthTransactError::Message(
2507 "a transaction with an authorization list requires a `from` address: \
2508 the authorization deposits are charged to it"
2509 .into(),
2510 ));
2511 }
2512
2513 let origin = T::AddressMapper::to_account_id(&tx.from.unwrap_or_default());
2514 Self::prepare_dry_run(&origin);
2515
2516 if let Some(overrides) = state_overrides {
2517 state_overrides::apply_state_overrides::<T>(overrides)?;
2518 }
2519
2520 let base_fee = Self::evm_base_fee();
2521 let effective_gas_price = tx.effective_gas_price(base_fee).unwrap_or(base_fee);
2522
2523 if effective_gas_price < base_fee {
2524 Err(EthTransactError::Message(format!(
2525 "Effective gas price {effective_gas_price:?} lower than base fee {base_fee:?}"
2526 )))?;
2527 }
2528
2529 if tx.nonce.is_none() {
2530 tx.nonce = Some(<System<T>>::account_nonce(&origin).into());
2531 }
2532 if tx.chain_id.is_none() {
2533 tx.chain_id = Some(T::ChainId::get().into());
2534 }
2535
2536 tx.gas_price = Some(effective_gas_price);
2538 tx.max_priority_fee_per_gas = Some(0.into());
2541 if tx.max_fee_per_gas.is_none() {
2542 tx.max_fee_per_gas = Some(effective_gas_price);
2543 }
2544
2545 let gas = tx.gas;
2546 if tx.gas.is_none() {
2547 tx.gas = Some(Self::evm_block_gas_limit());
2548 }
2549 if tx.r#type.is_none() {
2550 tx.r#type = Some(
2551 if tx.authorization_list.is_empty() { TYPE_EIP1559 } else { TYPE_EIP7702 }.into(),
2552 );
2553 }
2554
2555 let authorization_list = tx.authorization_list.clone();
2557 let value = tx.value.unwrap_or_default();
2558 let input = tx.input.clone().to_vec();
2559 let from = tx.from;
2560 let to = tx.to;
2561
2562 let mut call_info = tx
2565 .into_call::<T>(CreateCallMode::DryRun)
2566 .map_err(|err| EthTransactError::Message(format!("Invalid call: {err:?}")))?;
2567
2568 let base_info = T::FeeInfo::base_dispatch_info(&mut call_info.call);
2572 let mut base_weight = base_info.total_weight();
2573
2574 let fees = call_info.tx_fee.saturating_add(call_info.storage_deposit);
2576 if let Some(from) = &from {
2577 let fees = if gas.is_some() && perform_balance_checks { fees } else { Zero::zero() };
2578 let balance = Self::evm_balance(from);
2579 if balance < Pallet::<T>::convert_native_to_evm(fees).saturating_add(value) {
2580 return Err(EthTransactError::Message(format!(
2581 "insufficient funds for gas * price + value ({fees:?}): address {from:?} have {balance:?} (supplied gas {gas:?})",
2582 )));
2583 }
2584 }
2585
2586 T::FeeInfo::deposit_txfee(T::Currency::issue(fees));
2589
2590 let extract_error = |err| {
2591 if err == Error::<T>::StorageDepositNotEnoughFunds.into() {
2592 Err(EthTransactError::Message(format!("Not enough gas supplied: {err:?}")))
2593 } else {
2594 Err(EthTransactError::Message(format!("failed to run contract: {err:?}")))
2595 }
2596 };
2597
2598 let exec_config =
2599 ExecConfig::new_eth_tx(effective_gas_price, call_info.encoded_len, base_weight);
2600 let auth_result =
2601 evm::eip7702::process_authorizations::<T>(&authorization_list, &origin, &exec_config);
2602 base_weight = base_weight.saturating_sub(auth_result.weight_refund);
2603 let actual_auth_deposit = auth_result.deposit;
2604 let worst_case_auth_deposit = Self::worst_case_delegation_deposit()
2605 .saturating_mul(authorization_list.len().saturated_into());
2606
2607 let exec_config =
2608 ExecConfig::new_eth_tx(effective_gas_price, call_info.encoded_len, base_weight)
2609 .with_dry_run(timestamp_override);
2610
2611 let transaction_limits = TransactionLimits::EthereumGas {
2612 eth_gas_limit: call_info.eth_gas_limit.saturated_into(),
2613 weight_limit: Self::evm_max_extrinsic_weight()
2616 .saturating_sub(base_info.total_weight())
2617 .min(call_info.weight_limit),
2620 eth_tx_info: EthTxInfo::new(call_info.encoded_len, base_weight),
2621 authorization_deposit: actual_auth_deposit,
2622 };
2623
2624 let (mut dry_run, weight_consumed) = block_storage::with_receipt_scope::<T, _>(|| {
2627 let dry_run = match to {
2628 Some(dest) => {
2630 if dest == RUNTIME_PALLETS_ADDR {
2631 let Ok(dispatch_call) = <CallOf<T>>::decode(&mut &input[..]) else {
2632 return Err(EthTransactError::Message(format!(
2633 "Failed to decode pallet-call {input:?}"
2634 )));
2635 };
2636
2637 if let Err(result) =
2638 dispatch_call.clone().dispatch(RawOrigin::Signed(origin).into())
2639 {
2640 return Err(EthTransactError::Message(format!(
2641 "Failed to dispatch call: {:?}",
2642 result.error,
2643 )));
2644 };
2645 if let Err(err) = block_storage::ensure_receipt_within_limit::<T>() {
2646 return Err(EthTransactError::Message(format!(
2647 "Failed to dispatch call: {err:?}"
2648 )));
2649 }
2650
2651 Default::default()
2652 } else {
2653 let result = crate::Pallet::<T>::bare_call(
2655 OriginFor::<T>::signed(origin),
2656 dest,
2657 value,
2658 transaction_limits,
2659 input.clone(),
2660 &exec_config,
2661 );
2662
2663 let data = match result.result {
2664 Ok(return_value) => {
2665 if return_value.did_revert() {
2666 return Err(EthTransactError::Data(return_value.data));
2667 }
2668 return_value.data
2669 },
2670 Err(err) => {
2671 log::debug!(target: LOG_TARGET, "Failed to execute call: {err:?}");
2672 return extract_error(err);
2673 },
2674 };
2675
2676 (
2677 EthTransactInfo {
2678 weight_required: result.weight_required,
2679 storage_deposit: result.storage_deposit.charge_or_zero(),
2680 max_storage_deposit: result.max_storage_deposit.charge_or_zero(),
2681 data,
2682 eth_gas: Default::default(),
2683 },
2684 result.weight_consumed,
2685 )
2686 }
2687 },
2688 None => {
2690 let (code, data) = if input.starts_with(&polkavm_common::program::BLOB_MAGIC) {
2692 extract_code_and_data(&input).unwrap_or_else(|| (input, Default::default()))
2693 } else {
2694 (input, vec![])
2695 };
2696
2697 let result = crate::Pallet::<T>::bare_instantiate(
2699 OriginFor::<T>::signed(origin),
2700 value,
2701 transaction_limits,
2702 Code::Upload(code.clone()),
2703 data.clone(),
2704 None,
2705 &exec_config,
2706 );
2707
2708 let returned_data = match result.result {
2709 Ok(return_value) => {
2710 if return_value.result.did_revert() {
2711 return Err(EthTransactError::Data(return_value.result.data));
2712 }
2713 return_value.result.data
2714 },
2715 Err(err) => {
2716 log::debug!(target: LOG_TARGET, "Failed to instantiate: {err:?}");
2717 return extract_error(err);
2718 },
2719 };
2720
2721 (
2722 EthTransactInfo {
2723 weight_required: result.weight_required,
2724 storage_deposit: result.storage_deposit.charge_or_zero(),
2725 max_storage_deposit: result.max_storage_deposit.charge_or_zero(),
2726 data: returned_data,
2727 eth_gas: Default::default(),
2728 },
2729 result.weight_consumed,
2730 )
2731 },
2732 };
2733 Ok(dry_run)
2734 })?;
2735
2736 dry_run.max_storage_deposit = dry_run.max_storage_deposit.max(worst_case_auth_deposit);
2740
2741 call_info.call.set_weight_limit(dry_run.weight_required);
2743
2744 let total_weight = T::FeeInfo::dispatch_info(&call_info.call).total_weight();
2746 let max_weight = Self::evm_max_extrinsic_weight();
2747 if total_weight.any_gt(max_weight) {
2748 log::debug!(target: LOG_TARGET, "Transaction weight estimate exceeds extrinsic maximum: \
2749 total_weight={total_weight:?} \
2750 max_weight={max_weight:?}",
2751 );
2752
2753 Err(EthTransactError::Message(format!(
2754 "\
2755 The transaction consumes more than the allowed weight. \
2756 needed={total_weight} \
2757 allowed={max_weight} \
2758 overweight_by={}\
2759 ",
2760 total_weight.saturating_sub(max_weight),
2761 )))?;
2762 }
2763
2764 let actual_fee = T::FeeInfo::tx_fee_from_weight(
2768 call_info.encoded_len,
2769 &weight_consumed.saturating_add(base_weight),
2770 );
2771 let available_fee = T::FeeInfo::remaining_txfee();
2772 if actual_fee > available_fee {
2773 Err(EthTransactError::Message(format!(
2774 "Not enough gas supplied: Off by: {:?}",
2775 actual_fee.saturating_sub(available_fee),
2776 )))?;
2777 }
2778
2779 let transaction_fee = T::FeeInfo::tx_fee(call_info.encoded_len, &call_info.call);
2782 let total_cost = transaction_fee.saturating_add(dry_run.max_storage_deposit);
2783 let total_cost_wei = Pallet::<T>::convert_native_to_evm(total_cost);
2784 let (mut eth_gas, rest) = total_cost_wei.div_mod(base_fee);
2785 if !rest.is_zero() {
2786 eth_gas = eth_gas.saturating_add(1_u32.into());
2787 }
2788
2789 log::debug!(target: LOG_TARGET, "\
2790 dry_run_eth_transact finished: \
2791 weight_limit={}, \
2792 weight_consumed={weight_consumed}, \
2793 total_weight={total_weight}, \
2794 max_weight={max_weight}, \
2795 weight_left={}, \
2796 eth_gas={eth_gas}, \
2797 encoded_len={}, \
2798 tx_fee={transaction_fee:?}, \
2799 storage_deposit={:?}, \
2800 max_storage_deposit={:?}\
2801 ",
2802 dry_run.weight_required,
2803 max_weight.saturating_sub(total_weight),
2804 call_info.encoded_len,
2805 dry_run.storage_deposit,
2806 dry_run.max_storage_deposit,
2807
2808 );
2809 dry_run.eth_gas = eth_gas;
2810 Ok(dry_run)
2811 }
2812
2813 pub fn evm_balance(address: &H160) -> U256 {
2817 let balance = AccountInfo::<T>::balance_of((*address).into());
2818 Self::convert_native_to_evm(balance)
2819 }
2820
2821 pub fn eth_block() -> EthBlock {
2823 EthereumBlock::<T>::get()
2824 }
2825
2826 pub fn eth_block_hash_from_number(number: U256) -> Option<H256> {
2833 let number = BlockNumberFor::<T>::try_from(number).ok()?;
2834 let hash = <BlockHash<T>>::get(number);
2835 if hash == H256::zero() { None } else { Some(hash) }
2836 }
2837
2838 pub fn eth_receipt_data() -> Vec<ReceiptGasInfo> {
2840 ReceiptInfoData::<T>::get()
2841 }
2842
2843 pub fn set_evm_balance(address: &H160, evm_value: U256) -> Result<(), Error<T>> {
2849 let (balance, dust) = Self::new_balance_with_dust(evm_value)
2850 .map_err(|_| <Error<T>>::BalanceConversionFailed)?;
2851 let account_id = T::AddressMapper::to_account_id(&address);
2852 T::Currency::set_balance(&account_id, balance);
2853 AccountInfoOf::<T>::mutate(&address, |account| {
2854 if let Some(account) = account {
2855 account.dust = dust;
2856 } else {
2857 *account = Some(AccountInfo { dust, ..Default::default() });
2858 }
2859 });
2860
2861 Ok(())
2862 }
2863
2864 pub fn new_balance_with_dust(
2868 evm_value: U256,
2869 ) -> Result<(BalanceOf<T>, u32), BalanceConversionError> {
2870 let ed = T::Currency::minimum_balance();
2871 let balance_with_dust = BalanceWithDust::<BalanceOf<T>>::from_value::<T>(evm_value)?;
2872 let (value, dust) = balance_with_dust.deconstruct();
2873
2874 Ok((ed.saturating_add(value), dust))
2875 }
2876
2877 pub fn evm_nonce(address: &H160) -> u32
2879 where
2880 T::Nonce: Into<u32>,
2881 {
2882 let account = T::AddressMapper::to_account_id(&address);
2883 System::<T>::account_nonce(account).into()
2884 }
2885
2886 pub fn evm_block_gas_limit() -> U256 {
2888 u64::MAX.into()
2895 }
2896
2897 pub fn evm_max_extrinsic_weight_in_gas() -> U256 {
2899 let max_extrinsic_fee = T::FeeInfo::weight_to_fee(&Self::evm_max_extrinsic_weight());
2900 let gas_scale: BalanceOf<T> = T::GasScale::get().into();
2901 (max_extrinsic_fee / gas_scale).into()
2902 }
2903
2904 pub fn evm_max_extrinsic_weight() -> Weight {
2906 let factor = <T as Config>::MaxEthExtrinsicWeight::get();
2907 let max_weight = <T as frame_system::Config>::BlockWeights::get()
2908 .get(DispatchClass::Normal)
2909 .max_extrinsic
2910 .unwrap_or_else(|| <T as frame_system::Config>::BlockWeights::get().max_block);
2911 Weight::from_parts(
2912 factor.saturating_mul_int(max_weight.ref_time()),
2913 factor.saturating_mul_int(max_weight.proof_size()),
2914 )
2915 }
2916
2917 pub fn evm_base_fee() -> U256 {
2919 let gas_scale = <T as Config>::GasScale::get();
2920 let multiplier = T::FeeInfo::next_fee_multiplier();
2921 multiplier
2922 .saturating_mul_int::<u128>(T::NativeToEthRatio::get().into())
2923 .saturating_mul(gas_scale.saturated_into())
2924 .into()
2925 }
2926
2927 pub fn evm_tracer(tracer_type: TracerType) -> Tracer<T>
2929 where
2930 T::Nonce: Into<u32>,
2931 {
2932 match tracer_type {
2933 TracerType::CallTracer(config) => CallTracer::new(config.unwrap_or_default()).into(),
2934 TracerType::PrestateTracer(config) => {
2935 PrestateTracer::new(config.unwrap_or_default()).into()
2936 },
2937 TracerType::ExecutionTracer(config) => {
2938 ExecutionTracer::new(config.unwrap_or_default()).into()
2939 },
2940 }
2941 }
2942
2943 pub fn bare_upload_code(
2947 origin: OriginFor<T>,
2948 code: Vec<u8>,
2949 storage_deposit_limit: BalanceOf<T>,
2950 ) -> CodeUploadResult<BalanceOf<T>> {
2951 let origin = T::UploadOrigin::ensure_origin(origin)?;
2952
2953 let bytecode_type = if code.starts_with(&polkavm_common::program::BLOB_MAGIC) {
2954 BytecodeType::Pvm
2955 } else {
2956 if !T::AllowEVMBytecode::get() {
2957 return Err(<Error<T>>::CodeRejected.into());
2958 }
2959 BytecodeType::Evm
2960 };
2961
2962 let mut meter = TransactionMeter::new(TransactionLimits::WeightAndDeposit {
2963 weight_limit: Default::default(),
2964 deposit_limit: storage_deposit_limit,
2965 })?;
2966
2967 let module = Self::try_upload_code(
2968 origin,
2969 code,
2970 bytecode_type,
2971 &mut meter,
2972 &ExecConfig::new_substrate_tx(),
2973 )?;
2974 Ok(CodeUploadReturnValue {
2975 code_hash: *module.code_hash(),
2976 deposit: meter.deposit_consumed().charge_or_zero(),
2977 })
2978 }
2979
2980 pub fn get_storage(address: H160, key: [u8; 32]) -> GetStorageResult {
2982 let contract_info =
2983 AccountInfo::<T>::load_contract(&address).ok_or(ContractAccessError::DoesntExist)?;
2984
2985 let maybe_value = contract_info.read(&Key::from_fixed(key));
2986 Ok(maybe_value)
2987 }
2988
2989 pub fn get_immutables(address: H160) -> Option<ImmutableData> {
2993 let immutable_data = <ImmutableDataOf<T>>::get(address);
2994 immutable_data
2995 }
2996
2997 pub fn set_immutables(address: H160, data: ImmutableData) -> Result<(), ContractAccessError> {
3006 AccountInfo::<T>::load_contract(&address).ok_or(ContractAccessError::DoesntExist)?;
3007 <ImmutableDataOf<T>>::insert(address, data);
3008 Ok(())
3009 }
3010
3011 pub fn get_storage_var_key(address: H160, key: Vec<u8>) -> GetStorageResult {
3013 let contract_info =
3014 AccountInfo::<T>::load_contract(&address).ok_or(ContractAccessError::DoesntExist)?;
3015
3016 let maybe_value = contract_info.read(
3017 &Key::try_from_var(key)
3018 .map_err(|_| ContractAccessError::KeyDecodingFailed)?
3019 .into(),
3020 );
3021 Ok(maybe_value)
3022 }
3023
3024 pub fn convert_native_to_evm(value: impl Into<BalanceWithDust<BalanceOf<T>>>) -> U256 {
3026 let (value, dust) = value.into().deconstruct();
3027 value
3028 .into()
3029 .saturating_mul(T::NativeToEthRatio::get().into())
3030 .saturating_add(dust.into())
3031 }
3032
3033 pub fn set_storage(address: H160, key: [u8; 32], value: Option<Vec<u8>>) -> SetStorageResult {
3043 let contract_info =
3044 AccountInfo::<T>::load_contract(&address).ok_or(ContractAccessError::DoesntExist)?;
3045
3046 contract_info
3047 .write(&Key::from_fixed(key), value, None, false)
3048 .map_err(ContractAccessError::StorageWriteFailed)
3049 }
3050
3051 pub fn set_storage_var_key(
3062 address: H160,
3063 key: Vec<u8>,
3064 value: Option<Vec<u8>>,
3065 ) -> SetStorageResult {
3066 let contract_info =
3067 AccountInfo::<T>::load_contract(&address).ok_or(ContractAccessError::DoesntExist)?;
3068
3069 contract_info
3070 .write(
3071 &Key::try_from_var(key)
3072 .map_err(|_| ContractAccessError::KeyDecodingFailed)?
3073 .into(),
3074 value,
3075 None,
3076 false,
3077 )
3078 .map_err(ContractAccessError::StorageWriteFailed)
3079 }
3080
3081 pub fn account_id() -> T::AccountId {
3083 use frame_support::PalletId;
3084 use sp_runtime::traits::AccountIdConversion;
3085 PalletId(*b"py/reviv").into_account_truncating()
3086 }
3087
3088 pub fn block_author() -> H160 {
3090 use frame_support::traits::FindAuthor;
3091
3092 let digest = <frame_system::Pallet<T>>::digest();
3093 let pre_runtime_digests = digest.logs.iter().filter_map(|d| d.as_pre_runtime());
3094
3095 T::FindAuthor::find_author(pre_runtime_digests)
3096 .map(|account_id| T::AddressMapper::to_address(&account_id))
3097 .unwrap_or_default()
3098 }
3099
3100 pub fn code(address: &H160) -> Vec<u8> {
3105 use precompiles::{All, Precompiles};
3106 if let Some(code) = <All<T>>::code(address.as_fixed_bytes()) {
3107 return code.into();
3108 }
3109
3110 let Some(info) = <AccountInfoOf<T>>::get(address) else { return Vec::new() };
3111
3112 match info.account_type {
3113 AccountType::Contract(contract) => <PristineCode<T>>::get(contract.code_hash)
3114 .map(|code| code.into())
3115 .unwrap_or_default(),
3116 AccountType::DelegatedEOA { delegate_target: Some(target), .. } => {
3117 AccountInfo::<T>::delegation_indicator(&target).to_vec()
3118 },
3119 AccountType::EOA | AccountType::DelegatedEOA { .. } => Vec::new(),
3120 }
3121 }
3122
3123 pub fn try_upload_code(
3125 origin: T::AccountId,
3126 code: Vec<u8>,
3127 code_type: BytecodeType,
3128 meter: &mut TransactionMeter<T>,
3129 exec_config: &ExecConfig<T>,
3130 ) -> Result<ContractBlob<T>, DispatchError> {
3131 let mut module = match code_type {
3132 BytecodeType::Pvm => ContractBlob::from_pvm_code(code, origin)?,
3133 BytecodeType::Evm => ContractBlob::from_evm_runtime_code(code, origin)?,
3134 };
3135 module.store_code(exec_config, meter)?;
3136 Ok(module)
3137 }
3138
3139 fn run_guarded<R, F: FnOnce() -> Result<R, ExecError>>(f: F) -> Result<R, ExecError> {
3141 executing_contract::using_once(&mut false, || {
3142 executing_contract::with(|f| {
3143 if *f {
3145 return Err(())
3146 }
3147 *f = true;
3149 Ok(())
3150 })
3151 .expect("Returns `Ok` if called within `using_once`. It is syntactically obvious that this is the case; qed")
3152 .map_err(|_| <Error<T>>::ReenteredPallet.into())
3153 .map(|_| f())
3154 .and_then(|r| r)
3155 })
3156 }
3157
3158 fn charge_deposit(
3163 hold_reason: HoldReason,
3164 from: &T::AccountId,
3165 to: &T::AccountId,
3166 amount: BalanceOf<T>,
3167 exec_config: &ExecConfig<T>,
3168 ) -> DispatchResult {
3169 if amount.is_zero() {
3170 return Ok(());
3171 }
3172
3173 T::Deposit::charge_and_hold(hold_reason, exec_config.funds(from), to, amount)
3174 .map_err(|_| Error::<T>::StorageDepositNotEnoughFunds)?;
3175 Ok(())
3176 }
3177
3178 pub(crate) fn refund_deposit(
3183 hold_reason: HoldReason,
3184 from: &T::AccountId,
3185 dst: deposit_payment::Funds<T::AccountId>,
3186 amount: BalanceOf<T>,
3187 ) -> Result<(), DispatchError> {
3188 if amount.is_zero() {
3189 return Ok(());
3190 }
3191
3192 let to = match &dst {
3193 deposit_payment::Funds::Balance(to) | deposit_payment::Funds::TxFee(to) => *to,
3194 };
3195 let result = T::Deposit::refund_on_hold(hold_reason, from, dst, amount);
3196
3197 result.defensive_map_err(|err| {
3198 let available = T::Deposit::total_on_hold(hold_reason, from);
3199 if available < amount {
3200 log::error!(
3203 target: LOG_TARGET,
3204 "Failed to refund storage deposit {amount:?} from contract {from:?} to origin {to:?}. Not enough deposit: {available:?}. This is a bug.",
3205 );
3206 Error::<T>::StorageRefundNotEnoughFunds.into()
3207 } else {
3208 log::warn!(
3213 target: LOG_TARGET,
3214 "Failed to refund storage deposit {amount:?} from contract {from:?} to origin {to:?}: {err:?}. First remove locks (staking, governance) from the contracts account.",
3215 );
3216 Error::<T>::StorageRefundLocked.into()
3217 }
3218 })
3219 }
3220
3221 fn has_dust(value: U256) -> bool {
3223 value % U256::from(<T>::NativeToEthRatio::get()) != U256::zero()
3224 }
3225
3226 fn has_balance(value: U256) -> bool {
3228 value >= U256::from(<T>::NativeToEthRatio::get())
3229 }
3230
3231 #[cfg(any(feature = "runtime-benchmarks", feature = "try-runtime", test))]
3233 fn min_balance() -> BalanceOf<T> {
3234 <T::Currency as Inspect<AccountIdOf<T>>>::minimum_balance()
3235 }
3236
3237 pub(crate) fn worst_case_delegation_deposit() -> BalanceOf<T> {
3241 let ed = <T as Config>::Currency::minimum_balance();
3242 let contract_deposit = T::DepositPerByte::get()
3243 .saturating_mul((<ContractInfo<T>>::max_encoded_len() as u32).into())
3244 .saturating_add(T::DepositPerItem::get());
3245 let max_code_deposit = vm::calculate_code_deposit::<T>(limits::code::BLOB_BYTES);
3246 let code_lockup = T::CodeHashLockupDepositPercent::get().mul_ceil(max_code_deposit);
3247 ed.saturating_add(contract_deposit).saturating_add(code_lockup)
3248 }
3249
3250 fn deposit_event(event: Event<T>) {
3255 <frame_system::Pallet<T>>::deposit_event(<T as Config>::RuntimeEvent::from(event))
3256 }
3257
3258 fn ensure_eth_signed(origin: OriginFor<T>) -> Result<AccountIdOf<T>, DispatchError> {
3260 match <T as Config>::RuntimeOrigin::from(origin).into() {
3261 Ok(Origin::EthTransaction(signer)) => Ok(signer),
3262 _ => Err(BadOrigin.into()),
3263 }
3264 }
3265
3266 fn ensure_non_contract_if_signed(origin: &OriginFor<T>) -> DispatchResult {
3270 if DebugSettings::bypass_eip_3607::<T>() {
3271 return Ok(());
3272 }
3273 let Some(address) = origin
3274 .as_system_ref()
3275 .and_then(|o| o.as_signed())
3276 .map(<T::AddressMapper as AddressMapper<T>>::to_address)
3277 else {
3278 return Ok(());
3279 };
3280 if exec::is_precompile::<T, ContractBlob<T>>(&address) ||
3281 <AccountInfo<T>>::is_contract(&address)
3282 {
3283 log::debug!(
3284 target: crate::LOG_TARGET,
3285 "EIP-3607: reject tx as pre-compile or account exist at {address:?}",
3286 );
3287 Err(DispatchError::BadOrigin)
3288 } else {
3289 Ok(())
3290 }
3291 }
3292}
3293
3294pub const RUNTIME_PALLETS_ADDR: H160 =
3299 H160(hex_literal::hex!("6d6f646c70792f70616464720000000000000000"));
3300
3301environmental!(executing_contract: bool);
3303
3304sp_api::decl_runtime_apis! {
3305 #[api_version(2)]
3307 pub trait ReviveApi<AccountId, Balance, Nonce, BlockNumber, Moment> where
3308 AccountId: Codec,
3309 Balance: Codec,
3310 Nonce: Codec,
3311 BlockNumber: Codec,
3312 Moment: Codec,
3313 {
3314 #[deprecated(note = "Use the versioned equivalent `eth_block_versioned` if available on your runtime")]
3318 fn eth_block() -> BlockV1;
3319
3320 #[deprecated(note = "Use the versioned equivalent `eth_block_hash_versioned` if available on your runtime")]
3322 fn eth_block_hash(number: U256) -> Option<H256>;
3323
3324 #[deprecated(note = "Use the versioned equivalent `eth_receipt_data_versioned` if available on your runtime")]
3333 fn eth_receipt_data() -> Vec<ReceiptGasInfoV1>;
3334
3335 #[deprecated(note = "Use the versioned equivalent `block_gas_limit_versioned` if available on your runtime")]
3337 fn block_gas_limit() -> U256;
3338
3339 #[deprecated(note = "Use the versioned equivalent `max_extrinsic_weight_in_gas_versioned` if available on your runtime")]
3341 fn max_extrinsic_weight_in_gas() -> U256;
3342
3343 #[deprecated(note = "Use the versioned equivalent `balance_versioned` if available on your runtime")]
3345 fn balance(address: H160) -> U256;
3346
3347 #[deprecated(note = "Use the versioned equivalent `gas_price_versioned` if available on your runtime")]
3349 fn gas_price() -> U256;
3350
3351 #[deprecated(note = "Use the versioned equivalent `nonce_versioned` if available on your runtime")]
3353 fn nonce(address: H160) -> Nonce;
3354
3355 #[deprecated(note = "Use the versioned equivalent `call_versioned` if available on your runtime")]
3359 fn call(
3360 origin: AccountId,
3361 dest: H160,
3362 value: Balance,
3363 gas_limit: Option<Weight>,
3364 storage_deposit_limit: Option<Balance>,
3365 input_data: Vec<u8>,
3366 ) -> ContractResultV1<ExecReturnValueV1, Balance>;
3367
3368 #[deprecated(note = "Use the versioned equivalent `instantiate_versioned` if available on your runtime")]
3372 fn instantiate(
3373 origin: AccountId,
3374 value: Balance,
3375 gas_limit: Option<Weight>,
3376 storage_deposit_limit: Option<Balance>,
3377 code: CodeV1,
3378 data: Vec<u8>,
3379 salt: Option<[u8; 32]>,
3380 ) -> ContractResultV1<InstantiateReturnValueV1, Balance>;
3381
3382
3383 #[deprecated(note = "Use the versioned equivalent `eth_transact_versioned` if available on your runtime")]
3387 fn eth_transact(tx: GenericTransactionV1) -> Result<EthTransactInfoV1<Balance>, EthTransactError>;
3388
3389 #[deprecated(note = "Use the versioned equivalent `eth_transact_versioned` if available on your runtime")]
3393 fn eth_transact_with_config(
3394 tx: GenericTransactionV1,
3395 config: DryRunConfigV1<Moment>,
3396 ) -> Result<EthTransactInfoV1<Balance>, EthTransactError>;
3397
3398 #[deprecated(note = "Use the versioned equivalent `eth_estimate_gas_versioned` if available on your runtime")]
3404 fn eth_estimate_gas(
3405 tx: GenericTransactionV1,
3406 config: DryRunConfigV1<Moment>
3407 ) -> Result<U256, EthTransactError>;
3408
3409 #[deprecated(note = "Use the versioned equivalent `eth_pre_dispatch_weight_versioned` if available on your runtime")]
3411 fn eth_pre_dispatch_weight(tx: Vec<u8>) -> Result<Weight, EthTransactError>;
3412
3413 #[deprecated(note = "Use the versioned equivalent `upload_code_versioned` if available on your runtime")]
3417 fn upload_code(
3418 origin: AccountId,
3419 code: Vec<u8>,
3420 storage_deposit_limit: Option<Balance>,
3421 ) -> Result<CodeUploadReturnValueV1<Balance>, DispatchError>;
3422
3423 #[deprecated(note = "Use the versioned equivalent `get_storage_versioned` if available on your runtime")]
3429 fn get_storage(
3430 address: H160,
3431 key: [u8; 32],
3432 ) -> GetStorageResult;
3433
3434 #[deprecated(note = "Use the versioned equivalent `get_storage_versioned` if available on your runtime")]
3440 fn get_storage_var_key(
3441 address: H160,
3442 key: Vec<u8>,
3443 ) -> GetStorageResult;
3444
3445 #[deprecated(note = "Use the versioned equivalent `trace_block_versioned` if available on your runtime")]
3452 fn trace_block(
3453 block: Block,
3454 config: TracerTypeV1
3455 ) -> Vec<(u32, TraceV1)>;
3456
3457 #[deprecated(note = "Use the versioned equivalent `trace_tx_versioned` if available on your runtime")]
3464 fn trace_tx(
3465 block: Block,
3466 tx_index: u32,
3467 config: TracerTypeV1
3468 ) -> Option<TraceV1>;
3469
3470 #[deprecated(note = "Use the versioned equivalent `trace_call_versioned` if available on your runtime")]
3474 fn trace_call(tx: GenericTransactionV1, config: TracerTypeV1) -> Result<TraceV1, EthTransactError>;
3475
3476 #[deprecated(note = "Use the versioned equivalent `trace_call_versioned` if available on your runtime")]
3481 fn trace_call_with_config(
3482 tx: GenericTransactionV1,
3483 tracer_type: TracerTypeV1,
3484 config: TracingConfigV1,
3485 ) -> Result<TraceV1, EthTransactError>;
3486
3487 #[deprecated(note = "Use the versioned equivalent `block_author_versioned` if available on your runtime")]
3489 fn block_author() -> H160;
3490
3491 #[deprecated(note = "Use the versioned equivalent `address_versioned` if available on your runtime")]
3493 fn address(account_id: AccountId) -> H160;
3494
3495 #[deprecated(note = "Use the versioned equivalent `account_id_versioned` if available on your runtime")]
3497 fn account_id(address: H160) -> AccountId;
3498
3499 #[deprecated(note = "Use the versioned equivalent `runtime_pallets_address_versioned` if available on your runtime")]
3501 fn runtime_pallets_address() -> H160;
3502
3503 #[deprecated(note = "Use the versioned equivalent `code_versioned` if available on your runtime")]
3505 fn code(address: H160) -> Vec<u8>;
3506
3507 #[deprecated(note = "Use the versioned equivalent `new_balance_with_dust_versioned` if available on your runtime")]
3509 fn new_balance_with_dust(balance: U256) -> Result<(Balance, u32), BalanceConversionError>;
3510
3511 #[api_version(2)]
3514 fn version_declarations() -> ReviveRuntimeApiVersionDeclarations;
3515
3516 #[api_version(2)]
3517 fn eth_block_versioned(input: BlockVersionedInputPayload) -> BlockVersionedOutputPayload;
3518
3519 #[api_version(2)]
3520 fn eth_block_hash_versioned(input: BlockHashVersionedInputPayload) -> BlockHashVersionedOutputPayload;
3521
3522 #[api_version(2)]
3523 fn eth_receipt_data_versioned(input: ReceiptDataVersionedInputPayload) -> ReceiptDataVersionedOutputPayload;
3524
3525 #[api_version(2)]
3526 fn block_gas_limit_versioned(
3527 input: BlockGasLimitVersionedInputPayload
3528 ) -> BlockGasLimitVersionedOutputPayload;
3529
3530 #[api_version(2)]
3531 fn max_extrinsic_weight_in_gas_versioned(
3532 input: MaxExtrinsicWeightInGasVersionedInputPayload
3533 ) -> MaxExtrinsicWeightInGasVersionedOutputPayload;
3534
3535 #[api_version(2)]
3536 fn balance_versioned(input: BalanceVersionedInputPayload) -> BalanceVersionedOutputPayload;
3537
3538 #[api_version(2)]
3539 fn gas_price_versioned(input: GasPriceVersionedInputPayload) -> GasPriceVersionedOutputPayload;
3540
3541 #[api_version(2)]
3542 fn nonce_versioned(input: NonceVersionedInputPayload) -> NonceVersionedOutputPayload<Nonce>;
3543
3544 #[api_version(2)]
3545 fn call_versioned(
3546 input: CallVersionedInputPayload<AccountId, Balance>
3547 ) -> CallVersionedOutputPayload<Balance>;
3548
3549 #[api_version(2)]
3550 fn instantiate_versioned(
3551 input: InstantiateVersionedInputPayload<AccountId, Balance>
3552 ) -> InstantiateVersionedOutputPayload<Balance>;
3553
3554 #[api_version(2)]
3555 fn eth_transact_versioned(
3556 input: TransactVersionedInputPayload<Moment>
3557 ) -> Result<TransactVersionedOutputPayload<Balance>, EthTransactError>;
3558
3559 #[api_version(2)]
3560 fn eth_estimate_gas_versioned(
3561 input: EstimateGasVersionedInputPayload<Moment>
3562 ) -> Result<EstimateGasVersionedOutputPayload, EthTransactError>;
3563
3564 #[api_version(2)]
3565 fn eth_pre_dispatch_weight_versioned(
3566 input: PreDispatchWeightVersionedInputPayload
3567 ) -> Result<PreDispatchWeightVersionedOutputPayload, EthTransactError>;
3568
3569 #[api_version(2)]
3570 fn upload_code_versioned(
3571 input: UploadCodeVersionedInputPayload<AccountId, Balance>
3572 ) -> Result<UploadCodeVersionedOutputPayload<Balance>, DispatchError>;
3573
3574 #[api_version(2)]
3575 fn get_storage_versioned(
3576 input: GetStorageVersionedInputPayload
3577 ) -> Result<GetStorageVersionedOutputPayload, ContractAccessError>;
3578
3579 #[api_version(2)]
3580 fn runtime_pallets_address_versioned(
3581 input: RuntimePalletsAddressVersionedInputPayload
3582 ) -> RuntimePalletsAddressVersionedOutputPayload;
3583
3584 #[api_version(2)]
3585 fn code_versioned(input: CodeVersionedInputPayload) -> CodeVersionedOutputPayload;
3586
3587 #[api_version(2)]
3588 fn account_id_versioned(input: AccountIdVersionedInputPayload) -> AccountIdVersionedOutputPayload<AccountId>;
3589
3590 #[api_version(2)]
3591 fn new_balance_with_dust_versioned(
3592 input: NewBalanceWithDustVersionedInputPayload
3593 ) -> Result<NewBalanceWithDustVersionedOutputPayload<Balance>, BalanceConversionError>;
3594
3595 #[api_version(2)]
3596 fn block_author_versioned(input: BlockAuthorVersionedInputPayload) -> BlockAuthorVersionedOutputPayload;
3597
3598 #[api_version(2)]
3599 fn address_versioned(input: AddressVersionedInputPayload<AccountId>) -> AddressVersionedOutputPayload;
3600
3601 #[api_version(2)]
3602 fn trace_block_versioned(input: TraceBlockVersionedInputPayload<Block>) -> TraceBlockVersionedOutputPayload;
3603
3604 #[api_version(2)]
3605 fn trace_tx_versioned(input: TraceTxVersionedInputPayload<Block>) -> TraceTxVersionedOutputPayload;
3606
3607 #[api_version(2)]
3608 fn trace_call_versioned(
3609 input: TraceCallVersionedInputPayload
3610 ) -> Result<TraceCallVersionedOutputPayload, EthTransactError>;
3611 }
3612}
3613
3614#[macro_export]
3628macro_rules! impl_runtime_apis_plus_revive_traits {
3629 ($Runtime: ty, $Revive: ident, $Executive: ty, $EthExtra: ty, $($rest:tt)*) => {
3630
3631 type __ReviveMacroMoment = $crate::MomentOf<$Runtime>;
3632
3633 impl $crate::evm::runtime::SetWeightLimit for RuntimeCall {
3634 fn set_weight_limit(&mut self, new_weight_limit: Weight) -> Weight {
3635 use $crate::pallet::Call as ReviveCall;
3636 match self {
3637 Self::$Revive(
3638 ReviveCall::eth_call{ weight_limit, .. } |
3639 ReviveCall::eth_instantiate_with_code{ weight_limit, .. }
3640 ) => {
3641 let old = *weight_limit;
3642 *weight_limit = new_weight_limit;
3643 old
3644 },
3645 _ => Weight::default(),
3646 }
3647 }
3648 }
3649
3650 impl_runtime_apis! {
3651 $($rest)*
3652
3653 #[api_version(2)]
3654 impl pallet_revive::ReviveApi<Block, AccountId, Balance, Nonce, BlockNumber, __ReviveMacroMoment> for $Runtime
3655 {
3656 fn eth_block() -> $crate::pallet_revive_types::runtime_api::BlockV1 {
3657 use $crate::pallet_revive_types::runtime_api::*;
3658
3659 let input = BlockVersionedInputPayload::from(BlockInputPayloadV1);
3660 let output = Self::eth_block_versioned(input);
3661 BlockOutputPayloadV1::try_from(output)
3662 .expect("v1 input must produce v1 output; qed")
3663 .block
3664 }
3665
3666 fn eth_block_hash(number: $crate::U256) -> Option<$crate::H256> {
3667 use $crate::pallet_revive_types::runtime_api::*;
3668
3669 let input = BlockHashVersionedInputPayload::from(BlockHashInputPayloadV1 {
3670 block_number: number
3671 });
3672 let output = Self::eth_block_hash_versioned(input);
3673 BlockHashOutputPayloadV1::try_from(output)
3674 .expect("v1 input must produce v1 output; qed")
3675 .block_hash
3676 }
3677
3678 fn eth_receipt_data() -> Vec<$crate::pallet_revive_types::runtime_api::ReceiptGasInfoV1> {
3679 use $crate::pallet_revive_types::runtime_api::*;
3680
3681 let input = ReceiptDataVersionedInputPayload::from(ReceiptDataInputPayloadV1);
3682 let output = Self::eth_receipt_data_versioned(input);
3683 ReceiptDataOutputPayloadV1::try_from(output)
3684 .expect("v1 input must produce v1 output; qed")
3685 .receipt_data
3686 }
3687
3688 fn balance(address: $crate::H160) -> $crate::U256 {
3689 use $crate::pallet_revive_types::runtime_api::*;
3690
3691 let input = BalanceVersionedInputPayload::from(BalanceInputPayloadV1 { address });
3692 let output = Self::balance_versioned(input);
3693 BalanceOutputPayloadV1::try_from(output)
3694 .expect("v1 input must produce v1 output; qed")
3695 .balance
3696 }
3697
3698 fn block_author() -> $crate::H160 {
3699 use $crate::pallet_revive_types::runtime_api::*;
3700
3701 let input = BlockAuthorVersionedInputPayload::from(BlockAuthorInputPayloadV1);
3702 let output = Self::block_author_versioned(input);
3703 BlockAuthorOutputPayloadV1::try_from(output)
3704 .expect("v1 input must produce v1 output; qed")
3705 .block_author
3706 }
3707
3708 fn block_gas_limit() -> $crate::U256 {
3709 use $crate::pallet_revive_types::runtime_api::*;
3710
3711 let input = BlockGasLimitVersionedInputPayload::from(BlockGasLimitInputPayloadV1);
3712 let output = Self::block_gas_limit_versioned(input);
3713 BlockGasLimitOutputPayloadV1::try_from(output)
3714 .expect("v1 input must produce v1 output; qed")
3715 .block_gas_limit
3716 }
3717
3718 fn max_extrinsic_weight_in_gas() -> $crate::U256 {
3719 use $crate::pallet_revive_types::runtime_api::*;
3720
3721 let input = MaxExtrinsicWeightInGasVersionedInputPayload::from(
3722 MaxExtrinsicWeightInGasInputPayloadV1
3723 );
3724 let output = Self::max_extrinsic_weight_in_gas_versioned(input);
3725 MaxExtrinsicWeightInGasOutputPayloadV1::try_from(output)
3726 .expect("v1 input must produce v1 output; qed")
3727 .max_extrinsic_weight_in_gas
3728 }
3729
3730 fn gas_price() -> $crate::U256 {
3731 use $crate::pallet_revive_types::runtime_api::*;
3732
3733 let input = GasPriceVersionedInputPayload::from(GasPriceInputPayloadV1);
3734 let output = Self::gas_price_versioned(input);
3735 GasPriceOutputPayloadV1::try_from(output)
3736 .expect("v1 input must produce v1 output; qed")
3737 .gas_price
3738 }
3739
3740 fn nonce(address: $crate::H160) -> Nonce {
3741 use $crate::pallet_revive_types::runtime_api::*;
3742
3743 let input = NonceVersionedInputPayload::from(NonceInputPayloadV1 { address });
3744 let output = Self::nonce_versioned(input);
3745 NonceOutputPayloadV1::try_from(output)
3746 .expect("v1 input must produce v1 output; qed")
3747 .nonce
3748 }
3749
3750 fn address(account_id: AccountId) -> $crate::H160 {
3751 use $crate::pallet_revive_types::runtime_api::*;
3752
3753 let input = AddressVersionedInputPayload::from(AddressInputPayloadV1 { account_id });
3754 let output = Self::address_versioned(input);
3755 AddressOutputPayloadV1::try_from(output)
3756 .expect("v1 input must produce v1 output; qed")
3757 .address
3758 }
3759
3760 fn eth_transact(
3761 tx: $crate::pallet_revive_types::runtime_api::GenericTransactionV1,
3762 ) -> Result<
3763 $crate::pallet_revive_types::runtime_api::EthTransactInfoV1<Balance>,
3764 $crate::EthTransactError
3765 > {
3766 use $crate::pallet_revive_types::runtime_api::*;
3767
3768 let input = TransactVersionedInputPayload::from(TransactInputPayloadV1 {
3769 tx,
3770 timestamp_override: None,
3771 perform_balance_checks: true,
3772 state_overrides: None
3773 });
3774 let output = Self::eth_transact_versioned(input)?;
3775 Ok(TransactOutputPayloadV1::try_from(output)
3776 .expect("v1 input must produce v1 output; qed")
3777 .transact_info)
3778 }
3779
3780 fn eth_transact_with_config(
3781 tx: $crate::pallet_revive_types::runtime_api::GenericTransactionV1,
3782 config: $crate::pallet_revive_types::runtime_api::DryRunConfigV1<__ReviveMacroMoment>,
3783 ) -> Result<
3784 $crate::pallet_revive_types::runtime_api::EthTransactInfoV1<Balance>,
3785 $crate::EthTransactError
3786 > {
3787 use $crate::pallet_revive_types::runtime_api::*;
3788
3789 let DryRunConfigV1 { timestamp_override, perform_balance_checks, state_overrides } =
3790 config;
3791
3792 let input = TransactVersionedInputPayload::from(TransactInputPayloadV1 {
3793 tx,
3794 timestamp_override,
3795 perform_balance_checks: perform_balance_checks.unwrap_or(false),
3796 state_overrides
3797 });
3798 let output = Self::eth_transact_versioned(input)?;
3799 Ok(TransactOutputPayloadV1::try_from(output)
3800 .expect("v1 input must produce v1 output; qed")
3801 .transact_info)
3802 }
3803
3804 fn eth_estimate_gas(
3805 tx: $crate::pallet_revive_types::runtime_api::GenericTransactionV1,
3806 config: $crate::pallet_revive_types::runtime_api::DryRunConfigV1<__ReviveMacroMoment>,
3807 ) -> Result<$crate::U256, $crate::EthTransactError> {
3808 use $crate::pallet_revive_types::runtime_api::*;
3809
3810 let DryRunConfigV1 { timestamp_override, perform_balance_checks: _, state_overrides } =
3811 config;
3812
3813 let input = EstimateGasVersionedInputPayload::from(EstimateGasInputPayloadV1 {
3814 tx,
3815 timestamp_override,
3816 state_overrides
3817 });
3818 let output = Self::eth_estimate_gas_versioned(input)?;
3819 Ok(EstimateGasOutputPayloadV1::try_from(output)
3820 .expect("v1 input must produce v1 output; qed")
3821 .gas_estimate)
3822 }
3823
3824 fn eth_pre_dispatch_weight(
3825 tx: Vec<u8>,
3826 ) -> Result<$crate::Weight, $crate::EthTransactError> {
3827 use $crate::pallet_revive_types::runtime_api::*;
3828
3829 let input = PreDispatchWeightVersionedInputPayload::from(
3830 PreDispatchWeightInputPayloadV1 { tx }
3831 );
3832 let output = Self::eth_pre_dispatch_weight_versioned(input)?;
3833 Ok(PreDispatchWeightOutputPayloadV1::try_from(output)
3834 .expect("v1 input must produce v1 output; qed")
3835 .weight)
3836 }
3837
3838 fn call(
3839 origin: AccountId,
3840 dest: $crate::H160,
3841 value: Balance,
3842 weight_limit: Option<$crate::Weight>,
3843 storage_deposit_limit: Option<Balance>,
3844 input_data: Vec<u8>,
3845 ) -> $crate::pallet_revive_types::runtime_api::ContractResultV1<
3846 $crate::pallet_revive_types::runtime_api::ExecReturnValueV1,
3847 Balance
3848 > {
3849 use $crate::pallet_revive_types::runtime_api::*;
3850
3851 let input = CallVersionedInputPayload::from(CallInputPayloadV1 {
3852 origin,
3853 dest,
3854 value,
3855 gas_limit: weight_limit,
3856 storage_deposit_limit,
3857 input_data
3858 });
3859 let output = Self::call_versioned(input);
3860 CallOutputPayloadV1::try_from(output)
3861 .expect("v1 input must produce v1 output; qed")
3862 .contract_result
3863 }
3864
3865 fn instantiate(
3866 origin: AccountId,
3867 value: Balance,
3868 weight_limit: Option<$crate::Weight>,
3869 storage_deposit_limit: Option<Balance>,
3870 code: $crate::pallet_revive_types::runtime_api::CodeV1,
3871 data: Vec<u8>,
3872 salt: Option<[u8; 32]>,
3873 ) -> $crate::pallet_revive_types::runtime_api::ContractResultV1<
3874 $crate::pallet_revive_types::runtime_api::InstantiateReturnValueV1,
3875 Balance
3876 > {
3877 use $crate::pallet_revive_types::runtime_api::*;
3878
3879 let input = InstantiateVersionedInputPayload::from(InstantiateInputPayloadV1 {
3880 origin,
3881 value,
3882 gas_limit: weight_limit,
3883 storage_deposit_limit,
3884 code,
3885 data,
3886 salt
3887 });
3888 let output = Self::instantiate_versioned(input);
3889 InstantiateOutputPayloadV1::try_from(output)
3890 .expect("v1 input must produce v1 output; qed")
3891 .contract_result
3892 }
3893
3894 fn upload_code(
3895 origin: AccountId,
3896 code: Vec<u8>,
3897 storage_deposit_limit: Option<Balance>,
3898 ) -> Result<$crate::pallet_revive_types::runtime_api::CodeUploadReturnValueV1<Balance>, $crate::sp_runtime::DispatchError> {
3899 use $crate::pallet_revive_types::runtime_api::*;
3900
3901 let input = UploadCodeVersionedInputPayload::from(UploadCodeInputPayloadV1 {
3902 origin,
3903 code,
3904 storage_deposit_limit
3905 });
3906 let output = Self::upload_code_versioned(input)?;
3907 Ok(UploadCodeOutputPayloadV1::try_from(output)
3908 .expect("v1 input must produce v1 output; qed")
3909 .code_upload_return_value)
3910 }
3911
3912 fn get_storage_var_key(
3913 address: $crate::H160,
3914 key: Vec<u8>,
3915 ) -> $crate::GetStorageResult {
3916 use $crate::pallet_revive_types::runtime_api::*;
3917
3918 let input = GetStorageVersionedInputPayload::from(GetStorageInputPayloadV1 {
3919 address,
3920 key: StorageKeyV1::Variable(key)
3921 });
3922 let output = Self::get_storage_versioned(input)?;
3923 Ok(GetStorageOutputPayloadV1::try_from(output)
3924 .expect("v1 input must produce v1 output; qed")
3925 .storage)
3926 }
3927
3928 fn get_storage(address: $crate::H160, key: [u8; 32]) -> $crate::GetStorageResult {
3929 use $crate::pallet_revive_types::runtime_api::*;
3930
3931 let input = GetStorageVersionedInputPayload::from(GetStorageInputPayloadV1 {
3932 address,
3933 key: StorageKeyV1::Fixed(key)
3934 });
3935 let output = Self::get_storage_versioned(input)?;
3936 Ok(GetStorageOutputPayloadV1::try_from(output)
3937 .expect("v1 input must produce v1 output; qed")
3938 .storage)
3939 }
3940
3941 fn trace_block(
3942 block: Block,
3943 tracer_type: $crate::pallet_revive_types::runtime_api::TracerTypeV1,
3944 ) -> Vec<(u32, $crate::pallet_revive_types::runtime_api::TraceV1)> {
3945 use $crate::pallet_revive_types::runtime_api::*;
3946
3947 let input = TraceBlockVersionedInputPayload::from(TraceBlockInputPayloadV1 {
3948 block,
3949 config: tracer_type
3950 });
3951 let output = Self::trace_block_versioned(input);
3952 TraceBlockOutputPayloadV1::try_from(output)
3953 .expect("v1 input must produce v1 output; qed")
3954 .traces
3955 }
3956
3957 fn trace_tx(
3958 block: Block,
3959 tx_index: u32,
3960 tracer_type: $crate::pallet_revive_types::runtime_api::TracerTypeV1,
3961 ) -> Option<$crate::pallet_revive_types::runtime_api::TraceV1> {
3962 use $crate::pallet_revive_types::runtime_api::*;
3963
3964 let input = TraceTxVersionedInputPayload::from(TraceTxInputPayloadV1 {
3965 block,
3966 tx_index,
3967 config: tracer_type
3968 });
3969 let output = Self::trace_tx_versioned(input);
3970 TraceTxOutputPayloadV1::try_from(output)
3971 .expect("v1 input must produce v1 output; qed")
3972 .trace
3973 }
3974
3975 fn trace_call(
3976 tx: $crate::pallet_revive_types::runtime_api::GenericTransactionV1,
3977 tracer_type: $crate::pallet_revive_types::runtime_api::TracerTypeV1,
3978 ) -> Result<$crate::pallet_revive_types::runtime_api::TraceV1, $crate::EthTransactError> {
3979 use $crate::pallet_revive_types::runtime_api::*;
3980
3981 let input = TraceCallVersionedInputPayload::from(TraceCallInputPayloadV1 {
3982 tx,
3983 config: tracer_type,
3984 state_overrides: None
3985 });
3986 let output = Self::trace_call_versioned(input)?;
3987 Ok(TraceCallOutputPayloadV1::try_from(output)
3988 .expect("v1 input must produce v1 output; qed")
3989 .trace)
3990 }
3991
3992 fn trace_call_with_config(
3993 tx: $crate::pallet_revive_types::runtime_api::GenericTransactionV1,
3994 tracer_type: $crate::pallet_revive_types::runtime_api::TracerTypeV1,
3995 config: $crate::pallet_revive_types::runtime_api::TracingConfigV1,
3996 ) -> Result<$crate::pallet_revive_types::runtime_api::TraceV1, $crate::EthTransactError> {
3997 use $crate::pallet_revive_types::runtime_api::*;
3998
3999 let TracingConfigV1 { state_overrides } = config;
4000
4001 let input = TraceCallVersionedInputPayload::from(TraceCallInputPayloadV1 {
4002 tx,
4003 config: tracer_type,
4004 state_overrides
4005 });
4006 let output = Self::trace_call_versioned(input)?;
4007 Ok(TraceCallOutputPayloadV1::try_from(output)
4008 .expect("v1 input must produce v1 output; qed")
4009 .trace)
4010 }
4011
4012 fn runtime_pallets_address() -> $crate::H160 {
4013 use $crate::pallet_revive_types::runtime_api::*;
4014
4015 let input = RuntimePalletsAddressVersionedInputPayload::from(
4016 RuntimePalletsAddressInputPayloadV1
4017 );
4018 let output = Self::runtime_pallets_address_versioned(input);
4019 RuntimePalletsAddressOutputPayloadV1::try_from(output)
4020 .expect("v1 input must produce v1 output; qed")
4021 .runtime_pallets_address
4022 }
4023
4024 fn code(address: $crate::H160) -> Vec<u8> {
4025 use $crate::pallet_revive_types::runtime_api::*;
4026
4027 let input = CodeVersionedInputPayload::from(CodeInputPayloadV1 { address });
4028 let output = Self::code_versioned(input);
4029 CodeOutputPayloadV1::try_from(output)
4030 .expect("v1 input must produce v1 output; qed")
4031 .code
4032 }
4033
4034 fn account_id(address: $crate::H160) -> AccountId {
4035 use $crate::pallet_revive_types::runtime_api::*;
4036
4037 let input = AccountIdVersionedInputPayload::from(AccountIdInputPayloadV1 { address });
4038 let output = Self::account_id_versioned(input);
4039 AccountIdOutputPayloadV1::try_from(output)
4040 .expect("v1 input must produce v1 output; qed")
4041 .account_id
4042 }
4043
4044 fn new_balance_with_dust(balance: $crate::U256) -> Result<(Balance, u32), $crate::BalanceConversionError> {
4045 use $crate::pallet_revive_types::runtime_api::*;
4046
4047 let input = NewBalanceWithDustVersionedInputPayload::from(
4048 NewBalanceWithDustInputPayloadV1 { balance }
4049 );
4050 let output = Self::new_balance_with_dust_versioned(input)?;
4051 let output = NewBalanceWithDustOutputPayloadV1::try_from(output)
4052 .expect("v1 input must produce v1 output; qed");
4053 Ok((output.new_balance, output.dust))
4054 }
4055
4056 fn version_declarations()
4059 -> $crate::pallet_revive_types::runtime_api::ReviveRuntimeApiVersionDeclarations
4060 {
4061 use $crate::pallet_revive_types::runtime_api::*;
4062
4063 ReviveRuntimeApiVersionDeclarations::new()
4064 .insert("eth_block_versioned", 1)
4065 .insert("eth_block_hash_versioned", 1)
4066 .insert("eth_receipt_data_versioned", 2)
4067 .insert("block_gas_limit_versioned", 1)
4068 .insert("max_extrinsic_weight_in_gas_versioned", 1)
4069 .insert("balance_versioned", 1)
4070 .insert("gas_price_versioned", 1)
4071 .insert("nonce_versioned", 1)
4072 .insert("call_versioned", 1)
4073 .insert("instantiate_versioned", 1)
4074 .insert("eth_transact_versioned", 1)
4075 .insert("eth_estimate_gas_versioned", 1)
4076 .insert("eth_pre_dispatch_weight_versioned", 1)
4077 .insert("upload_code_versioned", 1)
4078 .insert("get_storage_versioned", 1)
4079 .insert("runtime_pallets_address_versioned", 1)
4080 .insert("code_versioned", 1)
4081 .insert("account_id_versioned", 1)
4082 .insert("new_balance_with_dust_versioned", 1)
4083 .insert("block_author_versioned", 1)
4084 .insert("address_versioned", 1)
4085 .insert("trace_block_versioned", 2)
4086 .insert("trace_tx_versioned", 2)
4087 .insert("trace_call_versioned", 2)
4088 }
4089
4090 fn eth_block_versioned(
4091 input: $crate::pallet_revive_types::runtime_api::BlockVersionedInputPayload
4092 ) -> $crate::pallet_revive_types::runtime_api::BlockVersionedOutputPayload {
4093 use $crate::pallet_revive_types::runtime_api::*;
4094 use $crate::runtime_api::*;
4095 use alloc::boxed::Box;
4096
4097 let (_input, output_wrapper): (
4098 _,
4099 Box<dyn Fn(BlockOutputPayload) -> BlockVersionedOutputPayload>,
4100 ) = match input {
4101 BlockVersionedInputPayload::V1(payload) => (
4102 BlockInputPayload::from(payload),
4103 Box::new(|output| BlockVersionedOutputPayload::V1(output.into())),
4104 ),
4105 };
4106
4107 let output = BlockOutputPayload { block: $crate::Pallet::<Self>::eth_block() };
4108 output_wrapper(output)
4109 }
4110
4111 fn eth_block_hash_versioned(
4112 input: $crate::pallet_revive_types::runtime_api::BlockHashVersionedInputPayload
4113 ) -> $crate::pallet_revive_types::runtime_api::BlockHashVersionedOutputPayload {
4114 use $crate::pallet_revive_types::runtime_api::*;
4115 use $crate::runtime_api::*;
4116 use alloc::boxed::Box;
4117
4118 let (input, output_wrapper): (
4119 _,
4120 Box<dyn Fn(BlockHashOutputPayload) -> BlockHashVersionedOutputPayload>,
4121 ) = match input {
4122 BlockHashVersionedInputPayload::V1(payload) => (
4123 BlockHashInputPayload::from(payload),
4124 Box::new(|output| BlockHashVersionedOutputPayload::V1(output.into())),
4125 ),
4126 };
4127
4128 let output = BlockHashOutputPayload {
4129 block_hash: $crate::Pallet::<Self>::eth_block_hash_from_number(input.block_number)
4130 };
4131 output_wrapper(output)
4132 }
4133
4134 fn eth_receipt_data_versioned(
4135 input: $crate::pallet_revive_types::runtime_api::ReceiptDataVersionedInputPayload
4136 ) -> $crate::pallet_revive_types::runtime_api::ReceiptDataVersionedOutputPayload {
4137 use $crate::pallet_revive_types::runtime_api::*;
4138 use $crate::runtime_api::*;
4139 use alloc::boxed::Box;
4140
4141 let (_input, output_wrapper): (
4142 _,
4143 Box<dyn Fn(ReceiptDataOutputPayload) -> ReceiptDataVersionedOutputPayload>,
4144 ) = match input {
4145 ReceiptDataVersionedInputPayload::V1(payload) => (
4146 ReceiptDataInputPayload::from(payload),
4147 Box::new(|output| ReceiptDataVersionedOutputPayload::V1(output.into())),
4148 ),
4149 ReceiptDataVersionedInputPayload::V2(payload) => (
4150 ReceiptDataInputPayload::from(payload),
4151 Box::new(|output| ReceiptDataVersionedOutputPayload::V2(output.into())),
4152 ),
4153 };
4154
4155 let output = ReceiptDataOutputPayload {
4156 receipt_data: $crate::Pallet::<Self>::eth_receipt_data(),
4157 synthetic: $crate::Pallet::<Self>::eth_synthetic_transaction(),
4158 };
4159 output_wrapper(output)
4160 }
4161
4162 fn block_gas_limit_versioned(
4163 input: $crate::pallet_revive_types::runtime_api::BlockGasLimitVersionedInputPayload
4164 ) -> $crate::pallet_revive_types::runtime_api::BlockGasLimitVersionedOutputPayload {
4165 use $crate::pallet_revive_types::runtime_api::*;
4166 use $crate::runtime_api::*;
4167 use alloc::boxed::Box;
4168
4169 let (_input, output_wrapper): (
4170 _,
4171 Box<dyn Fn(BlockGasLimitOutputPayload) -> BlockGasLimitVersionedOutputPayload>,
4172 ) = match input {
4173 BlockGasLimitVersionedInputPayload::V1(payload) => (
4174 BlockGasLimitInputPayload::from(payload),
4175 Box::new(|output| BlockGasLimitVersionedOutputPayload::V1(output.into())),
4176 ),
4177 };
4178
4179 let output = BlockGasLimitOutputPayload {
4180 block_gas_limit: $crate::Pallet::<Self>::evm_block_gas_limit()
4181 };
4182 output_wrapper(output)
4183 }
4184
4185 fn max_extrinsic_weight_in_gas_versioned(
4186 input: $crate::pallet_revive_types::runtime_api::MaxExtrinsicWeightInGasVersionedInputPayload
4187 ) -> $crate::pallet_revive_types::runtime_api::MaxExtrinsicWeightInGasVersionedOutputPayload {
4188 use $crate::pallet_revive_types::runtime_api::*;
4189 use $crate::runtime_api::*;
4190 use alloc::boxed::Box;
4191
4192 let (_input, output_wrapper): (
4193 _,
4194 Box<dyn Fn(MaxExtrinsicWeightInGasOutputPayload) -> MaxExtrinsicWeightInGasVersionedOutputPayload>,
4195 ) = match input {
4196 MaxExtrinsicWeightInGasVersionedInputPayload::V1(payload) => (
4197 MaxExtrinsicWeightInGasInputPayload::from(payload),
4198 Box::new(|output| MaxExtrinsicWeightInGasVersionedOutputPayload::V1(output.into())),
4199 ),
4200 };
4201
4202 let output = MaxExtrinsicWeightInGasOutputPayload {
4203 max_extrinsic_weight_in_gas: $crate::Pallet::<Self>::evm_max_extrinsic_weight_in_gas()
4204 };
4205 output_wrapper(output)
4206 }
4207
4208 fn balance_versioned(
4209 input: $crate::pallet_revive_types::runtime_api::BalanceVersionedInputPayload
4210 ) -> $crate::pallet_revive_types::runtime_api::BalanceVersionedOutputPayload {
4211 use $crate::pallet_revive_types::runtime_api::*;
4212 use $crate::runtime_api::*;
4213 use alloc::boxed::Box;
4214
4215 let (input, output_wrapper): (
4216 _,
4217 Box<dyn Fn(BalanceOutputPayload) -> BalanceVersionedOutputPayload>,
4218 ) = match input {
4219 BalanceVersionedInputPayload::V1(payload) => (
4220 BalanceInputPayload::from(payload),
4221 Box::new(|output| BalanceVersionedOutputPayload::V1(output.into())),
4222 ),
4223 };
4224
4225 let output = BalanceOutputPayload {
4226 balance: $crate::Pallet::<Self>::evm_balance(&input.address)
4227 };
4228 output_wrapper(output)
4229 }
4230
4231 fn gas_price_versioned(
4232 input: $crate::pallet_revive_types::runtime_api::GasPriceVersionedInputPayload
4233 ) -> $crate::pallet_revive_types::runtime_api::GasPriceVersionedOutputPayload {
4234 use $crate::pallet_revive_types::runtime_api::*;
4235 use $crate::runtime_api::*;
4236 use alloc::boxed::Box;
4237
4238 let (_input, output_wrapper): (
4239 _,
4240 Box<dyn Fn(GasPriceOutputPayload) -> GasPriceVersionedOutputPayload>,
4241 ) = match input {
4242 GasPriceVersionedInputPayload::V1(payload) => (
4243 GasPriceInputPayload::from(payload),
4244 Box::new(|output| GasPriceVersionedOutputPayload::V1(output.into())),
4245 ),
4246 };
4247
4248 let output = GasPriceOutputPayload {
4249 gas_price: $crate::Pallet::<Self>::evm_base_fee()
4250 };
4251 output_wrapper(output)
4252 }
4253
4254 fn nonce_versioned(
4255 input: $crate::pallet_revive_types::runtime_api::NonceVersionedInputPayload
4256 ) -> $crate::pallet_revive_types::runtime_api::NonceVersionedOutputPayload<Nonce> {
4257 use $crate::pallet_revive_types::runtime_api::*;
4258 use $crate::runtime_api::*;
4259 use $crate::AddressMapper;
4260 use alloc::boxed::Box;
4261
4262 let (input, output_wrapper): (
4263 _,
4264 Box<dyn Fn(NonceOutputPayload<Nonce>) -> NonceVersionedOutputPayload<Nonce>>,
4265 ) = match input {
4266 NonceVersionedInputPayload::V1(payload) => (
4267 NonceInputPayload::from(payload),
4268 Box::new(|output| NonceVersionedOutputPayload::V1(output.into())),
4269 ),
4270 };
4271
4272 let account = <Self as $crate::Config>::AddressMapper::to_account_id(&input.address);
4273 let output = NonceOutputPayload {
4274 nonce: $crate::frame_system::Pallet::<Self>::account_nonce(account)
4275 };
4276 output_wrapper(output)
4277 }
4278
4279 fn call_versioned(
4280 input: $crate::pallet_revive_types::runtime_api::CallVersionedInputPayload<AccountId, Balance>
4281 ) -> $crate::pallet_revive_types::runtime_api::CallVersionedOutputPayload<Balance> {
4282 use $crate::pallet_revive_types::runtime_api::*;
4283 use $crate::runtime_api::*;
4284 use $crate::frame_support::traits::Get;
4285 use alloc::boxed::Box;
4286
4287 let (input, output_wrapper): (
4288 _,
4289 Box<dyn Fn(CallOutputPayload<Balance>) -> CallVersionedOutputPayload<Balance>>,
4290 ) = match input {
4291 CallVersionedInputPayload::V1(payload) => (
4292 CallInputPayload::from(payload),
4293 Box::new(|output| CallVersionedOutputPayload::V1(output.into())),
4294 ),
4295 };
4296
4297 let blockweights: $crate::BlockWeights =
4298 <Self as $crate::frame_system::Config>::BlockWeights::get();
4299
4300 $crate::Pallet::<Self>::prepare_dry_run(&input.origin);
4301 let contract_result = $crate::Pallet::<Self>::bare_call(
4302 <Self as $crate::frame_system::Config>::RuntimeOrigin::signed(input.origin),
4303 input.dest,
4304 $crate::Pallet::<Self>::convert_native_to_evm(input.value),
4305 $crate::TransactionLimits::WeightAndDeposit {
4306 weight_limit: input.gas_limit.unwrap_or(blockweights.max_block),
4307 deposit_limit: input.storage_deposit_limit.unwrap_or(u128::MAX),
4308 },
4309 input.input_data,
4310 &$crate::ExecConfig::new_substrate_tx().with_dry_run(None),
4311 );
4312
4313 let output = CallOutputPayload { contract_result };
4314 output_wrapper(output)
4315 }
4316
4317 fn instantiate_versioned(
4318 input: $crate::pallet_revive_types::runtime_api::InstantiateVersionedInputPayload<AccountId, Balance>
4319 ) -> $crate::pallet_revive_types::runtime_api::InstantiateVersionedOutputPayload<Balance> {
4320 use $crate::pallet_revive_types::runtime_api::*;
4321 use $crate::runtime_api::*;
4322 use $crate::frame_support::traits::Get;
4323 use alloc::boxed::Box;
4324
4325 let (input, output_wrapper): (
4326 _,
4327 Box<dyn Fn(InstantiateOutputPayload<Balance>) -> InstantiateVersionedOutputPayload<Balance>>,
4328 ) = match input {
4329 InstantiateVersionedInputPayload::V1(payload) => (
4330 InstantiateInputPayload::from(payload),
4331 Box::new(|output| InstantiateVersionedOutputPayload::V1(output.into())),
4332 ),
4333 };
4334
4335 let blockweights: $crate::BlockWeights =
4336 <Self as $crate::frame_system::Config>::BlockWeights::get();
4337
4338 $crate::Pallet::<Self>::prepare_dry_run(&input.origin);
4339 let contract_result = $crate::Pallet::<Self>::bare_instantiate(
4340 <Self as $crate::frame_system::Config>::RuntimeOrigin::signed(input.origin),
4341 $crate::Pallet::<Self>::convert_native_to_evm(input.value),
4342 $crate::TransactionLimits::WeightAndDeposit {
4343 weight_limit: input.gas_limit.unwrap_or(blockweights.max_block),
4344 deposit_limit: input.storage_deposit_limit.unwrap_or(u128::MAX),
4345 },
4346 input.code,
4347 input.data,
4348 input.salt,
4349 &$crate::ExecConfig::new_substrate_tx().with_dry_run(None),
4350 );
4351
4352 let output = InstantiateOutputPayload { contract_result };
4353 output_wrapper(output)
4354 }
4355
4356 fn eth_transact_versioned(
4357 input: $crate::pallet_revive_types::runtime_api::TransactVersionedInputPayload<__ReviveMacroMoment>
4358 ) -> Result<
4359 $crate::pallet_revive_types::runtime_api::TransactVersionedOutputPayload<Balance>,
4360 $crate::EthTransactError
4361 > {
4362 use $crate::pallet_revive_types::runtime_api::*;
4363 use $crate::runtime_api::*;
4364 use $crate::{
4365 codec::Encode, evm::runtime::EthExtra, frame_support::traits::Get,
4366 sp_runtime::traits::TransactionExtension,
4367 sp_runtime::traits::Block as BlockT
4368 };
4369 use alloc::boxed::Box;
4370
4371 let (input, output_wrapper): (
4372 _,
4373 Box<dyn Fn(TransactOutputPayload<Balance>) -> TransactVersionedOutputPayload<Balance>>,
4374 ) = match input {
4375 TransactVersionedInputPayload::V1(payload) => (
4376 TransactInputPayload::from(payload),
4377 Box::new(|output| TransactVersionedOutputPayload::V1(output.into())),
4378 ),
4379 };
4380
4381 let transact_info = $crate::Pallet::<Self>::dry_run_eth_transact(
4382 input.tx,
4383 input.timestamp_override,
4384 input.perform_balance_checks,
4385 input.state_overrides,
4386 )?;
4387 let output = TransactOutputPayload { transact_info };
4388 Ok(output_wrapper(output))
4389 }
4390
4391 fn eth_estimate_gas_versioned(
4392 input: $crate::pallet_revive_types::runtime_api::EstimateGasVersionedInputPayload<__ReviveMacroMoment>
4393 ) -> Result<
4394 $crate::pallet_revive_types::runtime_api::EstimateGasVersionedOutputPayload,
4395 $crate::EthTransactError
4396 > {
4397 use $crate::pallet_revive_types::runtime_api::*;
4398 use $crate::runtime_api::*;
4399 use $crate::{
4400 codec::Encode, evm::runtime::EthExtra, frame_support::traits::Get,
4401 sp_runtime::traits::TransactionExtension,
4402 sp_runtime::traits::Block as BlockT
4403 };
4404 use alloc::boxed::Box;
4405
4406 let (input, output_wrapper): (
4407 _,
4408 Box<dyn Fn(EstimateGasOutputPayload) -> EstimateGasVersionedOutputPayload>,
4409 ) = match input {
4410 EstimateGasVersionedInputPayload::V1(payload) => (
4411 EstimateGasInputPayload::from(payload),
4412 Box::new(|output| EstimateGasVersionedOutputPayload::V1(output.into())),
4413 ),
4414 };
4415
4416 let gas_estimate = $crate::Pallet::<Self>::eth_estimate_gas(
4417 input.tx,
4418 input.timestamp_override,
4419 input.state_overrides,
4420 )?;
4421 let output = EstimateGasOutputPayload { gas_estimate };
4422 Ok(output_wrapper(output))
4423 }
4424
4425 fn eth_pre_dispatch_weight_versioned(
4426 input: $crate::pallet_revive_types::runtime_api::PreDispatchWeightVersionedInputPayload
4427 ) -> Result<
4428 $crate::pallet_revive_types::runtime_api::PreDispatchWeightVersionedOutputPayload,
4429 $crate::EthTransactError
4430 > {
4431 use $crate::pallet_revive_types::runtime_api::*;
4432 use $crate::runtime_api::*;
4433 use alloc::boxed::Box;
4434
4435 let (input, output_wrapper): (
4436 _,
4437 Box<dyn Fn(PreDispatchWeightOutputPayload) -> PreDispatchWeightVersionedOutputPayload>,
4438 ) = match input {
4439 PreDispatchWeightVersionedInputPayload::V1(payload) => (
4440 PreDispatchWeightInputPayload::from(payload),
4441 Box::new(|output| PreDispatchWeightVersionedOutputPayload::V1(output.into())),
4442 ),
4443 };
4444
4445 let output = PreDispatchWeightOutputPayload {
4446 weight: $crate::Pallet::<Self>::eth_pre_dispatch_weight(input.tx)?
4447 };
4448 Ok(output_wrapper(output))
4449 }
4450
4451 fn upload_code_versioned(
4452 input: $crate::pallet_revive_types::runtime_api::UploadCodeVersionedInputPayload<AccountId, Balance>
4453 ) -> Result<
4454 $crate::pallet_revive_types::runtime_api::UploadCodeVersionedOutputPayload<Balance>,
4455 $crate::sp_runtime::DispatchError
4456 > {
4457 use $crate::pallet_revive_types::runtime_api::*;
4458 use $crate::runtime_api::*;
4459 use alloc::boxed::Box;
4460
4461 let (input, output_wrapper): (
4462 _,
4463 Box<dyn Fn(UploadCodeOutputPayload<Balance>) -> UploadCodeVersionedOutputPayload<Balance>>,
4464 ) = match input {
4465 UploadCodeVersionedInputPayload::V1(payload) => (
4466 UploadCodeInputPayload::from(payload),
4467 Box::new(|output| UploadCodeVersionedOutputPayload::V1(output.into())),
4468 ),
4469 };
4470
4471 let origin =
4472 <Self as $crate::frame_system::Config>::RuntimeOrigin::signed(input.origin);
4473 let code_upload_return_value = $crate::Pallet::<Self>::bare_upload_code(
4474 origin,
4475 input.code,
4476 input.storage_deposit_limit.unwrap_or(u128::MAX),
4477 )?;
4478 let output = UploadCodeOutputPayload { code_upload_return_value };
4479 Ok(output_wrapper(output))
4480 }
4481
4482 fn get_storage_versioned(
4483 input: $crate::pallet_revive_types::runtime_api::GetStorageVersionedInputPayload
4484 ) -> Result<
4485 $crate::pallet_revive_types::runtime_api::GetStorageVersionedOutputPayload,
4486 $crate::ContractAccessError
4487 > {
4488 use $crate::pallet_revive_types::runtime_api::*;
4489 use $crate::runtime_api::*;
4490 use alloc::boxed::Box;
4491
4492 let (input, output_wrapper): (
4493 _,
4494 Box<dyn Fn(GetStorageOutputPayload) -> GetStorageVersionedOutputPayload>,
4495 ) = match input {
4496 GetStorageVersionedInputPayload::V1(payload) => (
4497 GetStorageInputPayload::from(payload),
4498 Box::new(|output| GetStorageVersionedOutputPayload::V1(output.into())),
4499 ),
4500 };
4501
4502 let storage = match input.key {
4503 StorageKey::Fixed(key) => $crate::Pallet::<Self>::get_storage(input.address, key)?,
4504 StorageKey::Variable(key) => $crate::Pallet::<Self>::get_storage_var_key(input.address, key)?,
4505 };
4506 let output = GetStorageOutputPayload { storage };
4507 Ok(output_wrapper(output))
4508 }
4509
4510 fn runtime_pallets_address_versioned(
4511 input: $crate::pallet_revive_types::runtime_api::RuntimePalletsAddressVersionedInputPayload
4512 ) -> $crate::pallet_revive_types::runtime_api::RuntimePalletsAddressVersionedOutputPayload {
4513 use $crate::pallet_revive_types::runtime_api::*;
4514 use $crate::runtime_api::*;
4515 use alloc::boxed::Box;
4516
4517 let (_input, output_wrapper): (
4518 _,
4519 Box<dyn Fn(RuntimePalletsAddressOutputPayload) -> RuntimePalletsAddressVersionedOutputPayload>,
4520 ) = match input {
4521 RuntimePalletsAddressVersionedInputPayload::V1(payload) => (
4522 RuntimePalletsAddressInputPayload::from(payload),
4523 Box::new(|output| RuntimePalletsAddressVersionedOutputPayload::V1(output.into())),
4524 ),
4525 };
4526
4527 let output = RuntimePalletsAddressOutputPayload {
4528 runtime_pallets_address: $crate::RUNTIME_PALLETS_ADDR
4529 };
4530 output_wrapper(output)
4531 }
4532
4533 fn code_versioned(
4534 input: $crate::pallet_revive_types::runtime_api::CodeVersionedInputPayload
4535 ) -> $crate::pallet_revive_types::runtime_api::CodeVersionedOutputPayload {
4536 use $crate::pallet_revive_types::runtime_api::*;
4537 use $crate::runtime_api::*;
4538 use alloc::boxed::Box;
4539
4540 let (input, output_wrapper): (
4541 _,
4542 Box<dyn Fn(CodeOutputPayload) -> CodeVersionedOutputPayload>,
4543 ) = match input {
4544 CodeVersionedInputPayload::V1(payload) => (
4545 CodeInputPayload::from(payload),
4546 Box::new(|output| CodeVersionedOutputPayload::V1(output.into())),
4547 ),
4548 };
4549
4550 let output = CodeOutputPayload {
4551 code: $crate::Pallet::<Self>::code(&input.address)
4552 };
4553 output_wrapper(output)
4554 }
4555
4556 fn account_id_versioned(
4557 input: $crate::pallet_revive_types::runtime_api::AccountIdVersionedInputPayload
4558 ) -> $crate::pallet_revive_types::runtime_api::AccountIdVersionedOutputPayload<AccountId> {
4559 use $crate::pallet_revive_types::runtime_api::*;
4560 use $crate::runtime_api::*;
4561 use $crate::AddressMapper;
4562 use alloc::boxed::Box;
4563
4564 let (input, output_wrapper): (
4565 _,
4566 Box<dyn Fn(AccountIdOutputPayload<AccountId>) -> AccountIdVersionedOutputPayload<AccountId>>,
4567 ) = match input {
4568 AccountIdVersionedInputPayload::V1(payload) => (
4569 AccountIdInputPayload::from(payload),
4570 Box::new(|output| AccountIdVersionedOutputPayload::V1(output.into())),
4571 ),
4572 };
4573
4574 let output = AccountIdOutputPayload {
4575 account_id: <Self as $crate::Config>::AddressMapper::to_account_id(&input.address)
4576 };
4577 output_wrapper(output)
4578 }
4579
4580 fn new_balance_with_dust_versioned(
4581 input: $crate::pallet_revive_types::runtime_api::NewBalanceWithDustVersionedInputPayload
4582 ) -> Result<
4583 $crate::pallet_revive_types::runtime_api::NewBalanceWithDustVersionedOutputPayload<Balance>,
4584 $crate::BalanceConversionError
4585 > {
4586 use $crate::pallet_revive_types::runtime_api::*;
4587 use $crate::runtime_api::*;
4588 use alloc::boxed::Box;
4589
4590 let (input, output_wrapper): (
4591 _,
4592 Box<
4593 dyn Fn(NewBalanceWithDustOutputPayload<Balance>) -> NewBalanceWithDustVersionedOutputPayload<Balance>,
4594 >,
4595 ) = match input {
4596 NewBalanceWithDustVersionedInputPayload::V1(payload) => (
4597 NewBalanceWithDustInputPayload::from(payload),
4598 Box::new(|output| NewBalanceWithDustVersionedOutputPayload::V1(output.into())),
4599 ),
4600 };
4601
4602 let (new_balance, dust) = $crate::Pallet::<Self>::new_balance_with_dust(input.balance)?;
4603 let output = NewBalanceWithDustOutputPayload { new_balance, dust };
4604 Ok(output_wrapper(output))
4605 }
4606
4607 fn block_author_versioned(
4608 input: $crate::pallet_revive_types::runtime_api::BlockAuthorVersionedInputPayload
4609 ) -> $crate::pallet_revive_types::runtime_api::BlockAuthorVersionedOutputPayload {
4610 use $crate::pallet_revive_types::runtime_api::*;
4611 use $crate::runtime_api::*;
4612 use alloc::boxed::Box;
4613
4614 let (_input, output_wrapper): (
4615 _,
4616 Box<dyn Fn(BlockAuthorOutputPayload) -> BlockAuthorVersionedOutputPayload>,
4617 ) = match input {
4618 BlockAuthorVersionedInputPayload::V1(payload) => (
4619 BlockAuthorInputPayload::from(payload),
4620 Box::new(|output| BlockAuthorVersionedOutputPayload::V1(output.into())),
4621 ),
4622 };
4623
4624 let output = BlockAuthorOutputPayload {
4625 block_author: $crate::Pallet::<Self>::block_author()
4626 };
4627 output_wrapper(output)
4628 }
4629
4630 fn address_versioned(
4631 input: $crate::pallet_revive_types::runtime_api::AddressVersionedInputPayload<AccountId>
4632 ) -> $crate::pallet_revive_types::runtime_api::AddressVersionedOutputPayload {
4633 use $crate::pallet_revive_types::runtime_api::*;
4634 use $crate::runtime_api::*;
4635 use $crate::AddressMapper;
4636 use alloc::boxed::Box;
4637
4638 let (input, output_wrapper): (
4639 _,
4640 Box<dyn Fn(AddressOutputPayload) -> AddressVersionedOutputPayload>,
4641 ) = match input {
4642 AddressVersionedInputPayload::V1(payload) => (
4643 AddressInputPayload::from(payload),
4644 Box::new(|output| AddressVersionedOutputPayload::V1(output.into())),
4645 ),
4646 };
4647
4648 let output = AddressOutputPayload {
4649 address: <Self as $crate::Config>::AddressMapper::to_address(&input.account_id)
4650 };
4651 output_wrapper(output)
4652 }
4653
4654 fn trace_block_versioned(
4655 input: $crate::pallet_revive_types::runtime_api::TraceBlockVersionedInputPayload<Block>
4656 ) -> $crate::pallet_revive_types::runtime_api::TraceBlockVersionedOutputPayload {
4657 use $crate::{
4658 sp_runtime::traits::Block,
4659 tracing::trace,
4660 evm::TraceEntry,
4661 runtime_api::*,
4662 pallet_revive_types::runtime_api::*
4663 };
4664 use alloc::boxed::Box;
4665
4666 let (input, output_wrapper): (_, Box<dyn Fn(TraceBlockOutputPayload) -> TraceBlockVersionedOutputPayload>) = match input {
4667 TraceBlockVersionedInputPayload::V1(payload) => (
4668 TraceBlockInputPayload::from(payload),
4669 Box::new(|output| TraceBlockVersionedOutputPayload::V1(output.into()))
4670 ),
4671 TraceBlockVersionedInputPayload::V2(payload) => (
4672 TraceBlockInputPayload::from(payload),
4673 Box::new(|output| TraceBlockVersionedOutputPayload::V2(output.into()))
4674 ),
4675 };
4676
4677 if matches!(input.config, $crate::evm::TracerType::ExecutionTracer(_)) &&
4678 !$crate::DebugSettings::is_execution_tracing_enabled::<Runtime>()
4679 {
4680 return output_wrapper(Default::default())
4681 }
4682
4683 let mut entries = vec![];
4687 let (header, extrinsics) = input.block.deconstruct();
4688 <$Executive>::initialize_block(&header);
4689 for (index, ext) in extrinsics.into_iter().enumerate() {
4690 let mut tracer = $crate::Pallet::<Self>::evm_tracer(input.config.clone());
4691 let t = tracer.as_tracing();
4692 let result = trace(t, || <$Executive>::apply_extrinsic(ext));
4693
4694 if let Some(tx_trace) = tracer.collect_trace() {
4695 entries.push((index as u32, TraceEntry::Traced(tx_trace)));
4696 } else if let Some(entry) = TraceEntry::for_untraced(&result) {
4697 entries.push((index as u32, entry));
4698 }
4699 }
4700
4701 let output = TraceBlockOutputPayload { entries };
4702 output_wrapper(output)
4703 }
4704
4705 fn trace_tx_versioned(
4706 input: $crate::pallet_revive_types::runtime_api::TraceTxVersionedInputPayload<Block>
4707 ) -> $crate::pallet_revive_types::runtime_api::TraceTxVersionedOutputPayload {
4708 use $crate::pallet_revive_types::runtime_api::*;
4709 use $crate::runtime_api::*;
4710 use $crate::{evm::TraceEntry, sp_runtime::traits::Block, tracing::trace};
4711 use alloc::boxed::Box;
4712
4713 let (input, output_wrapper): (
4714 _,
4715 Box<dyn Fn(TraceTxOutputPayload) -> TraceTxVersionedOutputPayload>,
4716 ) = match input {
4717 TraceTxVersionedInputPayload::V1(payload) => (
4718 TraceTxInputPayload::from(payload),
4719 Box::new(|output| TraceTxVersionedOutputPayload::V1(output.into())),
4720 ),
4721 TraceTxVersionedInputPayload::V2(payload) => (
4722 TraceTxInputPayload::from(payload),
4723 Box::new(|output| TraceTxVersionedOutputPayload::V2(output.into())),
4724 ),
4725 };
4726
4727 if matches!(&input.config, $crate::evm::TracerType::ExecutionTracer(_)) &&
4728 !$crate::DebugSettings::is_execution_tracing_enabled::<Runtime>()
4729 {
4730 return output_wrapper(TraceTxOutputPayload { entry: None })
4731 }
4732
4733 let mut tracer = $crate::Pallet::<Self>::evm_tracer(input.config);
4737 let (header, extrinsics) = input.block.deconstruct();
4738
4739 <$Executive>::initialize_block(&header);
4740 let mut entry = None;
4741 for (index, ext) in extrinsics.into_iter().enumerate() {
4742 if index as u32 == input.tx_index {
4743 let t = tracer.as_tracing();
4744 let result = trace(t, || <$Executive>::apply_extrinsic(ext));
4745 entry = match tracer.collect_trace() {
4746 Some(tx_trace) => Some(TraceEntry::Traced(tx_trace)),
4747 None => TraceEntry::for_untraced(&result),
4748 };
4749 break;
4750 } else {
4751 let _ = <$Executive>::apply_extrinsic(ext);
4752 }
4753 }
4754
4755 let output = TraceTxOutputPayload { entry };
4756 output_wrapper(output)
4757 }
4758
4759 fn trace_call_versioned(
4760 input: $crate::pallet_revive_types::runtime_api::TraceCallVersionedInputPayload
4761 ) -> Result<
4762 $crate::pallet_revive_types::runtime_api::TraceCallVersionedOutputPayload,
4763 $crate::EthTransactError
4764 > {
4765 use $crate::pallet_revive_types::runtime_api::*;
4766 use $crate::runtime_api::*;
4767 use $crate::tracing::trace;
4768 use alloc::boxed::Box;
4769
4770 let (input, output_wrapper): (
4771 _,
4772 Box<dyn Fn(TraceCallOutputPayload) -> TraceCallVersionedOutputPayload>,
4773 ) = match input {
4774 TraceCallVersionedInputPayload::V1(payload) => (
4775 TraceCallInputPayload::from(payload),
4776 Box::new(|output| TraceCallVersionedOutputPayload::V1(output.into())),
4777 ),
4778 TraceCallVersionedInputPayload::V2(payload) => (
4779 TraceCallInputPayload::from(payload),
4780 Box::new(|output| TraceCallVersionedOutputPayload::V2(output.into())),
4781 ),
4782 };
4783
4784 if let Some(overrides) = input.state_overrides {
4785 $crate::state_overrides::apply_state_overrides::<Runtime>(overrides)?;
4786 }
4787
4788 if matches!(input.config, $crate::evm::TracerType::ExecutionTracer(_)) &&
4789 !$crate::DebugSettings::is_execution_tracing_enabled::<Runtime>()
4790 {
4791 return Err($crate::EthTransactError::Message("Execution Tracing is disabled".into()))
4792 }
4793
4794 let mut tracer = $crate::Pallet::<Self>::evm_tracer(input.config.clone());
4795 let t = tracer.as_tracing();
4796
4797 t.watch_address(&input.tx.from.unwrap_or_default());
4798 t.watch_address(&$crate::Pallet::<Self>::block_author());
4799 let result = trace(t, || {
4800 $crate::Pallet::<Self>::dry_run_eth_transact(input.tx, None, true, None)
4801 });
4802
4803 let trace = if let Some(trace) = tracer.collect_trace() {
4804 Ok(trace)
4805 } else if let Err(err) = result {
4806 Err(err)
4807 } else {
4808 Ok($crate::Pallet::<Self>::evm_tracer(input.config).empty_trace())
4809 }?;
4810
4811 let output = TraceCallOutputPayload { trace };
4812 Ok(output_wrapper(output))
4813 }
4814 }
4815 }
4816 };
4817}