Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: more alloy cleanups #6226

Merged
merged 1 commit into from
Nov 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 4 additions & 11 deletions crates/anvil/core/src/eth/utils.rs
Original file line number Diff line number Diff line change
@@ -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<T: Encodable>(id: u8, v: &T, s: &mut RlpStream) {
Expand All @@ -17,18 +16,12 @@ pub fn enveloped<T: Encodable>(id: u8, v: &T, s: &mut RlpStream) {
out.rlp_append(s)
}

pub fn to_access_list(list: Vec<AccessListItem>) -> Vec<(Address, Vec<U256>)> {
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<AccessListItem>) -> Vec<(aAddress, Vec<rU256>)> {
pub fn to_revm_access_list(list: Vec<AccessListItem>) -> Vec<(Address, Vec<U256>)> {
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()
Expand Down
3 changes: 1 addition & 2 deletions crates/cast/bin/cmd/logs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)";
Expand Down
56 changes: 27 additions & 29 deletions crates/cast/bin/cmd/wallet/vanity.rs
Original file line number Diff line number Diff line change
@@ -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)]
Expand Down Expand Up @@ -47,15 +46,15 @@ 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}"))?);
}
}

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}$"))?);
Expand Down Expand Up @@ -140,7 +139,6 @@ pub fn find_vanity_address_with_nonce<T: VanityMatcher>(
matcher: T,
nonce: u64,
) -> Option<LocalWallet> {
let nonce: U256 = nonce.into();
wallet_generator().find_any(create_nonce_matcher(matcher, nonce)).map(|(key, _)| key.into())
}

Expand All @@ -156,30 +154,30 @@ pub fn create_matcher<T: VanityMatcher>(matcher: T) -> impl Fn(&GeneratedWallet)
#[inline]
pub fn create_nonce_matcher<T: VanityMatcher>(
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<iter::Repeat<()>, fn(()) -> GeneratedWallet> {
iter::repeat(()).map(|_| generate_wallet())
pub fn wallet_generator() -> iter::Map<iter::Repeat<()>, 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.
Expand All @@ -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)
}
}
Expand All @@ -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)
}
}
Expand All @@ -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)
}
}
Expand All @@ -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))
}
}
Expand All @@ -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))
}
}
Expand All @@ -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)
}
}
Expand All @@ -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)
}
}
Expand Down
2 changes: 1 addition & 1 deletion crates/cli/src/opts/ethereum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]))
Expand Down
2 changes: 1 addition & 1 deletion crates/common/src/abi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
13 changes: 5 additions & 8 deletions crates/evm/evm/src/executors/invariant/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -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;
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -673,7 +670,7 @@ impl<'a> InvariantExecutor<'a> {
address,
func.clone(),
vec![],
rU256::ZERO,
U256::ZERO,
Some(abi),
) {
return f(call_result.result)
Expand All @@ -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<rAddress, revm::primitives::Account>,
state_changeset: &mut HashMap<Address, revm::primitives::Account>,
sender: &Address,
call_result: &RawCallResult,
fuzz_state: EvmFuzzState,
Expand Down
8 changes: 3 additions & 5 deletions crates/evm/traces/src/identifier/etherscan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<Vec<_>>();
Expand Down
5 changes: 3 additions & 2 deletions crates/forge/bin/cmd/script/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.)
Expand Down
Loading