Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
730 changes: 385 additions & 345 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ alloy-sol-types = "1.2.1"

alloy-chains = "0.2"
alloy-rlp = "0.3"
alloy-trie = "0.9"
alloy-trie = "0.9.1"

## op-alloy
op-alloy-consensus = "0.17.2"
Expand Down
2 changes: 1 addition & 1 deletion crates/anvil-polkadot/src/substrate_node/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ fn gen_rpc_module(
let chain =
polkadot_sdk::sc_rpc::chain::new_full(client.clone(), task_executor.clone()).into_rpc();
let (state, child_state) =
polkadot_sdk::sc_rpc::state::new_full(client.clone(), task_executor.clone());
polkadot_sdk::sc_rpc::state::new_full(client.clone(), task_executor.clone(), None);
let state = state.into_rpc();
let child_state = child_state.into_rpc();

Expand Down
29 changes: 22 additions & 7 deletions crates/anvil-polkadot/substrate-runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,26 @@ use frame_support::weights::{
constants::{BlockExecutionWeight, ExtrinsicBaseWeight, WEIGHT_REF_TIME_PER_SECOND},
};
use frame_system::limits::BlockWeights;
use pallet_revive::{AccountId32Mapper, evm::runtime::EthExtra};
use pallet_transaction_payment::{FeeDetails, RuntimeDispatchInfo};
use pallet_revive::{
AccountId32Mapper,
evm::{
fees::{BlockRatioFee, Info as FeeInfo},
runtime::EthExtra,
},
};
use pallet_transaction_payment::{ConstFeeMultiplier, FeeDetails, Multiplier, RuntimeDispatchInfo};
use polkadot_sdk::{
parachains_common::{AccountId, BlockNumber, Hash as CommonHash, Header, Nonce, Signature},
polkadot_sdk_frame::{
deps::sp_genesis_builder,
runtime::{apis, prelude::*},
},
sp_runtime::traits::Block as BlockT,
*,
};

pub use polkadot_sdk::parachains_common::Balance;
use sp_weights::{ConstantMultiplier, IdentityFee};
use sp_weights::ConstantMultiplier;

pub mod currency {
use super::Balance;
Expand Down Expand Up @@ -140,6 +147,8 @@ type TxExtension = (
// Ensures that the sender has enough funds to pay for the transaction
// and deducts the fee from the sender's account.
pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
// Needs to be done after all extensions that rely on a signed origin.
pallet_revive::evm::tx_extension::SetOrigin<Runtime>,
// Reclaim the unused weight from the block using post dispatch information.
// It must be last in the pipeline in order to catch the refund in previous transaction
// extensions
Expand All @@ -164,6 +173,7 @@ impl EthExtra for EthExtraImpl {
frame_system::CheckNonce::<Runtime>::from(nonce),
frame_system::CheckWeight::<Runtime>::new(),
pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(tip),
pallet_revive::evm::tx_extension::SetOrigin::<Runtime>::new_from_eth_transaction(),
frame_system::WeightReclaim::<Runtime>::new(),
)
}
Expand Down Expand Up @@ -289,14 +299,16 @@ impl pallet_timestamp::Config for Runtime {}

parameter_types! {
pub const TransactionByteFee: Balance = 10 * MILLICENTS;
pub FeeMultiplier: Multiplier = Multiplier::one();
}

// Implements the types required for the transaction payment pallet.
#[derive_impl(pallet_transaction_payment::config_preludes::TestDefaultConfig)]
impl pallet_transaction_payment::Config for Runtime {
type OnChargeTransaction = pallet_transaction_payment::FungibleAdapter<Balances, ()>;
type WeightToFee = IdentityFee<Balance>;
type WeightToFee = BlockRatioFee<1, 1, Self>;
type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
type FeeMultiplierUpdate = ConstFeeMultiplier<FeeMultiplier>;
}

parameter_types! {
Expand All @@ -310,14 +322,17 @@ impl pallet_revive::Config for Runtime {
type ChainId = ChainId;
type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent;
type Currency = Balances;
type Balance = Balance;
type NativeToEthRatio = ConstU32<1_000_000>;
type UploadOrigin = EnsureSigned<Self::AccountId>;
type InstantiateOrigin = EnsureSigned<Self::AccountId>;
type Time = Timestamp;
type FeeInfo = FeeInfo<Address, Signature, EthExtraImpl>;
}

pallet_revive::impl_runtime_apis_plus_revive!(
pallet_revive::impl_runtime_apis_plus_revive_traits!(
Runtime,
Revive,
Executive,
EthExtraImpl,

Expand All @@ -326,7 +341,7 @@ pallet_revive::impl_runtime_apis_plus_revive!(
VERSION
}

fn execute_block(block: Block) {
fn execute_block(block: <Block as BlockT>::LazyBlock) {
Executive::execute_block(block)
}

Expand Down Expand Up @@ -363,7 +378,7 @@ pallet_revive::impl_runtime_apis_plus_revive!(
}

fn check_inherents(
block: Block,
block: <Block as BlockT>::LazyBlock,
data: InherentData,
) -> CheckInherentsResult {
data.check_extrinsics(&block)
Expand Down
9 changes: 7 additions & 2 deletions crates/anvil-polkadot/tests/it/snapshot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use polkadot_sdk::pallet_revive::{
self,
evm::{Account, Block},
};
use std::collections::HashSet;
use subxt::utils::H160;

async fn assert_block_number_is_best_and_finalized(node: &mut TestNode, n: u64) {
Expand Down Expand Up @@ -251,13 +252,17 @@ async fn test_balances_and_txs_index_after_evm_revert() {
unwrap_response::<()>(node.eth_rpc(EthRequest::Mine(None, None)).await.unwrap()).unwrap();
assert_block_number_is_best_and_finalized(&mut node, 6).await;

let mut tx_indices: HashSet<_> =
[pallet_revive::U256::one(), pallet_revive::U256::from(2)].into_iter().collect();

let receipt_info = node.get_transaction_receipt(tx_hash1).await;
assert_eq!(receipt_info.block_number, pallet_revive::U256::from(6));
assert_eq!(receipt_info.transaction_index, pallet_revive::U256::one());
assert!(tx_indices.remove(&receipt_info.transaction_index));
assert_eq!(receipt_info.transaction_hash, tx_hash1);

let receipt_info = node.get_transaction_receipt(tx_hash2).await;
assert_eq!(receipt_info.block_number, pallet_revive::U256::from(6));
assert_eq!(receipt_info.transaction_index, pallet_revive::U256::from(2));
assert!(tx_indices.remove(&receipt_info.transaction_index));
assert_eq!(receipt_info.transaction_hash, tx_hash2);
assert_eq!(node.get_nonce(alith_addr).await, U256::ONE);
assert_eq!(node.get_nonce(baltathar_addr).await, U256::ONE);
Expand Down
1 change: 1 addition & 0 deletions crates/revive-env/src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ parameter_types! {
#[derive_impl(pallet_revive::config_preludes::TestDefaultConfig)]
impl pallet_revive::Config for Runtime {
type Time = Timestamp;
type Balance = Balance;
type Currency = Balances;
type DepositPerByte = DepositPerByte;
type DepositPerItem = DepositPerItem;
Expand Down
64 changes: 14 additions & 50 deletions crates/revive-strategy/src/cheatcodes/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ use polkadot_sdk::{
frame_support::traits::{Currency, fungible::Mutate},
pallet_balances,
pallet_revive::{
self, AccountInfo, AddressMapper, BalanceOf, BalanceWithDust, BumpNonce, Code, Config,
ContractInfo, DepositLimit, Pallet, evm::GasEncoder,
self, AccountInfo, AddressMapper, BalanceOf, BalanceWithDust, Code, Config, ContractInfo,
ExecConfig, Pallet,
},
polkadot_sdk_frame::prelude::OriginFor,
sp_core::{self, H160},
Expand Down Expand Up @@ -650,14 +650,6 @@ impl foundry_cheatcodes::CheatcodeInspectorStrategyExt for PvmCheatcodeInspector
let constructor_args = find_contract.constructor_args();
let contract = find_contract.contract();

let max_gas =
<<Runtime as Config>::EthGasEncoder as GasEncoder<BalanceOf<Runtime>>>::encode(
Default::default(),
Weight::MAX,
1u128 << 99,
);
let gas_limit = sp_core::U256::from(input.gas_limit()).min(max_gas);

let (res, _call_trace, prestate_trace) = execute_with_externalities(|externalities| {
externalities.execute_with(|| {
trace::<Runtime, _, _>(|| {
Expand All @@ -666,12 +658,6 @@ impl foundry_cheatcodes::CheatcodeInspectorStrategyExt for PvmCheatcodeInspector
));
let evm_value = sp_core::U256::from_little_endian(&input.value().as_le_bytes());

let (gas_limit, storage_deposit_limit) =
<<Runtime as Config>::EthGasEncoder as GasEncoder<BalanceOf<Runtime>>>::decode(
gas_limit,
)
.expect("gas limit is valid");
let storage_deposit_limit = DepositLimit::Balance(storage_deposit_limit);
let code = Code::Upload(contract.resolc_bytecode.as_bytes().unwrap().to_vec());
let data = constructor_args.to_vec();
let salt = match input.scheme() {
Expand All @@ -685,32 +671,27 @@ impl foundry_cheatcodes::CheatcodeInspectorStrategyExt for PvmCheatcodeInspector
),
_ => None,
};
let bump_nonce = BumpNonce::Yes;

Pallet::<Runtime>::bare_instantiate(
origin,
evm_value,
gas_limit,
storage_deposit_limit,
Weight::MAX,
// TODO: fixing.
BalanceOf::<Runtime>::max_value(),
code,
data,
salt,
bump_nonce,
ExecConfig::new_substrate_tx(),
)
})
})
});

let mut gas = Gas::new(input.gas_limit());
let gas_used =
<<Runtime as Config>::EthGasEncoder as GasEncoder<BalanceOf<Runtime>>>::encode(
gas_limit,
res.gas_required,
res.storage_deposit.charge_or_zero(),
);

let result = match &res.result {
Ok(result) => {
let _ = gas.record_cost(gas_used.as_u64());
let _ = gas.record_cost(res.gas_required.ref_time());

let outcome = if result.result.did_revert() {
CreateOutcome {
Expand Down Expand Up @@ -787,14 +768,6 @@ impl foundry_cheatcodes::CheatcodeInspectorStrategyExt for PvmCheatcodeInspector

tracing::info!("running call in PVM {:#?}", call);

let max_gas =
<<Runtime as Config>::EthGasEncoder as GasEncoder<BalanceOf<Runtime>>>::encode(
Default::default(),
Weight::MAX,
1u128 << 99,
);
let gas_limit = sp_core::U256::from(call.gas_limit).min(max_gas);

let (res, _call_trace, prestate_trace) = execute_with_externalities(|externalities| {
externalities.execute_with(|| {
trace::<Runtime, _, _>(|| {
Expand All @@ -804,36 +777,27 @@ impl foundry_cheatcodes::CheatcodeInspectorStrategyExt for PvmCheatcodeInspector
let evm_value =
sp_core::U256::from_little_endian(&call.call_value().as_le_bytes());

let (gas_limit, storage_deposit_limit) =
<<Runtime as Config>::EthGasEncoder as GasEncoder<BalanceOf<Runtime>>>::decode(
gas_limit,
)
.expect("gas limit is valid");
let storage_deposit_limit = DepositLimit::Balance(storage_deposit_limit);
let target = H160::from_slice(call.target_address.as_slice());

Pallet::<Runtime>::bare_call(
origin,
target,
evm_value,
gas_limit,
storage_deposit_limit,
Weight::MAX,
// TODO: fixing.
BalanceOf::<Runtime>::max_value(),
call.input.bytes(ecx).to_vec(),
ExecConfig::new_substrate_tx(),
)
})
})
});

let mut gas = Gas::new(call.gas_limit);
let gas_used =
<<Runtime as Config>::EthGasEncoder as GasEncoder<BalanceOf<Runtime>>>::encode(
gas_limit,
res.gas_required,
res.storage_deposit.charge_or_zero(),
);
let result = match res.result {
Ok(result) => {
let _ = gas.record_cost(gas_used.as_u64());
let _ = gas.record_cost(res.gas_required.ref_time());

let outcome = if result.did_revert() {
tracing::error!("Contract call reverted");
CallOutcome {
Expand Down
1 change: 0 additions & 1 deletion crates/revive-strategy/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ mod cheatcodes;
mod executor;
mod tracing;

pub use cheatcodes::PvmStartupMigration;
pub use tracing::trace;

/// Create Revive strategy for [ExecutorStrategy].
Expand Down
25 changes: 11 additions & 14 deletions crates/revive-strategy/src/tracing/mod.rs
Original file line number Diff line number Diff line change
@@ -1,27 +1,24 @@
use alloy_primitives::{Address, Bytes, U256 as RU256};
use foundry_cheatcodes::Ecx;
use polkadot_sdk::{
frame_support::weights::Weight,
pallet_revive::{
Config, Pallet, U256,
evm::{
CallTrace, CallTracer, PrestateTrace, PrestateTraceInfo, PrestateTracer,
PrestateTracerConfig,
},
tracing::trace as trace_revive,
use polkadot_sdk::pallet_revive::{
Config, Pallet, U256,
evm::{
CallTrace, PrestateTrace, PrestateTraceInfo, PrestateTracer, PrestateTracerConfig, Tracer,
TracerType,
},
tracing::trace as trace_revive,
};
use revm::{context::JournalTr, state::Bytecode};

// Traces the execution inside pallet_revive.
// This is a temporary solution to the fact that custom Tracer is not implementable for the time
// being.
pub fn trace<T: Config, R, F: FnOnce() -> R>(f: F) -> (R, Option<CallTrace<U256>>, PrestateTrace) {
let mut call_tracer = CallTracer::new(
Default::default(),
Pallet::<revive_env::Runtime>::evm_gas_from_weight as fn(Weight) -> U256,
);

let mut call_tracer =
match Pallet::<revive_env::Runtime>::evm_tracer(TracerType::CallTracer(None)) {
Tracer::CallTracer(tracer) => tracer,
_ => unreachable!("Expected CallTracer variant"),
};
let mut prestate_tracer: PrestateTracer<revive_env::Runtime> =
PrestateTracer::new(PrestateTracerConfig {
diff_mode: true,
Expand Down
Loading