Skip to content

Commit 49f4530

Browse files
authored
(#1) Alloy Migration: first batch (type conversions) (foundry-rs#5768)
* 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
1 parent ecf9a10 commit 49f4530

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

85 files changed

+1170
-903
lines changed

Cargo.lock

+125-75
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

+6-4
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,8 @@ hex = { package = "const-hex", version = "1.6", features = ["hex"] }
154154
itertools = "0.11"
155155
solang-parser = "=0.3.2"
156156

157+
alloy-primitives = { version = "0.3", default-features = false }
158+
157159
#[patch."https://github.com/gakonst/ethers-rs"]
158160
#ethers = { path = "../ethers-rs/ethers" }
159161
#ethers-addressbook = { path = "../ethers-rs/ethers-addressbook" }
@@ -167,7 +169,7 @@ solang-parser = "=0.3.2"
167169
#ethers-solc = { path = "../ethers-rs/ethers-solc" }
168170

169171
[patch.crates-io]
170-
revm = { git = "https://github.com/bluealloy/revm/", rev = "429da731cd8efdc0939ed912240b2667b9155834" }
171-
revm-interpreter = { git = "https://github.com/bluealloy/revm/", rev = "429da731cd8efdc0939ed912240b2667b9155834" }
172-
revm-precompile = { git = "https://github.com/bluealloy/revm/", rev = "429da731cd8efdc0939ed912240b2667b9155834" }
173-
revm-primitives = { git = "https://github.com/bluealloy/revm/", rev = "429da731cd8efdc0939ed912240b2667b9155834" }
172+
revm = { git = "https://github.com/Evalir/revm/", branch = "reintroduce-alloy-rebased" }
173+
revm-interpreter = { git = "https://github.com/Evalir/revm/", branch = "reintroduce-alloy-rebased" }
174+
revm-precompile = { git = "https://github.com/Evalir/revm/", branch = "reintroduce-alloy-rebased" }
175+
revm-primitives = { git = "https://github.com/Evalir/revm/", branch = "reintroduce-alloy-rebased" }

crates/anvil/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ ethers = { workspace = true, features = ["rustls", "ws", "ipc"] }
3434
trie-db = { version = "0.23" }
3535
hash-db = { version = "0.15" }
3636
memory-db = { version = "0.29" }
37+
alloy-primitives = { workspace = true, default-features = false, features = ["std", "serde"] }
3738

3839
# axum related
3940
axum = { version = "0.5", features = ["ws"] }

crates/anvil/core/Cargo.toml

+2
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ repository.workspace = true
1414
foundry-evm = { path = "../../evm" }
1515
revm = { workspace = true, default-features = false, features = ["std", "serde", "memory_limit"] }
1616

17+
18+
alloy-primitives = { workspace = true, default-features = false, features = ["std", "serde"] }
1719
ethers-core.workspace = true
1820
serde = { version = "1", features = ["derive"], optional = true }
1921
serde_json = "1"

crates/anvil/core/src/eth/proof.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ use ethers_core::{
55
types::{H256, U256},
66
utils::rlp,
77
};
8+
use foundry_evm::utils::b256_to_h256;
89
use revm::primitives::KECCAK_EMPTY;
910
// reexport for convenience
1011
pub use ethers_core::types::{EIP1186ProofResponse as AccountProof, StorageProof};
@@ -28,7 +29,7 @@ impl Default for BasicAccount {
2829
BasicAccount {
2930
balance: 0.into(),
3031
nonce: 0.into(),
31-
code_hash: KECCAK_EMPTY.into(),
32+
code_hash: b256_to_h256(KECCAK_EMPTY),
3233
storage_root: KECCAK_NULL_RLP,
3334
}
3435
}

crates/anvil/core/src/eth/receipt.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use ethers_core::{
66
rlp::{Decodable, DecoderError, Encodable, Rlp, RlpStream},
77
},
88
};
9-
use foundry_evm::utils::{b256_to_h256, h256_to_b256};
9+
use foundry_evm::utils::{b160_to_h160, b256_to_h256, h160_to_b160, h256_to_b256};
1010

