Skip to content

Commit

Permalink
(#1) Alloy Migration: first batch (type conversions) (foundry-rs#5768)
Browse files Browse the repository at this point in the history
* feat: use alloy revm branch

* fuzz/mod migrated

* progress

* progress, fmt

* fix imdb

* feat: cheatcodes compile

* feat: fork backend compiles

* feat: trace

* fuzz

* anvil progress

* chore: mem, fmt

* chore: db.rs

* chore: it lives

* fix test

* chore: clippy

* workin

* main backend stuff migrated

* chore: add glue on other crates

* chore: make executor use alloy types

* add glue for executor migration

* chore: use workspace alloy

* chore: undo revm bump changes

* chore: remove unneded prefix

* chore: fix fork fixture

* chore: uncomment tests

* chore: switch to up-to-date revm

* chore: clippy

* (#2) Alloy Migration: Migrate non-cheatcode inspectors (foundry-rs#5770)

* feat: migrate non-cheatcode inspectors

* fix: properly create both create and create2 addresses

* chore: clippy

* (#3) Alloy Migration: migrate fork-adjacent files to alloy primitives (foundry-rs#5771)

* chore: use create2_from_code

* borrow it brah

* chore: use from word

* chore: drop to_be_bytes

* fmt

* chore: use from_word on both palces

* chore: use address::random

* chore: make failure slot b256

* chore: use address::random

* chore: fix indexes

* chore: use contract.hash

* chore: do not collect

* chore: use display on alloy nums

* use + operator

* chore: unwrap bytes and replace import

* chore: Into:: -> ::from

* chore: fix test

* chore: use alloy imports

* chore: switch to alloy typesd

* chore: fix test
  • Loading branch information
Evalir authored Sep 18, 2023
1 parent ecf9a10 commit 49f4530
Show file tree
Hide file tree
Showing 85 changed files with 1,170 additions and 903 deletions.
200 changes: 125 additions & 75 deletions Cargo.lock

Large diffs are not rendered by default.

10 changes: 6 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,8 @@ hex = { package = "const-hex", version = "1.6", features = ["hex"] }
itertools = "0.11"
solang-parser = "=0.3.2"

alloy-primitives = { version = "0.3", default-features = false }

#[patch."https://github.com/gakonst/ethers-rs"]
#ethers = { path = "../ethers-rs/ethers" }
#ethers-addressbook = { path = "../ethers-rs/ethers-addressbook" }
Expand All @@ -167,7 +169,7 @@ solang-parser = "=0.3.2"
#ethers-solc = { path = "../ethers-rs/ethers-solc" }

[patch.crates-io]
revm = { git = "https://github.com/bluealloy/revm/", rev = "429da731cd8efdc0939ed912240b2667b9155834" }
revm-interpreter = { git = "https://github.com/bluealloy/revm/", rev = "429da731cd8efdc0939ed912240b2667b9155834" }
revm-precompile = { git = "https://github.com/bluealloy/revm/", rev = "429da731cd8efdc0939ed912240b2667b9155834" }
revm-primitives = { git = "https://github.com/bluealloy/revm/", rev = "429da731cd8efdc0939ed912240b2667b9155834" }
revm = { git = "https://github.com/Evalir/revm/", branch = "reintroduce-alloy-rebased" }
revm-interpreter = { git = "https://github.com/Evalir/revm/", branch = "reintroduce-alloy-rebased" }
revm-precompile = { git = "https://github.com/Evalir/revm/", branch = "reintroduce-alloy-rebased" }
revm-primitives = { git = "https://github.com/Evalir/revm/", branch = "reintroduce-alloy-rebased" }
1 change: 1 addition & 0 deletions crates/anvil/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ ethers = { workspace = true, features = ["rustls", "ws", "ipc"] }
trie-db = { version = "0.23" }
hash-db = { version = "0.15" }
memory-db = { version = "0.29" }
alloy-primitives = { workspace = true, default-features = false, features = ["std", "serde"] }

# axum related
axum = { version = "0.5", features = ["ws"] }
Expand Down
2 changes: 2 additions & 0 deletions crates/anvil/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ repository.workspace = true
foundry-evm = { path = "../../evm" }
revm = { workspace = true, default-features = false, features = ["std", "serde", "memory_limit"] }


alloy-primitives = { workspace = true, default-features = false, features = ["std", "serde"] }
ethers-core.workspace = true
serde = { version = "1", features = ["derive"], optional = true }
serde_json = "1"
Expand Down
3 changes: 2 additions & 1 deletion crates/anvil/core/src/eth/proof.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use ethers_core::{
types::{H256, U256},
utils::rlp,
};
use foundry_evm::utils::b256_to_h256;
use revm::primitives::KECCAK_EMPTY;
// reexport for convenience
pub use ethers_core::types::{EIP1186ProofResponse as AccountProof, StorageProof};
Expand All @@ -28,7 +29,7 @@ impl Default for BasicAccount {
BasicAccount {
balance: 0.into(),
nonce: 0.into(),
code_hash: KECCAK_EMPTY.into(),
code_hash: b256_to_h256(KECCAK_EMPTY),
storage_root: KECCAK_NULL_RLP,
}
}
Expand Down
10 changes: 5 additions & 5 deletions crates/anvil/core/src/eth/receipt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use ethers_core::{
rlp::{Decodable, DecoderError, Encodable, Rlp, RlpStream},
},
};
use foundry_evm::utils::{b256_to_h256, h256_to_b256};
use foundry_evm::utils::{b160_to_h160, b256_to_h256, h160_to_b160, h256_to_b256};

#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "fastrlp", derive(open_fastrlp::RlpEncodable, open_fastrlp::RlpDecodable))]
Expand All @@ -21,9 +21,9 @@ impl From<revm::primitives::Log> for Log {
fn from(log: revm::primitives::Log) -> Self {
let revm::primitives::Log { address, topics, data } = log;
Log {
address: address.into(),
address: b160_to_h160(address),
topics: topics.into_iter().map(b256_to_h256).collect(),
data: data.into(),
data: ethers_core::types::Bytes(data.0),
}
}
}
Expand All @@ -32,9 +32,9 @@ impl From<Log> for revm::primitives::Log {
fn from(log: Log) -> Self {
let Log { address, topics, data } = log;
revm::primitives::Log {
address: address.into(),
address: h160_to_b160(address),
topics: topics.into_iter().map(h256_to_b256).collect(),
data: data.0,
data: alloy_primitives::Bytes(data.0),
}
}
}
Expand Down
33 changes: 18 additions & 15 deletions crates/anvil/core/src/eth/transaction/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@ use ethers_core::{
rlp::{Decodable, DecoderError, Encodable, Rlp, RlpStream},
},
};
use foundry_evm::trace::CallTraceArena;
use foundry_evm::{
trace::CallTraceArena,
utils::{h160_to_b160, u256_to_ru256},
};
use revm::{
interpreter::InstructionResult,
primitives::{CreateScheme, TransactTo, TxEnv},
Expand Down Expand Up @@ -1185,7 +1188,7 @@ impl PendingTransaction {
pub fn to_revm_tx_env(&self) -> TxEnv {
fn transact_to(kind: &TransactionKind) -> TransactTo {
match kind {
TransactionKind::Call(c) => TransactTo::Call((*c).into()),
TransactionKind::Call(c) => TransactTo::Call(h160_to_b160(*c)),
TransactionKind::Create => TransactTo::Create(CreateScheme::Create),
}
}
Expand All @@ -1196,13 +1199,13 @@ impl PendingTransaction {
let chain_id = tx.chain_id();
let LegacyTransaction { nonce, gas_price, gas_limit, value, kind, input, .. } = tx;
TxEnv {
caller: caller.into(),
caller: h160_to_b160(caller),
transact_to: transact_to(kind),
data: input.0.clone(),
data: alloy_primitives::Bytes(input.0.clone()),
chain_id,
nonce: Some(nonce.as_u64()),
value: (*value).into(),
gas_price: (*gas_price).into(),
value: u256_to_ru256(*value),
gas_price: u256_to_ru256(*gas_price),
gas_priority_fee: None,
gas_limit: gas_limit.as_u64(),
access_list: vec![],
Expand All @@ -1221,13 +1224,13 @@ impl PendingTransaction {
..
} = tx;
TxEnv {
caller: caller.into(),
caller: h160_to_b160(caller),
transact_to: transact_to(kind),
data: input.0.clone(),
data: alloy_primitives::Bytes(input.0.clone()),
chain_id: Some(*chain_id),
nonce: Some(nonce.as_u64()),
value: (*value).into(),
gas_price: (*gas_price).into(),
value: u256_to_ru256(*value),
gas_price: u256_to_ru256(*gas_price),
gas_priority_fee: None,
gas_limit: gas_limit.as_u64(),
access_list: to_revm_access_list(access_list.0.clone()),
Expand All @@ -1247,14 +1250,14 @@ impl PendingTransaction {
..
} = tx;
TxEnv {
caller: caller.into(),
caller: h160_to_b160(caller),
transact_to: transact_to(kind),
data: input.0.clone(),
data: alloy_primitives::Bytes(input.0.clone()),
chain_id: Some(*chain_id),
nonce: Some(nonce.as_u64()),
value: (*value).into(),
gas_price: (*max_fee_per_gas).into(),
gas_priority_fee: Some((*max_priority_fee_per_gas).into()),
value: u256_to_ru256(*value),
gas_price: u256_to_ru256(*max_fee_per_gas),
gas_priority_fee: Some(u256_to_ru256(*max_priority_fee_per_gas)),
gas_limit: gas_limit.as_u64(),
access_list: to_revm_access_list(access_list.0.clone()),
}
Expand Down
4 changes: 2 additions & 2 deletions crates/anvil/core/src/eth/utils.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use alloy_primitives::{Address as rAddress, U256 as rU256};
use ethers_core::{
types::{transaction::eip2930::AccessListItem, Address, U256},
utils::{
Expand All @@ -6,7 +7,6 @@ use ethers_core::{
},
};
use foundry_evm::utils::{h160_to_b160, h256_to_u256_be, u256_to_ru256};
use revm::primitives::{B160, U256 as rU256};

pub fn enveloped<T: Encodable>(id: u8, v: &T, s: &mut RlpStream) {
let encoded = rlp::encode(v);
Expand All @@ -22,7 +22,7 @@ pub fn to_access_list(list: Vec<AccessListItem>) -> Vec<(Address, Vec<U256>)> {
.collect()
}

pub fn to_revm_access_list(list: Vec<AccessListItem>) -> Vec<(B160, Vec<rU256>)> {
pub fn to_revm_access_list(list: Vec<AccessListItem>) -> Vec<(rAddress, Vec<rU256>)> {
list.into_iter()
.map(|item| {
(
Expand Down
16 changes: 9 additions & 7 deletions crates/anvil/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,9 @@ use foundry_evm::{
},
revm,
revm::primitives::{BlockEnv, CfgEnv, SpecId, TxEnv, U256 as rU256},
utils::{apply_chain_and_block_specific_env_changes, h256_to_b256, u256_to_ru256},
utils::{
apply_chain_and_block_specific_env_changes, b160_to_h160, h256_to_b256, u256_to_ru256,
},
};
use parking_lot::RwLock;
use serde_json::{json, to_writer, Value};
Expand Down Expand Up @@ -795,8 +797,8 @@ impl NodeConfig {
let mut env = revm::primitives::Env {
cfg,
block: BlockEnv {
gas_limit: self.gas_limit.into(),
basefee: self.get_base_fee().into(),
gas_limit: u256_to_ru256(self.gas_limit),
basefee: u256_to_ru256(self.get_base_fee()),
..Default::default()
},
tx: TxEnv { chain_id: self.get_chain_id().into(), ..Default::default() },
Expand Down Expand Up @@ -884,8 +886,8 @@ latest block number: {latest_block}"

env.block = BlockEnv {
number: rU256::from(fork_block_number),
timestamp: block.timestamp.into(),
difficulty: block.difficulty.into(),
timestamp: u256_to_ru256(block.timestamp),
difficulty: u256_to_ru256(block.difficulty),
// ensures prevrandao is set
prevrandao: Some(block.mix_hash.unwrap_or_default()).map(h256_to_b256),
gas_limit,
Expand Down Expand Up @@ -992,7 +994,7 @@ latest block number: {latest_block}"

let genesis = GenesisConfig {
timestamp: self.get_genesis_timestamp(),
balance: self.genesis_balance.into(),
balance: u256_to_ru256(self.genesis_balance),
accounts: self.genesis_accounts.iter().map(|acc| acc.address()).collect(),
fork_genesis_account_infos: Arc::new(Default::default()),
genesis_init: self.genesis.clone(),
Expand All @@ -1016,7 +1018,7 @@ latest block number: {latest_block}"
// if the option is not disabled and we are not forking.
if !self.disable_default_create2_deployer && self.eth_rpc_url.is_none() {
backend
.set_create2_deployer(DEFAULT_CREATE2_DEPLOYER)
.set_create2_deployer(b160_to_h160(DEFAULT_CREATE2_DEPLOYER))
.await
.expect("Failed to create default create2 deployer");
}
Expand Down
3 changes: 2 additions & 1 deletion crates/anvil/src/eth/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ use foundry_evm::{
interpreter::{return_ok, return_revert, InstructionResult},
primitives::BlockEnv,
},
utils::ru256_to_u256,
};
use futures::channel::mpsc::Receiver;
use parking_lot::RwLock;
Expand Down Expand Up @@ -2062,7 +2063,7 @@ impl EthApi {

// get the highest possible gas limit, either the request's set value or the currently
// configured gas limit
let mut highest_gas_limit = request.gas.unwrap_or(block_env.gas_limit.into());
let mut highest_gas_limit = request.gas.unwrap_or(ru256_to_u256(block_env.gas_limit));

// check with the funds of the sender
if let Some(from) = request.from {
Expand Down
28 changes: 16 additions & 12 deletions crates/anvil/src/eth/backend/db.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! Helper types for working with [revm](foundry_evm::revm)
use crate::{mem::state::trie_hash_db, revm::primitives::AccountInfo, U256};
use alloy_primitives::{Address as B160, B256, U256 as rU256};
use anvil_core::eth::trie::KeccakHasher;
use ethers::{
prelude::{Address, Bytes},
Expand All @@ -15,9 +16,10 @@ use foundry_evm::{
},
revm::{
db::{CacheDB, DbAccount},
primitives::{Bytecode, B160, B256, KECCAK_EMPTY, U256 as rU256},
primitives::{Bytecode, KECCAK_EMPTY},
Database, DatabaseCommit,
},
utils::{h160_to_b160, h256_to_b256, u256_to_ru256},
HashMap,
};
use hash_db::HashDB;
Expand Down Expand Up @@ -84,30 +86,30 @@ pub trait Db:

/// Sets the nonce of the given address
fn set_nonce(&mut self, address: Address, nonce: u64) -> DatabaseResult<()> {
let mut info = self.basic(address.into())?.unwrap_or_default();
let mut info = self.basic(h160_to_b160(address))?.unwrap_or_default();
info.nonce = nonce;
self.insert_account(address, info);
Ok(())
}

/// Sets the balance of the given address
fn set_balance(&mut self, address: Address, balance: U256) -> DatabaseResult<()> {
let mut info = self.basic(address.into())?.unwrap_or_default();
info.balance = balance.into();
let mut info = self.basic(h160_to_b160(address))?.unwrap_or_default();
info.balance = u256_to_ru256(balance);
self.insert_account(address, info);
Ok(())
}

/// Sets the balance of the given address
fn set_code(&mut self, address: Address, code: Bytes) -> DatabaseResult<()> {
let mut info = self.basic(address.into())?.unwrap_or_default();
let mut info = self.basic(h160_to_b160(address))?.unwrap_or_default();
let code_hash = if code.as_ref().is_empty() {
KECCAK_EMPTY
} else {
B256::from_slice(&keccak256(code.as_ref())[..])
};
info.code_hash = code_hash;
info.code = Some(Bytecode::new_raw(code.0).to_checked());
info.code = Some(Bytecode::new_raw(alloy_primitives::Bytes(code.0)).to_checked());
self.insert_account(address, info);
Ok(())
}
Expand All @@ -124,7 +126,7 @@ pub trait Db:
/// Deserialize and add all chain data to the backend storage
fn load_state(&mut self, state: SerializableState) -> DatabaseResult<bool> {
for (addr, account) in state.accounts.into_iter() {
let old_account_nonce = DatabaseRef::basic(self, addr.into())
let old_account_nonce = DatabaseRef::basic(self, h160_to_b160(addr))
.ok()
.and_then(|acc| acc.map(|acc| acc.nonce))
.unwrap_or_default();
Expand All @@ -135,12 +137,14 @@ pub trait Db:
self.insert_account(
addr,
AccountInfo {
balance: account.balance.into(),
balance: u256_to_ru256(account.balance),
code_hash: KECCAK_EMPTY, // will be set automatically
code: if account.code.0.is_empty() {
None
} else {
Some(Bytecode::new_raw(account.code.0).to_checked())
Some(
Bytecode::new_raw(alloy_primitives::Bytes(account.code.0)).to_checked(),
)
},
nonce,
},
Expand Down Expand Up @@ -176,15 +180,15 @@ pub trait Db:
/// [Backend::pending_block()](crate::eth::backend::mem::Backend::pending_block())
impl<T: DatabaseRef<Error = DatabaseError> + Send + Sync + Clone + fmt::Debug> Db for CacheDB<T> {
fn insert_account(&mut self, address: Address, account: AccountInfo) {
self.insert_account_info(address.into(), account)
self.insert_account_info(h160_to_b160(address), account)
}

fn set_storage_at(&mut self, address: Address, slot: U256, val: U256) -> DatabaseResult<()> {
self.insert_account_storage(address.into(), slot.into(), val.into())
self.insert_account_storage(h160_to_b160(address), u256_to_ru256(slot), u256_to_ru256(val))
}

fn insert_block_hash(&mut self, number: U256, hash: H256) {
self.block_hashes.insert(number.into(), hash.into());
self.block_hashes.insert(u256_to_ru256(number), h256_to_b256(hash));
}

fn dump_state(&self) -> DatabaseResult<Option<SerializableState>> {
Expand Down
14 changes: 7 additions & 7 deletions crates/anvil/src/eth/backend/executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,8 +170,8 @@ impl<'a, DB: Db + ?Sized, Validator: TransactionValidator> TransactionExecutor<'
traces: CallTraceArena { arena: traces },
exit,
out: match out {
Some(Output::Call(b)) => Some(b.into()),
Some(Output::Create(b, _)) => Some(b.into()),
Some(Output::Call(b)) => Some(ethers::types::Bytes(b.0)),
Some(Output::Create(b, _)) => Some(ethers::types::Bytes(b.0)),
_ => None,
},
};
Expand All @@ -190,15 +190,15 @@ impl<'a, DB: Db + ?Sized, Validator: TransactionValidator> TransactionExecutor<'
state_root: self.db.maybe_state_root().unwrap_or_default(),
receipts_root,
logs_bloom: bloom,
difficulty: difficulty.into(),
number: block_number.into(),
gas_limit: gas_limit.into(),
difficulty: ru256_to_u256(difficulty),
number: ru256_to_u256(block_number),
gas_limit: ru256_to_u256(gas_limit),
gas_used: cumulative_gas_used,
timestamp,
extra_data: Default::default(),
mix_hash: Default::default(),
nonce: Default::default(),
base_fee: base_fee.map(|x| x.into()),
base_fee: base_fee.map(ru256_to_u256),
};

let block = Block::new(partial_header, transactions.clone(), ommers);
Expand Down Expand Up @@ -238,7 +238,7 @@ impl<'a, 'b, DB: Db + ?Sized, Validator: TransactionValidator> Iterator
let env = self.env_for(&transaction.pending_transaction);
// check that we comply with the block's gas limit
let max_gas = self.gas_used.saturating_add(U256::from(env.tx.gas_limit));
if max_gas > env.block.gas_limit.into() {
if max_gas > ru256_to_u256(env.block.gas_limit) {
return Some(TransactionExecutionOutcome::Exhausted(transaction))
}

Expand Down
Loading

0 comments on commit 49f4530

Please sign in to comment.