From 8d3217cba9d9ae2dee525bf9b2a1ec64415bd3a9 Mon Sep 17 00:00:00 2001 From: Enrique Ortiz Date: Thu, 31 Aug 2023 13:26:30 -0700 Subject: [PATCH 01/10] feat: migrate non-cheatcode inspectors --- crates/anvil/src/eth/backend/mem/mod.rs | 7 ++-- crates/cli/src/utils/cmd.rs | 3 +- crates/evm/src/debug.rs | 6 ++-- crates/evm/src/executor/backend/mod.rs | 2 +- crates/evm/src/executor/builder.rs | 14 +++----- .../evm/src/executor/inspector/access_list.rs | 33 ++++++++--------- .../src/executor/inspector/cheatcodes/mod.rs | 2 +- crates/evm/src/executor/inspector/debugger.rs | 14 ++++---- crates/evm/src/executor/inspector/stack.rs | 32 +++++++++-------- crates/evm/src/executor/inspector/tracer.rs | 35 +++++++++---------- crates/evm/src/executor/inspector/utils.rs | 17 ++++----- crates/evm/src/executor/mod.rs | 4 +-- crates/evm/src/executor/opts.rs | 34 +++++++++--------- crates/forge/bin/cmd/coverage.rs | 6 ++-- crates/forge/bin/cmd/script/build.rs | 3 +- crates/forge/bin/cmd/script/cmd.rs | 18 ++++++---- crates/forge/bin/cmd/script/executor.rs | 15 ++++++-- crates/forge/bin/cmd/script/mod.rs | 6 ++-- crates/forge/bin/cmd/test/mod.rs | 9 +++-- crates/forge/src/multi_runner.rs | 5 +-- crates/forge/tests/it/config.rs | 3 +- crates/forge/tests/it/test_helpers.rs | 8 ++--- crates/ui/src/lib.rs | 8 ++--- 23 files changed, 151 insertions(+), 133 deletions(-) diff --git a/crates/anvil/src/eth/backend/mem/mod.rs b/crates/anvil/src/eth/backend/mem/mod.rs index 852092e27638..887cd5d573cf 100644 --- a/crates/anvil/src/eth/backend/mem/mod.rs +++ b/crates/anvil/src/eth/backend/mem/mod.rs @@ -78,6 +78,7 @@ use foundry_evm::{ }; use futures::channel::mpsc::{unbounded, UnboundedSender}; use hash_db::HashDB; +use itertools::Itertools; use parking_lot::{Mutex, RwLock}; use std::{ collections::HashMap, @@ -1144,9 +1145,9 @@ impl Backend { let mut tracer = AccessListTracer::new( AccessList(request.access_list.clone().unwrap_or_default()), - from, - to, - self.precompiles(), + h160_to_b160(from), + h160_to_b160(to), + self.precompiles().into_iter().map(h160_to_b160).collect(), ); let mut evm = revm::EVM::new(); diff --git a/crates/cli/src/utils/cmd.rs b/crates/cli/src/utils/cmd.rs index 4323ddb2c646..d24bba9974e8 100644 --- a/crates/cli/src/utils/cmd.rs +++ b/crates/cli/src/utils/cmd.rs @@ -19,6 +19,7 @@ use foundry_evm::{ identifier::{EtherscanIdentifier, SignaturesIdentifier}, CallTraceDecoder, CallTraceDecoderBuilder, TraceKind, Traces, }, + utils::b160_to_h160, }; use std::{collections::BTreeMap, fmt::Write, path::PathBuf, str::FromStr}; use tracing::trace; @@ -439,7 +440,7 @@ pub fn run_debugger( let calls: Vec = vec![result.debug]; let flattened = calls.last().expect("we should have collected debug info").flatten(0); let tui = Tui::new( - flattened, + flattened.into_iter().map(|f| (b160_to_h160(f.0), f.1, f.2)).collect(), 0, decoder.contracts, known_contracts.into_iter().map(|(id, artifact)| (id.name, artifact)).collect(), diff --git a/crates/evm/src/debug.rs b/crates/evm/src/debug.rs index 885830abb4da..ca777356d580 100644 --- a/crates/evm/src/debug.rs +++ b/crates/evm/src/debug.rs @@ -1,6 +1,8 @@ use crate::{abi::HEVM_ABI, CallKind}; -use ethers::types::{Address, U256}; -use revm::interpreter::{Memory, OpCode}; +use revm::{ + interpreter::{Memory, OpCode}, + primitives::{Address, U256}, +}; use serde::{Deserialize, Serialize}; use std::fmt::Display; diff --git a/crates/evm/src/executor/backend/mod.rs b/crates/evm/src/executor/backend/mod.rs index 708f74f6a7f9..932ce492afc4 100644 --- a/crates/evm/src/executor/backend/mod.rs +++ b/crates/evm/src/executor/backend/mod.rs @@ -69,7 +69,7 @@ const DEFAULT_PERSISTENT_ACCOUNTS: [Address; 3] = /// Slot corresponding to "failed" in bytes on the cheatcodes (HEVM) address. const GLOBAL_FAILURE_SLOT: &str = - "0x6661696c65640000000000000000000000000000000000000000000000000000"; + "6661696c65640000000000000000000000000000000000000000000000000000"; /// An extension trait that allows us to easily extend the `revm::Inspector` capabilities #[auto_impl::auto_impl(&mut, Box)] diff --git a/crates/evm/src/executor/builder.rs b/crates/evm/src/executor/builder.rs index 5eebfaba92e3..1b5dbbdc712d 100644 --- a/crates/evm/src/executor/builder.rs +++ b/crates/evm/src/executor/builder.rs @@ -1,10 +1,6 @@ use super::{inspector::InspectorStackBuilder, Executor}; -use crate::{ - executor::backend::Backend, - utils::{ru256_to_u256, u256_to_ru256}, -}; -use ethers::types::U256; -use revm::primitives::{Env, SpecId}; +use crate::{executor::backend::Backend}; +use revm::primitives::{Env, SpecId, U256}; /// The builder that allows to configure an evm [`Executor`] which a stack of optional /// [`revm::Inspector`]s, such as [`Cheatcodes`]. @@ -70,8 +66,8 @@ impl ExecutorBuilder { let Self { mut stack, gas_limit, spec_id } = self; env.cfg.spec_id = spec_id; stack.block = Some(env.block.clone()); - stack.gas_price = Some(ru256_to_u256(env.tx.gas_price)); - let gas_limit = gas_limit.unwrap_or(ru256_to_u256(env.block.gas_limit)); - Executor::new(db, env, stack.build(), u256_to_ru256(gas_limit)) + stack.gas_price = Some(env.tx.gas_price); + let gas_limit = gas_limit.unwrap_or(env.block.gas_limit); + Executor::new(db, env, stack.build(), gas_limit) } } diff --git a/crates/evm/src/executor/inspector/access_list.rs b/crates/evm/src/executor/inspector/access_list.rs index bd059b2e64d0..41fbc73681b3 100644 --- a/crates/evm/src/executor/inspector/access_list.rs +++ b/crates/evm/src/executor/inspector/access_list.rs @@ -1,23 +1,18 @@ -use ethers::{ - abi::{ethereum_types::BigEndianHash, Address}, - types::{ - transaction::eip2930::{AccessList, AccessListItem}, - H256, - }, -}; +use ethers::types::transaction::eip2930::{AccessList, AccessListItem}; use hashbrown::{HashMap, HashSet}; use revm::{ interpreter::{opcode, InstructionResult, Interpreter}, + primitives::{Address, B256}, Database, EVMData, Inspector, }; -use crate::utils::{b160_to_h160, ru256_to_u256}; +use crate::utils::{b160_to_h160, b256_to_h256, h160_to_b160, h256_to_b256}; /// An inspector that collects touched accounts and storage slots. #[derive(Default, Debug)] pub struct AccessListTracer { excluded: HashSet
, - access_list: HashMap>, + access_list: HashMap>, } impl AccessListTracer { @@ -32,7 +27,12 @@ impl AccessListTracer { access_list: access_list .0 .iter() - .map(|v| (v.address, v.storage_keys.iter().copied().collect())) + .map(|v| { + ( + h160_to_b160(v.address), + v.storage_keys.iter().copied().map(h256_to_b256).collect(), + ) + }) .collect(), } } @@ -42,8 +42,8 @@ impl AccessListTracer { self.access_list .iter() .map(|(address, slots)| AccessListItem { - address: *address, - storage_keys: slots.iter().copied().collect(), + address: b160_to_h160(*address), + storage_keys: slots.iter().copied().map(b256_to_h256).collect(), }) .collect::>(), ) @@ -61,10 +61,7 @@ impl Inspector for AccessListTracer { opcode::SLOAD | opcode::SSTORE => { if let Ok(slot) = interpreter.stack().peek(0) { let cur_contract = interpreter.contract.address; - self.access_list - .entry(b160_to_h160(cur_contract)) - .or_default() - .insert(H256::from_uint(&ru256_to_u256(slot))); + self.access_list.entry(cur_contract).or_default().insert(slot.into()); } } opcode::EXTCODECOPY | @@ -73,7 +70,7 @@ impl Inspector for AccessListTracer { opcode::BALANCE | opcode::SELFDESTRUCT => { if let Ok(slot) = interpreter.stack().peek(0) { - let addr: Address = H256::from_uint(&ru256_to_u256(slot)).into(); + let addr: Address = Address::from_slice(&slot.to_be_bytes::<32>()); if !self.excluded.contains(&addr) { self.access_list.entry(addr).or_default(); } @@ -81,7 +78,7 @@ impl Inspector for AccessListTracer { } opcode::DELEGATECALL | opcode::CALL | opcode::STATICCALL | opcode::CALLCODE => { if let Ok(slot) = interpreter.stack().peek(1) { - let addr: Address = H256::from_uint(&ru256_to_u256(slot)).into(); + let addr: Address = Address::from_slice(&slot.to_be_bytes::<32>()); if !self.excluded.contains(&addr) { self.access_list.entry(addr).or_default(); } diff --git a/crates/evm/src/executor/inspector/cheatcodes/mod.rs b/crates/evm/src/executor/inspector/cheatcodes/mod.rs index a2d1d5cbff69..86401825ac5d 100644 --- a/crates/evm/src/executor/inspector/cheatcodes/mod.rs +++ b/crates/evm/src/executor/inspector/cheatcodes/mod.rs @@ -261,7 +261,7 @@ impl Cheatcodes { return } - data.db.allow_cheatcode_access(h160_to_b160(created_address)); + data.db.allow_cheatcode_access(created_address); } /// Called when there was a revert. diff --git a/crates/evm/src/executor/inspector/debugger.rs b/crates/evm/src/executor/inspector/debugger.rs index 0650524a34ad..953c83fbc8bd 100644 --- a/crates/evm/src/executor/inspector/debugger.rs +++ b/crates/evm/src/executor/inspector/debugger.rs @@ -5,17 +5,15 @@ use crate::{ inspector::utils::{gas_used, get_create_address}, CHEATCODE_ADDRESS, }, - utils::{b160_to_h160, ru256_to_u256}, CallKind, }; -use ethers::types::Address; use foundry_utils::error::SolError; use revm::{ interpreter::{ opcode::{self, spec_opcode_gas}, CallInputs, CreateInputs, Gas, InstructionResult, Interpreter, Memory, }, - primitives::{Address as rAddress, Bytes}, + primitives::{Address, Bytes}, EVMData, Inspector, }; @@ -81,7 +79,7 @@ impl Inspector for Debugger { self.arena.arena[self.head].steps.push(DebugStep { pc, - stack: interpreter.stack().data().iter().copied().map(ru256_to_u256).collect(), + stack: interpreter.stack().data().clone(), memory: interpreter.memory.clone(), instruction: Instruction::OpCode(op), push_bytes, @@ -99,7 +97,7 @@ impl Inspector for Debugger { ) -> (InstructionResult, Gas, Bytes) { self.enter( data.journaled_state.depth() as usize, - b160_to_h160(call.context.code_address), + call.context.code_address, call.context.scheme.into(), ); if CHEATCODE_ADDRESS == call.contract { @@ -134,7 +132,7 @@ impl Inspector for Debugger { &mut self, data: &mut EVMData<'_, DB>, call: &mut CreateInputs, - ) -> (InstructionResult, Option, Gas, Bytes) { + ) -> (InstructionResult, Option
, Gas, Bytes) { // TODO: Does this increase gas cost? if let Err(err) = data.journaled_state.load_account(call.caller, data.db) { let gas = Gas::new(call.gas_limit); @@ -162,10 +160,10 @@ impl Inspector for Debugger { _: &mut EVMData<'_, DB>, _: &CreateInputs, status: InstructionResult, - address: Option, + address: Option
, gas: Gas, retdata: Bytes, - ) -> (InstructionResult, Option, Gas, Bytes) { + ) -> (InstructionResult, Option
, Gas, Bytes) { self.exit(); (status, address, gas, retdata) diff --git a/crates/evm/src/executor/inspector/stack.rs b/crates/evm/src/executor/inspector/stack.rs index 91a90856d830..e4bee0db02d6 100644 --- a/crates/evm/src/executor/inspector/stack.rs +++ b/crates/evm/src/executor/inspector/stack.rs @@ -6,17 +6,14 @@ use crate::{ debug::DebugArena, executor::{backend::DatabaseExt, inspector::CoverageCollector}, trace::CallTraceArena, - utils::ru256_to_u256, -}; -use ethers::{ - signers::LocalWallet, - types::{Address, Log, U256}, + utils::{h160_to_b160, ru256_to_u256}, }; +use ethers::{signers::LocalWallet, types::Log}; use revm::{ interpreter::{ return_revert, CallInputs, CreateInputs, Gas, InstructionResult, Interpreter, Memory, Stack, }, - primitives::{Address as rAddress, BlockEnv, Bytes, Env, B256}, + primitives::{Address, BlockEnv, Bytes, Env, B256, U256}, EVMData, Inspector, }; use std::{collections::BTreeMap, sync::Arc}; @@ -229,7 +226,7 @@ impl InspectorStack { #[inline] pub fn set_env(&mut self, env: &Env) { self.set_block(&env.block); - self.set_gas_price(ru256_to_u256(env.tx.gas_price)); + self.set_gas_price(env.tx.gas_price); } /// Sets the block for the relevant inspectors. @@ -244,7 +241,7 @@ impl InspectorStack { #[inline] pub fn set_gas_price(&mut self, gas_price: U256) { if let Some(cheatcodes) = &mut self.cheatcodes { - cheatcodes.gas_price = Some(gas_price); + cheatcodes.gas_price = Some(gas_price).map(ru256_to_u256); } } @@ -304,7 +301,14 @@ impl InspectorStack { labels: self .cheatcodes .as_ref() - .map(|cheatcodes| cheatcodes.labels.clone()) + .map(|cheatcodes| { + cheatcodes + .labels + .clone() + .into_iter() + .map(|l| (h160_to_b160(l.0), l.1)) + .collect() + }) .unwrap_or_default(), traces: self.tracer.map(|tracer| tracer.traces), debug: self.debugger.map(|debugger| debugger.arena), @@ -414,7 +418,7 @@ impl Inspector for InspectorStack { fn log( &mut self, evm_data: &mut EVMData<'_, DB>, - address: &rAddress, + address: &Address, topics: &[B256], data: &Bytes, ) { @@ -508,7 +512,7 @@ impl Inspector for InspectorStack { &mut self, data: &mut EVMData<'_, DB>, call: &mut CreateInputs, - ) -> (InstructionResult, Option, Gas, Bytes) { + ) -> (InstructionResult, Option
, Gas, Bytes) { call_inspectors!( [ &mut self.debugger, @@ -536,10 +540,10 @@ impl Inspector for InspectorStack { data: &mut EVMData<'_, DB>, call: &CreateInputs, status: InstructionResult, - address: Option, + address: Option
, remaining_gas: Gas, retdata: Bytes, - ) -> (InstructionResult, Option, Gas, Bytes) { + ) -> (InstructionResult, Option
, Gas, Bytes) { call_inspectors!( [ &mut self.debugger, @@ -568,7 +572,7 @@ impl Inspector for InspectorStack { (status, address, remaining_gas, retdata) } - fn selfdestruct(&mut self, contract: rAddress, target: rAddress) { + fn selfdestruct(&mut self, contract: Address, target: Address) { call_inspectors!( [ &mut self.debugger, diff --git a/crates/evm/src/executor/inspector/tracer.rs b/crates/evm/src/executor/inspector/tracer.rs index 864905ad9004..9d4ae1f2e507 100644 --- a/crates/evm/src/executor/inspector/tracer.rs +++ b/crates/evm/src/executor/inspector/tracer.rs @@ -8,16 +8,13 @@ use crate::{ utils::{b160_to_h160, b256_to_h256, ru256_to_u256}, CallKind, }; -use ethers::{ - abi::RawLog, - types::{Address, U256}, -}; +use ethers::abi::RawLog; use revm::{ interpreter::{ opcode, return_ok, CallInputs, CallScheme, CreateInputs, Gas, InstructionResult, Interpreter, }, - primitives::{Address as rAddress, Bytes, B256}, + primitives::{Address, Bytes, B256, U256}, Database, EVMData, Inspector, JournalEntry, }; @@ -49,12 +46,12 @@ impl Tracer { 0, CallTrace { depth, - address, + address: b160_to_h160(address), kind, data: RawOrDecodedCall::Raw(data.into()), - value, + value: ru256_to_u256(value), status: InstructionResult::Continue, - caller, + caller: b160_to_h160(caller), ..Default::default() }, )); @@ -77,7 +74,7 @@ impl Tracer { trace.output = RawOrDecodedReturnData::Raw(output.into()); if let Some(address) = address { - trace.address = address; + trace.address = b160_to_h160(address); } } @@ -164,7 +161,7 @@ impl Inspector for Tracer { } #[inline] - fn log(&mut self, _: &mut EVMData<'_, DB>, _: &rAddress, topics: &[B256], data: &Bytes) { + fn log(&mut self, _: &mut EVMData<'_, DB>, _: &Address, topics: &[B256], data: &Bytes) { let node = &mut self.traces.arena[*self.trace_stack.last().expect("no ongoing trace")]; let topics: Vec<_> = topics.iter().copied().map(b256_to_h256).collect(); node.ordering.push(LogCallOrder::Log(node.logs.len())); @@ -186,11 +183,11 @@ impl Inspector for Tracer { self.start_trace( data.journaled_state.depth() as usize, - b160_to_h160(to), + to, inputs.input.to_vec(), - ru256_to_u256(inputs.transfer.value), + inputs.transfer.value, inputs.context.scheme.into(), - b160_to_h160(from), + from, ); (InstructionResult::Continue, Gas::new(inputs.gas_limit), Bytes::new()) @@ -220,7 +217,7 @@ impl Inspector for Tracer { &mut self, data: &mut EVMData<'_, DB>, inputs: &mut CreateInputs, - ) -> (InstructionResult, Option, Gas, Bytes) { + ) -> (InstructionResult, Option
, Gas, Bytes) { // TODO: Does this increase gas cost? let _ = data.journaled_state.load_account(inputs.caller, data.db); let nonce = data.journaled_state.account(inputs.caller).info.nonce; @@ -228,9 +225,9 @@ impl Inspector for Tracer { data.journaled_state.depth() as usize, get_create_address(inputs, nonce), inputs.init_code.to_vec(), - ru256_to_u256(inputs.value), + inputs.value, inputs.scheme.into(), - b160_to_h160(inputs.caller), + inputs.caller, ); (InstructionResult::Continue, None, Gas::new(inputs.gas_limit), Bytes::new()) @@ -242,10 +239,10 @@ impl Inspector for Tracer { data: &mut EVMData<'_, DB>, _inputs: &CreateInputs, status: InstructionResult, - address: Option, + address: Option
, gas: Gas, retdata: Bytes, - ) -> (InstructionResult, Option, Gas, Bytes) { + ) -> (InstructionResult, Option
, Gas, Bytes) { let code = match address { Some(address) => data .journaled_state @@ -260,7 +257,7 @@ impl Inspector for Tracer { status, gas_used(data.env.cfg.spec_id, gas.spend(), gas.refunded() as u64), code, - address.map(b160_to_h160), + address, ); (status, address, gas, retdata) diff --git a/crates/evm/src/executor/inspector/utils.rs b/crates/evm/src/executor/inspector/utils.rs index 22fecc6b7b05..6cc9f71b111f 100644 --- a/crates/evm/src/executor/inspector/utils.rs +++ b/crates/evm/src/executor/inspector/utils.rs @@ -1,13 +1,11 @@ -use ethers::{ - types::Address, - utils::{get_contract_address, get_create2_address}, -}; +use bytes::Buf; + use revm::{ interpreter::CreateInputs, - primitives::{CreateScheme, SpecId}, + primitives::{Address, CreateScheme, SpecId}, }; -use crate::utils::{b160_to_h160, ru256_to_u256}; +use crate::utils::{ru256_to_u256}; /// Returns [InstructionResult::Continue] on an error, discarding the error. /// @@ -25,12 +23,15 @@ macro_rules! try_or_continue { /// Get the address of a contract creation pub fn get_create_address(call: &CreateInputs, nonce: u64) -> Address { match call.scheme { - CreateScheme::Create => get_contract_address(b160_to_h160(call.caller), nonce), + CreateScheme::Create => Address::create(&call.caller, nonce), CreateScheme::Create2 { salt } => { let salt = ru256_to_u256(salt); let mut salt_bytes = [0u8; 32]; salt.to_big_endian(&mut salt_bytes); - get_create2_address(b160_to_h160(call.caller), salt_bytes, call.init_code.clone()) + let init_code = + alloy_primitives::Bytes(call.init_code.clone().0).to_owned().0.copy_to_bytes(32); + let init_code_hash = alloy_primitives::keccak256(init_code); + Address::create2(&call.caller, salt_bytes, init_code_hash) } } } diff --git a/crates/evm/src/executor/mod.rs b/crates/evm/src/executor/mod.rs index 48b104a85246..405b5651cd40 100644 --- a/crates/evm/src/executor/mod.rs +++ b/crates/evm/src/executor/mod.rs @@ -6,7 +6,7 @@ use crate::{ debug::DebugArena, decode, trace::CallTraceArena, - utils::{eval_to_instruction_result, h160_to_b160, halt_to_instruction_result}, + utils::{eval_to_instruction_result, halt_to_instruction_result}, CALLER, }; pub use abi::{ @@ -801,7 +801,7 @@ fn convert_executed_result( gas_refunded, stipend, logs: logs.to_vec(), - labels: labels.into_iter().map(|label| (h160_to_b160(label.0), label.1)).collect(), + labels, traces, coverage, debug, diff --git a/crates/evm/src/executor/opts.rs b/crates/evm/src/executor/opts.rs index dfe978448b64..bf30cf0beb7f 100644 --- a/crates/evm/src/executor/opts.rs +++ b/crates/evm/src/executor/opts.rs @@ -1,15 +1,15 @@ use crate::{ executor::fork::CreateFork, - utils::{h160_to_b160, h256_to_b256, u256_to_ru256, RuntimeOrHandle}, + utils::{b160_to_h160, RuntimeOrHandle}, }; use ethers::{ providers::{Middleware, Provider}, - types::{Address, Block, Chain, TxHash, H256, U256}, + types::{Block, Chain, TxHash}, }; use eyre::WrapErr; use foundry_common::{self, ProviderBuilder, RpcUrl, ALCHEMY_FREE_TIER_CUPS}; use foundry_config::Config; -use revm::primitives::{BlockEnv, CfgEnv, SpecId, TxEnv, U256 as rU256}; +use revm::primitives::{Address, BlockEnv, CfgEnv, SpecId, TxEnv, B256, U256}; use serde::{Deserialize, Deserializer, Serialize}; use super::fork::environment; @@ -83,7 +83,7 @@ impl EvmOpts { self.env.gas_price, self.env.chain_id, self.fork_block_number, - self.sender, + b160_to_h160(self.sender), ) .await .wrap_err_with(|| { @@ -94,7 +94,7 @@ impl EvmOpts { /// Returns the `revm::Env` configured with only local settings pub fn local_evm_env(&self) -> revm::primitives::Env { let mut cfg = CfgEnv::default(); - cfg.chain_id = rU256::from(self.env.chain_id.unwrap_or(foundry_common::DEV_CHAIN_ID)); + cfg.chain_id = U256::from(self.env.chain_id.unwrap_or(foundry_common::DEV_CHAIN_ID)); cfg.spec_id = SpecId::MERGE; cfg.limit_contract_code_size = self.env.code_size_limit.or(Some(usize::MAX)); cfg.memory_limit = self.memory_limit; @@ -105,19 +105,19 @@ impl EvmOpts { revm::primitives::Env { block: BlockEnv { - number: rU256::from(self.env.block_number), - coinbase: h160_to_b160(self.env.block_coinbase), - timestamp: rU256::from(self.env.block_timestamp), - difficulty: rU256::from(self.env.block_difficulty), - prevrandao: Some(h256_to_b256(self.env.block_prevrandao)), - basefee: rU256::from(self.env.block_base_fee_per_gas), - gas_limit: u256_to_ru256(self.gas_limit()), + number: U256::from(self.env.block_number), + coinbase: self.env.block_coinbase, + timestamp: U256::from(self.env.block_timestamp), + difficulty: U256::from(self.env.block_difficulty), + prevrandao: Some(self.env.block_prevrandao), + basefee: U256::from(self.env.block_base_fee_per_gas), + gas_limit: self.gas_limit(), }, cfg, tx: TxEnv { - gas_price: rU256::from(self.env.gas_price.unwrap_or_default()), - gas_limit: self.gas_limit().as_u64(), - caller: h160_to_b160(self.sender), + gas_price: U256::from(self.env.gas_price.unwrap_or_default()), + gas_limit: self.gas_limit().to(), + caller: self.sender, ..Default::default() }, } @@ -144,7 +144,7 @@ impl EvmOpts { /// Returns the gas limit to use pub fn gas_limit(&self) -> U256 { - self.env.block_gas_limit.unwrap_or(self.env.gas_limit).into() + U256::from(self.env.block_gas_limit.unwrap_or(self.env.gas_limit)) } /// Returns the configured chain id, which will be @@ -228,7 +228,7 @@ pub struct Env { pub block_difficulty: u64, /// Previous block beacon chain random value. Before merge this field is used for mix_hash - pub block_prevrandao: H256, + pub block_prevrandao: B256, /// the block.gaslimit value during EVM execution #[serde( diff --git a/crates/forge/bin/cmd/coverage.rs b/crates/forge/bin/cmd/coverage.rs index ca0580f92331..a77cc3cd7428 100644 --- a/crates/forge/bin/cmd/coverage.rs +++ b/crates/forge/bin/cmd/coverage.rs @@ -27,7 +27,7 @@ use foundry_cli::{ }; use foundry_common::{compile::ProjectCompiler, evm::EvmArgs, fs}; use foundry_config::{Config, SolcReq}; -use foundry_evm::utils::evm_spec; +use foundry_evm::utils::{b160_to_h160, evm_spec, ru256_to_u256}; use semver::Version; use std::{collections::HashMap, sync::mpsc::channel}; use tracing::trace; @@ -289,9 +289,9 @@ impl CoverageArgs { let evm_spec = evm_spec(config.evm_version); let env = evm_opts.evm_env().await?; let mut runner = MultiContractRunnerBuilder::default() - .initial_balance(evm_opts.initial_balance) + .initial_balance(ru256_to_u256(evm_opts.initial_balance)) .evm_spec(evm_spec) - .sender(evm_opts.sender) + .sender(b160_to_h160(evm_opts.sender)) .with_fork(evm_opts.get_fork(&config, env.clone())) .with_cheats_config(CheatsConfig::new(&config, &evm_opts)) .with_test_options(TestOptions { fuzz: config.fuzz, ..Default::default() }) diff --git a/crates/forge/bin/cmd/script/build.rs b/crates/forge/bin/cmd/script/build.rs index e80a4ec92249..97f9ce21cc3b 100644 --- a/crates/forge/bin/cmd/script/build.rs +++ b/crates/forge/bin/cmd/script/build.rs @@ -14,6 +14,7 @@ use ethers::{ use eyre::{Context, ContextCompat, Result}; use foundry_cli::utils::get_cached_entry_by_name; use foundry_common::compile; +use foundry_evm::utils::b160_to_h160; use foundry_utils::{PostLinkInput, ResolvedDependency}; use std::{collections::BTreeMap, fs, str::FromStr}; use tracing::{trace, warn}; @@ -57,7 +58,7 @@ impl ScriptArgs { project, contracts, script_config.config.parsed_libraries()?, - script_config.evm_opts.sender, + b160_to_h160(script_config.evm_opts.sender), script_config.sender_nonce, )?; diff --git a/crates/forge/bin/cmd/script/cmd.rs b/crates/forge/bin/cmd/script/cmd.rs index 70c836877cdc..55a16896e4db 100644 --- a/crates/forge/bin/cmd/script/cmd.rs +++ b/crates/forge/bin/cmd/script/cmd.rs @@ -6,6 +6,7 @@ use ethers::{ use eyre::Result; use foundry_cli::utils::LoadConfig; use foundry_common::{contracts::flatten_contracts, try_get_http_provider}; +use foundry_evm::utils::b160_to_h160; use std::sync::Arc; use tracing::trace; @@ -30,8 +31,12 @@ impl ScriptArgs { if let Some(ref fork_url) = script_config.evm_opts.fork_url { // when forking, override the sender's nonce to the onchain value - script_config.sender_nonce = - foundry_utils::next_nonce(script_config.evm_opts.sender, fork_url, None).await? + script_config.sender_nonce = foundry_utils::next_nonce( + b160_to_h160(script_config.evm_opts.sender), + fork_url, + None, + ) + .await? } else { // if not forking, then ignore any pre-deployed library addresses script_config.config.libraries = Default::default(); @@ -63,8 +68,9 @@ impl ScriptArgs { // We need to execute the script even if just resuming, in case we need to collect private // keys from the execution. - let mut result = - self.execute(&mut script_config, contract, sender, &predeploy_libraries).await?; + let mut result = self + .execute(&mut script_config, contract, b160_to_h160(sender), &predeploy_libraries) + .await?; if self.resume || (self.verify && !self.broadcast) { return self @@ -159,7 +165,7 @@ impl ScriptArgs { // Add predeploy libraries to the list of broadcastable transactions. let mut lib_deploy = self.create_deploy_transactions( - script_config.evm_opts.sender, + b160_to_h160(script_config.evm_opts.sender), script_config.sender_nonce, &predeploy_libraries, &script_config.evm_opts.fork_url, @@ -349,7 +355,7 @@ impl ScriptArgs { } if let Some(wallets) = self.wallets.private_keys()? { if wallets.len() == 1 { - script_config.evm_opts.sender = wallets.get(0).unwrap().address() + script_config.evm_opts.sender = h160_to_b160(wallets.get(0).unwrap().address()) } } Ok(()) diff --git a/crates/forge/bin/cmd/script/executor.rs b/crates/forge/bin/cmd/script/executor.rs index ac42e3c2a9ee..e7fddf36cb5d 100644 --- a/crates/forge/bin/cmd/script/executor.rs +++ b/crates/forge/bin/cmd/script/executor.rs @@ -20,7 +20,7 @@ use forge::{ }; use foundry_cli::utils::{ensure_clean_constructor, needs_setup}; use foundry_common::{shell, RpcUrl}; -use foundry_evm::utils::evm_spec; +use foundry_evm::utils::{b160_to_h160, evm_spec, ru256_to_u256}; use futures::future::join_all; use parking_lot::RwLock; use std::{collections::VecDeque, sync::Arc}; @@ -261,7 +261,12 @@ impl ScriptArgs { ( rpc.clone(), - self.prepare_runner(&mut script_config, sender, SimulationStage::OnChain).await, + self.prepare_runner( + &mut script_config, + b160_to_h160(sender), + SimulationStage::OnChain, + ) + .await, ) }) .collect::>(); @@ -316,6 +321,10 @@ impl ScriptArgs { }); } - ScriptRunner::new(builder.build(env, db), script_config.evm_opts.initial_balance, sender) + ScriptRunner::new( + builder.build(env, db), + ru256_to_u256(script_config.evm_opts.initial_balance), + sender, + ) } } diff --git a/crates/forge/bin/cmd/script/mod.rs b/crates/forge/bin/cmd/script/mod.rs index e82e849ad30c..0a5a185f8da2 100644 --- a/crates/forge/bin/cmd/script/mod.rs +++ b/crates/forge/bin/cmd/script/mod.rs @@ -53,7 +53,7 @@ use foundry_evm::{ cheatcodes::{util::BroadcastableTransactions, BroadcastableTransaction}, DEFAULT_CREATE2_DEPLOYER, }, - utils::h160_to_b160, + utils::{b160_to_h160, h160_to_b160}, }; use futures::future; use serde::{Deserialize, Serialize}; @@ -414,7 +414,7 @@ impl ScriptArgs { shell::println("You have more than one deployer who could predeploy libraries. Using `--sender` instead.")?; return Ok(None) } - } else if sender != evm_opts.sender { + } else if h160_to_b160(sender) != evm_opts.sender { new_sender = Some(sender); } } @@ -478,7 +478,7 @@ impl ScriptArgs { .collect(); let tui = Tui::new( - flattened, + flattened.into_iter().map(|f| (b160_to_h160(f.0), f.1, f.2)).collect(), 0, identified_contracts, artifacts, diff --git a/crates/forge/bin/cmd/test/mod.rs b/crates/forge/bin/cmd/test/mod.rs index 6bf9441ec3a4..810a6f0915d4 100644 --- a/crates/forge/bin/cmd/test/mod.rs +++ b/crates/forge/bin/cmd/test/mod.rs @@ -30,7 +30,10 @@ use foundry_config::{ }, get_available_profiles, Config, }; -use foundry_evm::{fuzz::CounterExample, utils::evm_spec}; +use foundry_evm::{ + fuzz::CounterExample, + utils::{b160_to_h160, evm_spec, ru256_to_u256}, +}; use regex::Regex; use std::{collections::BTreeMap, path::PathBuf, sync::mpsc::channel, time::Duration}; use tracing::trace; @@ -180,9 +183,9 @@ impl TestArgs { let evm_spec = evm_spec(config.evm_version); let mut runner = MultiContractRunnerBuilder::default() - .initial_balance(evm_opts.initial_balance) + .initial_balance(ru256_to_u256(evm_opts.initial_balance)) .evm_spec(evm_spec) - .sender(evm_opts.sender) + .sender(b160_to_h160(evm_opts.sender)) .with_fork(evm_opts.get_fork(&config, env.clone())) .with_cheats_config(CheatsConfig::new(&config, &evm_opts)) .with_test_options(test_options.clone()) diff --git a/crates/forge/src/multi_runner.rs b/crates/forge/src/multi_runner.rs index 55b2c34e1364..af0c8b8288bc 100644 --- a/crates/forge/src/multi_runner.rs +++ b/crates/forge/src/multi_runner.rs @@ -13,6 +13,7 @@ use foundry_evm::{ ExecutorBuilder, }, revm, + utils::{b160_to_h160, ru256_to_u256}, }; use foundry_utils::{PostLinkInput, ResolvedDependency}; use rayon::prelude::*; @@ -189,7 +190,7 @@ impl MultiContractRunner { executor, contract, deploy_code, - self.evm_opts.initial_balance, + ru256_to_u256(self.evm_opts.initial_balance), self.sender, self.errors.as_ref(), libs, @@ -264,7 +265,7 @@ impl MultiContractRunnerBuilder { ArtifactContracts::from_iter(contracts), &mut known_contracts, Default::default(), - evm_opts.sender, + b160_to_h160(evm_opts.sender), U256::one(), &mut deployable_contracts, |post_link_input| { diff --git a/crates/forge/tests/it/config.rs b/crates/forge/tests/it/config.rs index f81472045d69..6490d7076da0 100644 --- a/crates/forge/tests/it/config.rs +++ b/crates/forge/tests/it/config.rs @@ -13,6 +13,7 @@ use foundry_config::{ }; use foundry_evm::{ decode::decode_console_logs, executor::inspector::CheatsConfig, revm::primitives::SpecId, + utils::b160_to_h160, }; use std::{ collections::BTreeMap, @@ -143,7 +144,7 @@ pub fn manifest_root() -> PathBuf { /// Builds a base runner pub fn base_runner() -> MultiContractRunnerBuilder { - MultiContractRunnerBuilder::default().sender(EVM_OPTS.sender) + MultiContractRunnerBuilder::default().sender(b160_to_h160(EVM_OPTS.sender)) } /// Builds a non-tracing runner diff --git a/crates/forge/tests/it/test_helpers.rs b/crates/forge/tests/it/test_helpers.rs index 0598793a5b51..ac66e43a7a06 100644 --- a/crates/forge/tests/it/test_helpers.rs +++ b/crates/forge/tests/it/test_helpers.rs @@ -14,7 +14,7 @@ use foundry_evm::{ DatabaseRef, Executor, ExecutorBuilder, }, fuzz::FuzzedExecutor, - utils::b160_to_h160, + utils::{b160_to_h160, h160_to_b160, u256_to_ru256}, CALLER, }; use std::{path::PathBuf, str::FromStr}; @@ -65,13 +65,13 @@ pub static EVM_OPTS: Lazy = Lazy::new(|| EvmOpts { env: Env { gas_limit: 18446744073709551615, chain_id: None, - tx_origin: Config::DEFAULT_SENDER, + tx_origin: h160_to_b160(Config::DEFAULT_SENDER), block_number: 1, block_timestamp: 1, ..Default::default() }, - sender: Config::DEFAULT_SENDER, - initial_balance: U256::MAX, + sender: h160_to_b160(Config::DEFAULT_SENDER), + initial_balance: u256_to_ru256(U256::MAX), ffi: true, memory_limit: 2u64.pow(24), ..Default::default() diff --git a/crates/ui/src/lib.rs b/crates/ui/src/lib.rs index ca13218fa726..b1249569e26d 100644 --- a/crates/ui/src/lib.rs +++ b/crates/ui/src/lib.rs @@ -887,7 +887,7 @@ Line::from(Span::styled("[t]: stack labels | [m]: memory decoding | [shift + j/k let min_len = format!("{:x}", max_i * 32).len(); // color memory words based on write/read - let mut word = None; + let mut word: Option = None; let mut color = None; if let Instruction::OpCode(op) = debug_steps[current_step].instruction { let stack_len = debug_steps[current_step].stack.len(); @@ -895,11 +895,11 @@ Line::from(Span::styled("[t]: stack labels | [m]: memory decoding | [shift + j/k let w = debug_steps[current_step].stack[stack_len - 1]; match op { opcode::MLOAD => { - word = Some(w.as_usize()); + word = Some(w.to()); color = Some(Color::Cyan); } opcode::MSTORE => { - word = Some(w.as_usize()); + word = Some(w.to()); color = Some(Color::Red); } _ => {} @@ -914,7 +914,7 @@ Line::from(Span::styled("[t]: stack labels | [m]: memory decoding | [shift + j/k if let Instruction::OpCode(op) = debug_steps[prev_step].instruction { if op == opcode::MSTORE { let prev_top = debug_steps[prev_step].stack[stack_len - 1]; - word = Some(prev_top.as_usize()); + word = Some(prev_top.to()); color = Some(Color::Green); } } From b430e7a3250cb10c9306daf3c467798c3b143bda Mon Sep 17 00:00:00 2001 From: Enrique Ortiz Date: Wed, 13 Sep 2023 11:50:34 -0400 Subject: [PATCH 02/10] fix: properly create both create and create2 addresses --- crates/evm/src/executor/builder.rs | 2 +- crates/evm/src/executor/inspector/access_list.rs | 7 ++----- crates/evm/src/executor/inspector/stack.rs | 2 +- crates/evm/src/executor/inspector/utils.rs | 14 ++++---------- crates/forge/bin/cmd/coverage.rs | 2 +- crates/forge/bin/cmd/script/build.rs | 2 +- crates/forge/bin/cmd/script/cmd.rs | 2 +- crates/forge/bin/cmd/test/mod.rs | 5 ++++- 8 files changed, 15 insertions(+), 21 deletions(-) diff --git a/crates/evm/src/executor/builder.rs b/crates/evm/src/executor/builder.rs index 1b5dbbdc712d..287c8f8f3c33 100644 --- a/crates/evm/src/executor/builder.rs +++ b/crates/evm/src/executor/builder.rs @@ -1,5 +1,5 @@ use super::{inspector::InspectorStackBuilder, Executor}; -use crate::{executor::backend::Backend}; +use crate::executor::backend::Backend; use revm::primitives::{Env, SpecId, U256}; /// The builder that allows to configure an evm [`Executor`] which a stack of optional diff --git a/crates/evm/src/executor/inspector/access_list.rs b/crates/evm/src/executor/inspector/access_list.rs index 41fbc73681b3..f65b53a53431 100644 --- a/crates/evm/src/executor/inspector/access_list.rs +++ b/crates/evm/src/executor/inspector/access_list.rs @@ -36,7 +36,6 @@ impl AccessListTracer { .collect(), } } - pub fn access_list(&self) -> AccessList { AccessList::from( self.access_list @@ -49,7 +48,6 @@ impl AccessListTracer { ) } } - impl Inspector for AccessListTracer { #[inline] fn step( @@ -70,7 +68,7 @@ impl Inspector for AccessListTracer { opcode::BALANCE | opcode::SELFDESTRUCT => { if let Ok(slot) = interpreter.stack().peek(0) { - let addr: Address = Address::from_slice(&slot.to_be_bytes::<32>()); + let addr: Address = Address::from_slice(&slot.to_be_bytes::<32>()[12..]); if !self.excluded.contains(&addr) { self.access_list.entry(addr).or_default(); } @@ -78,7 +76,7 @@ impl Inspector for AccessListTracer { } opcode::DELEGATECALL | opcode::CALL | opcode::STATICCALL | opcode::CALLCODE => { if let Ok(slot) = interpreter.stack().peek(1) { - let addr: Address = Address::from_slice(&slot.to_be_bytes::<32>()); + let addr: Address = Address::from_slice(&slot.to_be_bytes::<32>()[12..]); if !self.excluded.contains(&addr) { self.access_list.entry(addr).or_default(); } @@ -86,7 +84,6 @@ impl Inspector for AccessListTracer { } _ => (), } - InstructionResult::Continue } } diff --git a/crates/evm/src/executor/inspector/stack.rs b/crates/evm/src/executor/inspector/stack.rs index db8e2c878d0a..002843489f4a 100644 --- a/crates/evm/src/executor/inspector/stack.rs +++ b/crates/evm/src/executor/inspector/stack.rs @@ -13,7 +13,7 @@ use revm::{ interpreter::{ return_revert, CallInputs, CreateInputs, Gas, InstructionResult, Interpreter, Memory, Stack, }, - primitives::{Address as rAddress, U256 as rU256, BlockEnv, Bytes, Env, B256}, + primitives::{Address as rAddress, BlockEnv, Bytes, Env, B256, U256 as rU256}, EVMData, Inspector, }; use std::{collections::BTreeMap, sync::Arc}; diff --git a/crates/evm/src/executor/inspector/utils.rs b/crates/evm/src/executor/inspector/utils.rs index 6cc9f71b111f..fd0394243d38 100644 --- a/crates/evm/src/executor/inspector/utils.rs +++ b/crates/evm/src/executor/inspector/utils.rs @@ -1,12 +1,10 @@ -use bytes::Buf; +use alloy_primitives::B256; use revm::{ interpreter::CreateInputs, primitives::{Address, CreateScheme, SpecId}, }; -use crate::utils::{ru256_to_u256}; - /// Returns [InstructionResult::Continue] on an error, discarding the error. /// /// Useful for inspectors that read state that might be invalid, but do not want to emit @@ -23,15 +21,11 @@ macro_rules! try_or_continue { /// Get the address of a contract creation pub fn get_create_address(call: &CreateInputs, nonce: u64) -> Address { match call.scheme { - CreateScheme::Create => Address::create(&call.caller, nonce), + CreateScheme::Create => call.caller.create(nonce), CreateScheme::Create2 { salt } => { - let salt = ru256_to_u256(salt); - let mut salt_bytes = [0u8; 32]; - salt.to_big_endian(&mut salt_bytes); - let init_code = - alloy_primitives::Bytes(call.init_code.clone().0).to_owned().0.copy_to_bytes(32); + let init_code = alloy_primitives::Bytes(call.init_code.0.clone()); let init_code_hash = alloy_primitives::keccak256(init_code); - Address::create2(&call.caller, salt_bytes, init_code_hash) + call.caller.create2(B256::from(salt), init_code_hash) } } } diff --git a/crates/forge/bin/cmd/coverage.rs b/crates/forge/bin/cmd/coverage.rs index 0086b7c50416..473cb59ba8a2 100644 --- a/crates/forge/bin/cmd/coverage.rs +++ b/crates/forge/bin/cmd/coverage.rs @@ -27,7 +27,7 @@ use foundry_cli::{ }; use foundry_common::{compile::ProjectCompiler, evm::EvmArgs, fs}; use foundry_config::{Config, SolcReq}; -use foundry_evm::utils::{ru256_to_u256, b160_to_h160}; +use foundry_evm::utils::{b160_to_h160, ru256_to_u256}; use semver::Version; use std::{collections::HashMap, sync::mpsc::channel}; use tracing::trace; diff --git a/crates/forge/bin/cmd/script/build.rs b/crates/forge/bin/cmd/script/build.rs index 2793a67ac4b2..aee3846933c8 100644 --- a/crates/forge/bin/cmd/script/build.rs +++ b/crates/forge/bin/cmd/script/build.rs @@ -12,11 +12,11 @@ use ethers::{ }; use eyre::{Context, ContextCompat, Result}; use foundry_cli::utils::get_cached_entry_by_name; -use foundry_evm::utils::b160_to_h160; use foundry_common::{ compact_to_contract, compile::{self, ContractSources}, }; +use foundry_evm::utils::b160_to_h160; use foundry_utils::{PostLinkInput, ResolvedDependency}; use std::{collections::BTreeMap, fs, str::FromStr}; use tracing::{trace, warn}; diff --git a/crates/forge/bin/cmd/script/cmd.rs b/crates/forge/bin/cmd/script/cmd.rs index c23817115ddd..8c602180f247 100644 --- a/crates/forge/bin/cmd/script/cmd.rs +++ b/crates/forge/bin/cmd/script/cmd.rs @@ -6,8 +6,8 @@ use ethers::{ use eyre::Result; use foundry_cli::utils::LoadConfig; use foundry_common::{contracts::flatten_contracts, try_get_http_provider}; -use foundry_evm::utils::b160_to_h160; use foundry_debugger::DebuggerArgs; +use foundry_evm::utils::b160_to_h160; use std::sync::Arc; use tracing::trace; diff --git a/crates/forge/bin/cmd/test/mod.rs b/crates/forge/bin/cmd/test/mod.rs index c9ff7dea7621..83e528bf1908 100644 --- a/crates/forge/bin/cmd/test/mod.rs +++ b/crates/forge/bin/cmd/test/mod.rs @@ -31,8 +31,11 @@ use foundry_config::{ }, get_available_profiles, Config, }; -use foundry_evm::{fuzz::CounterExample, utils::{ru256_to_u256, b160_to_h160}}; use foundry_debugger::DebuggerArgs; +use foundry_evm::{ + fuzz::CounterExample, + utils::{b160_to_h160, ru256_to_u256}, +}; use regex::Regex; use std::{collections::BTreeMap, fs, sync::mpsc::channel, time::Duration}; use tracing::trace; From a5591d3de3842c319f16c5c80a3562a9b804d612 Mon Sep 17 00:00:00 2001 From: Enrique Ortiz Date: Wed, 13 Sep 2023 12:28:32 -0400 Subject: [PATCH 03/10] chore: clippy --- crates/anvil/src/config.rs | 21 +++++++++++---------- crates/evm/src/executor/backend/mod.rs | 7 ------- crates/evm/src/executor/fork/init.rs | 19 +++++++++++-------- crates/evm/src/executor/opts.rs | 21 +++++++++++---------- 4 files changed, 33 insertions(+), 35 deletions(-) diff --git a/crates/anvil/src/config.rs b/crates/anvil/src/config.rs index 3d5e2ed247b0..1dbbf497b15b 100644 --- a/crates/anvil/src/config.rs +++ b/crates/anvil/src/config.rs @@ -784,16 +784,17 @@ impl NodeConfig { pub(crate) async fn setup(&mut self) -> mem::Backend { // configure the revm environment - let mut cfg = CfgEnv::default(); - cfg.spec_id = self.get_hardfork().into(); - cfg.chain_id = rU256::from(self.get_chain_id()); - cfg.limit_contract_code_size = self.code_size_limit; - // EIP-3607 rejects transactions from senders with deployed code. - // If EIP-3607 is enabled it can cause issues during fuzz/invariant tests if the - // caller is a contract. So we disable the check by default. - cfg.disable_eip3607 = true; - cfg.disable_block_gas_limit = self.disable_block_gas_limit; - + let cfg = CfgEnv { + spec_id: self.get_hardfork().into(), + chain_id: rU256::from(self.get_chain_id()), + limit_contract_code_size: self.code_size_limit, + // EIP-3607 rejects transactions from senders with deployed code. + // If EIP-3607 is enabled it can cause issues during fuzz/invariant tests if the + // caller is a contract. So we disable the check by default. + disable_eip3607: true, + disable_block_gas_limit: self.disable_block_gas_limit, + ..Default::default() + }; let mut env = revm::primitives::Env { cfg, block: BlockEnv { diff --git a/crates/evm/src/executor/backend/mod.rs b/crates/evm/src/executor/backend/mod.rs index b84b54e35905..c441fd702793 100644 --- a/crates/evm/src/executor/backend/mod.rs +++ b/crates/evm/src/executor/backend/mod.rs @@ -592,7 +592,6 @@ impl Backend { address: Address, current_state: &JournaledState, ) -> bool { - let address = address; if let Some(account) = current_state.state.get(&address) { let value = account .storage @@ -1709,8 +1708,6 @@ fn merge_journaled_state_data( active_journaled_state: &JournaledState, fork_journaled_state: &mut JournaledState, ) { - let addr = addr; - if let Some(mut acc) = active_journaled_state.state.get(&addr).cloned() { trace!(?addr, "updating journaled_state account data"); if let Some(fork_account) = fork_journaled_state.state.get_mut(&addr) { @@ -1731,8 +1728,6 @@ fn merge_db_account_data( ) { trace!(?addr, "merging database data"); - let addr = addr; - let mut acc = if let Some(acc) = active.accounts.get(&addr).cloned() { acc } else { @@ -1756,8 +1751,6 @@ fn merge_db_account_data( /// Returns true of the address is a contract fn is_contract_in_state(journaled_state: &JournaledState, acc: Address) -> bool { - let acc = acc; - journaled_state .state .get(&acc) diff --git a/crates/evm/src/executor/fork/init.rs b/crates/evm/src/executor/fork/init.rs index e11772e35371..973c48a7f9f3 100644 --- a/crates/evm/src/executor/fork/init.rs +++ b/crates/evm/src/executor/fork/init.rs @@ -58,14 +58,17 @@ where eyre::bail!("Failed to get block for block number: {}", block_number) }; - let mut cfg = CfgEnv::default(); - cfg.chain_id = u256_to_ru256(override_chain_id.unwrap_or(rpc_chain_id.as_u64()).into()); - cfg.memory_limit = memory_limit; - cfg.limit_contract_code_size = Some(usize::MAX); - // EIP-3607 rejects transactions from senders with deployed code. - // If EIP-3607 is enabled it can cause issues during fuzz/invariant tests if the caller - // is a contract. So we disable the check by default. - cfg.disable_eip3607 = true; + let cfg = CfgEnv { + chain_id: u256_to_ru256(override_chain_id.unwrap_or(rpc_chain_id.as_u64()).into()), + memory_limit, + limit_contract_code_size: Some(usize::MAX), + // EIP-3607 rejects transactions from senders with deployed code. + // If EIP-3607 is enabled it can cause issues during fuzz/invariant tests if the caller + // is a contract. So we disable the check by default. + disable_eip3607: true, + ..Default::default() + }; + let mut env = Env { cfg, block: BlockEnv { diff --git a/crates/evm/src/executor/opts.rs b/crates/evm/src/executor/opts.rs index bf30cf0beb7f..4bb68721c2ad 100644 --- a/crates/evm/src/executor/opts.rs +++ b/crates/evm/src/executor/opts.rs @@ -93,16 +93,17 @@ impl EvmOpts { /// Returns the `revm::Env` configured with only local settings pub fn local_evm_env(&self) -> revm::primitives::Env { - let mut cfg = CfgEnv::default(); - cfg.chain_id = U256::from(self.env.chain_id.unwrap_or(foundry_common::DEV_CHAIN_ID)); - cfg.spec_id = SpecId::MERGE; - cfg.limit_contract_code_size = self.env.code_size_limit.or(Some(usize::MAX)); - cfg.memory_limit = self.memory_limit; - // EIP-3607 rejects transactions from senders with deployed code. - // If EIP-3607 is enabled it can cause issues during fuzz/invariant tests if the - // caller is a contract. So we disable the check by default. - cfg.disable_eip3607 = true; - + let cfg = CfgEnv { + chain_id: U256::from(self.env.chain_id.unwrap_or(foundry_common::DEV_CHAIN_ID)), + spec_id: SpecId::MERGE, + limit_contract_code_size: self.env.code_size_limit.or(Some(usize::MAX)), + memory_limit: self.memory_limit, + // EIP-3607 rejects transactions from senders with deployed code. + // If EIP-3607 is enabled it can cause issues during fuzz/invariant tests if the + // caller is a contract. So we disable the check by default. + disable_eip3607: true, + ..Default::default() + }; revm::primitives::Env { block: BlockEnv { number: U256::from(self.env.block_number), From d48d5892a83cc204724c338b436188c747bf9220 Mon Sep 17 00:00:00 2001 From: evalir Date: Fri, 15 Sep 2023 08:55:32 -0400 Subject: [PATCH 04/10] (#3) Alloy Migration: migrate fork-adjacent files to alloy primitives (#5771) --- crates/evm/src/executor/backend/mod.rs | 4 +- crates/evm/src/executor/fork/backend.rs | 128 ++++++++++++------------ crates/evm/src/executor/fork/init.rs | 7 +- crates/evm/src/executor/fork/multi.rs | 2 +- crates/evm/src/executor/opts.rs | 7 +- 5 files changed, 71 insertions(+), 77 deletions(-) diff --git a/crates/evm/src/executor/backend/mod.rs b/crates/evm/src/executor/backend/mod.rs index c441fd702793..160b787b7608 100644 --- a/crates/evm/src/executor/backend/mod.rs +++ b/crates/evm/src/executor/backend/mod.rs @@ -803,7 +803,7 @@ impl Backend { transaction: B256, ) -> eyre::Result<(U64, Block)> { let fork = self.inner.get_fork_by_id(id)?; - let tx = fork.db.db.get_transaction(b256_to_h256(transaction))?; + let tx = fork.db.db.get_transaction(transaction)?; // get the block number we need to fork if let Some(tx_block) = tx.block_number { @@ -1171,7 +1171,7 @@ impl DatabaseExt for Backend { }; let fork = self.inner.get_fork_by_id_mut(id)?; - let tx = fork.db.db.get_transaction(b256_to_h256(transaction))?; + let tx = fork.db.db.get_transaction(transaction)?; commit_transaction(tx, env, journaled_state, fork, &fork_id, cheatcodes_inspector)?; diff --git a/crates/evm/src/executor/fork/backend.rs b/crates/evm/src/executor/fork/backend.rs index f23c3c97a2b6..714c6325f78b 100644 --- a/crates/evm/src/executor/fork/backend.rs +++ b/crates/evm/src/executor/fork/backend.rs @@ -4,12 +4,12 @@ use crate::{ backend::error::{DatabaseError, DatabaseResult}, fork::{cache::FlushJsonBlockCacheDB, BlockchainDb}, }, - utils::{b160_to_h160, b256_to_h256, h160_to_b160, h256_to_b256, ru256_to_u256, u256_to_ru256}, + utils::{b160_to_h160, b256_to_h256, h256_to_b256, u256_to_ru256}, }; use ethers::{ core::abi::ethereum_types::BigEndianHash, providers::Middleware, - types::{Address, Block, BlockId, Bytes, Transaction, H256, U256}, + types::{Block, BlockId, NameOrAddress, Transaction}, utils::keccak256, }; use foundry_common::NON_ARCHIVE_NODE_WARNING; @@ -21,7 +21,7 @@ use futures::{ }; use revm::{ db::DatabaseRef, - primitives::{AccountInfo, Address as aB160, Bytecode, B256, KECCAK_EMPTY, U256 as rU256}, + primitives::{AccountInfo, Address, Bytecode, Bytes, B256, KECCAK_EMPTY, U256}, }; use std::{ collections::{hash_map::Entry, HashMap, VecDeque}, @@ -37,7 +37,7 @@ use std::{ type AccountFuture = Pin, Address)> + Send>>; type StorageFuture = Pin, Address, U256)> + Send>>; -type BlockHashFuture = Pin, u64)> + Send>>; +type BlockHashFuture = Pin, u64)> + Send>>; type FullBlockFuture = Pin< Box< dyn Future>, Err>, BlockId)> @@ -45,12 +45,12 @@ type FullBlockFuture = Pin< >, >; type TransactionFuture = Pin< - Box, Err>, H256)> + Send>, + Box, Err>, B256)> + Send>, >; type AccountInfoSender = OneshotSender>; type StorageSender = OneshotSender>; -type BlockHashSender = OneshotSender>; +type BlockHashSender = OneshotSender>; type FullBlockSender = OneshotSender>>; type TransactionSender = OneshotSender>; @@ -75,7 +75,7 @@ enum BackendRequest { /// Fetch an entire block with transactions FullBlock(BlockId, FullBlockSender), /// Fetch a transaction - Transaction(H256, TransactionSender), + Transaction(B256, TransactionSender), /// Sets the pinned block to fetch data from SetPinnedBlock(BlockId), } @@ -139,7 +139,7 @@ where match req { BackendRequest::Basic(addr, sender) => { trace!(target: "backendhandler", "received request basic address={:?}", addr); - let acc = self.db.accounts().read().get(&h160_to_b160(addr)).cloned(); + let acc = self.db.accounts().read().get(&addr).cloned(); if let Some(basic) = acc { let _ = sender.send(Ok(basic)); } else { @@ -147,9 +147,9 @@ where } } BackendRequest::BlockHash(number, sender) => { - let hash = self.db.block_hashes().read().get(&rU256::from(number)).cloned(); + let hash = self.db.block_hashes().read().get(&U256::from(number)).cloned(); if let Some(hash) = hash { - let _ = sender.send(Ok(b256_to_h256(hash))); + let _ = sender.send(Ok(hash)); } else { self.request_hash(number, sender); } @@ -162,14 +162,10 @@ where } BackendRequest::Storage(addr, idx, sender) => { // account is already stored in the cache - let value = self - .db - .storage() - .read() - .get(&h160_to_b160(addr)) - .and_then(|acc| acc.get(&u256_to_ru256(idx)).copied()); + let value = + self.db.storage().read().get(&addr).and_then(|acc| acc.get(&idx).copied()); if let Some(value) = value { - let _ = sender.send(Ok(ru256_to_u256(value))); + let _ = sender.send(Ok(value)); } else { // account present but not storage -> fetch storage self.request_account_storage(addr, idx, sender); @@ -194,9 +190,15 @@ where let block_id = self.block_id; let fut = Box::pin(async move { // serialize & deserialize back to U256 - let idx_req = H256::from_uint(&idx); - let storage = provider.get_storage_at(address, idx_req, block_id).await; - let storage = storage.map(|storage| storage.into_uint()); + let idx_req = B256::from(idx); + let storage = provider + .get_storage_at( + NameOrAddress::Address(b160_to_h160(address)), + b256_to_h256(idx_req), + block_id, + ) + .await; + let storage = storage.map(|storage| storage.into_uint()).map(u256_to_ru256); (storage, address, idx) }); self.pending_requests.push(ProviderRequest::Storage(fut)); @@ -210,10 +212,14 @@ where let provider = self.provider.clone(); let block_id = self.block_id; let fut = Box::pin(async move { - let balance = provider.get_balance(address, block_id); - let nonce = provider.get_transaction_count(address, block_id); - let code = provider.get_code(address, block_id); - let resp = tokio::try_join!(balance, nonce, code); + let balance = + provider.get_balance(NameOrAddress::Address(b160_to_h160(address)), block_id); + let nonce = provider + .get_transaction_count(NameOrAddress::Address(b160_to_h160(address)), block_id); + let code = provider.get_code(NameOrAddress::Address(b160_to_h160(address)), block_id); + let resp = tokio::try_join!(balance, nonce, code).map(|(balance, nonce, code)| { + (u256_to_ru256(balance), u256_to_ru256(nonce), Bytes::from(code.0)) + }); (resp, address) }); ProviderRequest::Account(fut) @@ -244,10 +250,10 @@ where } /// process a request for a transactions - fn request_transaction(&mut self, tx: H256, sender: TransactionSender) { + fn request_transaction(&mut self, tx: B256, sender: TransactionSender) { let provider = self.provider.clone(); let fut = Box::pin(async move { - let block = provider.get_transaction(tx).await; + let block = provider.get_transaction(b256_to_h256(tx)).await; (sender, block, tx) }); @@ -282,7 +288,7 @@ where Err(err) } }; - (block_hash, number) + (block_hash.map(h256_to_b256), number) }); self.pending_requests.push(ProviderRequest::BlockHash(fut)); } @@ -332,7 +338,7 @@ where if let Some(listeners) = pin.account_requests.remove(&addr) { listeners.into_iter().for_each(|l| { let _ = l.send(Err(DatabaseError::GetAccount( - h160_to_b160(addr), + addr, Arc::clone(&err), ))); }) @@ -350,14 +356,14 @@ where // update the cache let acc = AccountInfo { - nonce: nonce.as_u64(), - balance: u256_to_ru256(balance), + nonce: nonce.to(), + balance, code: code.map(|bytes| { Bytecode::new_raw(alloy_primitives::Bytes(bytes)).to_checked() }), code_hash, }; - pin.db.accounts().write().insert(h160_to_b160(addr), acc.clone()); + pin.db.accounts().write().insert(addr, acc.clone()); // notify all listeners if let Some(listeners) = pin.account_requests.remove(&addr) { @@ -380,8 +386,8 @@ where { listeners.into_iter().for_each(|l| { let _ = l.send(Err(DatabaseError::GetStorage( - h160_to_b160(addr), - u256_to_ru256(idx), + addr, + idx, Arc::clone(&err), ))); }) @@ -391,12 +397,7 @@ where }; // update the cache - pin.db - .storage() - .write() - .entry(h160_to_b160(addr)) - .or_default() - .insert(u256_to_ru256(idx), u256_to_ru256(value)); + pin.db.storage().write().entry(addr).or_default().insert(idx, value); // notify all listeners if let Some(listeners) = pin.storage_requests.remove(&(addr, idx)) { @@ -427,10 +428,7 @@ where }; // update the cache - pin.db - .block_hashes() - .write() - .insert(rU256::from(number), h256_to_b256(value)); + pin.db.block_hashes().write().insert(U256::from(number), value); // notify all listeners if let Some(listeners) = pin.block_requests.remove(&number) { @@ -459,12 +457,10 @@ where if let Poll::Ready((sender, tx, tx_hash)) = fut.poll_unpin(cx) { let msg = match tx { Ok(Some(tx)) => Ok(tx), - Ok(None) => { - Err(DatabaseError::TransactionNotFound(h256_to_b256(tx_hash))) - } + Ok(None) => Err(DatabaseError::TransactionNotFound(tx_hash)), Err(err) => { let err = Arc::new(eyre::Error::new(err)); - Err(DatabaseError::GetTransaction(h256_to_b256(tx_hash), err)) + Err(DatabaseError::GetTransaction(tx_hash, err)) } }; let _ = sender.send(msg); @@ -605,7 +601,7 @@ impl SharedBackend { } /// Returns the transaction for the hash - pub fn get_transaction(&self, tx: H256) -> DatabaseResult { + pub fn get_transaction(&self, tx: B256) -> DatabaseResult { tokio::task::block_in_place(|| { let (sender, rx) = oneshot_channel(); let req = BackendRequest::Transaction(tx, sender); @@ -632,7 +628,7 @@ impl SharedBackend { }) } - fn do_get_block_hash(&self, number: u64) -> DatabaseResult { + fn do_get_block_hash(&self, number: u64) -> DatabaseResult { tokio::task::block_in_place(|| { let (sender, rx) = oneshot_channel(); let req = BackendRequest::BlockHash(number, sender); @@ -650,9 +646,9 @@ impl SharedBackend { impl DatabaseRef for SharedBackend { type Error = DatabaseError; - fn basic(&self, address: aB160) -> Result, Self::Error> { + fn basic(&self, address: Address) -> Result, Self::Error> { trace!( target: "sharedbackend", "request basic {:?}", address); - self.do_get_basic(b160_to_h160(address)).map_err(|err| { + self.do_get_basic(address).map_err(|err| { error!(target: "sharedbackend", ?err, ?address, "Failed to send/recv `basic`"); if err.is_possibly_non_archive_node_error() { error!(target: "sharedbackend", "{NON_ARCHIVE_NODE_WARNING}"); @@ -665,26 +661,26 @@ impl DatabaseRef for SharedBackend { Err(DatabaseError::MissingCode(hash)) } - fn storage(&self, address: aB160, index: rU256) -> Result { + fn storage(&self, address: Address, index: U256) -> Result { trace!( target: "sharedbackend", "request storage {:?} at {:?}", address, index); - match self.do_get_storage(b160_to_h160(address), ru256_to_u256(index)).map_err(|err| { + match self.do_get_storage(address, index).map_err(|err| { error!( target: "sharedbackend", ?err, ?address, ?index, "Failed to send/recv `storage`"); if err.is_possibly_non_archive_node_error() { error!(target: "sharedbackend", "{NON_ARCHIVE_NODE_WARNING}"); } err }) { - Ok(val) => Ok(u256_to_ru256(val)), + Ok(val) => Ok(val), Err(err) => Err(err), } } - fn block_hash(&self, number: rU256) -> Result { - if number > rU256::from(u64::MAX) { + fn block_hash(&self, number: U256) -> Result { + if number > U256::from(u64::MAX) { return Ok(KECCAK_EMPTY) } - let number: U256 = ru256_to_u256(number); - let number = number.as_u64(); + let number: U256 = number; + let number = number.to(); trace!( target: "sharedbackend", "request block hash for number {:?}", number); match self.do_get_block_hash(number).map_err(|err| { error!(target: "sharedbackend",?err, ?number, "Failed to send/recv `block_hash`"); @@ -693,7 +689,7 @@ impl DatabaseRef for SharedBackend { } err }) { - Ok(val) => Ok(h256_to_b256(val)), + Ok(val) => Ok(val), Err(err) => Err(err), } } @@ -726,9 +722,9 @@ mod tests { let backend = SharedBackend::spawn_backend(Arc::new(provider), db.clone(), None).await; // some rng contract from etherscan - let address: aB160 = "63091244180ae240c87d1f528f5f269134cb07b3".parse().unwrap(); + let address: Address = "63091244180ae240c87d1f528f5f269134cb07b3".parse().unwrap(); - let idx = rU256::from(0u64); + let idx = U256::from(0u64); let value = backend.storage(address, idx).unwrap(); let account = backend.basic(address).unwrap().unwrap(); @@ -739,7 +735,7 @@ mod tests { assert_eq!(slots.len(), 1); assert_eq!(slots.get(&idx).copied().unwrap(), value); - let num = rU256::from(10u64); + let num = U256::from(10u64); let hash = backend.block_hash(num).unwrap(); let mem_hash = *db.block_hashes().read().get(&num).unwrap(); assert_eq!(hash, mem_hash); @@ -747,7 +743,7 @@ mod tests { let max_slots = 5; let handle = std::thread::spawn(move || { for i in 1..max_slots { - let idx = rU256::from(i); + let idx = U256::from(i); let _ = backend.storage(address, idx); } }); @@ -785,16 +781,16 @@ mod tests { let backend = Backend::spawn(Some(fork)).await; // some rng contract from etherscan - let address: aB160 = "63091244180ae240c87d1f528f5f269134cb07b3".parse().unwrap(); + let address: Address = "63091244180ae240c87d1f528f5f269134cb07b3".parse().unwrap(); - let idx = rU256::from(0u64); + let idx = U256::from(0u64); let _value = backend.storage(address, idx); let _account = backend.basic(address); // fill some slots let num_slots = 10u64; for idx in 1..num_slots { - let _ = backend.storage(address, rU256::from(idx)); + let _ = backend.storage(address, U256::from(idx)); } drop(backend); diff --git a/crates/evm/src/executor/fork/init.rs b/crates/evm/src/executor/fork/init.rs index abf6356c158f..539e4f888d50 100644 --- a/crates/evm/src/executor/fork/init.rs +++ b/crates/evm/src/executor/fork/init.rs @@ -1,9 +1,10 @@ use crate::utils::{ apply_chain_and_block_specific_env_changes, h160_to_b160, h256_to_b256, u256_to_ru256, }; +use alloy_primitives::{Address, U256}; use ethers::{ providers::Middleware, - types::{Address, Block, TxHash, U256}, + types::{Block, TxHash}, }; use eyre::WrapErr; use foundry_common::NON_ARCHIVE_NODE_WARNING; @@ -79,8 +80,8 @@ where gas_limit: u256_to_ru256(block.gas_limit), }, tx: TxEnv { - caller: h160_to_b160(origin), - gas_price: u256_to_ru256(gas_price.map(U256::from).unwrap_or(fork_gas_price)), + caller: origin, + gas_price: gas_price.map(U256::from).unwrap_or(u256_to_ru256(fork_gas_price)), chain_id: Some(override_chain_id.unwrap_or(rpc_chain_id.as_u64())), gas_limit: block.gas_limit.as_u64(), ..Default::default() diff --git a/crates/evm/src/executor/fork/multi.rs b/crates/evm/src/executor/fork/multi.rs index a3edb576a860..f2dafbfc333c 100644 --- a/crates/evm/src/executor/fork/multi.rs +++ b/crates/evm/src/executor/fork/multi.rs @@ -1,4 +1,4 @@ -//! Support for running multiple fork backend +//! Support for running multiple fork backends //! //! The design is similar to the single `SharedBackend`, `BackendHandler` but supports multiple //! concurrently active pairs at once. diff --git a/crates/evm/src/executor/opts.rs b/crates/evm/src/executor/opts.rs index 75c0835eddba..41abfaf627a4 100644 --- a/crates/evm/src/executor/opts.rs +++ b/crates/evm/src/executor/opts.rs @@ -1,7 +1,4 @@ -use crate::{ - executor::fork::CreateFork, - utils::{b160_to_h160, RuntimeOrHandle}, -}; +use crate::{executor::fork::CreateFork, utils::RuntimeOrHandle}; use ethers::{ providers::{Middleware, Provider}, types::{Block, Chain, TxHash}, @@ -83,7 +80,7 @@ impl EvmOpts { self.env.gas_price, self.env.chain_id, self.fork_block_number, - b160_to_h160(self.sender), + self.sender, ) .await .wrap_err_with(|| { From 6e4b0bfd572a27132c772fde4ddc3c5344d64176 Mon Sep 17 00:00:00 2001 From: Enrique Ortiz Date: Fri, 15 Sep 2023 09:53:06 -0400 Subject: [PATCH 05/10] chore: use create2_from_code --- crates/evm/src/executor/inspector/utils.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/crates/evm/src/executor/inspector/utils.rs b/crates/evm/src/executor/inspector/utils.rs index fd0394243d38..b657e7a32724 100644 --- a/crates/evm/src/executor/inspector/utils.rs +++ b/crates/evm/src/executor/inspector/utils.rs @@ -23,9 +23,7 @@ pub fn get_create_address(call: &CreateInputs, nonce: u64) -> Address { match call.scheme { CreateScheme::Create => call.caller.create(nonce), CreateScheme::Create2 { salt } => { - let init_code = alloy_primitives::Bytes(call.init_code.0.clone()); - let init_code_hash = alloy_primitives::keccak256(init_code); - call.caller.create2(B256::from(salt), init_code_hash) + call.caller.create2_from_code(B256::from(salt), call.init_code.clone()) } } } From fb64d10a913a2951c7976d233449b36f9afe1efb Mon Sep 17 00:00:00 2001 From: Enrique Ortiz Date: Fri, 15 Sep 2023 10:11:43 -0400 Subject: [PATCH 06/10] borrow it brah --- crates/evm/src/executor/inspector/utils.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/evm/src/executor/inspector/utils.rs b/crates/evm/src/executor/inspector/utils.rs index b657e7a32724..5b0659e4944a 100644 --- a/crates/evm/src/executor/inspector/utils.rs +++ b/crates/evm/src/executor/inspector/utils.rs @@ -23,7 +23,7 @@ pub fn get_create_address(call: &CreateInputs, nonce: u64) -> Address { match call.scheme { CreateScheme::Create => call.caller.create(nonce), CreateScheme::Create2 { salt } => { - call.caller.create2_from_code(B256::from(salt), call.init_code.clone()) + call.caller.create2_from_code(B256::from(salt), &call.init_code) } } } From a1fe075f764a79e636ab6237cc9ce2858ff9d31a Mon Sep 17 00:00:00 2001 From: Enrique Ortiz Date: Fri, 15 Sep 2023 10:14:40 -0400 Subject: [PATCH 07/10] chore: use from word --- crates/evm/src/executor/inspector/access_list.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/evm/src/executor/inspector/access_list.rs b/crates/evm/src/executor/inspector/access_list.rs index f65b53a53431..3611b2b898bd 100644 --- a/crates/evm/src/executor/inspector/access_list.rs +++ b/crates/evm/src/executor/inspector/access_list.rs @@ -1,3 +1,4 @@ +use alloy_primitives::FixedBytes; use ethers::types::transaction::eip2930::{AccessList, AccessListItem}; use hashbrown::{HashMap, HashSet}; use revm::{ @@ -68,7 +69,7 @@ impl Inspector for AccessListTracer { opcode::BALANCE | opcode::SELFDESTRUCT => { if let Ok(slot) = interpreter.stack().peek(0) { - let addr: Address = Address::from_slice(&slot.to_be_bytes::<32>()[12..]); + let addr: Address = Address::from_word(slot.to_be_bytes::<32>().into()); if !self.excluded.contains(&addr) { self.access_list.entry(addr).or_default(); } From 10899ee825ef56c76462d423f5f862dfd223bc99 Mon Sep 17 00:00:00 2001 From: Enrique Ortiz Date: Fri, 15 Sep 2023 10:46:08 -0400 Subject: [PATCH 08/10] chore: drop to_be_bytes --- crates/evm/src/executor/inspector/access_list.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/evm/src/executor/inspector/access_list.rs b/crates/evm/src/executor/inspector/access_list.rs index 3611b2b898bd..11e2ff7ad3ed 100644 --- a/crates/evm/src/executor/inspector/access_list.rs +++ b/crates/evm/src/executor/inspector/access_list.rs @@ -1,4 +1,4 @@ -use alloy_primitives::FixedBytes; + use ethers::types::transaction::eip2930::{AccessList, AccessListItem}; use hashbrown::{HashMap, HashSet}; use revm::{ @@ -69,7 +69,7 @@ impl Inspector for AccessListTracer { opcode::BALANCE | opcode::SELFDESTRUCT => { if let Ok(slot) = interpreter.stack().peek(0) { - let addr: Address = Address::from_word(slot.to_be_bytes::<32>().into()); + let addr: Address = Address::from_word(slot.into()); if !self.excluded.contains(&addr) { self.access_list.entry(addr).or_default(); } From 0d980e7dd3d74165cda4692e2377120f38fcba98 Mon Sep 17 00:00:00 2001 From: Enrique Ortiz Date: Fri, 15 Sep 2023 11:02:22 -0400 Subject: [PATCH 09/10] fmt --- crates/evm/src/executor/inspector/access_list.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/evm/src/executor/inspector/access_list.rs b/crates/evm/src/executor/inspector/access_list.rs index 11e2ff7ad3ed..0af0335734de 100644 --- a/crates/evm/src/executor/inspector/access_list.rs +++ b/crates/evm/src/executor/inspector/access_list.rs @@ -1,4 +1,3 @@ - use ethers::types::transaction::eip2930::{AccessList, AccessListItem}; use hashbrown::{HashMap, HashSet}; use revm::{ From 12d2de92868e22e9237d93cda654dc127420ea9b Mon Sep 17 00:00:00 2001 From: Enrique Ortiz Date: Fri, 15 Sep 2023 11:13:56 -0400 Subject: [PATCH 10/10] chore: use from_word on both palces --- crates/evm/src/executor/inspector/access_list.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/evm/src/executor/inspector/access_list.rs b/crates/evm/src/executor/inspector/access_list.rs index 0af0335734de..e33452fa1cc1 100644 --- a/crates/evm/src/executor/inspector/access_list.rs +++ b/crates/evm/src/executor/inspector/access_list.rs @@ -76,7 +76,7 @@ impl Inspector for AccessListTracer { } opcode::DELEGATECALL | opcode::CALL | opcode::STATICCALL | opcode::CALLCODE => { if let Ok(slot) = interpreter.stack().peek(1) { - let addr: Address = Address::from_slice(&slot.to_be_bytes::<32>()[12..]); + let addr: Address = Address::from_word(slot.into()); if !self.excluded.contains(&addr) { self.access_list.entry(addr).or_default(); }