1111
#[derive(Clone, Debug, PartialEq, Eq)]
1212
#[cfg_attr(feature = "fastrlp", derive(open_fastrlp::RlpEncodable, open_fastrlp::RlpDecodable))]
@@ -21,9 +21,9 @@ impl From<revm::primitives::Log> for Log {
2121
fn from(log: revm::primitives::Log) -> Self {
2222
let revm::primitives::Log { address, topics, data } = log;
2323
Log {
24-
address: address.into(),
24+
address: b160_to_h160(address),
2525
topics: topics.into_iter().map(b256_to_h256).collect(),
26-
data: data.into(),
26+
data: ethers_core::types::Bytes(data.0),
2727
}
2828
}
2929
}
@@ -32,9 +32,9 @@ impl From<Log> for revm::primitives::Log {
3232
fn from(log: Log) -> Self {
3333
let Log { address, topics, data } = log;
3434
revm::primitives::Log {
35-
address: address.into(),
35+
address: h160_to_b160(address),
3636
topics: topics.into_iter().map(h256_to_b256).collect(),
37-
data: data.0,
37+
data: alloy_primitives::Bytes(data.0),
3838
}
3939
}
4040
}

crates/anvil/core/src/eth/transaction/mod.rs

+18-15
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,10 @@ use ethers_core::{
1414
rlp::{Decodable, DecoderError, Encodable, Rlp, RlpStream},
1515
},
1616
};
17-
use foundry_evm::trace::CallTraceArena;
17+
use foundry_evm::{
18+
trace::CallTraceArena,
19+
utils::{h160_to_b160, u256_to_ru256},
20+
};
1821
use revm::{
1922
interpreter::InstructionResult,
2023
primitives::{CreateScheme, TransactTo, TxEnv},
@@ -1185,7 +1188,7 @@ impl PendingTransaction {
11851188
pub fn to_revm_tx_env(&self) -> TxEnv {
11861189
fn transact_to(kind: &TransactionKind) -> TransactTo {
11871190
match kind {
1188-
TransactionKind::Call(c) => TransactTo::Call((*c).into()),
1191+
TransactionKind::Call(c) => TransactTo::Call(h160_to_b160(*c)),
11891192
TransactionKind::Create => TransactTo::Create(CreateScheme::Create),
11901193
}
11911194
}
@@ -1196,13 +1199,13 @@ impl PendingTransaction {
11961199
let chain_id = tx.chain_id();
11971200
let LegacyTransaction { nonce, gas_price, gas_limit, value, kind, input, .. } = tx;
11981201
TxEnv {
1199-
caller: caller.into(),
1202+
caller: h160_to_b160(caller),
12001203
transact_to: transact_to(kind),
1201-
data: input.0.clone(),
1204+
data: alloy_primitives::Bytes(input.0.clone()),
12021205
chain_id,
12031206
nonce: Some(nonce.as_u64()),
1204-
value: (*value).into(),
1205-
gas_price: (*gas_price).into(),
1207+
value: u256_to_ru256(*value),
1208+
gas_price: u256_to_ru256(*gas_price),
12061209
gas_priority_fee: None,
12071210
gas_limit: gas_limit.as_u64(),
12081211
access_list: vec![],
@@ -1221,13 +1224,13 @@ impl PendingTransaction {
12211224
..
12221225
} = tx;
12231226
TxEnv {
1224-
caller: caller.into(),
1227+
caller: h160_to_b160(caller),
12251228
transact_to: transact_to(kind),
1226-
data: input.0.clone(),
1229+
data: alloy_primitives::Bytes(input.0.clone()),
12271230
chain_id: Some(*chain_id),
12281231
nonce: Some(nonce.as_u64()),
1229-
value: (*value).into(),
1230-
gas_price: (*gas_price).into(),
1232+
value: u256_to_ru256(*value),
1233+
gas_price: u256_to_ru256(*gas_price),
12311234
gas_priority_fee: None,
12321235
gas_limit: gas_limit.as_u64(),
12331236
access_list: to_revm_access_list(access_list.0.clone()),
@@ -1247,14 +1250,14 @@ impl PendingTransaction {
12471250
..
12481251
} = tx;
12491252
TxEnv {
1250-
caller: caller.into(),
1253+
caller: h160_to_b160(caller),
12511254
transact_to: transact_to(kind),
1252-
data: input.0.clone(),
1255+
data: alloy_primitives::Bytes(input.0.clone()),
12531256
chain_id: Some(*chain_id),
12541257
nonce: Some(nonce.as_u64()),
1255-
value: (*value).into(),
1256-
gas_price: (*max_fee_per_gas).into(),
1257-
gas_priority_fee: Some((*max_priority_fee_per_gas).into()),
1258+
value: u256_to_ru256(*value),
1259+
gas_price: u256_to_ru256(*max_fee_per_gas),
1260+
gas_priority_fee: Some(u256_to_ru256(*max_priority_fee_per_gas)),
12581261
gas_limit: gas_limit.as_u64(),
12591262
access_list: to_revm_access_list(access_list.0.clone()),
12601263
}

crates/anvil/core/src/eth/utils.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use alloy_primitives::{Address as rAddress, U256 as rU256};
12
use ethers_core::{
23
types::{transaction::eip2930::AccessListItem, Address, U256},
34
utils::{
@@ -6,7 +7,6 @@ use ethers_core::{
67
},
78
};
89
use foundry_evm::utils::{h160_to_b160, h256_to_u256_be, u256_to_ru256};
9-
use revm::primitives::{B160, U256 as rU256};
1010

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

25-
pub fn to_revm_access_list(list: Vec<AccessListItem>) -> Vec<(B160, Vec<rU256>)> {
25+
pub fn to_revm_access_list(list: Vec<AccessListItem>) -> Vec<(rAddress, Vec<rU256>)> {
2626
list.into_iter()
2727
.map(|item| {
2828
(

crates/anvil/src/config.rs

+9-7
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,9 @@ use foundry_evm::{
3838
},
3939
revm,
4040
revm::primitives::{BlockEnv, CfgEnv, SpecId, TxEnv, U256 as rU256},
41-
utils::{apply_chain_and_block_specific_env_changes, h256_to_b256, u256_to_ru256},
41+
utils::{
42+
apply_chain_and_block_specific_env_changes, b160_to_h160, h256_to_b256, u256_to_ru256,
43+
},
4244
};
4345
use parking_lot::RwLock;
4446
use serde_json::{json, to_writer, Value};
@@ -795,8 +797,8 @@ impl NodeConfig {
795797
let mut env = revm::primitives::Env {
796798
cfg,
797799
block: BlockEnv {
798-
gas_limit: self.gas_limit.into(),
799-
basefee: self.get_base_fee().into(),
800+
gas_limit: u256_to_ru256(self.gas_limit),
801+
basefee: u256_to_ru256(self.get_base_fee()),
800802
..Default::default()
801803
},
802804
tx: TxEnv { chain_id: self.get_chain_id().into(), ..Default::default() },
@@ -884,8 +886,8 @@ latest block number: {latest_block}"
884886

885887
env.block = BlockEnv {
886888
number: rU256::from(fork_block_number),
887-
timestamp: block.timestamp.into(),
888-
difficulty: block.difficulty.into(),
889+
timestamp: u256_to_ru256(block.timestamp),
890+
difficulty: u256_to_ru256(block.difficulty),
889891
// ensures prevrandao is set
890892
prevrandao: Some(block.mix_hash.unwrap_or_default()).map(h256_to_b256),
891893
gas_limit,
@@ -992,7 +994,7 @@ latest block number: {latest_block}"
992994

993995
let genesis = GenesisConfig {
994996
timestamp: self.get_genesis_timestamp(),
995-
balance: self.genesis_balance.into(),
997+
balance: u256_to_ru256(self.genesis_balance),
996998
accounts: self.genesis_accounts.iter().map(|acc| acc.address()).collect(),
997999
fork_genesis_account_infos: Arc::new(Default::default()),
9981000
genesis_init: self.genesis.clone(),
@@ -1016,7 +1018,7 @@ latest block number: {latest_block}"
10161018
// if the option is not disabled and we are not forking.
10171019
if !self.disable_default_create2_deployer && self.eth_rpc_url.is_none() {
10181020
backend
1019-
.set_create2_deployer(DEFAULT_CREATE2_DEPLOYER)
1021+
.set_create2_deployer(b160_to_h160(DEFAULT_CREATE2_DEPLOYER))
10201022
.await
10211023
.expect("Failed to create default create2 deployer");
10221024
}

crates/anvil/src/eth/api.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ use foundry_evm::{
6464
interpreter::{return_ok, return_revert, InstructionResult},
6565
primitives::BlockEnv,
6666
},
67+
utils::ru256_to_u256,
6768
};
6869
use futures::channel::mpsc::Receiver;
6970
use parking_lot::RwLock;
@@ -2062,7 +2063,7 @@ impl EthApi {
20622063

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

20672068
// check with the funds of the sender
20682069
if let Some(from) = request.from {

crates/anvil/src/eth/backend/db.rs

+16-12
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
//! Helper types for working with [revm](foundry_evm::revm)
22
33
use crate::{mem::state::trie_hash_db, revm::primitives::AccountInfo, U256};
4+
use alloy_primitives::{Address as B160, B256, U256 as rU256};
45
use anvil_core::eth::trie::KeccakHasher;
56
use ethers::{
67
prelude::{Address, Bytes},
@@ -15,9 +16,10 @@ use foundry_evm::{
1516
},
1617
revm::{
1718
db::{CacheDB, DbAccount},
18-
primitives::{Bytecode, B160, B256, KECCAK_EMPTY, U256 as rU256},
19+
primitives::{Bytecode, KECCAK_EMPTY},
1920
Database, DatabaseCommit,
2021
},
22+
utils::{h160_to_b160, h256_to_b256, u256_to_ru256},
2123
HashMap,
2224
};
2325
use hash_db::HashDB;
@@ -84,30 +86,30 @@ pub trait Db:
8486

8587
/// Sets the nonce of the given address
8688
fn set_nonce(&mut self, address: Address, nonce: u64) -> DatabaseResult<()> {
87-
let mut info = self.basic(address.into())?.unwrap_or_default();
89+
let mut info = self.basic(h160_to_b160(address))?.unwrap_or_default();
8890
info.nonce = nonce;
8991
self.insert_account(address, info);
9092
Ok(())
9193
}
9294

9395
/// Sets the balance of the given address
9496
fn set_balance(&mut self, address: Address, balance: U256) -> DatabaseResult<()> {
95-
let mut info = self.basic(address.into())?.unwrap_or_default();
96-
info.balance = balance.into();
97+
let mut info = self.basic(h160_to_b160(address))?.unwrap_or_default();
98+
info.balance = u256_to_ru256(balance);
9799
self.insert_account(address, info);
98100
Ok(())
99101
}
100102

101103
/// Sets the balance of the given address
102104
fn set_code(&mut self, address: Address, code: Bytes) -> DatabaseResult<()> {
103-
let mut info = self.basic(address.into())?.unwrap_or_default();
105+
let mut info = self.basic(h160_to_b160(address))?.unwrap_or_default();
104106
let code_hash = if code.as_ref().is_empty() {
105107
KECCAK_EMPTY
106108
} else {
107109
B256::from_slice(&keccak256(code.as_ref())[..])
108110
};
109111
info.code_hash = code_hash;
110-
info.code = Some(Bytecode::new_raw(code.0).to_checked());
112+
info.code = Some(Bytecode::new_raw(alloy_primitives::Bytes(code.0)).to_checked());
111113
self.insert_account(address, info);
112114
Ok(())
113115
}
@@ -124,7 +126,7 @@ pub trait Db:
124126
/// Deserialize and add all chain data to the backend storage
125127
fn load_state(&mut self, state: SerializableState) -> DatabaseResult<bool> {
126128
for (addr, account) in state.accounts.into_iter() {
127-
let old_account_nonce = DatabaseRef::basic(self, addr.into())
129+
let old_account_nonce = DatabaseRef::basic(self, h160_to_b160(addr))
128130
.ok()
129131
.and_then(|acc| acc.map(|acc| acc.nonce))
130132
.unwrap_or_default();
@@ -135,12 +137,14 @@ pub trait Db:
135137
self.insert_account(
136138
addr,
137139
AccountInfo {
138-
balance: account.balance.into(),
140+
balance: u256_to_ru256(account.balance),
139141
code_hash: KECCAK_EMPTY, // will be set automatically
140142
code: if account.code.0.is_empty() {
141143
None
142144
} else {
143-
Some(Bytecode::new_raw(account.code.0).to_checked())
145+
Some(
146+
Bytecode::new_raw(alloy_primitives::Bytes(account.code.0)).to_checked(),
147+
)
144148
},
145149
nonce,
146150
},
@@ -176,15 +180,15 @@ pub trait Db:
176180
/// [Backend::pending_block()](crate::eth::backend::mem::Backend::pending_block())
177181
impl<T: DatabaseRef<Error = DatabaseError> + Send + Sync + Clone + fmt::Debug> Db for CacheDB<T> {
178182
fn insert_account(&mut self, address: Address, account: AccountInfo) {
179-
self.insert_account_info(address.into(), account)
183+
self.insert_account_info(h160_to_b160(address), account)
180184
}
181185

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

186190
fn insert_block_hash(&mut self, number: U256, hash: H256) {
187-
self.block_hashes.insert(number.into(), hash.into());
191+
self.block_hashes.insert(u256_to_ru256(number), h256_to_b256(hash));
188192
}
189193

190194
fn dump_state(&self) -> DatabaseResult<Option<SerializableState>> {

crates/anvil/src/eth/backend/executor.rs

+7-7
Original file line numberDiff line numberDiff line change
@@ -170,8 +170,8 @@ impl<'a, DB: Db + ?Sized, Validator: TransactionValidator> TransactionExecutor<'
170170
traces: CallTraceArena { arena: traces },
171171
exit,
172172
out: match out {
173-
Some(Output::Call(b)) => Some(b.into()),
174-
Some(Output::Create(b, _)) => Some(b.into()),
173+
Some(Output::Call(b)) => Some(ethers::types::Bytes(b.0)),
174+
Some(Output::Create(b, _)) => Some(ethers::types::Bytes(b.0)),
175175
_ => None,
176176
},
177177
};
@@ -190,15 +190,15 @@ impl<'a, DB: Db + ?Sized, Validator: TransactionValidator> TransactionExecutor<'
190190
state_root: self.db.maybe_state_root().unwrap_or_default(),
191191
receipts_root,
192192
logs_bloom: bloom,
193-
difficulty: difficulty.into(),
194-
number: block_number.into(),
195-
gas_limit: gas_limit.into(),
193+
difficulty: ru256_to_u256(difficulty),
194+
number: ru256_to_u256(block_number),
195+
gas_limit: ru256_to_u256(gas_limit),
196196
gas_used: cumulative_gas_used,
197197
timestamp,
198198
extra_data: Default::default(),
199199
mix_hash: Default::default(),
200200
nonce: Default::default(),
201-
base_fee: base_fee.map(|x| x.into()),
201+
base_fee: base_fee.map(ru256_to_u256),
202202
};
203203

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

0 commit comments

Comments
 (0)