Skip to content

Commit

Permalink
chore: some alloy cleanup (#5975)
Browse files Browse the repository at this point in the history
* chore: some alloy cleanup

* features

* fix

* chrono
  • Loading branch information
DaniPopes authored Oct 2, 2023
1 parent 5118b78 commit dd89d64
Show file tree
Hide file tree
Showing 41 changed files with 146 additions and 160 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 5 additions & 7 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -135,11 +135,10 @@ foundry-utils = { path = "crates/utils" }
foundry-debugger = { path = "crates/debugger" }

## revm
revm = { version = "3", default-features = false }
revm-primitives = { version = "1", default-features = false }
revm = "3"
revm-primitives = "1"

## ethers

ethers = { version = "2.0", default-features = false }
ethers-addressbook = { version = "2.0", default-features = false }
ethers-core = { version = "2.0", default-features = false }
Expand All @@ -152,10 +151,9 @@ ethers-etherscan = { version = "2.0", default-features = false }
ethers-solc = { version = "2.0", default-features = false }

## alloy

alloy-primitives = { version = "0.4", default-features = false }
alloy-dyn-abi = { version = "0.4", default-features = false }
alloy-json-abi = { version = "0.4", default-features = false }
alloy-primitives = "0.4"
alloy-dyn-abi = "0.4"
alloy-json-abi = "0.4"

solang-parser = "=0.3.2"

Expand Down
2 changes: 1 addition & 1 deletion crates/anvil/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +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"] }
alloy-primitives = { workspace = true, features = ["serde"] }

# axum related
axum = { version = "0.5", features = ["ws"] }
Expand Down
7 changes: 3 additions & 4 deletions crates/anvil/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,10 @@ repository.workspace = true
[dependencies]
# foundry internal
foundry-evm = { path = "../../evm" }
foundry-utils = { path = "../../utils"}
revm = { workspace = true, default-features = false, features = ["std", "serde", "memory_limit"] }
foundry-utils = { path = "../../utils" }
revm = { workspace = true, features = ["serde", "memory_limit"] }


alloy-primitives = { workspace = true, default-features = false, features = ["std", "serde"] }
alloy-primitives = { workspace = true, features = ["serde"] }
ethers-core.workspace = true
serde = { version = "1", features = ["derive"], optional = true }
serde_json = "1"
Expand Down
14 changes: 7 additions & 7 deletions crates/anvil/src/eth/backend/mem/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ use ethers::{
DefaultFrame, Filter, FilteredParams, GethDebugTracingOptions, GethTrace, Log, OtherFields,
Trace, Transaction, TransactionReceipt, H160,
},
utils::{get_contract_address, hex, keccak256, rlp},
utils::{hex, keccak256, rlp},
};
use flate2::{read::GzDecoder, write::GzEncoder, Compression};
use foundry_evm::{
Expand Down Expand Up @@ -1170,18 +1170,18 @@ impl Backend {
where
D: DatabaseRef<Error = DatabaseError>,
{
let from = request.from.unwrap_or_default();
let from = request.from.unwrap_or_default().to_alloy();
let to = if let Some(to) = request.to {
to
to.to_alloy()
} else {
let nonce = state.basic(from.to_alloy())?.unwrap_or_default().nonce;
get_contract_address(from, nonce)
let nonce = state.basic(from)?.unwrap_or_default().nonce;
from.create(nonce)
};

let mut tracer = AccessListTracer::new(
AccessList(request.access_list.clone().unwrap_or_default()),
from.to_alloy(),
to.to_alloy(),
from,
to,
self.precompiles().into_iter().map(|p| p.to_alloy()).collect(),
);

Expand Down
2 changes: 1 addition & 1 deletion crates/cast/bin/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ async fn main() -> Result<()> {
}
Subcommands::FromBin => {
let hex = stdin::read_bytes(false)?;
println!("0x{}", hex::encode(hex));
println!("{}", hex::encode_prefixed(hex));
}
Subcommands::ToHexdata { input } => {
let value = stdin::unwrap_line(input)?;
Expand Down
6 changes: 3 additions & 3 deletions crates/cast/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1441,7 +1441,7 @@ impl SimpleCast {
/// Encodes string into bytes32 value
pub fn format_bytes32_string(s: &str) -> Result<String> {
let formatted = format_bytes32_string(s)?;
Ok(format!("0x{}", hex::encode(formatted)))
Ok(hex::encode_prefixed(formatted))
}

/// Decodes string from bytes32 value
Expand Down Expand Up @@ -1933,7 +1933,7 @@ impl SimpleCast {
}
if optimize == 0 {
let selector = HumanReadableParser::parse_function(signature)?.short_signature();
return Ok((format!("0x{}", hex::encode(selector)), String::from(signature)))
return Ok((hex::encode_prefixed(selector), String::from(signature)))
}
let Some((name, params)) = signature.split_once('(') else {
eyre::bail!("Invalid signature");
Expand All @@ -1955,7 +1955,7 @@ impl SimpleCast {

if selector.iter().take_while(|&&byte| byte == 0).count() == optimize {
found.store(true, Ordering::Relaxed);
return Some((nonce, format!("0x{}", hex::encode(selector)), input))
return Some((nonce, hex::encode_prefixed(selector), input))
}

nonce += nonce_step;
Expand Down
2 changes: 1 addition & 1 deletion crates/cast/src/tx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ async fn resolve_name_args<M: Middleware>(args: &[String], provider: &M) -> Vec<
if arg.contains('.') {
let addr = provider.resolve_name(arg).await;
match addr {
Ok(addr) => format!("0x{}", hex::encode(addr.as_bytes())),
Ok(addr) => format!("{addr:?}"),
Err(_) => arg.to_string(),
}
} else {
Expand Down
8 changes: 4 additions & 4 deletions crates/chisel/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@ ethers.workspace = true
ethers-solc = { workspace = true, features = ["project-util", "full"] }

# alloy
alloy-dyn-abi = { workspace = true, default-features = false, features = ["std", "arbitrary"] }
alloy-primitives = { workspace = true, default-features = false, features = ["std", "serde", "getrandom", "arbitrary", "rlp"] }
alloy-json-abi = { workspace = true, default-features = false, features = ["std"]}
alloy-dyn-abi = { workspace = true, features = ["arbitrary"] }
alloy-primitives = { workspace = true, features = ["serde", "getrandom", "arbitrary", "rlp"] }
alloy-json-abi.workspace = true

# async
tokio = { version = "1", features = ["full"] }
Expand All @@ -49,7 +49,7 @@ serde = "1"
serde_json = { version = "1", features = ["raw_value"] }
semver = "1"
bytes = "1"
revm = { workspace = true, default-features = false, features = ["std"] }
revm.workspace = true
eyre = "0.6"
dirs = "5"
time = { version = "0.3", features = ["formatting"] }
Expand Down
7 changes: 3 additions & 4 deletions crates/chisel/src/dispatcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -421,9 +421,8 @@ impl ChiselDispatcher {
i,
i + 32
)),
Paint::cyan(format!(
"0x{}",
hex::encode(&mem.data()[i..i + 32])
Paint::cyan(hex::encode_prefixed(
&mem.data()[i..i + 32]
))
);
});
Expand Down Expand Up @@ -839,7 +838,7 @@ impl ChiselDispatcher {
// We can always safely unwrap here due to the regex matching.
let addr: Address = match_str.parse().expect("Valid address regex");
// Replace all occurrences of the address with a checksummed version
heap_input = heap_input.replace(match_str, &addr.to_checksum(None));
heap_input = heap_input.replace(match_str, &addr.to_string());
});
// Replace the old input with the formatted input.
input = &heap_input;
Expand Down
6 changes: 3 additions & 3 deletions crates/chisel/src/executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -319,13 +319,13 @@ impl SessionSource {
fn format_token(token: DynSolValue) -> String {
match token {
DynSolValue::Address(a) => {
format!("Type: {}\n└ Data: {}", Paint::red("address"), Paint::cyan(format!("0x{a:x}")))
format!("Type: {}\n└ Data: {}", Paint::red("address"), Paint::cyan(a.to_string()))
}
DynSolValue::FixedBytes(b, _) => {
format!(
"Type: {}\n└ Data: {}",
Paint::red(format!("bytes{}", b.len())),
Paint::cyan(format!("0x{}", hex::encode(b)))
Paint::cyan(hex::encode_prefixed(b))
)
}
DynSolValue::Int(i, _) => {
Expand All @@ -349,7 +349,7 @@ fn format_token(token: DynSolValue) -> String {
}
DynSolValue::String(_) | DynSolValue::Bytes(_) => {
let hex = hex::encode(token.abi_encode());
let s = token.as_str().map(|s| s.to_owned());
let s = token.as_str();
format!(
"Type: {}\n{}├ Hex (Memory):\n├─ Length ({}): {}\n├─ Contents ({}): {}\n├ Hex (Tuple Encoded):\n├─ Pointer ({}): {}\n├─ Length ({}): {}\n└─ Contents ({}): {}",
Paint::red(if s.is_some() { "string" } else { "dynamic bytes" }),
Expand Down
4 changes: 2 additions & 2 deletions crates/common/src/abi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,8 +160,8 @@ pub fn format_tokens(tokens: &[Token]) -> impl Iterator<Item = String> + '_ {
pub fn format_token(param: &Token) -> String {
match param {
Token::Address(addr) => to_checksum(addr, None),
Token::FixedBytes(bytes) => format!("0x{}", hex::encode(bytes)),
Token::Bytes(bytes) => format!("0x{}", hex::encode(bytes)),
Token::FixedBytes(bytes) => hex::encode_prefixed(bytes),
Token::Bytes(bytes) => hex::encode_prefixed(bytes),
Token::Int(num) => format!("{}", I256::from_raw(*num)),
Token::Uint(num) => format_uint_with_exponential_notation_hint(*num),
Token::Bool(b) => format!("{b}"),
Expand Down
2 changes: 1 addition & 1 deletion crates/config/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ repository.workspace = true
ethers-core.workspace = true
ethers-solc = { workspace = true, features = ["async", "svm-solc"] }
ethers-etherscan.workspace = true
revm-primitives = { workspace = true, default-features = false, features = ["std"] }
revm-primitives.workspace = true

# formats
Inflector = "0.11"
Expand Down
2 changes: 1 addition & 1 deletion crates/debugger/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,5 @@ alloy-primitives.workspace = true
crossterm = "0.26"
eyre = "0.6"
tracing = "0.1"
revm = { workspace = true, default-features = false,features = ["std", "serde", "arbitrary"] }
revm = { workspace = true, features = ["serde", "arbitrary"] }
ratatui = { version = "0.22.0", default-features = false, features = ["crossterm"] }
7 changes: 4 additions & 3 deletions crates/debugger/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -677,10 +677,11 @@ Line::from(Span::styled("[t]: stack labels | [m]: memory decoding | [shift + j/k
text_output.extend(Text::from("No sourcemap for contract"));
}
} else {
text_output.extend(Text::from("No srcmap index for contract {contract_name}"));
text_output
.extend(Text::from(format!("No srcmap index for contract {contract_name}")));
}
} else {
text_output.extend(Text::from(format!("Unknown contract at address {address:?}")));
text_output.extend(Text::from(format!("Unknown contract at address {address}")));
}

let paragraph =
Expand All @@ -700,7 +701,7 @@ Line::from(Span::styled("[t]: stack labels | [m]: memory decoding | [shift + j/k
) {
let block_source_code = Block::default()
.title(format!(
"Address: {:?} | PC: {} | Gas used in call: {}",
"Address: {} | PC: {} | Gas used in call: {}",
address,
if let Some(step) = debug_steps.get(current_step) {
step.pc.to_string()
Expand Down
3 changes: 1 addition & 2 deletions crates/doc/src/writer/buf_writer.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use ethers_core::utils::hex;
use itertools::Itertools;
use once_cell::sync::Lazy;
use solang_parser::pt::Parameter;
Expand Down Expand Up @@ -183,7 +182,7 @@ impl BufWriter {

let row = [
Markdown::Bold(&network).as_doc()?,
Markdown::Code(&format!("0x{}", hex::encode(deployment.address))).as_doc()?,
Markdown::Code(&format!("{:?}", deployment.address)).as_doc()?,
];
self.write_piped(&row.join("|"))?;
}
Expand Down
10 changes: 4 additions & 6 deletions crates/evm/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,18 +40,16 @@ once_cell = "1"
# EVM
bytes = "1"
hashbrown = { version = "0.13", features = ["serde"] }
revm = { workspace = true, default-features = false, features = [
"std",
revm = { workspace = true, features = [
"serde",
"memory_limit",
"optional_eip3607",
"optional_block_gas_limit",
"optional_no_base_fee",
"arbitrary"
"arbitrary",
] }

alloy-primitives = { workspace = true, default-features = false, features = ["std", "serde", "getrandom", "arbitrary", "rlp"] }
alloy-dyn-abi = { workspace = true, default-features = false, features = ["std", "arbitrary"] }
alloy-primitives = { workspace = true, features = ["serde", "getrandom", "arbitrary", "rlp"] }
alloy-dyn-abi = { workspace = true, features = ["arbitrary"] }

# Fuzzer
proptest = "1"
Expand Down
5 changes: 3 additions & 2 deletions crates/evm/src/decode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use crate::{
abi::ConsoleEvents::{self, *},
executor::inspector::cheatcodes::util::MAGIC_SKIP_BYTES,
};
use alloy_primitives::B256;
use ethers::{
abi::{decode, AbiDecode, Contract as Abi, ParamType, RawLog, Token},
contract::EthLogDecode,
Expand Down Expand Up @@ -33,7 +34,7 @@ pub fn decode_console_log(log: &Log) -> Option<String> {
LogBytesFilter(inner) => format!("{}", inner.0),
LogNamedAddressFilter(inner) => format!("{}: {:?}", inner.key, inner.val),
LogNamedBytes32Filter(inner) => {
format!("{}: 0x{}", inner.key, hex::encode(inner.val))
format!("{}: {}", inner.key, B256::new(inner.val))
}
LogNamedDecimalIntFilter(inner) => {
let (sign, val) = inner.val.into_sign_and_abs();
Expand All @@ -54,7 +55,7 @@ pub fn decode_console_log(log: &Log) -> Option<String> {
LogNamedIntFilter(inner) => format!("{}: {:?}", inner.key, inner.val),
LogNamedUintFilter(inner) => format!("{}: {:?}", inner.key, inner.val),
LogNamedBytesFilter(inner) => {
format!("{}: 0x{}", inner.key, hex::encode(inner.val))
format!("{}: {}", inner.key, inner.val)
}
LogNamedStringFilter(inner) => format!("{}: {}", inner.key, inner.val),
LogNamedArray1Filter(inner) => format!("{}: {:?}", inner.key, inner.val),
Expand Down
2 changes: 1 addition & 1 deletion crates/evm/src/executor/backend/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ pub struct NoCheatcodeAccessError(pub Address);

impl fmt::Display for NoCheatcodeAccessError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "No cheatcode access granted for: {:?}, see `vm.allowCheatcodes()`", self.0)
write!(f, "No cheatcode access granted for: {}, see `vm.allowCheatcodes()`", self.0)
}
}

Expand Down
2 changes: 1 addition & 1 deletion crates/evm/src/executor/inspector/cheatcodes/expect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ pub fn handle_expect_revert(
String::decode(data.0.as_ref())
.ok()
.or_else(|| std::str::from_utf8(data.as_ref()).ok().map(ToOwned::to_owned))
.unwrap_or_else(|| format!("0x{}", hex::encode(data)))
.unwrap_or_else(|| hex::encode_prefixed(data))
};
Err(fmt_err!(
"Error != expected error: {} != {}",
Expand Down
4 changes: 2 additions & 2 deletions crates/evm/src/executor/inspector/printer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ impl<DB: Database> Inspector<DB> for TracePrinter {
inputs: &mut CallInputs,
) -> (InstructionResult, Gas, Bytes) {
println!(
"SM CALL: {:?},context:{:?}, is_static:{:?}, transfer:{:?}, input_size:{:?}",
"SM CALL: {},context:{:?}, is_static:{:?}, transfer:{:?}, input_size:{:?}",
inputs.contract,
inputs.context,
inputs.is_static,
Expand All @@ -55,7 +55,7 @@ impl<DB: Database> Inspector<DB> for TracePrinter {
inputs: &mut CreateInputs,
) -> (InstructionResult, Option<Address>, Gas, Bytes) {
println!(
"CREATE CALL: caller:{:?}, scheme:{:?}, value:{:?}, init_code:{:?}, gas:{:?}",
"CREATE CALL: caller:{}, scheme:{:?}, value:{:?}, init_code:{:?}, gas:{:?}",
inputs.caller,
inputs.scheme,
inputs.value,
Expand Down
2 changes: 1 addition & 1 deletion crates/evm/src/fuzz/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -351,7 +351,7 @@ impl fmt::Display for BaseCounterExample {
if let Some(sig) = &self.signature {
write!(f, "calldata={}", &sig)?
} else {
write!(f, "calldata=0x{}", hex::encode(&self.calldata))?
write!(f, "calldata=0x{}", self.calldata)?
}

write!(f, ", args=[{args}]")
Expand Down
2 changes: 1 addition & 1 deletion crates/evm/src/trace/identifier/signatures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ impl SignaturesIdentifier {
SelectorType::Event => &mut self.cached.events,
};

let hex_identifier = format!("0x{}", hex::encode(identifier));
let hex_identifier = hex::encode_prefixed(identifier);

if !self.offline && !map.contains_key(&hex_identifier) {
if let Ok(signatures) =
Expand Down
Loading

0 comments on commit dd89d64

Please sign in to comment.