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 address;
26mod benchmarking;
27mod call_builder;
28mod debug;
29mod exec;
30mod impl_fungibles;
31mod limits;
32mod metering;
33mod primitives;
34mod storage;
35#[cfg(test)]
36mod tests;
37mod transient_storage;
38mod vm;
39mod weightinfo_extension;
40
41pub mod evm;
42pub mod migrations;
43pub mod mock;
44pub mod precompiles;
45pub mod test_utils;
46pub mod tracing;
47pub mod weights;
48
49use crate::{
50 evm::{
51 block_hash::EthereumBlockBuilderIR, block_storage, fees::InfoT as FeeInfo,
52 runtime::SetWeightLimit, CallTracer, CreateCallMode, GenericTransaction, PrestateTracer,
53 Trace, Tracer, TracerType, TYPE_EIP1559,
54 },
55 exec::{AccountIdOf, ExecError, ReentrancyProtection, Stack as ExecStack},
56 storage::{AccountType, DeletionQueueManager},
57 tracing::if_tracing,
58 vm::{pvm::extract_code_and_data, CodeInfo, RuntimeCosts},
59 weightinfo_extension::OnFinalizeBlockParts,
60};
61use alloc::{boxed::Box, format, vec};
62use codec::{Codec, Decode, Encode};
63use environmental::*;
64use frame_support::{
65 dispatch::{
66 DispatchErrorWithPostInfo, DispatchResult, DispatchResultWithPostInfo, GetDispatchInfo,
67 Pays, PostDispatchInfo, RawOrigin,
68 },
69 ensure,
70 pallet_prelude::DispatchClass,
71 traits::{
72 fungible::{Balanced, Inspect, Mutate, MutateHold},
73 tokens::Balance,
74 ConstU32, ConstU64, EnsureOrigin, Get, IsSubType, IsType, OriginTrait,
75 },
76 weights::WeightMeter,
77 BoundedVec,
78};
79use frame_system::{
80 ensure_signed,
81 pallet_prelude::{BlockNumberFor, OriginFor},
82 Pallet as System,
83};
84use scale_info::TypeInfo;
85use sp_runtime::{
86 traits::{
87 BadOrigin, Bounded, Convert, Dispatchable, Saturating, UniqueSaturatedFrom,
88 UniqueSaturatedInto, Zero,
89 },
90 AccountId32, DispatchError, FixedPointNumber, FixedU128, SaturatedConversion,
91};
92
93pub use crate::{
94 address::{
95 create1, create2, is_eth_derived, AccountId32Mapper, AddressMapper, TestAccountMapper,
96 },
97 debug::DebugSettings,
98 evm::{
99 block_hash::ReceiptGasInfo, Address as EthAddress, Block as EthBlock, DryRunConfig,
100 ReceiptInfo,
101 },
102 exec::{CallResources, DelegateInfo, Executable, Key, MomentOf, Origin as ExecOrigin},
103 metering::{
104 EthTxInfo, FrameMeter, ResourceMeter, Token as WeightToken, TransactionLimits,
105 TransactionMeter,
106 },
107 pallet::{genesis, *},
108 storage::{AccountInfo, ContractInfo},
109 vm::{BytecodeType, ContractBlob},
110};
111pub use codec;
112pub use frame_support::{self, dispatch::DispatchInfo, traits::Time, weights::Weight};
113pub use frame_system::{self, limits::BlockWeights};
114pub use primitives::*;
115pub use sp_core::{keccak_256, H160, H256, U256};
116pub use sp_runtime;
117pub use weights::WeightInfo;
118
119#[cfg(doc)]
120pub use crate::vm::pvm::SyscallDoc;
121
122pub type BalanceOf<T> = <T as Config>::Balance;
123type TrieId = BoundedVec<u8, ConstU32<128>>;
124type ImmutableData = BoundedVec<u8, ConstU32<{ limits::IMMUTABLE_BYTES }>>;
125type CallOf<T> = <T as Config>::RuntimeCall;
126
127const SENTINEL: u32 = u32::MAX;
134
135const LOG_TARGET: &str = "runtime::revive";
141
142#[frame_support::pallet]
143pub mod pallet {
144 use super::*;
145 use frame_support::{pallet_prelude::*, traits::FindAuthor};
146 use frame_system::pallet_prelude::*;
147 use sp_core::U256;
148 use sp_runtime::Perbill;
149
150 pub(crate) const STORAGE_VERSION: StorageVersion = StorageVersion::new(0);
152
153 #[pallet::pallet]
154 #[pallet::storage_version(STORAGE_VERSION)]
155 pub struct Pallet<T>(_);
156
157 #[pallet::config(with_default)]
158 pub trait Config: frame_system::Config {
159 type Time: Time<Moment: Into<U256>>;
161
162 #[pallet::no_default]
166 type Balance: Balance
167 + TryFrom<U256>
168 + Into<U256>
169 + Bounded
170 + UniqueSaturatedInto<u64>
171 + UniqueSaturatedFrom<u64>
172 + UniqueSaturatedInto<u128>;
173
174 #[pallet::no_default]
176 type Currency: Inspect<Self::AccountId, Balance = Self::Balance>
177 + Mutate<Self::AccountId>
178 + MutateHold<Self::AccountId, Reason = Self::RuntimeHoldReason>
179 + Balanced<Self::AccountId>;
180
181 #[pallet::no_default_bounds]
183 #[allow(deprecated)]
184 type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
185
186 #[pallet::no_default_bounds]
188 type RuntimeCall: Parameter
189 + Dispatchable<
190 RuntimeOrigin = OriginFor<Self>,
191 Info = DispatchInfo,
192 PostInfo = PostDispatchInfo,
193 > + IsType<<Self as frame_system::Config>::RuntimeCall>
194 + From<Call<Self>>
195 + IsSubType<Call<Self>>
196 + GetDispatchInfo;
197
198 #[pallet::no_default_bounds]
200 type RuntimeOrigin: IsType<OriginFor<Self>>
201 + From<Origin<Self>>
202 + Into<Result<Origin<Self>, OriginFor<Self>>>;
203
204 #[pallet::no_default_bounds]
206 type RuntimeHoldReason: From<HoldReason>;
207
208 type WeightInfo: WeightInfo;
211
212 #[pallet::no_default_bounds]
216 #[allow(private_bounds)]
217 type Precompiles: precompiles::Precompiles<Self>;
218
219 type FindAuthor: FindAuthor<Self::AccountId>;
221
222 #[pallet::constant]
228 #[pallet::no_default_bounds]
229 type DepositPerByte: Get<BalanceOf<Self>>;
230
231 #[pallet::constant]
237 #[pallet::no_default_bounds]
238 type DepositPerItem: Get<BalanceOf<Self>>;
239
240 #[pallet::constant]
250 #[pallet::no_default_bounds]
251 type DepositPerChildTrieItem: Get<BalanceOf<Self>>;
252
253 #[pallet::constant]
257 type CodeHashLockupDepositPercent: Get<Perbill>;
258
259 #[pallet::no_default]
261 type AddressMapper: AddressMapper<Self>;
262
263 #[pallet::constant]
273 type UnsafeUnstableInterface: Get<bool>;
274
275 #[pallet::constant]
277 type AllowEVMBytecode: Get<bool>;
278
279 #[pallet::no_default_bounds]
284 type UploadOrigin: EnsureOrigin<OriginFor<Self>, Success = Self::AccountId>;
285
286 #[pallet::no_default_bounds]
297 type InstantiateOrigin: EnsureOrigin<OriginFor<Self>, Success = Self::AccountId>;
298
299 type RuntimeMemory: Get<u32>;
304
305 type PVFMemory: Get<u32>;
313
314 #[pallet::constant]
319 type ChainId: Get<u64>;
320
321 #[pallet::constant]
323 type NativeToEthRatio: Get<u32>;
324
325 #[pallet::no_default_bounds]
330 type FeeInfo: FeeInfo<Self>;
331
332 #[pallet::constant]
345 type MaxEthExtrinsicWeight: Get<FixedU128>;
346
347 #[pallet::constant]
349 type DebugEnabled: Get<bool>;
350
351 #[pallet::constant]
369 #[pallet::no_default_bounds]
370 type GasScale: Get<u32>;
371 }
372
373 pub mod config_preludes {
375 use super::*;
376 use frame_support::{
377 derive_impl,
378 traits::{ConstBool, ConstU32},
379 };
380 use frame_system::EnsureSigned;
381 use sp_core::parameter_types;
382
383 type Balance = u64;
384
385 pub const DOLLARS: Balance = 1_000_000_000_000;
386 pub const CENTS: Balance = DOLLARS / 100;
387 pub const MILLICENTS: Balance = CENTS / 1_000;
388
389 pub const fn deposit(items: u32, bytes: u32) -> Balance {
390 items as Balance * 20 * CENTS + (bytes as Balance) * MILLICENTS
391 }
392
393 parameter_types! {
394 pub const DepositPerItem: Balance = deposit(1, 0);
395 pub const DepositPerChildTrieItem: Balance = deposit(1, 0) / 100;
396 pub const DepositPerByte: Balance = deposit(0, 1);
397 pub const CodeHashLockupDepositPercent: Perbill = Perbill::from_percent(0);
398 pub const MaxEthExtrinsicWeight: FixedU128 = FixedU128::from_rational(9, 10);
399 pub const GasScale: u32 = 10u32;
400 }
401
402 pub struct TestDefaultConfig;
404
405 impl Time for TestDefaultConfig {
406 type Moment = u64;
407 fn now() -> Self::Moment {
408 0u64
409 }
410 }
411
412 impl<T: From<u64>> Convert<Weight, T> for TestDefaultConfig {
413 fn convert(w: Weight) -> T {
414 w.ref_time().into()
415 }
416 }
417
418 #[derive_impl(frame_system::config_preludes::TestDefaultConfig, no_aggregated_types)]
419 impl frame_system::DefaultConfig for TestDefaultConfig {}
420
421 #[frame_support::register_default_impl(TestDefaultConfig)]
422 impl DefaultConfig for TestDefaultConfig {
423 #[inject_runtime_type]
424 type RuntimeEvent = ();
425
426 #[inject_runtime_type]
427 type RuntimeHoldReason = ();
428
429 #[inject_runtime_type]
430 type RuntimeCall = ();
431
432 #[inject_runtime_type]
433 type RuntimeOrigin = ();
434
435 type Precompiles = ();
436 type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent;
437 type DepositPerByte = DepositPerByte;
438 type DepositPerItem = DepositPerItem;
439 type DepositPerChildTrieItem = DepositPerChildTrieItem;
440 type Time = Self;
441 type UnsafeUnstableInterface = ConstBool<true>;
442 type AllowEVMBytecode = ConstBool<true>;
443 type UploadOrigin = EnsureSigned<Self::AccountId>;
444 type InstantiateOrigin = EnsureSigned<Self::AccountId>;
445 type WeightInfo = ();
446 type RuntimeMemory = ConstU32<{ 128 * 1024 * 1024 }>;
447 type PVFMemory = ConstU32<{ 512 * 1024 * 1024 }>;
448 type ChainId = ConstU64<42>;
449 type NativeToEthRatio = ConstU32<1_000_000>;
450 type FindAuthor = ();
451 type FeeInfo = ();
452 type MaxEthExtrinsicWeight = MaxEthExtrinsicWeight;
453 type DebugEnabled = ConstBool<false>;
454 type GasScale = GasScale;
455 }
456 }
457
458 #[pallet::event]
459 pub enum Event<T: Config> {
460 ContractEmitted {
462 contract: H160,
464 data: Vec<u8>,
467 topics: Vec<H256>,
470 },
471
472 Instantiated { deployer: H160, contract: H160 },
474
475 EthExtrinsicRevert { dispatch_error: DispatchError },
482 }
483
484 #[pallet::error]
485 #[repr(u8)]
486 pub enum Error<T> {
487 InvalidSchedule = 0x01,
489 InvalidCallFlags = 0x02,
491 OutOfGas = 0x03,
493 TransferFailed = 0x04,
496 MaxCallDepthReached = 0x05,
499 ContractNotFound = 0x06,
501 CodeNotFound = 0x07,
503 CodeInfoNotFound = 0x08,
505 OutOfBounds = 0x09,
507 DecodingFailed = 0x0A,
509 ContractTrapped = 0x0B,
511 ValueTooLarge = 0x0C,
513 TerminatedWhileReentrant = 0x0D,
516 InputForwarded = 0x0E,
518 TooManyTopics = 0x0F,
520 DuplicateContract = 0x12,
522 TerminatedInConstructor = 0x13,
526 ReentranceDenied = 0x14,
528 ReenteredPallet = 0x15,
530 StateChangeDenied = 0x16,
532 StorageDepositNotEnoughFunds = 0x17,
534 StorageDepositLimitExhausted = 0x18,
536 CodeInUse = 0x19,
538 ContractReverted = 0x1A,
543 CodeRejected = 0x1B,
548 BlobTooLarge = 0x1C,
550 StaticMemoryTooLarge = 0x1D,
552 BasicBlockTooLarge = 0x1E,
554 InvalidInstruction = 0x1F,
556 MaxDelegateDependenciesReached = 0x20,
558 DelegateDependencyNotFound = 0x21,
560 DelegateDependencyAlreadyExists = 0x22,
562 CannotAddSelfAsDelegateDependency = 0x23,
564 OutOfTransientStorage = 0x24,
566 InvalidSyscall = 0x25,
568 InvalidStorageFlags = 0x26,
570 ExecutionFailed = 0x27,
572 BalanceConversionFailed = 0x28,
574 InvalidImmutableAccess = 0x2A,
577 AccountUnmapped = 0x2B,
581 AccountAlreadyMapped = 0x2C,
583 InvalidGenericTransaction = 0x2D,
585 RefcountOverOrUnderflow = 0x2E,
587 UnsupportedPrecompileAddress = 0x2F,
589 CallDataTooLarge = 0x30,
591 ReturnDataTooLarge = 0x31,
593 InvalidJump = 0x32,
595 StackUnderflow = 0x33,
597 StackOverflow = 0x34,
599 TxFeeOverdraw = 0x35,
603 EvmConstructorNonEmptyData = 0x36,
607 EvmConstructedFromHash = 0x37,
612 StorageRefundNotEnoughFunds = 0x38,
616 StorageRefundLocked = 0x39,
621 PrecompileDelegateDenied = 0x40,
626 #[cfg(feature = "runtime-benchmarks")]
628 BenchmarkingError = 0xFF,
629 }
630
631 #[pallet::composite_enum]
633 pub enum HoldReason {
634 CodeUploadDepositReserve,
636 StorageDepositReserve,
638 AddressMapping,
640 }
641
642 #[derive(
643 PartialEq, Eq, Clone, MaxEncodedLen, Encode, Decode, DecodeWithMemTracking, TypeInfo, Debug,
644 )]
645 #[pallet::origin]
646 pub enum Origin<T: Config> {
647 EthTransaction(T::AccountId),
648 }
649
650 #[pallet::storage]
654 #[pallet::unbounded]
655 pub(crate) type PristineCode<T: Config> = StorageMap<_, Identity, H256, Vec<u8>>;
656
657 #[pallet::storage]
659 pub(crate) type CodeInfoOf<T: Config> = StorageMap<_, Identity, H256, CodeInfo<T>>;
660
661 #[pallet::storage]
663 pub(crate) type AccountInfoOf<T: Config> = StorageMap<_, Identity, H160, AccountInfo<T>>;
664
665 #[pallet::storage]
667 pub(crate) type ImmutableDataOf<T: Config> = StorageMap<_, Identity, H160, ImmutableData>;
668
669 #[pallet::storage]
674 pub(crate) type DeletionQueue<T: Config> = StorageMap<_, Twox64Concat, u32, TrieId>;
675
676 #[pallet::storage]
679 pub(crate) type DeletionQueueCounter<T: Config> =
680 StorageValue<_, DeletionQueueManager<T>, ValueQuery>;
681
682 #[pallet::storage]
689 pub(crate) type OriginalAccount<T: Config> = StorageMap<_, Identity, H160, AccountId32>;
690
691 #[pallet::storage]
701 #[pallet::unbounded]
702 pub(crate) type EthereumBlock<T> = StorageValue<_, EthBlock, ValueQuery>;
703
704 #[pallet::storage]
708 pub(crate) type BlockHash<T: Config> =
709 StorageMap<_, Identity, BlockNumberFor<T>, H256, ValueQuery>;
710
711 #[pallet::storage]
718 #[pallet::unbounded]
719 pub(crate) type ReceiptInfoData<T: Config> = StorageValue<_, Vec<ReceiptGasInfo>, ValueQuery>;
720
721 #[pallet::storage]
723 #[pallet::unbounded]
724 pub(crate) type EthBlockBuilderIR<T: Config> =
725 StorageValue<_, EthereumBlockBuilderIR<T>, ValueQuery>;
726
727 #[pallet::storage]
732 #[pallet::unbounded]
733 pub(crate) type EthBlockBuilderFirstValues<T: Config> =
734 StorageValue<_, Option<(Vec<u8>, Vec<u8>)>, ValueQuery>;
735
736 #[pallet::storage]
738 pub(crate) type DebugSettingsOf<T: Config> = StorageValue<_, DebugSettings, ValueQuery>;
739
740 pub mod genesis {
741 use super::*;
742 use crate::evm::Bytes32;
743
744 #[derive(Clone, PartialEq, Debug, Default, serde::Serialize, serde::Deserialize)]
746 pub struct ContractData {
747 pub code: Vec<u8>,
749 pub storage: alloc::collections::BTreeMap<Bytes32, Bytes32>,
751 }
752
753 #[derive(PartialEq, Default, Debug, Clone, serde::Serialize, serde::Deserialize)]
755 pub struct Account<T: Config> {
756 pub address: H160,
758 #[serde(default)]
760 pub balance: U256,
761 #[serde(default)]
763 pub nonce: T::Nonce,
764 #[serde(flatten, skip_serializing_if = "Option::is_none")]
766 pub contract_data: Option<ContractData>,
767 }
768 }
769
770 #[pallet::genesis_config]
771 #[derive(Debug, PartialEq, frame_support::DefaultNoBound)]
772 pub struct GenesisConfig<T: Config> {
773 #[serde(default, skip_serializing_if = "Vec::is_empty")]
776 pub mapped_accounts: Vec<T::AccountId>,
777
778 #[serde(default, skip_serializing_if = "Vec::is_empty")]
780 pub accounts: Vec<genesis::Account<T>>,
781
782 #[serde(default, skip_serializing_if = "Option::is_none")]
784 pub debug_settings: Option<DebugSettings>,
785 }
786
787 #[pallet::genesis_build]
788 impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
789 fn build(&self) {
790 use crate::{exec::Key, vm::ContractBlob};
791 use frame_support::traits::fungible::Mutate;
792
793 if !System::<T>::account_exists(&Pallet::<T>::account_id()) {
794 let _ = T::Currency::mint_into(
795 &Pallet::<T>::account_id(),
796 T::Currency::minimum_balance(),
797 );
798 }
799
800 for id in &self.mapped_accounts {
801 if let Err(err) = T::AddressMapper::map_no_deposit(id) {
802 log::error!(target: LOG_TARGET, "Failed to map account {id:?}: {err:?}");
803 }
804 }
805
806 let owner = Pallet::<T>::account_id();
807
808 for genesis::Account { address, balance, nonce, contract_data } in &self.accounts {
809 let account_id = T::AddressMapper::to_account_id(address);
810
811 if !System::<T>::account_exists(&account_id) {
812 let _ = T::Currency::mint_into(&account_id, T::Currency::minimum_balance());
813 }
814
815 frame_system::Account::<T>::mutate(&account_id, |info| {
816 info.nonce = (*nonce).into();
817 });
818
819 match contract_data {
820 None => {
821 AccountInfoOf::<T>::insert(
822 address,
823 AccountInfo { account_type: AccountType::EOA, dust: 0 },
824 );
825 },
826 Some(genesis::ContractData { code, storage }) => {
827 let blob = if code.starts_with(&polkavm_common::program::BLOB_MAGIC) {
828 ContractBlob::<T>::from_pvm_code( code.clone(), owner.clone()).inspect_err(|err| {
829 log::error!(target: LOG_TARGET, "Failed to create PVM ContractBlob for {address:?}: {err:?}");
830 })
831 } else {
832 ContractBlob::<T>::from_evm_runtime_code(code.clone(), account_id).inspect_err(|err| {
833 log::error!(target: LOG_TARGET, "Failed to create EVM ContractBlob for {address:?}: {err:?}");
834 })
835 };
836
837 let Ok(blob) = blob else {
838 continue;
839 };
840
841 let code_hash = *blob.code_hash();
842 let Ok(info) = <ContractInfo<T>>::new(&address, 0u32.into(), code_hash)
843 .inspect_err(|err| {
844 log::error!(target: LOG_TARGET, "Failed to create ContractInfo for {address:?}: {err:?}");
845 })
846 else {
847 continue;
848 };
849
850 AccountInfoOf::<T>::insert(
851 address,
852 AccountInfo { account_type: info.clone().into(), dust: 0 },
853 );
854
855 <PristineCode<T>>::insert(blob.code_hash(), code);
856 <CodeInfoOf<T>>::insert(blob.code_hash(), blob.code_info().clone());
857 for (k, v) in storage {
858 let _ = info.write(&Key::from_fixed(k.0), Some(v.0.to_vec()), None, false).inspect_err(|err| {
859 log::error!(target: LOG_TARGET, "Failed to write genesis storage for {address:?} at key {k:?}: {err:?}");
860 });
861 }
862 },
863 }
864
865 let _ = Pallet::<T>::set_evm_balance(address, *balance).inspect_err(|err| {
866 log::error!(target: LOG_TARGET, "Failed to set EVM balance for {address:?}: {err:?}");
867 });
868 }
869
870 block_storage::on_finalize_build_eth_block::<T>(
872 frame_system::Pallet::<T>::block_number(),
875 );
876
877 if let Some(settings) = self.debug_settings.as_ref() {
879 settings.write_to_storage::<T>()
880 }
881 }
882 }
883
884 #[pallet::hooks]
885 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
886 fn on_idle(_block: BlockNumberFor<T>, limit: Weight) -> Weight {
887 let mut meter = WeightMeter::with_limit(limit);
888 ContractInfo::<T>::process_deletion_queue_batch(&mut meter);
889 meter.consumed()
890 }
891
892 fn on_initialize(_n: BlockNumberFor<T>) -> Weight {
893 block_storage::on_initialize::<T>();
895
896 System::<T>::account_exists(&Pallet::<T>::account_id());
898 <T as Config>::WeightInfo::on_finalize_block_fixed()
900 }
901
902 fn on_finalize(block_number: BlockNumberFor<T>) {
903 block_storage::on_finalize_build_eth_block::<T>(block_number);
905 }
906
907 fn integrity_test() {
908 assert!(T::ChainId::get() > 0, "ChainId must be greater than 0");
909
910 assert!(T::GasScale::get() > 0u32.into(), "GasScale must not be 0");
911
912 T::FeeInfo::integrity_test();
913
914 let max_runtime_mem: u64 = T::RuntimeMemory::get().into();
916
917 const TOTAL_MEMORY_DEVIDER: u64 = 2;
920
921 let max_block_weight = T::BlockWeights::get()
927 .get(DispatchClass::Normal)
928 .max_total
929 .unwrap_or_else(|| T::BlockWeights::get().max_block);
930 let max_key_size: u64 =
931 Key::try_from_var(alloc::vec![0u8; limits::STORAGE_KEY_BYTES as usize])
932 .expect("Key of maximal size shall be created")
933 .hash()
934 .len()
935 .try_into()
936 .unwrap();
937
938 let max_immutable_key_size: u64 = T::AccountId::max_encoded_len().try_into().unwrap();
939 let max_immutable_size: u64 = max_block_weight
940 .checked_div_per_component(&<RuntimeCosts as WeightToken<T>>::weight(
941 &RuntimeCosts::SetImmutableData(limits::IMMUTABLE_BYTES),
942 ))
943 .unwrap()
944 .saturating_mul(
945 u64::from(limits::IMMUTABLE_BYTES)
946 .saturating_add(max_immutable_key_size)
947 .into(),
948 );
949
950 let max_pvf_mem: u64 = T::PVFMemory::get().into();
951 let storage_size_limit = max_pvf_mem.saturating_sub(max_runtime_mem) / 2;
952
953 let max_events_size = max_block_weight
957 .checked_div_per_component(
958 &(<RuntimeCosts as WeightToken<T>>::weight(&RuntimeCosts::DepositEvent {
959 num_topic: 0,
960 len: limits::EVENT_BYTES,
961 })
962 .saturating_add(<RuntimeCosts as WeightToken<T>>::weight(
963 &RuntimeCosts::HostFn,
964 ))),
965 )
966 .unwrap()
967 .saturating_mul(limits::EVENT_BYTES.into());
968
969 assert!(
970 max_events_size <= storage_size_limit,
971 "Maximal events size {} exceeds the events limit {}",
972 max_events_size,
973 storage_size_limit
974 );
975
976 let max_eth_block_builder_bytes =
1011 block_storage::block_builder_bytes_usage(max_events_size.try_into().unwrap());
1012
1013 log::debug!(
1014 target: LOG_TARGET,
1015 "Integrity check: max_eth_block_builder_bytes={} KB using max_events_size={} KB",
1016 max_eth_block_builder_bytes / 1024,
1017 max_events_size / 1024,
1018 );
1019
1020 let memory_left = i128::from(max_runtime_mem)
1025 .saturating_div(TOTAL_MEMORY_DEVIDER.into())
1026 .saturating_sub(limits::MEMORY_REQUIRED.into())
1027 .saturating_sub(max_eth_block_builder_bytes.into());
1028
1029 log::debug!(target: LOG_TARGET, "Integrity check: memory_left={} KB", memory_left / 1024);
1030
1031 assert!(
1032 memory_left >= 0,
1033 "Runtime does not have enough memory for current limits. Additional runtime memory required: {} KB",
1034 memory_left.saturating_mul(TOTAL_MEMORY_DEVIDER.into()).abs() / 1024
1035 );
1036
1037 let max_storage_size = max_block_weight
1040 .checked_div_per_component(
1041 &<RuntimeCosts as WeightToken<T>>::weight(&RuntimeCosts::SetStorage {
1042 new_bytes: limits::STORAGE_BYTES,
1043 old_bytes: 0,
1044 })
1045 .saturating_mul(u64::from(limits::STORAGE_BYTES).saturating_add(max_key_size)),
1046 )
1047 .unwrap()
1048 .saturating_add(max_immutable_size.into())
1049 .saturating_add(max_eth_block_builder_bytes.into());
1050
1051 assert!(
1052 max_storage_size <= storage_size_limit,
1053 "Maximal storage size {} exceeds the storage limit {}",
1054 max_storage_size,
1055 storage_size_limit
1056 );
1057 }
1058 }
1059
1060 #[pallet::call]
1061 impl<T: Config> Pallet<T> {
1062 #[allow(unused_variables)]
1075 #[pallet::call_index(0)]
1076 #[pallet::weight(Weight::MAX)]
1077 pub fn eth_transact(origin: OriginFor<T>, payload: Vec<u8>) -> DispatchResultWithPostInfo {
1078 Err(frame_system::Error::CallFiltered::<T>.into())
1079 }
1080
1081 #[pallet::call_index(1)]
1098 #[pallet::weight(<T as Config>::WeightInfo::call().saturating_add(*weight_limit))]
1099 pub fn call(
1100 origin: OriginFor<T>,
1101 dest: H160,
1102 #[pallet::compact] value: BalanceOf<T>,
1103 weight_limit: Weight,
1104 #[pallet::compact] storage_deposit_limit: BalanceOf<T>,
1105 data: Vec<u8>,
1106 ) -> DispatchResultWithPostInfo {
1107 Self::ensure_non_contract_if_signed(&origin)?;
1108 let mut output = Self::bare_call(
1109 origin,
1110 dest,
1111 Pallet::<T>::convert_native_to_evm(value),
1112 TransactionLimits::WeightAndDeposit {
1113 weight_limit,
1114 deposit_limit: storage_deposit_limit,
1115 },
1116 data,
1117 ExecConfig::new_substrate_tx(),
1118 );
1119
1120 if let Ok(return_value) = &output.result {
1121 if return_value.did_revert() {
1122 output.result = Err(<Error<T>>::ContractReverted.into());
1123 }
1124 }
1125 dispatch_result(
1126 output.result,
1127 output.weight_consumed,
1128 <T as Config>::WeightInfo::call(),
1129 )
1130 }
1131
1132 #[pallet::call_index(2)]
1138 #[pallet::weight(
1139 <T as Config>::WeightInfo::instantiate(data.len() as u32).saturating_add(*weight_limit)
1140 )]
1141 pub fn instantiate(
1142 origin: OriginFor<T>,
1143 #[pallet::compact] value: BalanceOf<T>,
1144 weight_limit: Weight,
1145 #[pallet::compact] storage_deposit_limit: BalanceOf<T>,
1146 code_hash: sp_core::H256,
1147 data: Vec<u8>,
1148 salt: Option<[u8; 32]>,
1149 ) -> DispatchResultWithPostInfo {
1150 Self::ensure_non_contract_if_signed(&origin)?;
1151 let data_len = data.len() as u32;
1152 let mut output = Self::bare_instantiate(
1153 origin,
1154 Pallet::<T>::convert_native_to_evm(value),
1155 TransactionLimits::WeightAndDeposit {
1156 weight_limit,
1157 deposit_limit: storage_deposit_limit,
1158 },
1159 Code::Existing(code_hash),
1160 data,
1161 salt,
1162 ExecConfig::new_substrate_tx(),
1163 );
1164 if let Ok(retval) = &output.result {
1165 if retval.result.did_revert() {
1166 output.result = Err(<Error<T>>::ContractReverted.into());
1167 }
1168 }
1169 dispatch_result(
1170 output.result.map(|result| result.result),
1171 output.weight_consumed,
1172 <T as Config>::WeightInfo::instantiate(data_len),
1173 )
1174 }
1175
1176 #[pallet::call_index(3)]
1204 #[pallet::weight(
1205 <T as Config>::WeightInfo::instantiate_with_code(code.len() as u32, data.len() as u32)
1206 .saturating_add(*weight_limit)
1207 )]
1208 pub fn instantiate_with_code(
1209 origin: OriginFor<T>,
1210 #[pallet::compact] value: BalanceOf<T>,
1211 weight_limit: Weight,
1212 #[pallet::compact] storage_deposit_limit: BalanceOf<T>,
1213 code: Vec<u8>,
1214 data: Vec<u8>,
1215 salt: Option<[u8; 32]>,
1216 ) -> DispatchResultWithPostInfo {
1217 Self::ensure_non_contract_if_signed(&origin)?;
1218 let code_len = code.len() as u32;
1219 let data_len = data.len() as u32;
1220 let mut output = Self::bare_instantiate(
1221 origin,
1222 Pallet::<T>::convert_native_to_evm(value),
1223 TransactionLimits::WeightAndDeposit {
1224 weight_limit,
1225 deposit_limit: storage_deposit_limit,
1226 },
1227 Code::Upload(code),
1228 data,
1229 salt,
1230 ExecConfig::new_substrate_tx(),
1231 );
1232 if let Ok(retval) = &output.result {
1233 if retval.result.did_revert() {
1234 output.result = Err(<Error<T>>::ContractReverted.into());
1235 }
1236 }
1237 dispatch_result(
1238 output.result.map(|result| result.result),
1239 output.weight_consumed,
1240 <T as Config>::WeightInfo::instantiate_with_code(code_len, data_len),
1241 )
1242 }
1243
1244 #[pallet::call_index(10)]
1266 #[pallet::weight(
1267 <T as Config>::WeightInfo::eth_instantiate_with_code(code.len() as u32, data.len() as u32, Pallet::<T>::has_dust(*value).into())
1268 .saturating_add(*weight_limit)
1269 )]
1270 pub fn eth_instantiate_with_code(
1271 origin: OriginFor<T>,
1272 value: U256,
1273 weight_limit: Weight,
1274 eth_gas_limit: U256,
1275 code: Vec<u8>,
1276 data: Vec<u8>,
1277 transaction_encoded: Vec<u8>,
1278 effective_gas_price: U256,
1279 encoded_len: u32,
1280 ) -> DispatchResultWithPostInfo {
1281 let signer = Self::ensure_eth_signed(origin)?;
1282 let origin = OriginFor::<T>::signed(signer.clone());
1283 Self::ensure_non_contract_if_signed(&origin)?;
1284 let mut call = Call::<T>::eth_instantiate_with_code {
1285 value,
1286 weight_limit,
1287 eth_gas_limit,
1288 code: code.clone(),
1289 data: data.clone(),
1290 transaction_encoded: transaction_encoded.clone(),
1291 effective_gas_price,
1292 encoded_len,
1293 }
1294 .into();
1295 let info = T::FeeInfo::dispatch_info(&call);
1296 let base_info = T::FeeInfo::base_dispatch_info(&mut call);
1297 drop(call);
1298
1299 block_storage::with_ethereum_context::<T>(transaction_encoded, || {
1300 let extra_weight = base_info.total_weight();
1301 let output = Self::bare_instantiate(
1302 origin,
1303 value,
1304 TransactionLimits::EthereumGas {
1305 eth_gas_limit: eth_gas_limit.saturated_into(),
1306 maybe_weight_limit: Some(weight_limit),
1307 eth_tx_info: EthTxInfo::new(encoded_len, extra_weight),
1308 },
1309 Code::Upload(code),
1310 data,
1311 None,
1312 ExecConfig::new_eth_tx(effective_gas_price, encoded_len, extra_weight),
1313 );
1314
1315 block_storage::EthereumCallResult::new::<T>(
1316 signer,
1317 output.map_result(|r| r.result),
1318 base_info.call_weight,
1319 encoded_len,
1320 &info,
1321 effective_gas_price,
1322 )
1323 })
1324 }
1325
1326 #[pallet::call_index(11)]
1343 #[pallet::weight(
1344 T::WeightInfo::eth_call(Pallet::<T>::has_dust(*value).into())
1345 .saturating_add(*weight_limit)
1346 .saturating_add(T::WeightInfo::on_finalize_block_per_tx(transaction_encoded.len() as u32))
1347 )]
1348 pub fn eth_call(
1349 origin: OriginFor<T>,
1350 dest: H160,
1351 value: U256,
1352 weight_limit: Weight,
1353 eth_gas_limit: U256,
1354 data: Vec<u8>,
1355 transaction_encoded: Vec<u8>,
1356 effective_gas_price: U256,
1357 encoded_len: u32,
1358 ) -> DispatchResultWithPostInfo {
1359 let signer = Self::ensure_eth_signed(origin)?;
1360 let origin = OriginFor::<T>::signed(signer.clone());
1361
1362 Self::ensure_non_contract_if_signed(&origin)?;
1363 let mut call = Call::<T>::eth_call {
1364 dest,
1365 value,
1366 weight_limit,
1367 eth_gas_limit,
1368 data: data.clone(),
1369 transaction_encoded: transaction_encoded.clone(),
1370 effective_gas_price,
1371 encoded_len,
1372 }
1373 .into();
1374 let info = T::FeeInfo::dispatch_info(&call);
1375 let base_info = T::FeeInfo::base_dispatch_info(&mut call);
1376 drop(call);
1377
1378 block_storage::with_ethereum_context::<T>(transaction_encoded, || {
1379 let extra_weight = base_info.total_weight();
1380 let output = Self::bare_call(
1381 origin,
1382 dest,
1383 value,
1384 TransactionLimits::EthereumGas {
1385 eth_gas_limit: eth_gas_limit.saturated_into(),
1386 maybe_weight_limit: Some(weight_limit),
1387 eth_tx_info: EthTxInfo::new(encoded_len, extra_weight),
1388 },
1389 data,
1390 ExecConfig::new_eth_tx(effective_gas_price, encoded_len, extra_weight),
1391 );
1392
1393 block_storage::EthereumCallResult::new::<T>(
1394 signer,
1395 output,
1396 base_info.call_weight,
1397 encoded_len,
1398 &info,
1399 effective_gas_price,
1400 )
1401 })
1402 }
1403
1404 #[pallet::call_index(12)]
1415 #[pallet::weight(T::WeightInfo::eth_substrate_call(transaction_encoded.len() as u32).saturating_add(call.get_dispatch_info().call_weight))]
1416 pub fn eth_substrate_call(
1417 origin: OriginFor<T>,
1418 call: Box<<T as Config>::RuntimeCall>,
1419 transaction_encoded: Vec<u8>,
1420 ) -> DispatchResultWithPostInfo {
1421 let signer = Self::ensure_eth_signed(origin)?;
1424 let weight_overhead =
1425 T::WeightInfo::eth_substrate_call(transaction_encoded.len() as u32);
1426
1427 block_storage::with_ethereum_context::<T>(transaction_encoded, || {
1428 let call_weight = call.get_dispatch_info().call_weight;
1429 let mut call_result = call.dispatch(RawOrigin::Signed(signer).into());
1430
1431 match &mut call_result {
1433 Ok(post_info) | Err(DispatchErrorWithPostInfo { post_info, .. }) => {
1434 post_info.actual_weight = Some(
1435 post_info
1436 .actual_weight
1437 .unwrap_or_else(|| call_weight)
1438 .saturating_add(weight_overhead),
1439 );
1440 },
1441 }
1442
1443 block_storage::EthereumCallResult {
1446 receipt_gas_info: ReceiptGasInfo::default(),
1447 result: call_result,
1448 }
1449 })
1450 }
1451
1452 #[pallet::call_index(4)]
1467 #[pallet::weight(<T as Config>::WeightInfo::upload_code(code.len() as u32))]
1468 pub fn upload_code(
1469 origin: OriginFor<T>,
1470 code: Vec<u8>,
1471 #[pallet::compact] storage_deposit_limit: BalanceOf<T>,
1472 ) -> DispatchResult {
1473 Self::ensure_non_contract_if_signed(&origin)?;
1474 Self::bare_upload_code(origin, code, storage_deposit_limit).map(|_| ())
1475 }
1476
1477 #[pallet::call_index(5)]
1482 #[pallet::weight(<T as Config>::WeightInfo::remove_code())]
1483 pub fn remove_code(
1484 origin: OriginFor<T>,
1485 code_hash: sp_core::H256,
1486 ) -> DispatchResultWithPostInfo {
1487 let origin = ensure_signed(origin)?;
1488 <ContractBlob<T>>::remove(&origin, code_hash)?;
1489 Ok(Pays::No.into())
1491 }
1492
1493 #[pallet::call_index(6)]
1504 #[pallet::weight(<T as Config>::WeightInfo::set_code())]
1505 pub fn set_code(
1506 origin: OriginFor<T>,
1507 dest: H160,
1508 code_hash: sp_core::H256,
1509 ) -> DispatchResult {
1510 ensure_root(origin)?;
1511 <AccountInfoOf<T>>::try_mutate(&dest, |account| {
1512 let Some(account) = account else {
1513 return Err(<Error<T>>::ContractNotFound.into());
1514 };
1515
1516 let AccountType::Contract(ref mut contract) = account.account_type else {
1517 return Err(<Error<T>>::ContractNotFound.into());
1518 };
1519
1520 <CodeInfo<T>>::increment_refcount(code_hash)?;
1521 let _ = <CodeInfo<T>>::decrement_refcount(contract.code_hash)?;
1522 contract.code_hash = code_hash;
1523
1524 Ok(())
1525 })
1526 }
1527
1528 #[pallet::call_index(7)]
1533 #[pallet::weight(<T as Config>::WeightInfo::map_account())]
1534 pub fn map_account(origin: OriginFor<T>) -> DispatchResult {
1535 Self::ensure_non_contract_if_signed(&origin)?;
1536 let origin = ensure_signed(origin)?;
1537 T::AddressMapper::map(&origin)
1538 }
1539
1540 #[pallet::call_index(8)]
1545 #[pallet::weight(<T as Config>::WeightInfo::unmap_account())]
1546 pub fn unmap_account(origin: OriginFor<T>) -> DispatchResult {
1547 let origin = ensure_signed(origin)?;
1548 T::AddressMapper::unmap(&origin)
1549 }
1550
1551 #[pallet::call_index(9)]
1557 #[pallet::weight({
1558 let dispatch_info = call.get_dispatch_info();
1559 (
1560 <T as Config>::WeightInfo::dispatch_as_fallback_account().saturating_add(dispatch_info.call_weight),
1561 dispatch_info.class
1562 )
1563 })]
1564 pub fn dispatch_as_fallback_account(
1565 origin: OriginFor<T>,
1566 call: Box<<T as Config>::RuntimeCall>,
1567 ) -> DispatchResultWithPostInfo {
1568 Self::ensure_non_contract_if_signed(&origin)?;
1569 let origin = ensure_signed(origin)?;
1570 let unmapped_account =
1571 T::AddressMapper::to_fallback_account_id(&T::AddressMapper::to_address(&origin));
1572 call.dispatch(RawOrigin::Signed(unmapped_account).into())
1573 }
1574 }
1575}
1576
1577fn dispatch_result<R>(
1579 result: Result<R, DispatchError>,
1580 weight_consumed: Weight,
1581 base_weight: Weight,
1582) -> DispatchResultWithPostInfo {
1583 let post_info = PostDispatchInfo {
1584 actual_weight: Some(weight_consumed.saturating_add(base_weight)),
1585 pays_fee: Default::default(),
1586 };
1587
1588 result
1589 .map(|_| post_info)
1590 .map_err(|e| DispatchErrorWithPostInfo { post_info, error: e })
1591}
1592
1593impl<T: Config> Pallet<T> {
1594 pub fn bare_call(
1601 origin: OriginFor<T>,
1602 dest: H160,
1603 evm_value: U256,
1604 transaction_limits: TransactionLimits<T>,
1605 data: Vec<u8>,
1606 exec_config: ExecConfig<T>,
1607 ) -> ContractResult<ExecReturnValue, BalanceOf<T>> {
1608 let mut transaction_meter = match TransactionMeter::new(transaction_limits) {
1609 Ok(transaction_meter) => transaction_meter,
1610 Err(error) => return ContractResult { result: Err(error), ..Default::default() },
1611 };
1612
1613 let mut storage_deposit = Default::default();
1614
1615 let try_call = || {
1616 let origin = ExecOrigin::from_runtime_origin(origin)?;
1617 let result = ExecStack::<T, ContractBlob<T>>::run_call(
1618 origin.clone(),
1619 dest,
1620 &mut transaction_meter,
1621 evm_value,
1622 data,
1623 &exec_config,
1624 )?;
1625
1626 storage_deposit = transaction_meter
1627 .execute_postponed_deposits(&origin, &exec_config)
1628 .inspect_err(|err| {
1629 log::debug!(target: LOG_TARGET, "Failed to transfer deposit: {err:?}");
1630 })?;
1631
1632 Ok(result)
1633 };
1634 let result = Self::run_guarded(try_call);
1635
1636 log::trace!(target: LOG_TARGET, "Bare call ends: \
1637 result={result:?}, \
1638 weight_consumed={:?}, \
1639 weight_required={:?}, \
1640 storage_deposit={:?}, \
1641 gas_consumed={:?}, \
1642 max_storage_deposit={:?}",
1643 transaction_meter.weight_consumed(),
1644 transaction_meter.weight_required(),
1645 storage_deposit,
1646 transaction_meter.total_consumed_gas(),
1647 transaction_meter.deposit_required()
1648 );
1649
1650 ContractResult {
1651 result: result.map_err(|r| r.error),
1652 weight_consumed: transaction_meter.weight_consumed(),
1653 weight_required: transaction_meter.weight_required(),
1654 storage_deposit,
1655 gas_consumed: transaction_meter.total_consumed_gas(),
1656 max_storage_deposit: transaction_meter.deposit_required(),
1657 }
1658 }
1659
1660 pub fn prepare_dry_run(account: &T::AccountId) {
1666 frame_system::Pallet::<T>::inc_account_nonce(account);
1669 }
1670
1671 pub fn bare_instantiate(
1677 origin: OriginFor<T>,
1678 evm_value: U256,
1679 transaction_limits: TransactionLimits<T>,
1680 code: Code,
1681 data: Vec<u8>,
1682 salt: Option<[u8; 32]>,
1683 exec_config: ExecConfig<T>,
1684 ) -> ContractResult<InstantiateReturnValue, BalanceOf<T>> {
1685 let mut transaction_meter = match TransactionMeter::new(transaction_limits) {
1686 Ok(transaction_meter) => transaction_meter,
1687 Err(error) => return ContractResult { result: Err(error), ..Default::default() },
1688 };
1689
1690 let mut storage_deposit = Default::default();
1691
1692 let try_instantiate = || {
1693 let instantiate_account = T::InstantiateOrigin::ensure_origin(origin.clone())?;
1694
1695 if_tracing(|t| t.instantiate_code(&code, salt.as_ref()));
1696 let executable = match code {
1697 Code::Upload(code) if code.starts_with(&polkavm_common::program::BLOB_MAGIC) => {
1698 let upload_account = T::UploadOrigin::ensure_origin(origin)?;
1699 let executable = Self::try_upload_code(
1700 upload_account,
1701 code,
1702 BytecodeType::Pvm,
1703 &mut transaction_meter,
1704 &exec_config,
1705 )?;
1706 executable
1707 },
1708 Code::Upload(code) =>
1709 if T::AllowEVMBytecode::get() {
1710 ensure!(data.is_empty(), <Error<T>>::EvmConstructorNonEmptyData);
1711 let origin = T::UploadOrigin::ensure_origin(origin)?;
1712 let executable = ContractBlob::from_evm_init_code(code, origin)?;
1713 executable
1714 } else {
1715 return Err(<Error<T>>::CodeRejected.into())
1716 },
1717 Code::Existing(code_hash) => {
1718 let executable = ContractBlob::from_storage(code_hash, &mut transaction_meter)?;
1719 ensure!(executable.code_info().is_pvm(), <Error<T>>::EvmConstructedFromHash);
1720 executable
1721 },
1722 };
1723 let instantiate_origin = ExecOrigin::from_account_id(instantiate_account.clone());
1724 let result = ExecStack::<T, ContractBlob<T>>::run_instantiate(
1725 instantiate_account,
1726 executable,
1727 &mut transaction_meter,
1728 evm_value,
1729 data,
1730 salt.as_ref(),
1731 &exec_config,
1732 );
1733
1734 storage_deposit = transaction_meter
1735 .execute_postponed_deposits(&instantiate_origin, &exec_config)
1736 .inspect_err(|err| {
1737 log::debug!(target: LOG_TARGET, "Failed to transfer deposit: {err:?}");
1738 })?;
1739 result
1740 };
1741 let output = Self::run_guarded(try_instantiate);
1742
1743 log::trace!(target: LOG_TARGET, "Bare instantiate ends: weight_consumed={:?}\
1744 weight_required={:?} \
1745 storage_deposit={:?} \
1746 gas_consumed={:?} \
1747 max_storage_deposit={:?}",
1748 transaction_meter.weight_consumed(),
1749 transaction_meter.weight_required(),
1750 storage_deposit,
1751 transaction_meter.total_consumed_gas(),
1752 transaction_meter.deposit_required()
1753 );
1754
1755 ContractResult {
1756 result: output
1757 .map(|(addr, result)| InstantiateReturnValue { result, addr })
1758 .map_err(|e| e.error),
1759 weight_consumed: transaction_meter.weight_consumed(),
1760 weight_required: transaction_meter.weight_required(),
1761 storage_deposit,
1762 gas_consumed: transaction_meter.total_consumed_gas(),
1763 max_storage_deposit: transaction_meter.deposit_required(),
1764 }
1765 }
1766
1767 pub fn dry_run_eth_transact(
1773 mut tx: GenericTransaction,
1774 dry_run_config: DryRunConfig<<<T as Config>::Time as Time>::Moment>,
1775 ) -> Result<EthTransactInfo<BalanceOf<T>>, EthTransactError>
1776 where
1777 T::Nonce: Into<U256>,
1778 CallOf<T>: SetWeightLimit,
1779 {
1780 log::debug!(target: LOG_TARGET, "dry_run_eth_transact: {tx:?}");
1781
1782 let origin = T::AddressMapper::to_account_id(&tx.from.unwrap_or_default());
1783 Self::prepare_dry_run(&origin);
1784
1785 let base_fee = Self::evm_base_fee();
1786 let effective_gas_price = tx.effective_gas_price(base_fee).unwrap_or(base_fee);
1787
1788 if effective_gas_price < base_fee {
1789 Err(EthTransactError::Message(format!(
1790 "Effective gas price {effective_gas_price:?} lower than base fee {base_fee:?}"
1791 )))?;
1792 }
1793
1794 if tx.nonce.is_none() {
1795 tx.nonce = Some(<System<T>>::account_nonce(&origin).into());
1796 }
1797 if tx.chain_id.is_none() {
1798 tx.chain_id = Some(T::ChainId::get().into());
1799 }
1800
1801 tx.gas_price = Some(effective_gas_price);
1803 tx.max_priority_fee_per_gas = Some(0.into());
1806 if tx.max_fee_per_gas.is_none() {
1807 tx.max_fee_per_gas = Some(effective_gas_price);
1808 }
1809
1810 let gas = tx.gas;
1811 if tx.gas.is_none() {
1812 tx.gas = Some(Self::evm_block_gas_limit());
1813 }
1814 if tx.r#type.is_none() {
1815 tx.r#type = Some(TYPE_EIP1559.into());
1816 }
1817
1818 let value = tx.value.unwrap_or_default();
1820 let input = tx.input.clone().to_vec();
1821 let from = tx.from;
1822 let to = tx.to;
1823
1824 let mut call_info = tx
1827 .into_call::<T>(CreateCallMode::DryRun)
1828 .map_err(|err| EthTransactError::Message(format!("Invalid call: {err:?}")))?;
1829
1830 let base_info = T::FeeInfo::base_dispatch_info(&mut call_info.call);
1834 let base_weight = base_info.total_weight();
1835 let exec_config =
1836 ExecConfig::new_eth_tx(effective_gas_price, call_info.encoded_len, base_weight)
1837 .with_dry_run(dry_run_config);
1838
1839 let fees = call_info.tx_fee.saturating_add(call_info.storage_deposit);
1841 if let Some(from) = &from {
1842 let fees = if gas.is_some() { fees } else { Zero::zero() };
1843 let balance = Self::evm_balance(from);
1844 if balance < Pallet::<T>::convert_native_to_evm(fees).saturating_add(value) {
1845 return Err(EthTransactError::Message(format!(
1846 "insufficient funds for gas * price + value ({fees:?}): address {from:?} have {balance:?} (supplied gas {gas:?})",
1847 )));
1848 }
1849 }
1850
1851 T::FeeInfo::deposit_txfee(T::Currency::issue(fees));
1854
1855 let extract_error = |err| {
1856 if err == Error::<T>::StorageDepositNotEnoughFunds.into() {
1857 Err(EthTransactError::Message(format!("Not enough gas supplied: {err:?}")))
1858 } else {
1859 Err(EthTransactError::Message(format!("failed to run contract: {err:?}")))
1860 }
1861 };
1862
1863 let transaction_limits = TransactionLimits::EthereumGas {
1864 eth_gas_limit: call_info.eth_gas_limit.saturated_into(),
1865 maybe_weight_limit: None,
1868 eth_tx_info: EthTxInfo::new(call_info.encoded_len, base_weight),
1869 };
1870
1871 let mut dry_run = match to {
1873 Some(dest) => {
1875 if dest == RUNTIME_PALLETS_ADDR {
1876 let Ok(dispatch_call) = <CallOf<T>>::decode(&mut &input[..]) else {
1877 return Err(EthTransactError::Message(format!(
1878 "Failed to decode pallet-call {input:?}"
1879 )));
1880 };
1881
1882 if let Err(result) =
1883 dispatch_call.clone().dispatch(RawOrigin::Signed(origin).into())
1884 {
1885 return Err(EthTransactError::Message(format!(
1886 "Failed to dispatch call: {:?}",
1887 result.error,
1888 )));
1889 };
1890
1891 Default::default()
1892 } else {
1893 let result = crate::Pallet::<T>::bare_call(
1895 OriginFor::<T>::signed(origin),
1896 dest,
1897 value,
1898 transaction_limits,
1899 input.clone(),
1900 exec_config,
1901 );
1902
1903 let data = match result.result {
1904 Ok(return_value) => {
1905 if return_value.did_revert() {
1906 return Err(EthTransactError::Data(return_value.data));
1907 }
1908 return_value.data
1909 },
1910 Err(err) => {
1911 log::debug!(target: LOG_TARGET, "Failed to execute call: {err:?}");
1912 return extract_error(err);
1913 },
1914 };
1915
1916 EthTransactInfo {
1917 weight_required: result.weight_required,
1918 storage_deposit: result.storage_deposit.charge_or_zero(),
1919 max_storage_deposit: result.max_storage_deposit.charge_or_zero(),
1920 data,
1921 eth_gas: Default::default(),
1922 }
1923 }
1924 },
1925 None => {
1927 let (code, data) = if input.starts_with(&polkavm_common::program::BLOB_MAGIC) {
1929 extract_code_and_data(&input).unwrap_or_else(|| (input, Default::default()))
1930 } else {
1931 (input, vec![])
1932 };
1933
1934 let result = crate::Pallet::<T>::bare_instantiate(
1936 OriginFor::<T>::signed(origin),
1937 value,
1938 transaction_limits,
1939 Code::Upload(code.clone()),
1940 data.clone(),
1941 None,
1942 exec_config,
1943 );
1944
1945 let returned_data = match result.result {
1946 Ok(return_value) => {
1947 if return_value.result.did_revert() {
1948 return Err(EthTransactError::Data(return_value.result.data));
1949 }
1950 return_value.result.data
1951 },
1952 Err(err) => {
1953 log::debug!(target: LOG_TARGET, "Failed to instantiate: {err:?}");
1954 return extract_error(err);
1955 },
1956 };
1957
1958 EthTransactInfo {
1959 weight_required: result.weight_required,
1960 storage_deposit: result.storage_deposit.charge_or_zero(),
1961 max_storage_deposit: result.max_storage_deposit.charge_or_zero(),
1962 data: returned_data,
1963 eth_gas: Default::default(),
1964 }
1965 },
1966 };
1967
1968 call_info.call.set_weight_limit(dry_run.weight_required);
1970
1971 let total_weight = T::FeeInfo::dispatch_info(&call_info.call).total_weight();
1973 let max_weight = Self::evm_max_extrinsic_weight();
1974 if total_weight.any_gt(max_weight) {
1975 log::debug!(target: LOG_TARGET, "Transaction weight estimate exceeds extrinsic maximum: \
1976 total_weight={total_weight:?} \
1977 max_weight={max_weight:?}",
1978 );
1979
1980 Err(EthTransactError::Message(format!(
1981 "\
1982 The transaction consumes more than the allowed weight. \
1983 needed={total_weight} \
1984 allowed={max_weight} \
1985 overweight_by={}\
1986 ",
1987 total_weight.saturating_sub(max_weight),
1988 )))?;
1989 }
1990
1991 let transaction_fee = T::FeeInfo::tx_fee(call_info.encoded_len, &call_info.call);
1993 let available_fee = T::FeeInfo::remaining_txfee();
1994 if transaction_fee > available_fee {
1995 Err(EthTransactError::Message(format!(
1996 "Not enough gas supplied: Off by: {:?}",
1997 transaction_fee.saturating_sub(available_fee),
1998 )))?;
1999 }
2000
2001 let total_cost = transaction_fee.saturating_add(dry_run.max_storage_deposit);
2002 let total_cost_wei = Pallet::<T>::convert_native_to_evm(total_cost);
2003 let (mut eth_gas, rest) = total_cost_wei.div_mod(base_fee);
2004 if !rest.is_zero() {
2005 eth_gas = eth_gas.saturating_add(1_u32.into());
2006 }
2007
2008 log::debug!(target: LOG_TARGET, "\
2009 dry_run_eth_transact finished: \
2010 weight_limit={}, \
2011 total_weight={total_weight}, \
2012 max_weight={max_weight}, \
2013 weight_left={}, \
2014 eth_gas={eth_gas}, \
2015 encoded_len={}, \
2016 tx_fee={transaction_fee:?}, \
2017 storage_deposit={:?}, \
2018 max_storage_deposit={:?}\
2019 ",
2020 dry_run.weight_required,
2021 max_weight.saturating_sub(total_weight),
2022 call_info.encoded_len,
2023 dry_run.storage_deposit,
2024 dry_run.max_storage_deposit,
2025
2026 );
2027 dry_run.eth_gas = eth_gas;
2028 Ok(dry_run)
2029 }
2030
2031 pub fn evm_balance(address: &H160) -> U256 {
2035 let balance = AccountInfo::<T>::balance_of((*address).into());
2036 Self::convert_native_to_evm(balance)
2037 }
2038
2039 pub fn eth_block() -> EthBlock {
2041 EthereumBlock::<T>::get()
2042 }
2043
2044 pub fn eth_block_hash_from_number(number: U256) -> Option<H256> {
2051 let number = BlockNumberFor::<T>::try_from(number).ok()?;
2052 let hash = <BlockHash<T>>::get(number);
2053 if hash == H256::zero() {
2054 None
2055 } else {
2056 Some(hash)
2057 }
2058 }
2059
2060 pub fn eth_receipt_data() -> Vec<ReceiptGasInfo> {
2062 ReceiptInfoData::<T>::get()
2063 }
2064
2065 pub fn set_evm_balance(address: &H160, evm_value: U256) -> Result<(), Error<T>> {
2071 let (balance, dust) = Self::new_balance_with_dust(evm_value)
2072 .map_err(|_| <Error<T>>::BalanceConversionFailed)?;
2073 let account_id = T::AddressMapper::to_account_id(&address);
2074 T::Currency::set_balance(&account_id, balance);
2075 AccountInfoOf::<T>::mutate(&address, |account| {
2076 if let Some(account) = account {
2077 account.dust = dust;
2078 } else {
2079 *account = Some(AccountInfo { dust, ..Default::default() });
2080 }
2081 });
2082
2083 Ok(())
2084 }
2085
2086 pub fn new_balance_with_dust(
2090 evm_value: U256,
2091 ) -> Result<(BalanceOf<T>, u32), BalanceConversionError> {
2092 let ed = T::Currency::minimum_balance();
2093 let balance_with_dust = BalanceWithDust::<BalanceOf<T>>::from_value::<T>(evm_value)?;
2094 let (value, dust) = balance_with_dust.deconstruct();
2095
2096 Ok((ed.saturating_add(value), dust))
2097 }
2098
2099 pub fn evm_nonce(address: &H160) -> u32
2101 where
2102 T::Nonce: Into<u32>,
2103 {
2104 let account = T::AddressMapper::to_account_id(&address);
2105 System::<T>::account_nonce(account).into()
2106 }
2107
2108 pub fn evm_block_gas_limit() -> U256 {
2110 u64::MAX.into()
2117 }
2118
2119 pub fn evm_max_extrinsic_weight() -> Weight {
2121 let factor = <T as Config>::MaxEthExtrinsicWeight::get();
2122 let max_weight = <T as frame_system::Config>::BlockWeights::get()
2123 .get(DispatchClass::Normal)
2124 .max_extrinsic
2125 .unwrap_or_else(|| <T as frame_system::Config>::BlockWeights::get().max_block);
2126 Weight::from_parts(
2127 factor.saturating_mul_int(max_weight.ref_time()),
2128 factor.saturating_mul_int(max_weight.proof_size()),
2129 )
2130 }
2131
2132 pub fn evm_base_fee() -> U256 {
2134 let gas_scale = <T as Config>::GasScale::get();
2135 let multiplier = T::FeeInfo::next_fee_multiplier();
2136 multiplier
2137 .saturating_mul_int::<u128>(T::NativeToEthRatio::get().into())
2138 .saturating_mul(gas_scale.saturated_into())
2139 .into()
2140 }
2141
2142 pub fn evm_tracer(tracer_type: TracerType) -> Tracer<T>
2144 where
2145 T::Nonce: Into<u32>,
2146 {
2147 match tracer_type {
2148 TracerType::CallTracer(config) => CallTracer::new(config.unwrap_or_default()).into(),
2149 TracerType::PrestateTracer(config) =>
2150 PrestateTracer::new(config.unwrap_or_default()).into(),
2151 }
2152 }
2153
2154 pub fn bare_upload_code(
2158 origin: OriginFor<T>,
2159 code: Vec<u8>,
2160 storage_deposit_limit: BalanceOf<T>,
2161 ) -> CodeUploadResult<BalanceOf<T>> {
2162 let origin = T::UploadOrigin::ensure_origin(origin)?;
2163
2164 let bytecode_type = if code.starts_with(&polkavm_common::program::BLOB_MAGIC) {
2165 BytecodeType::Pvm
2166 } else {
2167 if !T::AllowEVMBytecode::get() {
2168 return Err(<Error<T>>::CodeRejected.into())
2169 }
2170 BytecodeType::Evm
2171 };
2172
2173 let mut meter = TransactionMeter::new(TransactionLimits::WeightAndDeposit {
2174 weight_limit: Default::default(),
2175 deposit_limit: storage_deposit_limit,
2176 })?;
2177
2178 let module = Self::try_upload_code(
2179 origin,
2180 code,
2181 bytecode_type,
2182 &mut meter,
2183 &ExecConfig::new_substrate_tx(),
2184 )?;
2185 Ok(CodeUploadReturnValue {
2186 code_hash: *module.code_hash(),
2187 deposit: meter.deposit_consumed().charge_or_zero(),
2188 })
2189 }
2190
2191 pub fn get_storage(address: H160, key: [u8; 32]) -> GetStorageResult {
2193 let contract_info =
2194 AccountInfo::<T>::load_contract(&address).ok_or(ContractAccessError::DoesntExist)?;
2195
2196 let maybe_value = contract_info.read(&Key::from_fixed(key));
2197 Ok(maybe_value)
2198 }
2199
2200 pub fn get_immutables(address: H160) -> Option<ImmutableData> {
2204 let immutable_data = <ImmutableDataOf<T>>::get(address);
2205 immutable_data
2206 }
2207
2208 pub fn set_immutables(address: H160, data: ImmutableData) -> Result<(), ContractAccessError> {
2216 AccountInfo::<T>::load_contract(&address).ok_or(ContractAccessError::DoesntExist)?;
2217 <ImmutableDataOf<T>>::insert(address, data);
2218 Ok(())
2219 }
2220
2221 pub fn get_storage_var_key(address: H160, key: Vec<u8>) -> GetStorageResult {
2223 let contract_info =
2224 AccountInfo::<T>::load_contract(&address).ok_or(ContractAccessError::DoesntExist)?;
2225
2226 let maybe_value = contract_info.read(
2227 &Key::try_from_var(key)
2228 .map_err(|_| ContractAccessError::KeyDecodingFailed)?
2229 .into(),
2230 );
2231 Ok(maybe_value)
2232 }
2233
2234 pub fn convert_native_to_evm(value: impl Into<BalanceWithDust<BalanceOf<T>>>) -> U256 {
2236 let (value, dust) = value.into().deconstruct();
2237 value
2238 .into()
2239 .saturating_mul(T::NativeToEthRatio::get().into())
2240 .saturating_add(dust.into())
2241 }
2242
2243 pub fn set_storage(address: H160, key: [u8; 32], value: Option<Vec<u8>>) -> SetStorageResult {
2253 let contract_info =
2254 AccountInfo::<T>::load_contract(&address).ok_or(ContractAccessError::DoesntExist)?;
2255
2256 contract_info
2257 .write(&Key::from_fixed(key), value, None, false)
2258 .map_err(ContractAccessError::StorageWriteFailed)
2259 }
2260
2261 pub fn set_storage_var_key(
2272 address: H160,
2273 key: Vec<u8>,
2274 value: Option<Vec<u8>>,
2275 ) -> SetStorageResult {
2276 let contract_info =
2277 AccountInfo::<T>::load_contract(&address).ok_or(ContractAccessError::DoesntExist)?;
2278
2279 contract_info
2280 .write(
2281 &Key::try_from_var(key)
2282 .map_err(|_| ContractAccessError::KeyDecodingFailed)?
2283 .into(),
2284 value,
2285 None,
2286 false,
2287 )
2288 .map_err(ContractAccessError::StorageWriteFailed)
2289 }
2290
2291 pub fn account_id() -> T::AccountId {
2293 use frame_support::PalletId;
2294 use sp_runtime::traits::AccountIdConversion;
2295 PalletId(*b"py/reviv").into_account_truncating()
2296 }
2297
2298 pub fn block_author() -> H160 {
2300 use frame_support::traits::FindAuthor;
2301
2302 let digest = <frame_system::Pallet<T>>::digest();
2303 let pre_runtime_digests = digest.logs.iter().filter_map(|d| d.as_pre_runtime());
2304
2305 T::FindAuthor::find_author(pre_runtime_digests)
2306 .map(|account_id| T::AddressMapper::to_address(&account_id))
2307 .unwrap_or_default()
2308 }
2309
2310 pub fn code(address: &H160) -> Vec<u8> {
2314 use precompiles::{All, Precompiles};
2315 if let Some(code) = <All<T>>::code(address.as_fixed_bytes()) {
2316 return code.into()
2317 }
2318 AccountInfo::<T>::load_contract(&address)
2319 .and_then(|contract| <PristineCode<T>>::get(contract.code_hash))
2320 .map(|code| code.into())
2321 .unwrap_or_default()
2322 }
2323
2324 pub fn try_upload_code(
2326 origin: T::AccountId,
2327 code: Vec<u8>,
2328 code_type: BytecodeType,
2329 meter: &mut TransactionMeter<T>,
2330 exec_config: &ExecConfig<T>,
2331 ) -> Result<ContractBlob<T>, DispatchError> {
2332 let mut module = match code_type {
2333 BytecodeType::Pvm => ContractBlob::from_pvm_code(code, origin)?,
2334 BytecodeType::Evm => ContractBlob::from_evm_runtime_code(code, origin)?,
2335 };
2336 module.store_code(exec_config, meter)?;
2337 Ok(module)
2338 }
2339
2340 fn run_guarded<R, F: FnOnce() -> Result<R, ExecError>>(f: F) -> Result<R, ExecError> {
2342 executing_contract::using_once(&mut false, || {
2343 executing_contract::with(|f| {
2344 if *f {
2346 return Err(())
2347 }
2348 *f = true;
2350 Ok(())
2351 })
2352 .expect("Returns `Ok` if called within `using_once`. It is syntactically obvious that this is the case; qed")
2353 .map_err(|_| <Error<T>>::ReenteredPallet.into())
2354 .map(|_| f())
2355 .and_then(|r| r)
2356 })
2357 }
2358
2359 fn charge_deposit(
2364 hold_reason: Option<HoldReason>,
2365 from: &T::AccountId,
2366 to: &T::AccountId,
2367 amount: BalanceOf<T>,
2368 exec_config: &ExecConfig<T>,
2369 ) -> DispatchResult {
2370 use frame_support::traits::tokens::{Fortitude, Precision, Preservation};
2371
2372 if amount.is_zero() {
2373 return Ok(());
2374 }
2375
2376 match (exec_config.collect_deposit_from_hold.is_some(), hold_reason) {
2377 (true, hold_reason) => {
2378 T::FeeInfo::withdraw_txfee(amount)
2379 .ok_or(())
2380 .and_then(|credit| T::Currency::resolve(to, credit).map_err(|_| ()))
2381 .and_then(|_| {
2382 if let Some(hold_reason) = hold_reason {
2383 T::Currency::hold(&hold_reason.into(), to, amount).map_err(|_| ())?;
2384 }
2385 Ok(())
2386 })
2387 .map_err(|_| Error::<T>::StorageDepositNotEnoughFunds)?;
2388 },
2389 (false, Some(hold_reason)) => {
2390 T::Currency::transfer_and_hold(
2391 &hold_reason.into(),
2392 from,
2393 to,
2394 amount,
2395 Precision::Exact,
2396 Preservation::Preserve,
2397 Fortitude::Polite,
2398 )
2399 .map_err(|_| Error::<T>::StorageDepositNotEnoughFunds)?;
2400 },
2401 (false, None) => {
2402 T::Currency::transfer(from, to, amount, Preservation::Preserve)
2403 .map_err(|_| Error::<T>::StorageDepositNotEnoughFunds)?;
2404 },
2405 }
2406 Ok(())
2407 }
2408
2409 fn refund_deposit(
2414 hold_reason: HoldReason,
2415 from: &T::AccountId,
2416 to: &T::AccountId,
2417 amount: BalanceOf<T>,
2418 exec_config: Option<&ExecConfig<T>>,
2419 ) -> Result<(), DispatchError> {
2420 use frame_support::traits::{
2421 fungible::InspectHold,
2422 tokens::{Fortitude, Precision, Preservation, Restriction},
2423 };
2424
2425 if amount.is_zero() {
2426 return Ok(());
2427 }
2428
2429 let hold_reason = hold_reason.into();
2430 let result = if exec_config.map(|c| c.collect_deposit_from_hold.is_some()).unwrap_or(false)
2431 {
2432 T::Currency::release(&hold_reason, from, amount, Precision::Exact)
2433 .and_then(|amount| {
2434 T::Currency::withdraw(
2435 from,
2436 amount,
2437 Precision::Exact,
2438 Preservation::Preserve,
2439 Fortitude::Polite,
2440 )
2441 })
2442 .map(T::FeeInfo::deposit_txfee)
2443 } else {
2444 T::Currency::transfer_on_hold(
2445 &hold_reason,
2446 from,
2447 to,
2448 amount,
2449 Precision::Exact,
2450 Restriction::Free,
2451 Fortitude::Polite,
2452 )
2453 .map(|_| ())
2454 };
2455
2456 result.map_err(|_| {
2457 let available = T::Currency::balance_on_hold(&hold_reason, from);
2458 if available < amount {
2459 log::error!(
2462 target: LOG_TARGET,
2463 "Failed to refund storage deposit {:?} from contract {:?} to origin {:?}. Not enough deposit: {:?}. This is a bug.",
2464 amount, from, to, available,
2465 );
2466 Error::<T>::StorageRefundNotEnoughFunds.into()
2467 } else {
2468 log::warn!(
2473 target: LOG_TARGET,
2474 "Failed to refund storage deposit {:?} from contract {:?} to origin {:?}. First remove locks (staking, governance) from the contracts account.",
2475 amount, from, to,
2476 );
2477 Error::<T>::StorageRefundLocked.into()
2478 }
2479 })
2480 }
2481
2482 fn has_dust(value: U256) -> bool {
2484 value % U256::from(<T>::NativeToEthRatio::get()) != U256::zero()
2485 }
2486
2487 fn has_balance(value: U256) -> bool {
2489 value >= U256::from(<T>::NativeToEthRatio::get())
2490 }
2491
2492 fn min_balance() -> BalanceOf<T> {
2494 <T::Currency as Inspect<AccountIdOf<T>>>::minimum_balance()
2495 }
2496
2497 fn deposit_event(event: Event<T>) {
2502 <frame_system::Pallet<T>>::deposit_event(<T as Config>::RuntimeEvent::from(event))
2503 }
2504
2505 fn ensure_eth_signed(origin: OriginFor<T>) -> Result<AccountIdOf<T>, DispatchError> {
2507 match <T as Config>::RuntimeOrigin::from(origin).into() {
2508 Ok(Origin::EthTransaction(signer)) => Ok(signer),
2509 _ => Err(BadOrigin.into()),
2510 }
2511 }
2512
2513 fn ensure_non_contract_if_signed(origin: &OriginFor<T>) -> DispatchResult {
2517 if DebugSettings::bypass_eip_3607::<T>() {
2518 return Ok(())
2519 }
2520 let Some(address) = origin
2521 .as_system_ref()
2522 .and_then(|o| o.as_signed())
2523 .map(<T::AddressMapper as AddressMapper<T>>::to_address)
2524 else {
2525 return Ok(())
2526 };
2527 if exec::is_precompile::<T, ContractBlob<T>>(&address) ||
2528 <AccountInfo<T>>::is_contract(&address)
2529 {
2530 log::debug!(
2531 target: crate::LOG_TARGET,
2532 "EIP-3607: reject tx as pre-compile or account exist at {address:?}",
2533 );
2534 Err(DispatchError::BadOrigin)
2535 } else {
2536 Ok(())
2537 }
2538 }
2539}
2540
2541pub const RUNTIME_PALLETS_ADDR: H160 =
2546 H160(hex_literal::hex!("6d6f646c70792f70616464720000000000000000"));
2547
2548environmental!(executing_contract: bool);
2550
2551sp_api::decl_runtime_apis! {
2552 #[api_version(1)]
2554 pub trait ReviveApi<AccountId, Balance, Nonce, BlockNumber, Moment> where
2555 AccountId: Codec,
2556 Balance: Codec,
2557 Nonce: Codec,
2558 BlockNumber: Codec,
2559 Moment: Codec,
2560 {
2561 fn eth_block() -> EthBlock;
2565
2566 fn eth_block_hash(number: U256) -> Option<H256>;
2568
2569 fn eth_receipt_data() -> Vec<ReceiptGasInfo>;
2575
2576 fn block_gas_limit() -> U256;
2578
2579 fn balance(address: H160) -> U256;
2581
2582 fn gas_price() -> U256;
2584
2585 fn nonce(address: H160) -> Nonce;
2587
2588 fn call(
2592 origin: AccountId,
2593 dest: H160,
2594 value: Balance,
2595 gas_limit: Option<Weight>,
2596 storage_deposit_limit: Option<Balance>,
2597 input_data: Vec<u8>,
2598 ) -> ContractResult<ExecReturnValue, Balance>;
2599
2600 fn instantiate(
2604 origin: AccountId,
2605 value: Balance,
2606 gas_limit: Option<Weight>,
2607 storage_deposit_limit: Option<Balance>,
2608 code: Code,
2609 data: Vec<u8>,
2610 salt: Option<[u8; 32]>,
2611 ) -> ContractResult<InstantiateReturnValue, Balance>;
2612
2613
2614 fn eth_transact(tx: GenericTransaction) -> Result<EthTransactInfo<Balance>, EthTransactError>;
2619
2620 fn eth_transact_with_config(
2624 tx: GenericTransaction,
2625 config: DryRunConfig<Moment>,
2626 ) -> Result<EthTransactInfo<Balance>, EthTransactError>;
2627
2628 fn upload_code(
2632 origin: AccountId,
2633 code: Vec<u8>,
2634 storage_deposit_limit: Option<Balance>,
2635 ) -> CodeUploadResult<Balance>;
2636
2637 fn get_storage(
2643 address: H160,
2644 key: [u8; 32],
2645 ) -> GetStorageResult;
2646
2647 fn get_storage_var_key(
2653 address: H160,
2654 key: Vec<u8>,
2655 ) -> GetStorageResult;
2656
2657 fn trace_block(
2664 block: Block,
2665 config: TracerType
2666 ) -> Vec<(u32, Trace)>;
2667
2668 fn trace_tx(
2675 block: Block,
2676 tx_index: u32,
2677 config: TracerType
2678 ) -> Option<Trace>;
2679
2680 fn trace_call(tx: GenericTransaction, config: TracerType) -> Result<Trace, EthTransactError>;
2684
2685 fn block_author() -> H160;
2687
2688 fn address(account_id: AccountId) -> H160;
2690
2691 fn account_id(address: H160) -> AccountId;
2693
2694 fn runtime_pallets_address() -> H160;
2696
2697 fn code(address: H160) -> Vec<u8>;
2699
2700 fn new_balance_with_dust(balance: U256) -> Result<(Balance, u32), BalanceConversionError>;
2702 }
2703}
2704
2705#[macro_export]
2719macro_rules! impl_runtime_apis_plus_revive_traits {
2720 ($Runtime: ty, $Revive: ident, $Executive: ty, $EthExtra: ty, $($rest:tt)*) => {
2721
2722 type __ReviveMacroMoment = <<$Runtime as $crate::Config>::Time as $crate::Time>::Moment;
2723
2724 impl $crate::evm::runtime::SetWeightLimit for RuntimeCall {
2725 fn set_weight_limit(&mut self, new_weight_limit: Weight) -> Weight {
2726 use $crate::pallet::Call as ReviveCall;
2727 match self {
2728 Self::$Revive(
2729 ReviveCall::eth_call{ weight_limit, .. } |
2730 ReviveCall::eth_instantiate_with_code{ weight_limit, .. }
2731 ) => {
2732 let old = *weight_limit;
2733 *weight_limit = new_weight_limit;
2734 old
2735 },
2736 _ => Weight::default(),
2737 }
2738 }
2739 }
2740
2741 impl_runtime_apis! {
2742 $($rest)*
2743
2744
2745 impl pallet_revive::ReviveApi<Block, AccountId, Balance, Nonce, BlockNumber, __ReviveMacroMoment> for $Runtime
2746 {
2747 fn eth_block() -> $crate::EthBlock {
2748 $crate::Pallet::<Self>::eth_block()
2749 }
2750
2751 fn eth_block_hash(number: $crate::U256) -> Option<$crate::H256> {
2752 $crate::Pallet::<Self>::eth_block_hash_from_number(number)
2753 }
2754
2755 fn eth_receipt_data() -> Vec<$crate::ReceiptGasInfo> {
2756 $crate::Pallet::<Self>::eth_receipt_data()
2757 }
2758
2759 fn balance(address: $crate::H160) -> $crate::U256 {
2760 $crate::Pallet::<Self>::evm_balance(&address)
2761 }
2762
2763 fn block_author() -> $crate::H160 {
2764 $crate::Pallet::<Self>::block_author()
2765 }
2766
2767 fn block_gas_limit() -> $crate::U256 {
2768 $crate::Pallet::<Self>::evm_block_gas_limit()
2769 }
2770
2771 fn gas_price() -> $crate::U256 {
2772 $crate::Pallet::<Self>::evm_base_fee()
2773 }
2774
2775 fn nonce(address: $crate::H160) -> Nonce {
2776 use $crate::AddressMapper;
2777 let account = <Self as $crate::Config>::AddressMapper::to_account_id(&address);
2778 $crate::frame_system::Pallet::<Self>::account_nonce(account)
2779 }
2780
2781 fn address(account_id: AccountId) -> $crate::H160 {
2782 use $crate::AddressMapper;
2783 <Self as $crate::Config>::AddressMapper::to_address(&account_id)
2784 }
2785
2786 fn eth_transact(
2787 tx: $crate::evm::GenericTransaction,
2788 ) -> Result<$crate::EthTransactInfo<Balance>, $crate::EthTransactError> {
2789 use $crate::{
2790 codec::Encode, evm::runtime::EthExtra, frame_support::traits::Get,
2791 sp_runtime::traits::TransactionExtension,
2792 sp_runtime::traits::Block as BlockT
2793 };
2794 $crate::Pallet::<Self>::dry_run_eth_transact(tx, Default::default())
2795 }
2796
2797 fn eth_transact_with_config(
2798 tx: $crate::evm::GenericTransaction,
2799 config: $crate::DryRunConfig<__ReviveMacroMoment>,
2800 ) -> Result<$crate::EthTransactInfo<Balance>, $crate::EthTransactError> {
2801 use $crate::{
2802 codec::Encode, evm::runtime::EthExtra, frame_support::traits::Get,
2803 sp_runtime::traits::TransactionExtension,
2804 sp_runtime::traits::Block as BlockT
2805 };
2806 $crate::Pallet::<Self>::dry_run_eth_transact(tx, config)
2807 }
2808
2809 fn call(
2810 origin: AccountId,
2811 dest: $crate::H160,
2812 value: Balance,
2813 weight_limit: Option<$crate::Weight>,
2814 storage_deposit_limit: Option<Balance>,
2815 input_data: Vec<u8>,
2816 ) -> $crate::ContractResult<$crate::ExecReturnValue, Balance> {
2817 use $crate::frame_support::traits::Get;
2818 let blockweights: $crate::BlockWeights =
2819 <Self as $crate::frame_system::Config>::BlockWeights::get();
2820
2821 $crate::Pallet::<Self>::prepare_dry_run(&origin);
2822 $crate::Pallet::<Self>::bare_call(
2823 <Self as $crate::frame_system::Config>::RuntimeOrigin::signed(origin),
2824 dest,
2825 $crate::Pallet::<Self>::convert_native_to_evm(value),
2826 $crate::TransactionLimits::WeightAndDeposit {
2827 weight_limit: weight_limit.unwrap_or(blockweights.max_block),
2828 deposit_limit: storage_deposit_limit.unwrap_or(u128::MAX),
2829 },
2830 input_data,
2831 $crate::ExecConfig::new_substrate_tx().with_dry_run(Default::default()),
2832 )
2833 }
2834
2835 fn instantiate(
2836 origin: AccountId,
2837 value: Balance,
2838 weight_limit: Option<$crate::Weight>,
2839 storage_deposit_limit: Option<Balance>,
2840 code: $crate::Code,
2841 data: Vec<u8>,
2842 salt: Option<[u8; 32]>,
2843 ) -> $crate::ContractResult<$crate::InstantiateReturnValue, Balance> {
2844 use $crate::frame_support::traits::Get;
2845 let blockweights: $crate::BlockWeights =
2846 <Self as $crate::frame_system::Config>::BlockWeights::get();
2847
2848 $crate::Pallet::<Self>::prepare_dry_run(&origin);
2849 $crate::Pallet::<Self>::bare_instantiate(
2850 <Self as $crate::frame_system::Config>::RuntimeOrigin::signed(origin),
2851 $crate::Pallet::<Self>::convert_native_to_evm(value),
2852 $crate::TransactionLimits::WeightAndDeposit {
2853 weight_limit: weight_limit.unwrap_or(blockweights.max_block),
2854 deposit_limit: storage_deposit_limit.unwrap_or(u128::MAX),
2855 },
2856 code,
2857 data,
2858 salt,
2859 $crate::ExecConfig::new_substrate_tx().with_dry_run(Default::default()),
2860 )
2861 }
2862
2863 fn upload_code(
2864 origin: AccountId,
2865 code: Vec<u8>,
2866 storage_deposit_limit: Option<Balance>,
2867 ) -> $crate::CodeUploadResult<Balance> {
2868 let origin =
2869 <Self as $crate::frame_system::Config>::RuntimeOrigin::signed(origin);
2870 $crate::Pallet::<Self>::bare_upload_code(
2871 origin,
2872 code,
2873 storage_deposit_limit.unwrap_or(u128::MAX),
2874 )
2875 }
2876
2877 fn get_storage_var_key(
2878 address: $crate::H160,
2879 key: Vec<u8>,
2880 ) -> $crate::GetStorageResult {
2881 $crate::Pallet::<Self>::get_storage_var_key(address, key)
2882 }
2883
2884 fn get_storage(address: $crate::H160, key: [u8; 32]) -> $crate::GetStorageResult {
2885 $crate::Pallet::<Self>::get_storage(address, key)
2886 }
2887
2888 fn trace_block(
2889 block: Block,
2890 tracer_type: $crate::evm::TracerType,
2891 ) -> Vec<(u32, $crate::evm::Trace)> {
2892 use $crate::{sp_runtime::traits::Block, tracing::trace};
2893 let mut traces = vec![];
2894 let (header, extrinsics) = block.deconstruct();
2895 <$Executive>::initialize_block(&header);
2896 for (index, ext) in extrinsics.into_iter().enumerate() {
2897 let mut tracer = $crate::Pallet::<Self>::evm_tracer(tracer_type.clone());
2898 let t = tracer.as_tracing();
2899 let _ = trace(t, || <$Executive>::apply_extrinsic(ext));
2900
2901 if let Some(tx_trace) = tracer.collect_trace() {
2902 traces.push((index as u32, tx_trace));
2903 }
2904 }
2905
2906 traces
2907 }
2908
2909 fn trace_tx(
2910 block: Block,
2911 tx_index: u32,
2912 tracer_type: $crate::evm::TracerType,
2913 ) -> Option<$crate::evm::Trace> {
2914 use $crate::{sp_runtime::traits::Block, tracing::trace};
2915
2916 let mut tracer = $crate::Pallet::<Self>::evm_tracer(tracer_type);
2917 let (header, extrinsics) = block.deconstruct();
2918
2919 <$Executive>::initialize_block(&header);
2920 for (index, ext) in extrinsics.into_iter().enumerate() {
2921 if index as u32 == tx_index {
2922 let t = tracer.as_tracing();
2923 let _ = trace(t, || <$Executive>::apply_extrinsic(ext));
2924 break;
2925 } else {
2926 let _ = <$Executive>::apply_extrinsic(ext);
2927 }
2928 }
2929
2930 tracer.collect_trace()
2931 }
2932
2933 fn trace_call(
2934 tx: $crate::evm::GenericTransaction,
2935 tracer_type: $crate::evm::TracerType,
2936 ) -> Result<$crate::evm::Trace, $crate::EthTransactError> {
2937 use $crate::tracing::trace;
2938 let mut tracer = $crate::Pallet::<Self>::evm_tracer(tracer_type.clone());
2939 let t = tracer.as_tracing();
2940
2941 t.watch_address(&tx.from.unwrap_or_default());
2942 t.watch_address(&$crate::Pallet::<Self>::block_author());
2943 let result = trace(t, || Self::eth_transact(tx));
2944
2945 if let Some(trace) = tracer.collect_trace() {
2946 Ok(trace)
2947 } else if let Err(err) = result {
2948 Err(err)
2949 } else {
2950 Ok($crate::Pallet::<Self>::evm_tracer(tracer_type).empty_trace())
2951 }
2952 }
2953
2954 fn runtime_pallets_address() -> $crate::H160 {
2955 $crate::RUNTIME_PALLETS_ADDR
2956 }
2957
2958 fn code(address: $crate::H160) -> Vec<u8> {
2959 $crate::Pallet::<Self>::code(&address)
2960 }
2961
2962 fn account_id(address: $crate::H160) -> AccountId {
2963 use $crate::AddressMapper;
2964 <Self as $crate::Config>::AddressMapper::to_account_id(&address)
2965 }
2966
2967 fn new_balance_with_dust(balance: $crate::U256) -> Result<(Balance, u32), $crate::BalanceConversionError> {
2968 $crate::Pallet::<Self>::new_balance_with_dust(balance)
2969 }
2970 }
2971 }
2972 };
2973}