From 934664b271edfd16fe7e46d1d755c123869b8be2 Mon Sep 17 00:00:00 2001 From: DaniPopes <57450786+DaniPopes@users.noreply.github.com> Date: Mon, 6 Nov 2023 21:43:05 +0100 Subject: [PATCH] chore: more alloy cleanups (#6226) --- crates/anvil/core/src/eth/utils.rs | 15 ++--- crates/cast/bin/cmd/logs.rs | 3 +- crates/cast/bin/cmd/wallet/vanity.rs | 56 +++++++++---------- crates/cli/src/opts/ethereum.rs | 2 +- crates/common/src/abi.rs | 2 +- crates/evm/evm/src/executors/invariant/mod.rs | 13 ++--- crates/evm/traces/src/identifier/etherscan.rs | 8 +-- crates/forge/bin/cmd/script/transaction.rs | 5 +- 8 files changed, 45 insertions(+), 59 deletions(-) diff --git a/crates/anvil/core/src/eth/utils.rs b/crates/anvil/core/src/eth/utils.rs index e15d494acacd..3e903e4270fd 100644 --- a/crates/anvil/core/src/eth/utils.rs +++ b/crates/anvil/core/src/eth/utils.rs @@ -1,12 +1,11 @@ -use alloy_primitives::{Address as aAddress, U256 as rU256}; +use alloy_primitives::{Address, U256}; use ethers_core::{ - types::{transaction::eip2930::AccessListItem, Address, U256}, + types::transaction::eip2930::AccessListItem, utils::{ rlp, rlp::{Encodable, RlpStream}, }, }; -use foundry_evm::utils::h256_to_u256_be; use foundry_utils::types::ToAlloy; pub fn enveloped(id: u8, v: &T, s: &mut RlpStream) { @@ -17,18 +16,12 @@ pub fn enveloped(id: u8, v: &T, s: &mut RlpStream) { out.rlp_append(s) } -pub fn to_access_list(list: Vec) -> Vec<(Address, Vec)> { - list.into_iter() - .map(|item| (item.address, item.storage_keys.into_iter().map(h256_to_u256_be).collect())) - .collect() -} - -pub fn to_revm_access_list(list: Vec) -> Vec<(aAddress, Vec)> { +pub fn to_revm_access_list(list: Vec) -> Vec<(Address, Vec)> { list.into_iter() .map(|item| { ( item.address.to_alloy(), - item.storage_keys.into_iter().map(|k| k.to_alloy()).map(|k| k.into()).collect(), + item.storage_keys.into_iter().map(|k| k.to_alloy().into()).collect(), ) }) .collect() diff --git a/crates/cast/bin/cmd/logs.rs b/crates/cast/bin/cmd/logs.rs index 94cf85b0bca8..f5fb351e0fd6 100644 --- a/crates/cast/bin/cmd/logs.rs +++ b/crates/cast/bin/cmd/logs.rs @@ -285,11 +285,10 @@ pub fn sanitize_token(token: Token) -> Token { #[cfg(test)] mod tests { - use std::str::FromStr; - use super::*; use ethers::types::H160; use ethers_core::types::H256; + use std::str::FromStr; const ADDRESS: &str = "0x4D1A2e2bB4F88F0250f26Ffff098B0b30B26BF38"; const TRANSFER_SIG: &str = "Transfer(address indexed,address indexed,uint256)"; diff --git a/crates/cast/bin/cmd/wallet/vanity.rs b/crates/cast/bin/cmd/wallet/vanity.rs index c5762a7b2428..2fbde4cca421 100644 --- a/crates/cast/bin/cmd/wallet/vanity.rs +++ b/crates/cast/bin/cmd/wallet/vanity.rs @@ -1,19 +1,18 @@ +use alloy_primitives::Address; use clap::{builder::TypedValueParser, Parser}; use ethers::{ - core::{k256::ecdsa::SigningKey, rand::thread_rng}, + core::{k256::ecdsa::SigningKey, rand}, prelude::{LocalWallet, Signer}, - types::{H160, U256}, - utils::{get_contract_address, secret_key_to_address}, + utils::secret_key_to_address, }; use eyre::Result; - use foundry_utils::types::ToAlloy; use rayon::iter::{self, ParallelIterator}; use regex::Regex; use std::time::Instant; /// Type alias for the result of [generate_wallet]. -pub type GeneratedWallet = (SigningKey, H160); +pub type GeneratedWallet = (SigningKey, Address); /// CLI arguments for `cast wallet vanity`. #[derive(Debug, Clone, Parser)] @@ -47,7 +46,7 @@ impl VanityArgs { let mut right_regex = None; if let Some(prefix) = starts_with { - if let Ok(decoded) = hex::decode(prefix.as_bytes()) { + if let Ok(decoded) = hex::decode(&prefix) { left_exact_hex = Some(decoded) } else { left_regex = Some(Regex::new(&format!(r"^{prefix}"))?); @@ -55,7 +54,7 @@ impl VanityArgs { } if let Some(suffix) = ends_with { - if let Ok(decoded) = hex::decode(suffix.as_bytes()) { + if let Ok(decoded) = hex::decode(&suffix) { right_exact_hex = Some(decoded) } else { right_regex = Some(Regex::new(&format!(r"{suffix}$"))?); @@ -140,7 +139,6 @@ pub fn find_vanity_address_with_nonce( matcher: T, nonce: u64, ) -> Option { - let nonce: U256 = nonce.into(); wallet_generator().find_any(create_nonce_matcher(matcher, nonce)).map(|(key, _)| key.into()) } @@ -156,30 +154,30 @@ pub fn create_matcher(matcher: T) -> impl Fn(&GeneratedWallet) #[inline] pub fn create_nonce_matcher( matcher: T, - nonce: U256, + nonce: u64, ) -> impl Fn(&GeneratedWallet) -> bool { move |(_, addr)| { - let contract_addr = get_contract_address(*addr, nonce); + let contract_addr = addr.create(nonce); matcher.is_match(&contract_addr) } } /// Returns an infinite parallel iterator which yields a [GeneratedWallet]. #[inline] -pub fn wallet_generator() -> iter::Map, fn(()) -> GeneratedWallet> { - iter::repeat(()).map(|_| generate_wallet()) +pub fn wallet_generator() -> iter::Map, impl Fn(()) -> GeneratedWallet> { + iter::repeat(()).map(|()| generate_wallet()) } /// Generates a random K-256 signing key and derives its Ethereum address. pub fn generate_wallet() -> GeneratedWallet { - let key = SigningKey::random(&mut thread_rng()); + let key = SigningKey::random(&mut rand::thread_rng()); let address = secret_key_to_address(&key); - (key, address) + (key, address.to_alloy()) } /// A trait to match vanity addresses. pub trait VanityMatcher: Send + Sync { - fn is_match(&self, addr: &H160) -> bool; + fn is_match(&self, addr: &Address) -> bool; } /// Matches start and end hex. @@ -190,8 +188,8 @@ pub struct HexMatcher { impl VanityMatcher for HexMatcher { #[inline] - fn is_match(&self, addr: &H160) -> bool { - let bytes = addr.as_bytes(); + fn is_match(&self, addr: &Address) -> bool { + let bytes = addr.as_slice(); bytes.starts_with(&self.left) && bytes.ends_with(&self.right) } } @@ -203,8 +201,8 @@ pub struct LeftHexMatcher { impl VanityMatcher for LeftHexMatcher { #[inline] - fn is_match(&self, addr: &H160) -> bool { - let bytes = addr.as_bytes(); + fn is_match(&self, addr: &Address) -> bool { + let bytes = addr.as_slice(); bytes.starts_with(&self.left) } } @@ -216,8 +214,8 @@ pub struct RightHexMatcher { impl VanityMatcher for RightHexMatcher { #[inline] - fn is_match(&self, addr: &H160) -> bool { - let bytes = addr.as_bytes(); + fn is_match(&self, addr: &Address) -> bool { + let bytes = addr.as_slice(); bytes.ends_with(&self.right) } } @@ -230,8 +228,8 @@ pub struct LeftExactRightRegexMatcher { impl VanityMatcher for LeftExactRightRegexMatcher { #[inline] - fn is_match(&self, addr: &H160) -> bool { - let bytes = addr.as_bytes(); + fn is_match(&self, addr: &Address) -> bool { + let bytes = addr.as_slice(); bytes.starts_with(&self.left) && self.right.is_match(&hex::encode(bytes)) } } @@ -244,8 +242,8 @@ pub struct LeftRegexRightExactMatcher { impl VanityMatcher for LeftRegexRightExactMatcher { #[inline] - fn is_match(&self, addr: &H160) -> bool { - let bytes = addr.as_bytes(); + fn is_match(&self, addr: &Address) -> bool { + let bytes = addr.as_slice(); bytes.ends_with(&self.right) && self.left.is_match(&hex::encode(bytes)) } } @@ -257,8 +255,8 @@ pub struct SingleRegexMatcher { impl VanityMatcher for SingleRegexMatcher { #[inline] - fn is_match(&self, addr: &H160) -> bool { - let addr = hex::encode(addr.as_ref()); + fn is_match(&self, addr: &Address) -> bool { + let addr = hex::encode(addr); self.re.is_match(&addr) } } @@ -271,8 +269,8 @@ pub struct RegexMatcher { impl VanityMatcher for RegexMatcher { #[inline] - fn is_match(&self, addr: &H160) -> bool { - let addr = hex::encode(addr.as_ref()); + fn is_match(&self, addr: &Address) -> bool { + let addr = hex::encode(addr); self.left.is_match(&addr) && self.right.is_match(&addr) } } diff --git a/crates/cli/src/opts/ethereum.rs b/crates/cli/src/opts/ethereum.rs index 96a82c31e1a8..78504e584800 100644 --- a/crates/cli/src/opts/ethereum.rs +++ b/crates/cli/src/opts/ethereum.rs @@ -160,7 +160,7 @@ impl figment::Provider for EthereumOpts { dict.extend(self.rpc.dict()); if let Some(from) = self.wallet.from { - dict.insert("sender".to_string(), format!("{from:?}").into()); + dict.insert("sender".to_string(), from.to_string().into()); } Ok(Map::from([(Config::selected_profile(), dict)])) diff --git a/crates/common/src/abi.rs b/crates/common/src/abi.rs index 955fa80ad99b..0bc960f1dbee 100644 --- a/crates/common/src/abi.rs +++ b/crates/common/src/abi.rs @@ -166,7 +166,7 @@ pub fn find_source( } else { let implementation = metadata.implementation.unwrap(); println!( - "Contract at {address} is a proxy, trying to fetch source at {implementation:?}..." + "Contract at {address} is a proxy, trying to fetch source at {implementation}..." ); match find_source(client, implementation).await { impl_source @ Ok(_) => impl_source, diff --git a/crates/evm/evm/src/executors/invariant/mod.rs b/crates/evm/evm/src/executors/invariant/mod.rs index d0c60f4b7720..2412a5df6056 100644 --- a/crates/evm/evm/src/executors/invariant/mod.rs +++ b/crates/evm/evm/src/executors/invariant/mod.rs @@ -4,7 +4,7 @@ use crate::{ }; use alloy_dyn_abi::DynSolValue; use alloy_json_abi::JsonAbi as Abi; -use alloy_primitives::{Address, FixedBytes}; +use alloy_primitives::{Address, FixedBytes, U256}; use eyre::{eyre, ContextCompat, Result}; use foundry_common::contracts::{ContractsByAddress, ContractsByArtifact}; use foundry_config::{FuzzDictionaryConfig, InvariantConfig}; @@ -28,10 +28,7 @@ use proptest::{ strategy::{BoxedStrategy, Strategy, ValueTree}, test_runner::{TestCaseError, TestRunner}, }; -use revm::{ - primitives::{Address as rAddress, HashMap, U256 as rU256}, - DatabaseCommit, -}; +use revm::{primitives::HashMap, DatabaseCommit}; use std::{cell::RefCell, collections::BTreeMap, sync::Arc}; mod error; @@ -160,7 +157,7 @@ impl<'a> InvariantExecutor<'a> { // Executes the call from the randomly generated sequence. let call_result = executor - .call_raw(*sender, *address, calldata.clone(), rU256::ZERO) + .call_raw(*sender, *address, calldata.clone(), U256::ZERO) .expect("could not make raw evm call"); // Collect data for fuzzing from the state changeset. @@ -673,7 +670,7 @@ impl<'a> InvariantExecutor<'a> { address, func.clone(), vec![], - rU256::ZERO, + U256::ZERO, Some(abi), ) { return f(call_result.result) @@ -693,7 +690,7 @@ impl<'a> InvariantExecutor<'a> { /// before inserting it into the dictionary. Otherwise, we flood the dictionary with /// randomly generated addresses. fn collect_data( - state_changeset: &mut HashMap, + state_changeset: &mut HashMap, sender: &Address, call_result: &RawCallResult, fuzz_state: EvmFuzzState, diff --git a/crates/evm/traces/src/identifier/etherscan.rs b/crates/evm/traces/src/identifier/etherscan.rs index 5bebbe2c9d0e..9a92b9ac7ba1 100644 --- a/crates/evm/traces/src/identifier/etherscan.rs +++ b/crates/evm/traces/src/identifier/etherscan.rs @@ -67,11 +67,9 @@ impl EtherscanIdentifier { let outputs_fut = contracts_iter .clone() .map(|(address, metadata)| { - println!("Compiling: {} {address:?}", metadata.contract_name); - let err_msg = format!( - "Failed to compile contract {} from {address:?}", - metadata.contract_name - ); + println!("Compiling: {} {address}", metadata.contract_name); + let err_msg = + format!("Failed to compile contract {} from {address}", metadata.contract_name); compile::compile_from_source(metadata).map_err(move |err| err.wrap_err(err_msg)) }) .collect::>(); diff --git a/crates/forge/bin/cmd/script/transaction.rs b/crates/forge/bin/cmd/script/transaction.rs index 93002e1aec9b..8c33fb6788d8 100644 --- a/crates/forge/bin/cmd/script/transaction.rs +++ b/crates/forge/bin/cmd/script/transaction.rs @@ -298,11 +298,12 @@ pub mod wrapper { // copied from https://github.com/gakonst/ethers-rs #[derive(Serialize, Deserialize)] struct WrappedLog { - /// H160. the contract that emitted the log + /// The contract address that emitted the log. #[serde(serialize_with = "serialize_addr")] pub address: Address, - /// topics: Array of 0 to 4 32 Bytes of indexed log arguments. + /// Array of 0 to 4 32 Bytes of indexed log arguments. + /// /// (In solidity: The first topic is the hash of the signature of the event /// (e.g. `Deposit(address,bytes32,uint256)`), except you declared the event /// with the anonymous specifier.)