From 16aebe2c365021c79aba41367c88c45963b6bc68 Mon Sep 17 00:00:00 2001 From: Enrique Ortiz Date: Tue, 13 Feb 2024 12:01:48 -0400 Subject: [PATCH 01/63] chore: make cast use an alloy provider --- Cargo.lock | 87 ++++++++++++++++-------------- crates/cast/bin/cmd/access_list.rs | 9 ++-- crates/cast/bin/cmd/call.rs | 3 +- crates/cast/bin/cmd/estimate.rs | 3 +- crates/cast/bin/cmd/find_block.rs | 3 +- crates/cast/bin/cmd/logs.rs | 3 +- crates/cast/bin/cmd/rpc.rs | 3 +- crates/cast/bin/cmd/send.rs | 9 +++- crates/cast/bin/cmd/storage.rs | 3 +- crates/cast/bin/main.rs | 53 +++++++++++------- crates/cast/src/lib.rs | 10 ++-- crates/cli/src/utils/mod.rs | 26 +++++++++ 12 files changed, 140 insertions(+), 72 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ec2e562b8f2f..b93e23d28dae 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -51,9 +51,9 @@ dependencies = [ [[package]] name = "ahash" -version = "0.8.7" +version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77c3a9648d43b9cd48db467b3f87fdd6e146bcc88ab0180006cef2179fe11d01" +checksum = "42cd52102d3df161c77a887b608d7a4897d7cc112886a9537b738a887a03aaff" dependencies = [ "cfg-if", "once_cell", @@ -90,7 +90,7 @@ dependencies = [ [[package]] name = "alloy-consensus" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#098ad5657d55bbc5fe9469ede2a9ca79def738f2" +source = "git+https://github.com/alloy-rs/alloy#a4453d42ffb755a46bace2ceca3baa454e0cd807" dependencies = [ "alloy-eips", "alloy-network", @@ -116,13 +116,13 @@ dependencies = [ "proptest", "serde", "serde_json", - "winnow", + "winnow 0.5.40", ] [[package]] name = "alloy-eips" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#098ad5657d55bbc5fe9469ede2a9ca79def738f2" +source = "git+https://github.com/alloy-rs/alloy#a4453d42ffb755a46bace2ceca3baa454e0cd807" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -133,7 +133,7 @@ dependencies = [ [[package]] name = "alloy-genesis" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#098ad5657d55bbc5fe9469ede2a9ca79def738f2" +source = "git+https://github.com/alloy-rs/alloy#a4453d42ffb755a46bace2ceca3baa454e0cd807" dependencies = [ "alloy-primitives", "alloy-rpc-types", @@ -155,7 +155,7 @@ dependencies = [ [[package]] name = "alloy-json-rpc" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#098ad5657d55bbc5fe9469ede2a9ca79def738f2" +source = "git+https://github.com/alloy-rs/alloy#a4453d42ffb755a46bace2ceca3baa454e0cd807" dependencies = [ "alloy-primitives", "serde", @@ -166,7 +166,7 @@ dependencies = [ [[package]] name = "alloy-network" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#098ad5657d55bbc5fe9469ede2a9ca79def738f2" +source = "git+https://github.com/alloy-rs/alloy#a4453d42ffb755a46bace2ceca3baa454e0cd807" dependencies = [ "alloy-eips", "alloy-json-rpc", @@ -205,7 +205,7 @@ dependencies = [ [[package]] name = "alloy-providers" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#098ad5657d55bbc5fe9469ede2a9ca79def738f2" +source = "git+https://github.com/alloy-rs/alloy#a4453d42ffb755a46bace2ceca3baa454e0cd807" dependencies = [ "alloy-network", "alloy-primitives", @@ -224,7 +224,7 @@ dependencies = [ [[package]] name = "alloy-pubsub" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#098ad5657d55bbc5fe9469ede2a9ca79def738f2" +source = "git+https://github.com/alloy-rs/alloy#a4453d42ffb755a46bace2ceca3baa454e0cd807" dependencies = [ "alloy-json-rpc", "alloy-primitives", @@ -263,7 +263,7 @@ dependencies = [ [[package]] name = "alloy-rpc-client" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#098ad5657d55bbc5fe9469ede2a9ca79def738f2" +source = "git+https://github.com/alloy-rs/alloy#a4453d42ffb755a46bace2ceca3baa454e0cd807" dependencies = [ "alloy-json-rpc", "alloy-transport", @@ -280,7 +280,7 @@ dependencies = [ [[package]] name = "alloy-rpc-trace-types" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#098ad5657d55bbc5fe9469ede2a9ca79def738f2" +source = "git+https://github.com/alloy-rs/alloy#a4453d42ffb755a46bace2ceca3baa454e0cd807" dependencies = [ "alloy-primitives", "alloy-rpc-types", @@ -291,7 +291,7 @@ dependencies = [ [[package]] name = "alloy-rpc-types" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#098ad5657d55bbc5fe9469ede2a9ca79def738f2" +source = "git+https://github.com/alloy-rs/alloy#a4453d42ffb755a46bace2ceca3baa454e0cd807" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -304,7 +304,7 @@ dependencies = [ [[package]] name = "alloy-signer" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#098ad5657d55bbc5fe9469ede2a9ca79def738f2" +source = "git+https://github.com/alloy-rs/alloy#a4453d42ffb755a46bace2ceca3baa454e0cd807" dependencies = [ "alloy-network", "alloy-primitives", @@ -346,7 +346,7 @@ version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4dd124ec0a456ec5e9dcca5b6e8b011bc723cc410d4d9a66bf032770feaeef4b" dependencies = [ - "winnow", + "winnow 0.5.40", ] [[package]] @@ -365,7 +365,7 @@ dependencies = [ [[package]] name = "alloy-transport" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#098ad5657d55bbc5fe9469ede2a9ca79def738f2" +source = "git+https://github.com/alloy-rs/alloy#a4453d42ffb755a46bace2ceca3baa454e0cd807" dependencies = [ "alloy-json-rpc", "base64 0.21.7", @@ -381,7 +381,7 @@ dependencies = [ [[package]] name = "alloy-transport-http" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#098ad5657d55bbc5fe9469ede2a9ca79def738f2" +source = "git+https://github.com/alloy-rs/alloy#a4453d42ffb755a46bace2ceca3baa454e0cd807" dependencies = [ "alloy-json-rpc", "alloy-transport", @@ -394,7 +394,7 @@ dependencies = [ [[package]] name = "alloy-transport-ipc" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#098ad5657d55bbc5fe9469ede2a9ca79def738f2" +source = "git+https://github.com/alloy-rs/alloy#a4453d42ffb755a46bace2ceca3baa454e0cd807" dependencies = [ "alloy-json-rpc", "alloy-pubsub", @@ -412,7 +412,7 @@ dependencies = [ [[package]] name = "alloy-transport-ws" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#098ad5657d55bbc5fe9469ede2a9ca79def738f2" +source = "git+https://github.com/alloy-rs/alloy#a4453d42ffb755a46bace2ceca3baa454e0cd807" dependencies = [ "alloy-pubsub", "alloy-transport", @@ -1361,9 +1361,9 @@ dependencies = [ [[package]] name = "chrono" -version = "0.4.33" +version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f13690e35a5e4ace198e7beea2895d29f3a9cc55015fcebe6336bd2010af9eb" +checksum = "5bc015644b92d5890fab7489e49d21f879d5c990186827d42ec511919404f38b" dependencies = [ "android-tzdata", "iana-time-zone", @@ -1731,9 +1731,9 @@ checksum = "19d374276b40fb8bbdee95aef7c7fa6b5316ec764510eb64b8dd0e2ed0d7e7f5" [[package]] name = "crc32fast" -version = "1.3.2" +version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b540bd8bc810d3885c6ea91e2018302f68baba2129ab3e88f32389ee9370880d" +checksum = "b3855a8a784b474f333699ef2bbca9db2c4a1f6d9088a90a2d25b1eb53111eaa" dependencies = [ "cfg-if", ] @@ -3906,7 +3906,7 @@ version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "290f1a1d9242c78d09ce40a5e87e7554ee637af1351968159f4952f028f75604" dependencies = [ - "ahash 0.8.7", + "ahash 0.8.8", "allocator-api2", "serde", ] @@ -4226,9 +4226,9 @@ checksum = "ce23b50ad8242c51a442f3ff322d56b02f08852c77e4c0b4d3fd684abc89c683" [[package]] name = "indexmap" -version = "2.2.2" +version = "2.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "824b2ae422412366ba479e8111fd301f7b5faece8149317bb81925979a53f520" +checksum = "233cf39063f058ea2caae4091bf4a3ef70a653afbc026f5c4a4135d114e3c177" dependencies = [ "equivalent", "hashbrown 0.14.3", @@ -7353,18 +7353,18 @@ dependencies = [ [[package]] name = "thiserror" -version = "1.0.56" +version = "1.0.57" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d54378c645627613241d077a3a79db965db602882668f9136ac42af9ecb730ad" +checksum = "1e45bcbe8ed29775f228095caf2cd67af7a4ccf756ebff23a306bf3e8b47b24b" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.56" +version = "1.0.57" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa0faa943b50f3db30a20aa7e265dbc66076993efed8463e8de414e5d06d3471" +checksum = "a953cb265bef375dae3de6663da4d3804eee9682ea80d8e2542529b73c531c81" dependencies = [ "proc-macro2", "quote", @@ -7586,7 +7586,7 @@ dependencies = [ "serde", "serde_spanned", "toml_datetime", - "toml_edit 0.22.4", + "toml_edit 0.22.5", ] [[package]] @@ -7606,7 +7606,7 @@ checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" dependencies = [ "indexmap", "toml_datetime", - "winnow", + "winnow 0.5.40", ] [[package]] @@ -7617,7 +7617,7 @@ checksum = "70f427fce4d84c72b5b732388bf4a9f4531b53f74e2887e3ecb2481f68f66d81" dependencies = [ "indexmap", "toml_datetime", - "winnow", + "winnow 0.5.40", ] [[package]] @@ -7628,20 +7628,20 @@ checksum = "6a8534fd7f78b5405e860340ad6575217ce99f38d4d5c8f2442cb5ecb50090e1" dependencies = [ "indexmap", "toml_datetime", - "winnow", + "winnow 0.5.40", ] [[package]] name = "toml_edit" -version = "0.22.4" +version = "0.22.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c9ffdf896f8daaabf9b66ba8e77ea1ed5ed0f72821b398aba62352e95062951" +checksum = "99e68c159e8f5ba8a28c4eb7b0c0c190d77bb479047ca713270048145a9ad28a" dependencies = [ "indexmap", "serde", "serde_spanned", "toml_datetime", - "winnow", + "winnow 0.6.0", ] [[package]] @@ -8469,9 +8469,18 @@ checksum = "dff9641d1cd4be8d1a070daf9e3773c5f67e78b4d9d42263020c057706765c04" [[package]] name = "winnow" -version = "0.5.39" +version = "0.5.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f593a95398737aeed53e489c785df13f3618e41dbcd6718c6addbf1395aa6876" +dependencies = [ + "memchr", +] + +[[package]] +name = "winnow" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5389a154b01683d28c77f8f68f49dea75f0a4da32557a58f68ee51ebba472d29" +checksum = "6b1dbce9e90e5404c5a52ed82b1d13fc8cfbdad85033b6f57546ffd1265f8451" dependencies = [ "memchr", ] diff --git a/crates/cast/bin/cmd/access_list.rs b/crates/cast/bin/cmd/access_list.rs index fa31380ff14d..e87c8b0dda04 100644 --- a/crates/cast/bin/cmd/access_list.rs +++ b/crates/cast/bin/cmd/access_list.rs @@ -1,3 +1,4 @@ +use alloy_providers::provider::TempProvider; use cast::{Cast, TxBuilder}; use clap::Parser; use ethers_core::types::{BlockId, NameOrAddress}; @@ -60,18 +61,20 @@ impl AccessListArgs { let config = Config::from(ð); let provider = utils::get_provider(&config)?; + let alloy_provider = utils::get_alloy_provider(&config)?; let chain = utils::get_chain(config.chain, &provider).await?; let sender = eth.wallet.sender().await; - access_list(&provider, sender.to_ethers(), to, sig, args, data, tx, chain, block, to_json) + access_list(&provider, alloy_provider, sender.to_ethers(), to, sig, args, data, tx, chain, block, to_json) .await?; Ok(()) } } #[allow(clippy::too_many_arguments)] -async fn access_list, T: Into>( +async fn access_list, T: Into>( provider: M, + alloy_provider: P, from: F, to: Option, sig: Option, @@ -104,7 +107,7 @@ where let builder_output = builder.peek(); - let cast = Cast::new(&provider); + let cast = Cast::new(&provider, alloy_provider); let access_list: String = cast.access_list(builder_output, block, to_json).await?; diff --git a/crates/cast/bin/cmd/call.rs b/crates/cast/bin/cmd/call.rs index 4851e9cf9a6f..1c6c5b1de566 100644 --- a/crates/cast/bin/cmd/call.rs +++ b/crates/cast/bin/cmd/call.rs @@ -116,6 +116,7 @@ impl CallArgs { let config = Config::from(ð); let provider = utils::get_provider(&config)?; + let alloy_provider = utils::get_alloy_provider(&config)?; let chain = utils::get_chain(config.chain, &provider).await?; let sender = eth.wallet.sender().await; @@ -196,7 +197,7 @@ impl CallArgs { }; let builder_output = builder.build(); - println!("{}", Cast::new(provider).call(builder_output, block).await?); + println!("{}", Cast::new(provider, alloy_provider).call(builder_output, block).await?); Ok(()) } diff --git a/crates/cast/bin/cmd/estimate.rs b/crates/cast/bin/cmd/estimate.rs index 6089f0153fd7..c963cfcacdae 100644 --- a/crates/cast/bin/cmd/estimate.rs +++ b/crates/cast/bin/cmd/estimate.rs @@ -81,6 +81,7 @@ impl EstimateArgs { let figment = Figment::from(Config::figment()).merge(etherscan).merge(rpc); let config = Config::try_from(figment)?; + let alloy_provider = utils::get_alloy_provider(&config)?; let provider = utils::get_provider(&config)?; let chain = utils::get_chain(config.chain, &provider).await?; @@ -109,7 +110,7 @@ impl EstimateArgs { }; let builder_output = builder.peek(); - let gas = Cast::new(&provider).estimate(builder_output).await?; + let gas = Cast::new(&provider, alloy_provider).estimate(builder_output).await?; println!("{gas}"); Ok(()) } diff --git a/crates/cast/bin/cmd/find_block.rs b/crates/cast/bin/cmd/find_block.rs index 381d52c50cc3..1a5c268b2ab4 100644 --- a/crates/cast/bin/cmd/find_block.rs +++ b/crates/cast/bin/cmd/find_block.rs @@ -25,9 +25,10 @@ impl FindBlockArgs { let ts_target = U256::from(timestamp); let config = Config::from(&rpc); let provider = utils::get_provider(&config)?; + let alloy_provider = utils::get_alloy_provider(&config)?; let last_block_num = provider.get_block_number().await?; - let cast_provider = Cast::new(provider); + let cast_provider = Cast::new(provider, alloy_provider); let res = join!(cast_provider.timestamp(last_block_num), cast_provider.timestamp(1)); let ts_block_latest = res.0?; diff --git a/crates/cast/bin/cmd/logs.rs b/crates/cast/bin/cmd/logs.rs index e7e6aed5d9b7..7085646c0422 100644 --- a/crates/cast/bin/cmd/logs.rs +++ b/crates/cast/bin/cmd/logs.rs @@ -76,8 +76,9 @@ impl LogsArgs { let config = Config::from(ð); let provider = utils::get_provider(&config)?; + let alloy_provider = utils::get_alloy_provider(&config)?; - let cast = Cast::new(&provider); + let cast = Cast::new(&provider, alloy_provider); let address = match address { Some(address) => { diff --git a/crates/cast/bin/cmd/rpc.rs b/crates/cast/bin/cmd/rpc.rs index 44275204adef..910ff4d7f275 100644 --- a/crates/cast/bin/cmd/rpc.rs +++ b/crates/cast/bin/cmd/rpc.rs @@ -39,6 +39,7 @@ impl RpcArgs { let config = Config::from(&rpc); let provider = utils::get_provider(&config)?; + let alloy_provider = utils::get_alloy_provider(&config)?; let params = if raw { if params.is_empty() { @@ -53,7 +54,7 @@ impl RpcArgs { } else { serde_json::Value::Array(params.into_iter().map(value_or_string).collect()) }; - println!("{}", Cast::new(provider).rpc(&method, params).await?); + println!("{}", Cast::new(provider, alloy_provider).rpc(&method, params).await?); Ok(()) } } diff --git a/crates/cast/bin/cmd/send.rs b/crates/cast/bin/cmd/send.rs index b79bf1d7cd9b..e208b7ed39e4 100644 --- a/crates/cast/bin/cmd/send.rs +++ b/crates/cast/bin/cmd/send.rs @@ -1,3 +1,4 @@ +use alloy_providers::provider::TempProvider; use cast::{Cast, TxBuilder}; use clap::Parser; use ethers_core::types::NameOrAddress; @@ -114,6 +115,7 @@ impl SendTxArgs { let config = Config::from(ð); let provider = utils::get_provider(&config)?; + let alloy_provider = utils::get_alloy_provider(&config)?; let chain = utils::get_chain(config.chain, &provider).await?; let api_key = config.get_etherscan_api_key(Some(chain)); @@ -152,6 +154,7 @@ impl SendTxArgs { cast_send( provider, + alloy_provider, config.sender.to_ethers(), to, code, @@ -195,6 +198,7 @@ corresponds to the sender, or let foundry automatically detect it by not specify cast_send( provider, + alloy_provider, from, to, code, @@ -212,8 +216,9 @@ corresponds to the sender, or let foundry automatically detect it by not specify } #[allow(clippy::too_many_arguments)] -async fn cast_send, T: Into>( +async fn cast_send, T: Into>( provider: M, + alloy_provider: P, from: F, to: Option, code: Option, @@ -253,7 +258,7 @@ where }; let builder_output = builder.build(); - let cast = Cast::new(provider); + let cast = Cast::new(provider, alloy_provider); let pending_tx = cast.send(builder_output).await?; let tx_hash = *pending_tx; diff --git a/crates/cast/bin/cmd/storage.rs b/crates/cast/bin/cmd/storage.rs index 5769360484ad..00be5ee570a5 100644 --- a/crates/cast/bin/cmd/storage.rs +++ b/crates/cast/bin/cmd/storage.rs @@ -82,10 +82,11 @@ impl StorageArgs { let Self { address, slot, block, build, .. } = self; let provider = utils::get_provider(&config)?; + let alloy_provider = utils::get_alloy_provider(&config)?; // Slot was provided, perform a simple RPC call if let Some(slot) = slot { - let cast = Cast::new(provider); + let cast = Cast::new(provider, alloy_provider); println!("{}", cast.storage(address, slot.to_ethers(), block).await?); return Ok(()); } diff --git a/crates/cast/bin/main.rs b/crates/cast/bin/main.rs index c4ee0e56388e..04d08d5f7b86 100644 --- a/crates/cast/bin/main.rs +++ b/crates/cast/bin/main.rs @@ -197,14 +197,16 @@ async fn main() -> Result<()> { CastSubcommand::Age { block, rpc } => { let config = Config::from(&rpc); let provider = utils::get_provider(&config)?; + let alloy_provider = utils::get_alloy_provider(&config)?; println!( "{}", - Cast::new(provider).age(block.unwrap_or(BlockId::Number(Latest))).await? + Cast::new(provider, alloy_provider).age(block.unwrap_or(BlockId::Number(Latest))).await? ); } CastSubcommand::Balance { block, who, ether, rpc, erc20 } => { let config = Config::from(&rpc); let provider = utils::get_provider(&config)?; + let alloy_provider = utils::get_alloy_provider(&config)?; match erc20 { Some(token) => { @@ -230,10 +232,10 @@ async fn main() -> Result<()> { ) .await?; let builder_output = builder.build(); - println!("{}", Cast::new(provider).call(builder_output, block).await?); + println!("{}", Cast::new(provider, alloy_provider).call(builder_output, block).await?); } None => { - let value = Cast::new(provider).balance(who, block).await?; + let value = Cast::new(provider, alloy_provider).balance(who, block).await?; if ether { println!("{}", SimpleCast::from_wei(&value.to_string(), "eth")?); } else { @@ -245,17 +247,19 @@ async fn main() -> Result<()> { CastSubcommand::BaseFee { block, rpc } => { let config = Config::from(&rpc); let provider = utils::get_provider(&config)?; + let alloy_provider = utils::get_alloy_provider(&config)?; println!( "{}", - Cast::new(provider).base_fee(block.unwrap_or(BlockId::Number(Latest))).await? + Cast::new(provider, alloy_provider).base_fee(block.unwrap_or(BlockId::Number(Latest))).await? ); } CastSubcommand::Block { block, full, field, json, rpc } => { let config = Config::from(&rpc); let provider = utils::get_provider(&config)?; + let alloy_provider = utils::get_alloy_provider(&config)?; println!( "{}", - Cast::new(provider) + Cast::new(provider, alloy_provider) .block(block.unwrap_or(BlockId::Number(Latest)), full, field, json) .await? ); @@ -263,17 +267,20 @@ async fn main() -> Result<()> { CastSubcommand::BlockNumber { rpc } => { let config = Config::from(&rpc); let provider = utils::get_provider(&config)?; - println!("{}", Cast::new(provider).block_number().await?); + let alloy_provider = utils::get_alloy_provider(&config)?; + println!("{}", Cast::new(provider, alloy_provider).block_number().await?); } CastSubcommand::Chain { rpc } => { let config = Config::from(&rpc); let provider = utils::get_provider(&config)?; - println!("{}", Cast::new(provider).chain().await?); + let alloy_provider = utils::get_alloy_provider(&config)?; + println!("{}", Cast::new(provider, alloy_provider).chain().await?); } CastSubcommand::ChainId { rpc } => { let config = Config::from(&rpc); let provider = utils::get_provider(&config)?; - println!("{}", Cast::new(provider).chain_id().await?); + let alloy_provider = utils::get_alloy_provider(&config)?; + println!("{}", Cast::new(provider, alloy_provider).chain_id().await?); } CastSubcommand::Client { rpc } => { let config = Config::from(&rpc); @@ -283,19 +290,22 @@ async fn main() -> Result<()> { CastSubcommand::Code { block, who, disassemble, rpc } => { let config = Config::from(&rpc); let provider = utils::get_provider(&config)?; - println!("{}", Cast::new(provider).code(who, block, disassemble).await?); + let alloy_provider = utils::get_alloy_provider(&config)?; + println!("{}", Cast::new(provider, alloy_provider).code(who, block, disassemble).await?); } CastSubcommand::Codesize { block, who, rpc } => { let config = Config::from(&rpc); let provider = utils::get_provider(&config)?; - println!("{}", Cast::new(provider).codesize(who, block).await?); + let alloy_provider = utils::get_alloy_provider(&config)?; + println!("{}", Cast::new(provider, alloy_provider).codesize(who, block).await?); } CastSubcommand::ComputeAddress { address, nonce, rpc } => { let config = Config::from(&rpc); let provider = utils::get_provider(&config)?; + let alloy_provider = utils::get_alloy_provider(&config)?; let address: Address = stdin::unwrap_line(address)?.parse()?; - let computed = Cast::new(&provider).compute_address(address, nonce).await?; + let computed = Cast::new(&provider, alloy_provider).compute_address(address, nonce).await?; println!("Computed Address: {}", computed.to_checksum(None)); } CastSubcommand::Disassemble { bytecode } => { @@ -328,7 +338,8 @@ async fn main() -> Result<()> { CastSubcommand::GasPrice { rpc } => { let config = Config::from(&rpc); let provider = utils::get_provider(&config)?; - println!("{}", Cast::new(provider).gas_price().await?); + let alloy_provider = utils::get_alloy_provider(&config)?; + println!("{}", Cast::new(provider, alloy_provider).gas_price().await?); } CastSubcommand::Index { key_type, key, slot_number } => { println!("{}", SimpleCast::index(&key_type, &key, &slot_number)?); @@ -336,17 +347,20 @@ async fn main() -> Result<()> { CastSubcommand::Implementation { block, who, rpc } => { let config = Config::from(&rpc); let provider = utils::get_provider(&config)?; - println!("{}", Cast::new(provider).implementation(who, block).await?); + let alloy_provider = utils::get_alloy_provider(&config)?; + println!("{}", Cast::new(provider, alloy_provider).implementation(who, block).await?); } CastSubcommand::Admin { block, who, rpc } => { let config = Config::from(&rpc); let provider = utils::get_provider(&config)?; - println!("{}", Cast::new(provider).admin(who, block).await?); + let alloy_provider = utils::get_alloy_provider(&config)?; + println!("{}", Cast::new(provider, alloy_provider).admin(who, block).await?); } CastSubcommand::Nonce { block, who, rpc } => { let config = Config::from(&rpc); let provider = utils::get_provider(&config)?; - println!("{}", Cast::new(provider).nonce(who, block).await?); + let alloy_provider = utils::get_alloy_provider(&config)?; + println!("{}", Cast::new(provider, alloy_provider).nonce(who, block).await?); } CastSubcommand::Proof { address, slots, rpc, block } => { let config = Config::from(&rpc); @@ -365,7 +379,8 @@ async fn main() -> Result<()> { CastSubcommand::PublishTx { raw_tx, cast_async, rpc } => { let config = Config::from(&rpc); let provider = utils::get_provider(&config)?; - let cast = Cast::new(&provider); + let alloy_provider = utils::get_alloy_provider(&config)?; + let cast = Cast::new(&provider, alloy_provider); let pending_tx = cast.publish(raw_tx).await?; let tx_hash = *pending_tx; @@ -380,9 +395,10 @@ async fn main() -> Result<()> { CastSubcommand::Receipt { tx_hash, field, json, cast_async, confirmations, rpc } => { let config = Config::from(&rpc); let provider = utils::get_provider(&config)?; + let alloy_provider = utils::get_alloy_provider(&config)?; println!( "{}", - Cast::new(provider) + Cast::new(provider, alloy_provider) .receipt(tx_hash, field, confirmations, cast_async, json) .await? ); @@ -392,11 +408,12 @@ async fn main() -> Result<()> { CastSubcommand::Tx { tx_hash, field, raw, json, rpc } => { let config = Config::from(&rpc); let provider = utils::get_provider(&config)?; + let alloy_provider = utils::get_alloy_provider(&config)?; // Can use either --raw or specify raw as a field let raw = raw || field.as_ref().is_some_and(|f| f == "raw"); - println!("{}", Cast::new(&provider).transaction(tx_hash, field, raw, json).await?) + println!("{}", Cast::new(&provider, alloy_provider).transaction(tx_hash, field, raw, json).await?) } // 4Byte diff --git a/crates/cast/src/lib.rs b/crates/cast/src/lib.rs index 0c941913cf14..d20ce0c89c6d 100644 --- a/crates/cast/src/lib.rs +++ b/crates/cast/src/lib.rs @@ -5,6 +5,7 @@ use alloy_primitives::{ Address, Bytes, B256, I256, U256, }; use alloy_rlp::Decodable; +use alloy_providers::provider::TempProvider; use base::{Base, NumberWithBase, ToBase}; use chrono::NaiveDateTime; use ethers_core::{ @@ -53,11 +54,12 @@ use rlp_converter::Item; // TODO: CastContract with common contract initializers? Same for CastProviders? -pub struct Cast { +pub struct Cast { provider: M, + alloy_provider: P, } -impl Cast +impl Cast where M::Error: 'static, { @@ -75,8 +77,8 @@ where /// # Ok(()) /// # } /// ``` - pub fn new(provider: M) -> Self { - Self { provider } + pub fn new(provider: M, alloy_provider: P) -> Self { + Self { provider, alloy_provider } } /// Makes a read-only call to the specified address diff --git a/crates/cli/src/utils/mod.rs b/crates/cli/src/utils/mod.rs index f900c50b071d..15101abbbe0e 100644 --- a/crates/cli/src/utils/mod.rs +++ b/crates/cli/src/utils/mod.rs @@ -89,6 +89,11 @@ pub fn get_provider(config: &Config) -> Result Result { + get_alloy_provider_builder(config)?.build() +} + /// Returns a [ProviderBuilder](foundry_common::ProviderBuilder) instantiated using [Config]'s RPC /// URL and chain. /// @@ -111,6 +116,27 @@ pub fn get_provider_builder( Ok(builder) } +/// Returns a [ProviderBuilder](foundry_common::provider::alloy::ProviderBuilder) instantiated using [Config] values. +/// +/// Defaults to `http://localhost:8545` and `Mainnet`. +pub fn get_alloy_provider_builder( + config: &Config, +) -> Result { + let url = config.get_rpc_url_or_localhost_http()?; + let mut builder = foundry_common::provider::alloy::ProviderBuilder::new(url.as_ref()); + + if let Ok(chain) = config.chain.unwrap_or_default().try_into() { + builder = builder.chain(chain); + } + + let jwt = config.get_rpc_jwt_secret()?; + if let Some(jwt) = jwt { + builder = builder.jwt(jwt.as_ref()); + } + + Ok(builder) +} + pub async fn get_chain(chain: Option, provider: M) -> Result where M: Middleware, From 08a9cca5f8ca8ab2919960c95cf16804f0c3a8e7 Mon Sep 17 00:00:00 2001 From: Enrique Ortiz Date: Tue, 13 Feb 2024 12:23:59 -0400 Subject: [PATCH 02/63] move initial methods to alloy --- crates/cast/bin/cmd/access_list.rs | 23 ++++++++++++++++--- crates/cast/bin/cmd/find_block.rs | 2 +- crates/cast/bin/cmd/logs.rs | 14 ++++++------ crates/cast/bin/cmd/storage.rs | 2 +- crates/cast/bin/main.rs | 26 ++++++++++++++++----- crates/cast/src/lib.rs | 36 +++++++++++++++++------------- crates/cli/src/utils/mod.rs | 12 ++++++---- crates/common/src/types.rs | 20 +++++++++++++++-- 8 files changed, 96 insertions(+), 39 deletions(-) diff --git a/crates/cast/bin/cmd/access_list.rs b/crates/cast/bin/cmd/access_list.rs index e87c8b0dda04..3bb215c7d721 100644 --- a/crates/cast/bin/cmd/access_list.rs +++ b/crates/cast/bin/cmd/access_list.rs @@ -65,14 +65,31 @@ impl AccessListArgs { let chain = utils::get_chain(config.chain, &provider).await?; let sender = eth.wallet.sender().await; - access_list(&provider, alloy_provider, sender.to_ethers(), to, sig, args, data, tx, chain, block, to_json) - .await?; + access_list( + &provider, + alloy_provider, + sender.to_ethers(), + to, + sig, + args, + data, + tx, + chain, + block, + to_json, + ) + .await?; Ok(()) } } #[allow(clippy::too_many_arguments)] -async fn access_list, T: Into>( +async fn access_list< + M: Middleware, + P: TempProvider, + F: Into, + T: Into, +>( provider: M, alloy_provider: P, from: F, diff --git a/crates/cast/bin/cmd/find_block.rs b/crates/cast/bin/cmd/find_block.rs index 1a5c268b2ab4..4e8594d0a7e8 100644 --- a/crates/cast/bin/cmd/find_block.rs +++ b/crates/cast/bin/cmd/find_block.rs @@ -25,7 +25,7 @@ impl FindBlockArgs { let ts_target = U256::from(timestamp); let config = Config::from(&rpc); let provider = utils::get_provider(&config)?; - let alloy_provider = utils::get_alloy_provider(&config)?; + let alloy_provider = utils::get_alloy_provider(&config)?; let last_block_num = provider.get_block_number().await?; let cast_provider = Cast::new(provider, alloy_provider); diff --git a/crates/cast/bin/cmd/logs.rs b/crates/cast/bin/cmd/logs.rs index 7085646c0422..fc195b63fcf7 100644 --- a/crates/cast/bin/cmd/logs.rs +++ b/crates/cast/bin/cmd/logs.rs @@ -1,3 +1,4 @@ +use alloy_rpc_types::BlockHashOrNumber; use cast::Cast; use clap::Parser; use ethers_core::{ @@ -5,13 +6,12 @@ use ethers_core::{ token::{LenientTokenizer, StrictTokenizer, Tokenizer}, Address, Event, HumanReadableParser, ParamType, RawTopicFilter, Token, Topic, TopicFilter, }, - types::{ - BlockId, BlockNumber, Filter, FilterBlockOption, NameOrAddress, ValueOrArray, H256, U256, - }, + types::{BlockNumber, Filter, FilterBlockOption, NameOrAddress, ValueOrArray, H256, U256}, }; use ethers_providers::Middleware; use eyre::{Result, WrapErr}; use foundry_cli::{opts::EthereumOpts, utils}; +use foundry_common::types::ToEthers; use foundry_config::Config; use itertools::Itertools; use std::{io, str::FromStr}; @@ -23,13 +23,13 @@ pub struct LogsArgs { /// /// Can also be the tags earliest, finalized, safe, latest, or pending. #[clap(long)] - from_block: Option, + from_block: Option, /// The block height to stop query at. /// /// Can also be the tags earliest, finalized, safe, latest, or pending. #[clap(long)] - to_block: Option, + to_block: Option, /// The contract address to filter on. #[clap( @@ -91,8 +91,8 @@ impl LogsArgs { None => None, }; - let from_block = cast.convert_block_number(from_block).await?; - let to_block = cast.convert_block_number(to_block).await?; + let from_block = cast.convert_block_number(from_block).await?.map(ToEthers::to_ethers); + let to_block = cast.convert_block_number(to_block).await?.map(ToEthers::to_ethers); let filter = build_filter(from_block, to_block, address, sig_or_topic, topics_or_args)?; diff --git a/crates/cast/bin/cmd/storage.rs b/crates/cast/bin/cmd/storage.rs index 00be5ee570a5..e1a033a0f463 100644 --- a/crates/cast/bin/cmd/storage.rs +++ b/crates/cast/bin/cmd/storage.rs @@ -82,7 +82,7 @@ impl StorageArgs { let Self { address, slot, block, build, .. } = self; let provider = utils::get_provider(&config)?; - let alloy_provider = utils::get_alloy_provider(&config)?; + let alloy_provider = utils::get_alloy_provider(&config)?; // Slot was provided, perform a simple RPC call if let Some(slot) = slot { diff --git a/crates/cast/bin/main.rs b/crates/cast/bin/main.rs index 04d08d5f7b86..96d3a30ad440 100644 --- a/crates/cast/bin/main.rs +++ b/crates/cast/bin/main.rs @@ -200,7 +200,9 @@ async fn main() -> Result<()> { let alloy_provider = utils::get_alloy_provider(&config)?; println!( "{}", - Cast::new(provider, alloy_provider).age(block.unwrap_or(BlockId::Number(Latest))).await? + Cast::new(provider, alloy_provider) + .age(block.unwrap_or(BlockId::Number(Latest))) + .await? ); } CastSubcommand::Balance { block, who, ether, rpc, erc20 } => { @@ -232,7 +234,10 @@ async fn main() -> Result<()> { ) .await?; let builder_output = builder.build(); - println!("{}", Cast::new(provider, alloy_provider).call(builder_output, block).await?); + println!( + "{}", + Cast::new(provider, alloy_provider).call(builder_output, block).await? + ); } None => { let value = Cast::new(provider, alloy_provider).balance(who, block).await?; @@ -250,7 +255,9 @@ async fn main() -> Result<()> { let alloy_provider = utils::get_alloy_provider(&config)?; println!( "{}", - Cast::new(provider, alloy_provider).base_fee(block.unwrap_or(BlockId::Number(Latest))).await? + Cast::new(provider, alloy_provider) + .base_fee(block.unwrap_or(BlockId::Number(Latest))) + .await? ); } CastSubcommand::Block { block, full, field, json, rpc } => { @@ -291,7 +298,10 @@ async fn main() -> Result<()> { let config = Config::from(&rpc); let provider = utils::get_provider(&config)?; let alloy_provider = utils::get_alloy_provider(&config)?; - println!("{}", Cast::new(provider, alloy_provider).code(who, block, disassemble).await?); + println!( + "{}", + Cast::new(provider, alloy_provider).code(who, block, disassemble).await? + ); } CastSubcommand::Codesize { block, who, rpc } => { let config = Config::from(&rpc); @@ -305,7 +315,8 @@ async fn main() -> Result<()> { let alloy_provider = utils::get_alloy_provider(&config)?; let address: Address = stdin::unwrap_line(address)?.parse()?; - let computed = Cast::new(&provider, alloy_provider).compute_address(address, nonce).await?; + let computed = + Cast::new(&provider, alloy_provider).compute_address(address, nonce).await?; println!("Computed Address: {}", computed.to_checksum(None)); } CastSubcommand::Disassemble { bytecode } => { @@ -413,7 +424,10 @@ async fn main() -> Result<()> { // Can use either --raw or specify raw as a field let raw = raw || field.as_ref().is_some_and(|f| f == "raw"); - println!("{}", Cast::new(&provider, alloy_provider).transaction(tx_hash, field, raw, json).await?) + println!( + "{}", + Cast::new(&provider, alloy_provider).transaction(tx_hash, field, raw, json).await? + ) } // 4Byte diff --git a/crates/cast/src/lib.rs b/crates/cast/src/lib.rs index d20ce0c89c6d..8467fd8de637 100644 --- a/crates/cast/src/lib.rs +++ b/crates/cast/src/lib.rs @@ -2,16 +2,17 @@ use alloy_dyn_abi::{DynSolType, DynSolValue, FunctionExt}; use alloy_json_abi::ContractObject; use alloy_primitives::{ utils::{keccak256, ParseUnits, Unit}, - Address, Bytes, B256, I256, U256, + Address, Bytes, B256, I256, U256, U64, }; -use alloy_rlp::Decodable; use alloy_providers::provider::TempProvider; +use alloy_rlp::Decodable; +use alloy_rpc_types::{BlockHashOrNumber, BlockNumberOrTag}; use base::{Base, NumberWithBase, ToBase}; use chrono::NaiveDateTime; use ethers_core::{ types::{ - transaction::eip2718::TypedTransaction, BlockId, BlockNumber, Filter, NameOrAddress, - Signature, H160, H256, U64, + transaction::eip2718::TypedTransaction, BlockId, Filter, NameOrAddress, Signature, H160, + H256, }, utils::rlp, }; @@ -465,15 +466,15 @@ where } pub async fn chain_id(&self) -> Result { - Ok(self.provider.get_chainid().await?.to_alloy()) + Ok(U256::from(self.alloy_provider.get_chain_id().await?)) } pub async fn block_number(&self) -> Result { - Ok(self.provider.get_block_number().await?) + Ok(U64::from(self.alloy_provider.get_block_number().await?)) } pub async fn gas_price(&self) -> Result { - Ok(self.provider.get_gas_price().await?.to_alloy()) + Ok(self.alloy_provider.get_gas_price().await?) } /// # Example @@ -761,9 +762,10 @@ where /// ``` pub async fn rpc(&self, method: &str, params: T) -> Result where - T: std::fmt::Debug + serde::Serialize + Send + Sync, + T: std::fmt::Debug + serde::Serialize + Send + Sync + Clone, { - let res = self.provider.provider().request::(method, params).await?; + let method = Box::new(method.to_string()).leak(); + let res = self.alloy_provider.raw_request::(method, params).await?; Ok(serde_json::to_string(&res)?) } @@ -848,14 +850,18 @@ where /// ``` pub async fn convert_block_number( &self, - block: Option, - ) -> Result, eyre::Error> { + block: Option, + ) -> Result, eyre::Error> { match block { Some(block) => match block { - BlockId::Number(block_number) => Ok(Some(block_number)), - BlockId::Hash(hash) => { - let block = self.provider.get_block(hash).await?; - Ok(block.map(|block| block.number.unwrap()).map(BlockNumber::from)) + BlockHashOrNumber::Number(block_number) => { + Ok(Some(BlockNumberOrTag::Number(block_number))) + } + BlockHashOrNumber::Hash(hash) => { + let block = self.alloy_provider.get_block_by_hash(hash, false).await?; + Ok(block + .map(|block| block.header.number.unwrap().to::()) + .map(BlockNumberOrTag::from)) } }, None => Ok(None), diff --git a/crates/cli/src/utils/mod.rs b/crates/cli/src/utils/mod.rs index 15101abbbe0e..b4a22547b1b2 100644 --- a/crates/cli/src/utils/mod.rs +++ b/crates/cli/src/utils/mod.rs @@ -89,8 +89,11 @@ pub fn get_provider(config: &Config) -> Result Result { +/// Returns a [RetryProvider](foundry_common::alloy::RetryProvider) instantiated using [Config]'s +/// RPC +pub fn get_alloy_provider( + config: &Config, +) -> Result { get_alloy_provider_builder(config)?.build() } @@ -116,8 +119,9 @@ pub fn get_provider_builder( Ok(builder) } -/// Returns a [ProviderBuilder](foundry_common::provider::alloy::ProviderBuilder) instantiated using [Config] values. -/// +/// Returns a [ProviderBuilder](foundry_common::provider::alloy::ProviderBuilder) instantiated using +/// [Config] values. +/// /// Defaults to `http://localhost:8545` and `Mainnet`. pub fn get_alloy_provider_builder( config: &Config, diff --git a/crates/common/src/types.rs b/crates/common/src/types.rs index 6f4284b32410..85b7e87ba568 100644 --- a/crates/common/src/types.rs +++ b/crates/common/src/types.rs @@ -4,14 +4,14 @@ use alloy_primitives::{Address, Bloom, Bytes, B256, B64, I256, U128, U256, U64}; use alloy_rpc_types::{ other::OtherFields, request::{TransactionInput, TransactionRequest as CallRequest}, - AccessList, AccessListItem, Signature, Transaction, + AccessList, AccessListItem, BlockNumberOrTag, Signature, Transaction, }; use alloy_signer::{LocalWallet, Signer}; use ethers_core::types::{ transaction::eip2930::{ AccessList as EthersAccessList, AccessListItem as EthersAccessListItem, }, - Bloom as EthersBloom, Bytes as EthersBytes, TransactionRequest, H160, H256, H64, + BlockNumber, Bloom as EthersBloom, Bytes as EthersBytes, TransactionRequest, H160, H256, H64, I256 as EthersI256, U256 as EthersU256, U64 as EthersU64, }; @@ -260,3 +260,19 @@ impl ToEthers for Bytes { EthersBytes(self.0) } } + +impl ToEthers for BlockNumberOrTag { + type To = BlockNumber; + + #[inline(always)] + fn to_ethers(self) -> Self::To { + match self { + BlockNumberOrTag::Number(n) => BlockNumber::Number(n.into()), + BlockNumberOrTag::Earliest => BlockNumber::Earliest, + BlockNumberOrTag::Latest => BlockNumber::Latest, + BlockNumberOrTag::Pending => BlockNumber::Pending, + BlockNumberOrTag::Finalized => BlockNumber::Finalized, + BlockNumberOrTag::Safe => BlockNumber::Safe, + } + } +} From 3de8241a850b93b734abac80afaf79bf0f22305d Mon Sep 17 00:00:00 2001 From: Enrique Date: Wed, 14 Feb 2024 15:24:38 -0400 Subject: [PATCH 03/63] feat(`foundry-common`): NameOrAddress ENS util (#7122) * feat(foundry-common): NameOrAddress ENS util * chore: rename err * chore: remove from impl for str * chore: unrelated fix from alloy upgrade * nit --- Cargo.lock | 70 +++++++------ Cargo.toml | 12 ++- crates/anvil/src/eth/backend/fork.rs | 2 +- crates/common/Cargo.toml | 1 + crates/common/src/ens.rs | 142 +++++++++++++++++++++++++++ crates/common/src/lib.rs | 1 + crates/config/Cargo.toml | 2 +- crates/evm/core/src/fork/backend.rs | 5 +- 8 files changed, 197 insertions(+), 38 deletions(-) create mode 100644 crates/common/src/ens.rs diff --git a/Cargo.lock b/Cargo.lock index b93e23d28dae..af9328a22583 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -90,7 +90,7 @@ dependencies = [ [[package]] name = "alloy-consensus" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#a4453d42ffb755a46bace2ceca3baa454e0cd807" +source = "git+https://github.com/alloy-rs/alloy#d0fb78ac708a9bd15f3964fc3006dcae2992489d" dependencies = [ "alloy-eips", "alloy-network", @@ -98,11 +98,25 @@ dependencies = [ "alloy-rlp", ] +[[package]] +name = "alloy-contract" +version = "0.1.0" +source = "git+https://github.com/alloy-rs/alloy#d0fb78ac708a9bd15f3964fc3006dcae2992489d" +dependencies = [ + "alloy-dyn-abi", + "alloy-json-abi", + "alloy-primitives", + "alloy-providers", + "alloy-rpc-types", + "alloy-sol-types", + "alloy-transport", + "thiserror", +] + [[package]] name = "alloy-dyn-abi" version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7265ac54c88a78604cea8444addfa9dfdad08d3098f153484cb4ee66fc202cc" +source = "git+https://github.com/alloy-rs/core?rev=18b0509950c90d9ec38f25913b692ae4cdd6f227#18b0509950c90d9ec38f25913b692ae4cdd6f227" dependencies = [ "alloy-json-abi", "alloy-primitives", @@ -122,7 +136,7 @@ dependencies = [ [[package]] name = "alloy-eips" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#a4453d42ffb755a46bace2ceca3baa454e0cd807" +source = "git+https://github.com/alloy-rs/alloy#d0fb78ac708a9bd15f3964fc3006dcae2992489d" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -133,7 +147,7 @@ dependencies = [ [[package]] name = "alloy-genesis" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#a4453d42ffb755a46bace2ceca3baa454e0cd807" +source = "git+https://github.com/alloy-rs/alloy#d0fb78ac708a9bd15f3964fc3006dcae2992489d" dependencies = [ "alloy-primitives", "alloy-rpc-types", @@ -143,8 +157,7 @@ dependencies = [ [[package]] name = "alloy-json-abi" version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7c5aecfe87e06da0e760840974c6e3cc19d4247be17a3172825fbbe759c8e60" +source = "git+https://github.com/alloy-rs/core?rev=18b0509950c90d9ec38f25913b692ae4cdd6f227#18b0509950c90d9ec38f25913b692ae4cdd6f227" dependencies = [ "alloy-primitives", "alloy-sol-type-parser", @@ -155,7 +168,7 @@ dependencies = [ [[package]] name = "alloy-json-rpc" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#a4453d42ffb755a46bace2ceca3baa454e0cd807" +source = "git+https://github.com/alloy-rs/alloy#d0fb78ac708a9bd15f3964fc3006dcae2992489d" dependencies = [ "alloy-primitives", "serde", @@ -166,7 +179,7 @@ dependencies = [ [[package]] name = "alloy-network" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#a4453d42ffb755a46bace2ceca3baa454e0cd807" +source = "git+https://github.com/alloy-rs/alloy#d0fb78ac708a9bd15f3964fc3006dcae2992489d" dependencies = [ "alloy-eips", "alloy-json-rpc", @@ -178,8 +191,7 @@ dependencies = [ [[package]] name = "alloy-primitives" version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4b6fb2b432ff223d513db7f908937f63c252bee0af9b82bfd25b0a5dd1eb0d8" +source = "git+https://github.com/alloy-rs/core?rev=18b0509950c90d9ec38f25913b692ae4cdd6f227#18b0509950c90d9ec38f25913b692ae4cdd6f227" dependencies = [ "alloy-rlp", "arbitrary", @@ -205,7 +217,7 @@ dependencies = [ [[package]] name = "alloy-providers" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#a4453d42ffb755a46bace2ceca3baa454e0cd807" +source = "git+https://github.com/alloy-rs/alloy#d0fb78ac708a9bd15f3964fc3006dcae2992489d" dependencies = [ "alloy-network", "alloy-primitives", @@ -224,7 +236,7 @@ dependencies = [ [[package]] name = "alloy-pubsub" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#a4453d42ffb755a46bace2ceca3baa454e0cd807" +source = "git+https://github.com/alloy-rs/alloy#d0fb78ac708a9bd15f3964fc3006dcae2992489d" dependencies = [ "alloy-json-rpc", "alloy-primitives", @@ -263,7 +275,7 @@ dependencies = [ [[package]] name = "alloy-rpc-client" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#a4453d42ffb755a46bace2ceca3baa454e0cd807" +source = "git+https://github.com/alloy-rs/alloy#d0fb78ac708a9bd15f3964fc3006dcae2992489d" dependencies = [ "alloy-json-rpc", "alloy-transport", @@ -280,7 +292,7 @@ dependencies = [ [[package]] name = "alloy-rpc-trace-types" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#a4453d42ffb755a46bace2ceca3baa454e0cd807" +source = "git+https://github.com/alloy-rs/alloy#d0fb78ac708a9bd15f3964fc3006dcae2992489d" dependencies = [ "alloy-primitives", "alloy-rpc-types", @@ -291,7 +303,7 @@ dependencies = [ [[package]] name = "alloy-rpc-types" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#a4453d42ffb755a46bace2ceca3baa454e0cd807" +source = "git+https://github.com/alloy-rs/alloy#d0fb78ac708a9bd15f3964fc3006dcae2992489d" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -304,7 +316,7 @@ dependencies = [ [[package]] name = "alloy-signer" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#a4453d42ffb755a46bace2ceca3baa454e0cd807" +source = "git+https://github.com/alloy-rs/alloy#d0fb78ac708a9bd15f3964fc3006dcae2992489d" dependencies = [ "alloy-network", "alloy-primitives", @@ -323,8 +335,7 @@ dependencies = [ [[package]] name = "alloy-sol-macro" version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b0b5ab0cb07c21adf9d72e988b34e8200ce648c2bba8d009183bb1c50fb1216" +source = "git+https://github.com/alloy-rs/core?rev=18b0509950c90d9ec38f25913b692ae4cdd6f227#18b0509950c90d9ec38f25913b692ae4cdd6f227" dependencies = [ "alloy-json-abi", "const-hex", @@ -343,8 +354,7 @@ dependencies = [ [[package]] name = "alloy-sol-type-parser" version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4dd124ec0a456ec5e9dcca5b6e8b011bc723cc410d4d9a66bf032770feaeef4b" +source = "git+https://github.com/alloy-rs/core?rev=18b0509950c90d9ec38f25913b692ae4cdd6f227#18b0509950c90d9ec38f25913b692ae4cdd6f227" dependencies = [ "winnow 0.5.40", ] @@ -352,8 +362,7 @@ dependencies = [ [[package]] name = "alloy-sol-types" version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c08f62ded7ce03513bfb60ef5cad4fff5d4f67eac6feb4df80426b7b9ffb06e" +source = "git+https://github.com/alloy-rs/core?rev=18b0509950c90d9ec38f25913b692ae4cdd6f227#18b0509950c90d9ec38f25913b692ae4cdd6f227" dependencies = [ "alloy-json-abi", "alloy-primitives", @@ -365,7 +374,7 @@ dependencies = [ [[package]] name = "alloy-transport" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#a4453d42ffb755a46bace2ceca3baa454e0cd807" +source = "git+https://github.com/alloy-rs/alloy#d0fb78ac708a9bd15f3964fc3006dcae2992489d" dependencies = [ "alloy-json-rpc", "base64 0.21.7", @@ -381,7 +390,7 @@ dependencies = [ [[package]] name = "alloy-transport-http" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#a4453d42ffb755a46bace2ceca3baa454e0cd807" +source = "git+https://github.com/alloy-rs/alloy#d0fb78ac708a9bd15f3964fc3006dcae2992489d" dependencies = [ "alloy-json-rpc", "alloy-transport", @@ -394,7 +403,7 @@ dependencies = [ [[package]] name = "alloy-transport-ipc" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#a4453d42ffb755a46bace2ceca3baa454e0cd807" +source = "git+https://github.com/alloy-rs/alloy#d0fb78ac708a9bd15f3964fc3006dcae2992489d" dependencies = [ "alloy-json-rpc", "alloy-pubsub", @@ -412,7 +421,7 @@ dependencies = [ [[package]] name = "alloy-transport-ws" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#a4453d42ffb755a46bace2ceca3baa454e0cd807" +source = "git+https://github.com/alloy-rs/alloy#d0fb78ac708a9bd15f3964fc3006dcae2992489d" dependencies = [ "alloy-pubsub", "alloy-transport", @@ -1248,6 +1257,7 @@ checksum = "df8670b8c7b9dae1793364eafadf7239c40d669904660c5960d74cfd80b46a53" name = "cast" version = "0.2.0" dependencies = [ + "alloy-contract", "alloy-dyn-abi", "alloy-json-abi", "alloy-primitives", @@ -3039,6 +3049,7 @@ dependencies = [ name = "foundry-common" version = "0.2.0" dependencies = [ + "alloy-contract", "alloy-dyn-abi", "alloy-json-abi", "alloy-json-rpc", @@ -3152,7 +3163,7 @@ dependencies = [ "tempfile", "thiserror", "toml 0.8.10", - "toml_edit 0.21.1", + "toml_edit 0.22.5", "tracing", "walkdir", ] @@ -7240,8 +7251,7 @@ dependencies = [ [[package]] name = "syn-solidity" version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63bef2e2c735acbc06874eca3a8506f02a3c4700e6e748afc92cc2e4220e8a03" +source = "git+https://github.com/alloy-rs/core?rev=18b0509950c90d9ec38f25913b692ae4cdd6f227#18b0509950c90d9ec38f25913b692ae4cdd6f227" dependencies = [ "paste", "proc-macro2", diff --git a/Cargo.toml b/Cargo.toml index 97e815342e71..aa84bc51f019 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -148,6 +148,7 @@ ethers-solc = { version = "2.0", default-features = false } ## alloy alloy-consensus = { git = "https://github.com/alloy-rs/alloy" } +alloy-contract = { git = "https://github.com/alloy-rs/alloy" } alloy-eips = { git = "https://github.com/alloy-rs/alloy" } alloy-genesis = { git = "https://github.com/alloy-rs/alloy" } alloy-json-rpc = { git = "https://github.com/alloy-rs/alloy" } @@ -164,9 +165,9 @@ alloy-transport-http = { git = "https://github.com/alloy-rs/alloy" } alloy-transport-ipc = { git = "https://github.com/alloy-rs/alloy" } alloy-transport-ws = { git = "https://github.com/alloy-rs/alloy" } alloy-primitives = { version = "0.6.2", features = ["getrandom"] } -alloy-dyn-abi = "0.6.2" -alloy-json-abi = "0.6.2" -alloy-sol-types = "0.6.2" +alloy-dyn-abi = "0.6" +alloy-json-abi = "0.6" +alloy-sol-types = "0.6" syn-solidity = "0.6.0" alloy-chains = "0.1" @@ -227,6 +228,11 @@ ethers-signers = { git = "https://github.com/gakonst/ethers-rs", rev = "f0e5b194 ethers-middleware = { git = "https://github.com/gakonst/ethers-rs", rev = "f0e5b194f09c533feb10d1a686ddb9e5946ec107" } ethers-solc = { git = "https://github.com/gakonst/ethers-rs", rev = "f0e5b194f09c533feb10d1a686ddb9e5946ec107" } +alloy-sol-types = { git = "https://github.com/alloy-rs/core", rev = "18b0509950c90d9ec38f25913b692ae4cdd6f227" } +alloy-dyn-abi = { git = "https://github.com/alloy-rs/core", rev = "18b0509950c90d9ec38f25913b692ae4cdd6f227" } +alloy-json-abi = { git = "https://github.com/alloy-rs/core", rev = "18b0509950c90d9ec38f25913b692ae4cdd6f227" } +alloy-primitives = { git = "https://github.com/alloy-rs/core", rev = "18b0509950c90d9ec38f25913b692ae4cdd6f227" } + revm = { git = "https://github.com/bluealloy/revm", branch = "reth_freeze" } revm-primitives = { git = "https://github.com/bluealloy/revm", branch = "reth_freeze" } revm-interpreter = { git = "https://github.com/bluealloy/revm", branch = "reth_freeze" } diff --git a/crates/anvil/src/eth/backend/fork.rs b/crates/anvil/src/eth/backend/fork.rs index baf177e25b62..033039bfa49c 100644 --- a/crates/anvil/src/eth/backend/fork.rs +++ b/crates/anvil/src/eth/backend/fork.rs @@ -268,7 +268,7 @@ impl ClientFork { let block_id = BlockId::Number(blocknumber.into()); - let code = self.provider().get_code_at(address, block_id).await?; + let code = self.provider().get_code_at(address, Some(block_id)).await?; let mut storage = self.storage_write(); storage.code_at.insert((address, blocknumber), code.clone().0.into()); diff --git a/crates/common/Cargo.toml b/crates/common/Cargo.toml index 530d75d8ef70..478186273120 100644 --- a/crates/common/Cargo.toml +++ b/crates/common/Cargo.toml @@ -33,6 +33,7 @@ alloy-transport-ipc.workspace = true alloy-json-rpc.workspace = true alloy-pubsub.workspace = true alloy-sol-types.workspace = true +alloy-contract.workspace = true tower.workspace = true diff --git a/crates/common/src/ens.rs b/crates/common/src/ens.rs new file mode 100644 index 000000000000..12da5a74ffa5 --- /dev/null +++ b/crates/common/src/ens.rs @@ -0,0 +1,142 @@ +//! ENS Name resolving utilities. +#![allow(missing_docs)] +use alloy_primitives::{address, keccak256, Address, B256}; +use alloy_providers::provider::TempProvider; +use alloy_sol_types::sol; +use std::str::FromStr; + +// ENS Registry and Resolver contracts. +sol! { + #[sol(rpc)] + // ENS Registry contract. + contract EnsRegistry { + /// Returns the resolver for the specified node. + function resolver(bytes32 node) view returns (address); + } + + #[sol(rpc)] + // ENS Resolver interface. + contract EnsResolver { + // Returns the address associated with the specified node. + function addr(bytes32 node) view returns (address); + } +} + +/// ENS registry address (`0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e`) +pub const ENS_ADDRESS: Address = address!("00000000000C2E074eC69A0dFb2997BA6C7d2e1e"); + +/// ENS name or Ethereum Address. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum NameOrAddress { + /// An ENS Name (format does not get checked) + Name(String), + /// An Ethereum Address + Address(Address), +} + +impl NameOrAddress { + /// Resolves the name to an Ethereum Address. + pub async fn resolve( + &self, + provider: &P, + ) -> Result { + let name = match self { + NameOrAddress::Name(name) => name.clone(), + NameOrAddress::Address(addr) => return Ok(*addr), + }; + let node = namehash(&name); + let registry = EnsRegistry::new(ENS_ADDRESS, provider); + let resolver = registry + .resolver(node) + .call() + .await + .map_err(|err| EnsResolutionError::EnsRegistryResolutionFailed(err.to_string()))? + ._0; + let resolver = EnsResolver::new(resolver, provider); + let addr = resolver + .addr(node) + .call() + .await + .map_err(|err| EnsResolutionError::EnsResolutionFailed(err.to_string()))? + ._0; + Ok(addr) + } +} + +impl From for NameOrAddress { + fn from(name: String) -> Self { + NameOrAddress::Name(name) + } +} + +impl From<&String> for NameOrAddress { + fn from(name: &String) -> Self { + NameOrAddress::Name(name.clone()) + } +} + +impl From
for NameOrAddress { + fn from(addr: Address) -> Self { + NameOrAddress::Address(addr) + } +} + +impl FromStr for NameOrAddress { + type Err =
::Err; + + fn from_str(s: &str) -> Result { + if let Ok(addr) = Address::from_str(s) { + Ok(NameOrAddress::Address(addr)) + } else { + Ok(NameOrAddress::Name(s.to_string())) + } + } +} + +/// Error type for ENS resolution. +#[derive(Debug, thiserror::Error)] +pub enum EnsResolutionError { + /// Failed to resolve ENS registry. + #[error("Failed to get resolver from ENS registry: {0}")] + EnsRegistryResolutionFailed(String), + /// Failed to resolve ENS name to an address. + #[error("Failed to resolve ENS name to an address: {0}")] + EnsResolutionFailed(String), +} + +/// Returns the ENS namehash as specified in [EIP-137](https://eips.ethereum.org/EIPS/eip-137) +pub fn namehash(name: &str) -> B256 { + if name.is_empty() { + return B256::ZERO + } + + // Remove the variation selector U+FE0F + let name = name.replace('\u{fe0f}', ""); + + // Generate the node starting from the right + name.rsplit('.') + .fold([0u8; 32], |node, label| *keccak256([node, *keccak256(label.as_bytes())].concat())) + .into() +} + +#[cfg(test)] +mod test { + use super::*; + + fn assert_hex(hash: B256, val: &str) { + assert_eq!(hash.0.to_vec(), hex::decode(val).unwrap()); + } + + #[test] + fn test_namehash() { + for (name, expected) in &[ + ("", "0000000000000000000000000000000000000000000000000000000000000000"), + ("foo.eth", "de9b09fd7c5f901e23a3f19fecc54828e9c848539801e86591bd9801b019f84f"), + ("eth", "0x93cdeb708b7545dc668eb9280176169d1c33cfd8ed6f04690a0bcc88a93fc4ae"), + ("alice.eth", "0x787192fc5378cc32aa956ddfdedbf26b24e8d78e40109add0eea2c1a012c3dec"), + ("ret↩️rn.eth", "0x3de5f4c02db61b221e7de7f1c40e29b6e2f07eb48d65bf7e304715cd9ed33b24"), + ] { + assert_hex(namehash(name), expected); + } + } +} diff --git a/crates/common/src/lib.rs b/crates/common/src/lib.rs index c2825ac2f997..36298ae8fe76 100644 --- a/crates/common/src/lib.rs +++ b/crates/common/src/lib.rs @@ -12,6 +12,7 @@ pub mod calc; pub mod compile; pub mod constants; pub mod contracts; +pub mod ens; pub mod errors; pub mod evm; pub mod fmt; diff --git a/crates/config/Cargo.toml b/crates/config/Cargo.toml index b3f4c514a766..3b1169b82438 100644 --- a/crates/config/Cargo.toml +++ b/crates/config/Cargo.toml @@ -34,7 +34,7 @@ serde_regex = "1" serde.workspace = true thiserror = "1" toml = { version = "0.8", features = ["preserve_order"] } -toml_edit = "0.21" +toml_edit = "0.22.4" tracing.workspace = true walkdir = "2" diff --git a/crates/evm/core/src/fork/backend.rs b/crates/evm/core/src/fork/backend.rs index 4223e2dea772..3a87583b6da4 100644 --- a/crates/evm/core/src/fork/backend.rs +++ b/crates/evm/core/src/fork/backend.rs @@ -5,7 +5,7 @@ use crate::{ }; use alloy_primitives::{keccak256, Address, Bytes, B256, U256}; use alloy_providers::provider::TempProvider; -use alloy_rpc_types::{Block, BlockId, BlockNumberOrTag, Transaction}; +use alloy_rpc_types::{Block, BlockId, Transaction}; use eyre::WrapErr; use foundry_common::NON_ARCHIVE_NODE_WARNING; use futures::{ @@ -196,8 +196,7 @@ where let fut = Box::pin(async move { let balance = provider.get_balance(address, block_id); let nonce = provider.get_transaction_count(address, block_id); - let code = - provider.get_code_at(address, block_id.unwrap_or(BlockNumberOrTag::Latest.into())); + let code = provider.get_code_at(address, block_id); let resp = tokio::try_join!(balance, nonce, code).map_err(Into::into); (resp, address) }); From f9d6c99dac4141ebd6a02d2313efde703f2b0d73 Mon Sep 17 00:00:00 2001 From: Enrique Date: Fri, 16 Feb 2024 12:37:01 -0400 Subject: [PATCH 04/63] feat(`cast`): Move non `tx` methods to alloy (#7129) * chore: add alloy contract * feat(cast): migrate most methods to alloy * chore: leave todo for converting a tx envelope into an rpc tx * fix: use proper type for storage * readd decodetx for now * chore: extend txbuilder to build an alloy tx request * feat: migrate most methods bar send/decode raw tx * fix: include tx data * simplify txbuilder * chore: simplify back access_list * chore: remove unnecesary conversion * fmt * doctests * fmt * do not use trait * Update crates/cast/bin/main.rs Co-authored-by: Matthias Seitz * cleanup builder * clippy * fix doc comments --------- Co-authored-by: Matthias Seitz --- Cargo.lock | 1 + crates/cast/Cargo.toml | 2 + crates/cast/bin/cmd/access_list.rs | 30 +++-- crates/cast/bin/cmd/call.rs | 31 ++--- crates/cast/bin/cmd/estimate.rs | 15 ++- crates/cast/bin/cmd/logs.rs | 6 +- crates/cast/bin/cmd/send.rs | 23 ++-- crates/cast/bin/cmd/storage.rs | 51 ++++---- crates/cast/bin/main.rs | 36 +++--- crates/cast/bin/opts.rs | 38 +++--- crates/cast/src/lib.rs | 123 +++++++++---------- crates/cast/src/tx.rs | 184 +++++++++++++---------------- 12 files changed, 261 insertions(+), 279 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index af9328a22583..dfc5ffee96eb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1257,6 +1257,7 @@ checksum = "df8670b8c7b9dae1793364eafadf7239c40d669904660c5960d74cfd80b46a53" name = "cast" version = "0.2.0" dependencies = [ + "alloy-consensus", "alloy-contract", "alloy-dyn-abi", "alloy-json-abi", diff --git a/crates/cast/Cargo.toml b/crates/cast/Cargo.toml index e97ae59c5241..1f5cbadba89c 100644 --- a/crates/cast/Cargo.toml +++ b/crates/cast/Cargo.toml @@ -33,6 +33,8 @@ alloy-rlp.workspace = true alloy-providers.workspace = true alloy-rpc-types.workspace = true alloy-signer.workspace = true +alloy-contract.workspace = true +alloy-consensus.workspace = true ethers-core.workspace = true ethers-providers.workspace = true diff --git a/crates/cast/bin/cmd/access_list.rs b/crates/cast/bin/cmd/access_list.rs index 3bb215c7d721..1c49ac67009b 100644 --- a/crates/cast/bin/cmd/access_list.rs +++ b/crates/cast/bin/cmd/access_list.rs @@ -1,14 +1,15 @@ +use alloy_primitives::Address; use alloy_providers::provider::TempProvider; +use alloy_rpc_types::BlockId; use cast::{Cast, TxBuilder}; use clap::Parser; -use ethers_core::types::{BlockId, NameOrAddress}; use ethers_providers::Middleware; use eyre::{Result, WrapErr}; use foundry_cli::{ opts::{EthereumOpts, TransactionOpts}, utils, }; -use foundry_common::types::ToEthers; +use foundry_common::ens::NameOrAddress; use foundry_config::{Chain, Config}; use std::str::FromStr; @@ -65,10 +66,18 @@ impl AccessListArgs { let chain = utils::get_chain(config.chain, &provider).await?; let sender = eth.wallet.sender().await; + let to = match to { + Some(NameOrAddress::Name(name)) => { + Some(NameOrAddress::Name(name).resolve(&alloy_provider).await?) + } + Some(NameOrAddress::Address(addr)) => Some(addr), + None => None, + }; + access_list( &provider, alloy_provider, - sender.to_ethers(), + sender, to, sig, args, @@ -84,16 +93,11 @@ impl AccessListArgs { } #[allow(clippy::too_many_arguments)] -async fn access_list< - M: Middleware, - P: TempProvider, - F: Into, - T: Into, ->( +async fn access_list( provider: M, alloy_provider: P, - from: F, - to: Option, + from: Address, + to: Option
, sig: Option, args: Vec, data: Option, @@ -105,7 +109,7 @@ async fn access_list< where M::Error: 'static, { - let mut builder = TxBuilder::new(&provider, from, to, chain, tx.legacy).await?; + let mut builder = TxBuilder::new(&alloy_provider, from, to, chain, tx.legacy).await?; builder .gas(tx.gas_limit) .gas_price(tx.gas_price) @@ -124,7 +128,7 @@ where let builder_output = builder.peek(); - let cast = Cast::new(&provider, alloy_provider); + let cast = Cast::new(&provider, &alloy_provider); let access_list: String = cast.access_list(builder_output, block, to_json).await?; diff --git a/crates/cast/bin/cmd/call.rs b/crates/cast/bin/cmd/call.rs index 1c6c5b1de566..894e9c1aa99b 100644 --- a/crates/cast/bin/cmd/call.rs +++ b/crates/cast/bin/cmd/call.rs @@ -1,23 +1,19 @@ use alloy_primitives::U256; +use alloy_providers::provider::TempProvider; +use alloy_rpc_types::BlockId; use cast::{Cast, TxBuilder}; use clap::Parser; -use ethers_core::types::{BlockId, NameOrAddress}; use eyre::{Result, WrapErr}; use foundry_cli::{ opts::{EthereumOpts, TransactionOpts}, utils::{self, handle_traces, parse_ether_value, TraceResult}, }; -use foundry_common::{ - runtime_client::RuntimeClient, - types::{ToAlloy, ToEthers}, -}; +use foundry_common::{ens::NameOrAddress, types::ToAlloy}; use foundry_compilers::EvmVersion; use foundry_config::{find_project_root_path, Config}; use foundry_evm::{executors::TracingExecutor, opts::EvmOpts}; use std::str::FromStr; -type Provider = ethers_providers::Provider; - /// CLI arguments for `cast call`. #[derive(Debug, Parser)] pub struct CallArgs { @@ -120,8 +116,15 @@ impl CallArgs { let chain = utils::get_chain(config.chain, &provider).await?; let sender = eth.wallet.sender().await; - let mut builder: TxBuilder<'_, Provider> = - TxBuilder::new(&provider, sender.to_ethers(), to, chain, tx.legacy).await?; + let to = match to { + Some(NameOrAddress::Name(name)) => { + Some(NameOrAddress::Name(name).resolve(&alloy_provider).await?) + } + Some(NameOrAddress::Address(addr)) => Some(addr), + None => None, + }; + + let mut builder = TxBuilder::new(&alloy_provider, sender, to, chain, tx.legacy).await?; builder .gas(tx.gas_limit) @@ -196,7 +199,7 @@ impl CallArgs { } }; - let builder_output = builder.build(); + let builder_output = builder.build_alloy(); println!("{}", Cast::new(provider, alloy_provider).call(builder_output, block).await?); Ok(()) @@ -204,8 +207,8 @@ impl CallArgs { } /// fills the builder from create arg -async fn fill_create( - builder: &mut TxBuilder<'_, Provider>, +async fn fill_create( + builder: &mut TxBuilder<'_, P>, value: Option, code: String, sig: Option, @@ -226,8 +229,8 @@ async fn fill_create( } /// fills the builder from args -async fn fill_tx( - builder: &mut TxBuilder<'_, Provider>, +async fn fill_tx( + builder: &mut TxBuilder<'_, P>, value: Option, sig: Option, args: Vec, diff --git a/crates/cast/bin/cmd/estimate.rs b/crates/cast/bin/cmd/estimate.rs index c963cfcacdae..3ae6ad9cc1a7 100644 --- a/crates/cast/bin/cmd/estimate.rs +++ b/crates/cast/bin/cmd/estimate.rs @@ -1,12 +1,12 @@ use alloy_primitives::U256; use cast::{Cast, TxBuilder}; use clap::Parser; -use ethers_core::types::NameOrAddress; use eyre::Result; use foundry_cli::{ opts::{EtherscanOpts, RpcOpts}, utils::{self, parse_ether_value}, }; +use foundry_common::ens::NameOrAddress; use foundry_config::{figment::Figment, Config}; use std::str::FromStr; @@ -87,7 +87,16 @@ impl EstimateArgs { let chain = utils::get_chain(config.chain, &provider).await?; let api_key = config.get_etherscan_api_key(Some(chain)); - let mut builder = TxBuilder::new(&provider, from, to, chain, false).await?; + let from = from.resolve(&alloy_provider).await?; + let to = match to { + Some(NameOrAddress::Name(name)) => { + Some(NameOrAddress::Name(name).resolve(&alloy_provider).await?) + } + Some(NameOrAddress::Address(addr)) => Some(addr), + None => None, + }; + + let mut builder = TxBuilder::new(&alloy_provider, from, to, chain, false).await?; builder.etherscan_api_key(api_key); match command { @@ -110,7 +119,7 @@ impl EstimateArgs { }; let builder_output = builder.peek(); - let gas = Cast::new(&provider, alloy_provider).estimate(builder_output).await?; + let gas = Cast::new(&provider, &alloy_provider).estimate(builder_output).await?; println!("{gas}"); Ok(()) } diff --git a/crates/cast/bin/cmd/logs.rs b/crates/cast/bin/cmd/logs.rs index fc195b63fcf7..5021b7a3ffa6 100644 --- a/crates/cast/bin/cmd/logs.rs +++ b/crates/cast/bin/cmd/logs.rs @@ -1,4 +1,4 @@ -use alloy_rpc_types::BlockHashOrNumber; +use alloy_rpc_types::BlockId; use cast::Cast; use clap::Parser; use ethers_core::{ @@ -23,13 +23,13 @@ pub struct LogsArgs { /// /// Can also be the tags earliest, finalized, safe, latest, or pending. #[clap(long)] - from_block: Option, + from_block: Option, /// The block height to stop query at. /// /// Can also be the tags earliest, finalized, safe, latest, or pending. #[clap(long)] - to_block: Option, + to_block: Option, /// The contract address to filter on. #[clap( diff --git a/crates/cast/bin/cmd/send.rs b/crates/cast/bin/cmd/send.rs index e208b7ed39e4..0b8f68750dde 100644 --- a/crates/cast/bin/cmd/send.rs +++ b/crates/cast/bin/cmd/send.rs @@ -1,7 +1,7 @@ +use alloy_primitives::Address; use alloy_providers::provider::TempProvider; use cast::{Cast, TxBuilder}; use clap::Parser; -use ethers_core::types::NameOrAddress; use ethers_middleware::MiddlewareBuilder; use ethers_providers::Middleware; use ethers_signers::Signer; @@ -12,6 +12,7 @@ use foundry_cli::{ }; use foundry_common::{ cli_warn, + ens::NameOrAddress, types::{ToAlloy, ToEthers}, }; use foundry_config::{Chain, Config}; @@ -119,6 +120,14 @@ impl SendTxArgs { let chain = utils::get_chain(config.chain, &provider).await?; let api_key = config.get_etherscan_api_key(Some(chain)); + let to = match to { + Some(NameOrAddress::Name(name)) => { + Some(NameOrAddress::Name(name).resolve(&alloy_provider).await?) + } + Some(NameOrAddress::Address(addr)) => Some(addr), + None => None, + }; + // Case 1: // Default to sending via eth_sendTransaction if the --unlocked flag is passed. // This should be the only way this RPC method is used as it requires a local node @@ -155,7 +164,7 @@ impl SendTxArgs { cast_send( provider, alloy_provider, - config.sender.to_ethers(), + config.sender, to, code, (sig, args), @@ -199,7 +208,7 @@ corresponds to the sender, or let foundry automatically detect it by not specify cast_send( provider, alloy_provider, - from, + from.to_alloy(), to, code, (sig, args), @@ -216,11 +225,11 @@ corresponds to the sender, or let foundry automatically detect it by not specify } #[allow(clippy::too_many_arguments)] -async fn cast_send, T: Into>( +async fn cast_send( provider: M, alloy_provider: P, - from: F, - to: Option, + from: Address, + to: Option
, code: Option, args: (String, Vec), tx: TransactionOpts, @@ -235,7 +244,7 @@ where { let (sig, params) = args; let params = if !sig.is_empty() { Some((&sig[..], params)) } else { None }; - let mut builder = TxBuilder::new(&provider, from, to, chain, tx.legacy).await?; + let mut builder = TxBuilder::new(&alloy_provider, from, to, chain, tx.legacy).await?; builder .etherscan_api_key(etherscan_api_key) .gas(tx.gas_limit) diff --git a/crates/cast/bin/cmd/storage.rs b/crates/cast/bin/cmd/storage.rs index e1a033a0f463..a7047f52dc6e 100644 --- a/crates/cast/bin/cmd/storage.rs +++ b/crates/cast/bin/cmd/storage.rs @@ -1,10 +1,10 @@ use crate::opts::parse_slot; -use alloy_primitives::{B256, U256}; +use alloy_primitives::{Address, B256, U256}; +use alloy_providers::provider::TempProvider; +use alloy_rpc_types::BlockId; use cast::Cast; use clap::Parser; use comfy_table::{presets::ASCII_MARKDOWN, Table}; -use ethers_core::types::{BlockId, NameOrAddress}; -use ethers_providers::Middleware; use eyre::Result; use foundry_block_explorers::Client; use foundry_cli::{ @@ -14,8 +14,7 @@ use foundry_cli::{ use foundry_common::{ abi::find_source, compile::{etherscan_project, ProjectCompiler}, - provider::ethers::RetryProvider, - types::{ToAlloy, ToEthers}, + ens::NameOrAddress, }; use foundry_compilers::{ artifacts::StorageLayout, Artifact, ConfigurableContractArtifact, Project, Solc, @@ -80,20 +79,20 @@ impl StorageArgs { let config = Config::from(&self); let Self { address, slot, block, build, .. } = self; - - let provider = utils::get_provider(&config)?; - let alloy_provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_alloy_provider(&config)?; + let ethers_provider = utils::get_provider(&config)?; + let address = address.resolve(&provider).await?; // Slot was provided, perform a simple RPC call if let Some(slot) = slot { - let cast = Cast::new(provider, alloy_provider); - println!("{}", cast.storage(address, slot.to_ethers(), block).await?); + let cast = Cast::new(ethers_provider, provider); + println!("{}", cast.storage(address, slot, block).await?); return Ok(()); } // No slot was provided // Get deployed bytecode at given address - let address_code = provider.get_code(address.clone(), block).await?.to_alloy(); + let address_code = provider.get_code_at(address, block).await?; if address_code.is_empty() { eyre::bail!("Provided address has no deployed code and thus no storage"); } @@ -108,8 +107,7 @@ impl StorageArgs { artifact.get_deployed_bytecode_bytes().is_some_and(|b| *b == address_code) }); if let Some((_, artifact)) = artifact { - return fetch_and_print_storage(provider, address.clone(), block, artifact, true) - .await; + return fetch_and_print_storage(provider, address, block, artifact, true).await; } } @@ -121,14 +119,10 @@ impl StorageArgs { eyre::bail!("You must provide an Etherscan API key if you're fetching a remote contract's storage."); } - let chain = utils::get_chain(config.chain, &provider).await?; + let chain = utils::get_chain(config.chain, ðers_provider).await?; let api_key = config.get_etherscan_api_key(Some(chain)).unwrap_or_default(); let client = Client::new(chain, api_key)?; - let addr = address - .as_address() - .ok_or_else(|| eyre::eyre!("Could not resolve address"))? - .to_alloy(); - let source = find_source(client, addr).await?; + let source = find_source(client, address).await?; let metadata = source.items.first().unwrap(); if metadata.is_vyper() { eyre::bail!("Contract at provided address is not a valid Solidity contract") @@ -210,9 +204,9 @@ impl StorageValue { } } -async fn fetch_and_print_storage( - provider: RetryProvider, - address: NameOrAddress, +async fn fetch_and_print_storage( + provider: P, + address: Address, block: Option, artifact: &ConfigurableContractArtifact, pretty: bool, @@ -227,18 +221,17 @@ async fn fetch_and_print_storage( } } -async fn fetch_storage_slots( - provider: RetryProvider, - address: NameOrAddress, +async fn fetch_storage_slots( + provider: P, + address: Address, block: Option, layout: &StorageLayout, ) -> Result> { let requests = layout.storage.iter().map(|storage_slot| async { let slot = B256::from(U256::from_str(&storage_slot.slot)?); - let raw_slot_value = - provider.get_storage_at(address.clone(), slot.to_ethers(), block).await?.to_alloy(); + let raw_slot_value = provider.get_storage_at(address, slot.into(), block).await?; - let value = StorageValue { slot, raw_slot_value }; + let value = StorageValue { slot, raw_slot_value: raw_slot_value.into() }; Ok(value) }); @@ -267,7 +260,7 @@ fn print_storage(layout: StorageLayout, values: Vec, pretty: bool) storage_type.map_or("?", |t| &t.label), &slot.slot, &slot.offset.to_string(), - &storage_type.map_or("?", |t| &t.number_of_bytes), + (storage_type.map_or("?", |t| &t.number_of_bytes)), &converted_value.to_string(), &value.to_string(), &slot.contract, diff --git a/crates/cast/bin/main.rs b/crates/cast/bin/main.rs index 96d3a30ad440..ceadb96d1a20 100644 --- a/crates/cast/bin/main.rs +++ b/crates/cast/bin/main.rs @@ -5,15 +5,14 @@ use alloy_primitives::{keccak256, Address, B256}; use cast::{Cast, SimpleCast, TxBuilder}; use clap::{CommandFactory, Parser}; use clap_complete::generate; -use ethers_core::types::{BlockId, BlockNumber::Latest, NameOrAddress}; -use ethers_providers::{Middleware, Provider}; +use ethers_core::types::{BlockId, BlockNumber::Latest}; +use ethers_providers::Middleware; use eyre::Result; use foundry_cli::{handler, prompt, stdin, utils}; use foundry_common::{ abi::get_event, fmt::format_tokens, fs, - runtime_client::RuntimeClient, selectors::{ decode_calldata, decode_event_topic, decode_function_selector, decode_selectors, import_selectors, parse_signatures, pretty_calldata, ParsedSignatures, SelectorImportData, @@ -209,23 +208,14 @@ async fn main() -> Result<()> { let config = Config::from(&rpc); let provider = utils::get_provider(&config)?; let alloy_provider = utils::get_alloy_provider(&config)?; + let account_addr = who.resolve(&alloy_provider).await?; match erc20 { Some(token) => { let chain = utils::get_chain(config.chain, &provider).await?; - let mut builder: TxBuilder<'_, Provider> = TxBuilder::new( - &provider, - NameOrAddress::Address(Address::ZERO.to_ethers()), - Some(NameOrAddress::Address(token.to_ethers())), - chain, - true, - ) - .await?; - - let account_addr = match who { - NameOrAddress::Name(ens_name) => provider.resolve_name(&ens_name).await?, - NameOrAddress::Address(addr) => addr, - }; + let mut builder = + TxBuilder::new(&alloy_provider, Address::ZERO, Some(token), chain, true) + .await?; builder .set_args( @@ -233,14 +223,15 @@ async fn main() -> Result<()> { vec![format!("{account_addr:#x}")], ) .await?; - let builder_output = builder.build(); + let builder_output = builder.build_alloy(); println!( "{}", - Cast::new(provider, alloy_provider).call(builder_output, block).await? + Cast::new(&provider, &alloy_provider).call(builder_output, block).await? ); } None => { - let value = Cast::new(provider, alloy_provider).balance(who, block).await?; + let value = + Cast::new(&provider, &alloy_provider).balance(account_addr, block).await?; if ether { println!("{}", SimpleCast::from_wei(&value.to_string(), "eth")?); } else { @@ -298,6 +289,7 @@ async fn main() -> Result<()> { let config = Config::from(&rpc); let provider = utils::get_provider(&config)?; let alloy_provider = utils::get_alloy_provider(&config)?; + let who = who.resolve(&alloy_provider).await?; println!( "{}", Cast::new(provider, alloy_provider).code(who, block, disassemble).await? @@ -307,6 +299,7 @@ async fn main() -> Result<()> { let config = Config::from(&rpc); let provider = utils::get_provider(&config)?; let alloy_provider = utils::get_alloy_provider(&config)?; + let who = who.resolve(&alloy_provider).await?; println!("{}", Cast::new(provider, alloy_provider).codesize(who, block).await?); } CastSubcommand::ComputeAddress { address, nonce, rpc } => { @@ -359,18 +352,21 @@ async fn main() -> Result<()> { let config = Config::from(&rpc); let provider = utils::get_provider(&config)?; let alloy_provider = utils::get_alloy_provider(&config)?; + let who = who.resolve(&alloy_provider).await?; println!("{}", Cast::new(provider, alloy_provider).implementation(who, block).await?); } CastSubcommand::Admin { block, who, rpc } => { let config = Config::from(&rpc); let provider = utils::get_provider(&config)?; let alloy_provider = utils::get_alloy_provider(&config)?; + let who = who.resolve(&alloy_provider).await?; println!("{}", Cast::new(provider, alloy_provider).admin(who, block).await?); } CastSubcommand::Nonce { block, who, rpc } => { let config = Config::from(&rpc); let provider = utils::get_provider(&config)?; let alloy_provider = utils::get_alloy_provider(&config)?; + let who = who.resolve(&alloy_provider).await?; println!("{}", Cast::new(provider, alloy_provider).nonce(who, block).await?); } CastSubcommand::Proof { address, slots, rpc, block } => { @@ -578,7 +574,7 @@ async fn main() -> Result<()> { let tx = stdin::unwrap_line(tx)?; let (tx, sig) = SimpleCast::decode_raw_transaction(&tx)?; - // Serialize tx, sig and constructed a merged json string + // Serialize tx, sig and construct a merged json string let mut tx = serde_json::to_value(&tx)?; let tx_map = tx.as_object_mut().unwrap(); serde_json::to_value(sig)?.as_object().unwrap().iter().for_each(|(k, v)| { diff --git a/crates/cast/bin/opts.rs b/crates/cast/bin/opts.rs index 2f09c2534830..ac63684b588a 100644 --- a/crates/cast/bin/opts.rs +++ b/crates/cast/bin/opts.rs @@ -4,10 +4,12 @@ use crate::cmd::{ rpc::RpcArgs, run::RunArgs, send::SendTxArgs, storage::StorageArgs, wallet::WalletSubcommands, }; use alloy_primitives::{Address, B256, U256}; +use alloy_rpc_types::BlockId as AlloyBlockId; use clap::{Parser, Subcommand, ValueHint}; use ethers_core::types::{BlockId, NameOrAddress}; use eyre::Result; use foundry_cli::opts::{EtherscanOpts, RpcOpts}; +use foundry_common::ens::NameOrAddress as EnsNameOrAddress; use std::{path::PathBuf, str::FromStr}; const VERSION_MESSAGE: &str = concat!( @@ -516,11 +518,11 @@ pub enum CastSubcommand { /// /// Can also be the tags earliest, finalized, safe, latest, or pending. #[clap(long, short = 'B')] - block: Option, + block: Option, /// The address to get the nonce for. - #[clap(value_parser = NameOrAddress::from_str)] - who: NameOrAddress, + #[clap(value_parser = EnsNameOrAddress::from_str)] + who: EnsNameOrAddress, #[clap(flatten)] rpc: RpcOpts, @@ -533,11 +535,11 @@ pub enum CastSubcommand { /// /// Can also be the tags earliest, finalized, safe, latest, or pending. #[clap(long, short = 'B')] - block: Option, + block: Option, /// The address to get the nonce for. - #[clap(value_parser = NameOrAddress::from_str)] - who: NameOrAddress, + #[clap(value_parser = EnsNameOrAddress::from_str)] + who: EnsNameOrAddress, #[clap(flatten)] rpc: RpcOpts, @@ -613,11 +615,11 @@ pub enum CastSubcommand { /// /// Can also be the tags earliest, finalized, safe, latest, or pending. #[clap(long, short = 'B')] - block: Option, + block: Option, /// The account to query. - #[clap(value_parser = NameOrAddress::from_str)] - who: NameOrAddress, + #[clap(value_parser = EnsNameOrAddress::from_str)] + who: EnsNameOrAddress, /// Format the balance in ether. #[clap(long, short)] @@ -651,11 +653,11 @@ pub enum CastSubcommand { /// /// Can also be the tags earliest, finalized, safe, latest, or pending. #[clap(long, short = 'B')] - block: Option, + block: Option, /// The contract address. - #[clap(value_parser = NameOrAddress::from_str)] - who: NameOrAddress, + #[clap(value_parser = EnsNameOrAddress::from_str)] + who: EnsNameOrAddress, /// Disassemble bytecodes into individual opcodes. #[clap(long, short)] @@ -672,11 +674,11 @@ pub enum CastSubcommand { /// /// Can also be the tags earliest, finalized, safe, latest, or pending. #[clap(long, short = 'B')] - block: Option, + block: Option, /// The contract address. - #[clap(value_parser = NameOrAddress::from_str)] - who: NameOrAddress, + #[clap(value_parser = EnsNameOrAddress::from_str)] + who: EnsNameOrAddress, #[clap(flatten)] rpc: RpcOpts, @@ -763,11 +765,11 @@ pub enum CastSubcommand { /// /// Can also be the tags earliest, finalized, safe, latest, or pending. #[clap(long, short = 'B')] - block: Option, + block: Option, /// The address to get the nonce for. - #[clap(value_parser = NameOrAddress::from_str)] - who: NameOrAddress, + #[clap(value_parser = EnsNameOrAddress::from_str)] + who: EnsNameOrAddress, #[clap(flatten)] rpc: RpcOpts, diff --git a/crates/cast/src/lib.rs b/crates/cast/src/lib.rs index 8467fd8de637..c4e5f26ac57a 100644 --- a/crates/cast/src/lib.rs +++ b/crates/cast/src/lib.rs @@ -6,14 +6,11 @@ use alloy_primitives::{ }; use alloy_providers::provider::TempProvider; use alloy_rlp::Decodable; -use alloy_rpc_types::{BlockHashOrNumber, BlockNumberOrTag}; +use alloy_rpc_types::{BlockId as AlloyBlockId, BlockNumberOrTag}; use base::{Base, NumberWithBase, ToBase}; use chrono::NaiveDateTime; use ethers_core::{ - types::{ - transaction::eip2718::TypedTransaction, BlockId, Filter, NameOrAddress, Signature, H160, - H256, - }, + types::{transaction::eip2718::TypedTransaction, BlockId, Filter, Signature, H256}, utils::rlp, }; use ethers_providers::{Middleware, PendingTransaction, PubsubClient}; @@ -23,7 +20,6 @@ use foundry_block_explorers::Client; use foundry_common::{ abi::{encode_function_args, get_func}, fmt::*, - types::{ToAlloy, ToEthers}, TransactionReceiptWithRevertReason, }; use foundry_config::Chain; @@ -36,7 +32,7 @@ use std::{ sync::atomic::{AtomicBool, Ordering}, }; use tokio::signal::ctrl_c; -use tx::{TxBuilderOutput, TxBuilderPeekOutput}; +use tx::{TxBuilderAlloyOutput, TxBuilderOutput, TxBuilderPeekOutput}; pub use foundry_evm::*; pub use rusoto_core::{ @@ -71,10 +67,12 @@ where /// ``` /// use cast::Cast; /// use ethers_providers::{Http, Provider}; + /// use foundry_common::provider::alloy::get_http_provider; /// /// # async fn foo() -> eyre::Result<()> { /// let provider = Provider::::try_from("http://localhost:8545")?; - /// let cast = Cast::new(provider); + /// let alloy_provider = get_http_provider("http://localhost:8545"); + /// let cast = Cast::new(provider, alloy_provider); /// # Ok(()) /// # } /// ``` @@ -90,10 +88,12 @@ where /// use cast::{Cast, TxBuilder}; /// use ethers_core::types::Address; /// use ethers_providers::{Http, Provider}; + /// use foundry_common::provider::alloy::get_http_provider; /// use std::str::FromStr; /// /// # async fn foo() -> eyre::Result<()> { /// let provider = Provider::::try_from("http://localhost:8545")?; + /// let alloy_provider = get_http_provider("http://localhost:8545"); /// let to = Address::from_str("0xB3C95ff08316fb2F2e3E52Ee82F8e7b605Aa1304")?; /// let sig = "function greeting(uint256 i) public returns (string)"; /// let args = vec!["5".to_owned()]; @@ -101,7 +101,7 @@ where /// TxBuilder::new(&provider, Address::zero(), Some(to), Chain::Mainnet, false).await?; /// builder.set_args(sig, args).await?; /// let builder_output = builder.build(); - /// let cast = Cast::new(provider); + /// let cast = Cast::new(provider, alloy_provider); /// let data = cast.call(builder_output, None).await?; /// println!("{}", data); /// # Ok(()) @@ -109,11 +109,11 @@ where /// ``` pub async fn call<'a>( &self, - builder_output: TxBuilderOutput, - block: Option, + builder_output: TxBuilderAlloyOutput, + block: Option, ) -> Result { let (tx, func) = builder_output; - let res = self.provider.call(&tx, block).await?; + let res = self.alloy_provider.call(tx.clone(), block).await?; let mut decoded = vec![]; @@ -125,8 +125,8 @@ where // ensure the address is a contract if res.is_empty() { // check that the recipient is a contract that can be called - if let Some(NameOrAddress::Address(addr)) = tx.to() { - if let Ok(code) = self.provider.get_code(*addr, block).await { + if let Some(addr) = tx.to { + if let Ok(code) = self.alloy_provider.get_code_at(addr, block).await { if code.is_empty() { eyre::bail!("contract {addr:?} does not have any code") } @@ -177,18 +177,18 @@ where pub async fn access_list( &self, builder_output: TxBuilderPeekOutput<'_>, - block: Option, + block: Option, to_json: bool, ) -> Result { let (tx, _) = builder_output; - let access_list = self.provider.create_access_list(tx, block).await?; + let access_list = self.alloy_provider.create_access_list(tx.clone(), block).await?; let res = if to_json { serde_json::to_string(&access_list)? } else { let mut s = vec![format!("gas used: {}", access_list.gas_used), "access list:".to_string()]; for al in access_list.access_list.0 { - s.push(format!("- address: {}", &al.address.to_alloy().to_checksum(None))); + s.push(format!("- address: {}", &al.address.to_checksum(None))); if !al.storage_keys.is_empty() { s.push(" keys:".to_string()); for key in al.storage_keys { @@ -202,12 +202,8 @@ where Ok(res) } - pub async fn balance + Send + Sync>( - &self, - who: T, - block: Option, - ) -> Result { - Ok(self.provider.get_balance(who, block).await?.to_alloy()) + pub async fn balance(&self, who: Address, block: Option) -> Result { + Ok(self.alloy_provider.get_balance(who, block).await?) } /// Sends a transaction to the specified address @@ -305,9 +301,9 @@ where pub async fn estimate(&self, builder_output: TxBuilderPeekOutput<'_>) -> Result { let (tx, _) = builder_output; - let res = self.provider.estimate_gas(tx, None).await?; + let res = self.alloy_provider.estimate_gas(tx.clone(), None).await?; - Ok::<_, eyre::Error>(res.to_alloy()) + Ok::<_, eyre::Error>(res) } /// # Example @@ -494,12 +490,8 @@ where /// # Ok(()) /// # } /// ``` - pub async fn nonce + Send + Sync>( - &self, - who: T, - block: Option, - ) -> Result { - Ok(self.provider.get_transaction_count(who, block).await?.to_alloy().to()) + pub async fn nonce(&self, who: Address, block: Option) -> Result { + Ok(self.alloy_provider.get_transaction_count(who, block).await?.to()) } /// # Example @@ -519,15 +511,15 @@ where /// # Ok(()) /// # } /// ``` - pub async fn implementation + Send + Sync>( + pub async fn implementation( &self, - who: T, - block: Option, + who: Address, + block: Option, ) -> Result { let slot = - H256::from_str("0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc")?; - let value = self.provider.get_storage_at(who, slot, block).await?; - let addr: H160 = value.into(); + B256::from_str("0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc")?; + let value = self.alloy_provider.get_storage_at(who, slot.into(), block).await?; + let addr = Address::from_word(value.into()); Ok(format!("{addr:?}")) } @@ -548,15 +540,11 @@ where /// # Ok(()) /// # } /// ``` - pub async fn admin + Send + Sync>( - &self, - who: T, - block: Option, - ) -> Result { + pub async fn admin(&self, who: Address, block: Option) -> Result { let slot = - H256::from_str("0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103")?; - let value = self.provider.get_storage_at(who, slot, block).await?; - let addr: H160 = value.into(); + B256::from_str("0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103")?; + let value = self.alloy_provider.get_storage_at(who, slot.into(), block).await?; + let addr = Address::from_word(value.into()); Ok(format!("{addr:?}")) } @@ -578,8 +566,7 @@ where /// # } /// ``` pub async fn compute_address(&self, address: Address, nonce: Option) -> Result
{ - let unpacked = - if let Some(n) = nonce { n } else { self.nonce(address.to_ethers(), None).await? }; + let unpacked = if let Some(n) = nonce { n } else { self.nonce(address, None).await? }; Ok(address.create(unpacked)) } @@ -600,17 +587,17 @@ where /// # Ok(()) /// # } /// ``` - pub async fn code + Send + Sync>( + pub async fn code( &self, - who: T, - block: Option, + who: Address, + block: Option, disassemble: bool, ) -> Result { if disassemble { - let code = self.provider.get_code(who, block).await?.to_vec(); + let code = self.alloy_provider.get_code_at(who, block).await?.to_vec(); Ok(format_operations(disassemble_bytes(code)?)?) } else { - Ok(format!("{}", self.provider.get_code(who, block).await?)) + Ok(format!("{}", self.alloy_provider.get_code_at(who, block).await?)) } } @@ -631,12 +618,8 @@ where /// # Ok(()) /// # } /// ``` - pub async fn codesize + Send + Sync>( - &self, - who: T, - block: Option, - ) -> Result { - let code = self.provider.get_code(who, block).await?.to_vec(); + pub async fn codesize(&self, who: Address, block: Option) -> Result { + let code = self.alloy_provider.get_code_at(who, block).await?.to_vec(); Ok(format!("{}", code.len())) } @@ -789,13 +772,16 @@ where /// # Ok(()) /// # } /// ``` - pub async fn storage + Send + Sync>( + pub async fn storage( &self, - from: T, - slot: H256, - block: Option, + from: Address, + slot: B256, + block: Option, ) -> Result { - Ok(format!("{:?}", self.provider.get_storage_at(from, slot, block).await?)) + Ok(format!( + "{:?}", + B256::from(self.alloy_provider.get_storage_at(from, slot.into(), block).await?) + )) } pub async fn filter_logs(&self, filter: Filter, to_json: bool) -> Result { @@ -850,15 +836,14 @@ where /// ``` pub async fn convert_block_number( &self, - block: Option, + block: Option, ) -> Result, eyre::Error> { match block { Some(block) => match block { - BlockHashOrNumber::Number(block_number) => { - Ok(Some(BlockNumberOrTag::Number(block_number))) - } - BlockHashOrNumber::Hash(hash) => { - let block = self.alloy_provider.get_block_by_hash(hash, false).await?; + AlloyBlockId::Number(block_number) => Ok(Some(block_number)), + AlloyBlockId::Hash(hash) => { + let block = + self.alloy_provider.get_block_by_hash(hash.block_hash, false).await?; Ok(block .map(|block| block.header.number.unwrap().to::()) .map(BlockNumberOrTag::from)) diff --git a/crates/cast/src/tx.rs b/crates/cast/src/tx.rs index 1bfd0c40ff67..b20d24563c8b 100644 --- a/crates/cast/src/tx.rs +++ b/crates/cast/src/tx.rs @@ -1,21 +1,23 @@ use crate::errors::FunctionSignatureError; use alloy_json_abi::Function; -use alloy_primitives::{Address, U256}; +use alloy_primitives::{Address, Bytes, U256, U64}; +use alloy_providers::provider::TempProvider; +use alloy_rpc_types::request::{TransactionInput, TransactionRequest as AlloyTransactionRequest}; use ethers_core::types::{ - transaction::eip2718::TypedTransaction, Eip1559TransactionRequest, NameOrAddress, - TransactionRequest, + transaction::eip2718::TypedTransaction, Eip1559TransactionRequest, TransactionRequest, }; -use ethers_providers::Middleware; -use eyre::{eyre, Result}; +use eyre::Result; use foundry_common::{ abi::{encode_function_args, get_func, get_func_etherscan}, - types::{ToAlloy, ToEthers}, + ens::NameOrAddress, + types::ToEthers, }; use foundry_config::Chain; use futures::future::join_all; pub type TxBuilderOutput = (TypedTransaction, Option); -pub type TxBuilderPeekOutput<'a> = (&'a TypedTransaction, &'a Option); +pub type TxBuilderAlloyOutput = (AlloyTransactionRequest, Option); +pub type TxBuilderPeekOutput<'a> = (&'a AlloyTransactionRequest, &'a Option); /// Transaction builder /// @@ -23,62 +25,77 @@ pub type TxBuilderPeekOutput<'a> = (&'a TypedTransaction, &'a Option); /// /// ``` /// # async fn foo() -> eyre::Result<()> { -/// # use alloy_primitives::U256; +/// # use alloy_primitives::{Address, U256}; /// # use cast::TxBuilder; /// # use foundry_config::NamedChain; -/// let provider = ethers_providers::test_provider::MAINNET.provider(); -/// let mut builder = -/// TxBuilder::new(&provider, "a.eth", Some("b.eth"), NamedChain::Mainnet, false).await?; +/// # use std::str::FromStr; +/// let provider = foundry_common::provider::alloy::get_http_provider("http://localhost:8545"); +/// let from = Address::from_str("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045").unwrap(); +/// let to = Address::from_str("0xb8c2c29ee19d8307cb7255e1cd9cbde883a267d5").unwrap(); +/// let mut builder = TxBuilder::new(&provider, from, Some(to), NamedChain::Mainnet, false).await?; /// builder.gas(Some(U256::from(1))); /// let (tx, _) = builder.build(); /// # Ok(()) /// # } /// ``` -pub struct TxBuilder<'a, M: Middleware> { +#[derive(Debug)] +pub struct TxBuilder<'a, P: TempProvider> { to: Option
, chain: Chain, tx: TypedTransaction, + alloy_tx: AlloyTransactionRequest, func: Option, etherscan_api_key: Option, - provider: &'a M, + provider: &'a P, } -impl<'a, M: Middleware> TxBuilder<'a, M> { +impl<'a, P: TempProvider> TxBuilder<'a, P> { /// Create a new TxBuilder /// `provider` - provider to use /// `from` - 'from' field. Could be an ENS name /// `to` - `to`. Could be a ENS /// `chain` - chain to construct the tx for /// `legacy` - use type 1 transaction - pub async fn new, T: Into>( - provider: &'a M, - from: F, - to: Option, + pub async fn new( + provider: &'a P, + from: Address, + to: Option
, chain: impl Into, legacy: bool, - ) -> Result> { + ) -> Result> { let chain = chain.into(); - let from_addr = resolve_ens(provider, from).await?; - let mut tx: TypedTransaction = if chain.is_legacy() || legacy { - TransactionRequest::new().from(from_addr.to_ethers()).chain_id(chain.id()).into() + let (mut tx, mut alloy_tx): (TypedTransaction, AlloyTransactionRequest) = if chain + .is_legacy() || + legacy + { + ( + TransactionRequest::new().from(from.to_ethers()).chain_id(chain.id()).into(), + AlloyTransactionRequest::default().from(from).transaction_type(0), + ) } else { - Eip1559TransactionRequest::new().from(from_addr.to_ethers()).chain_id(chain.id()).into() + ( + Eip1559TransactionRequest::new().from(from.to_ethers()).chain_id(chain.id()).into(), + AlloyTransactionRequest::default().from(from).transaction_type(2), + ) }; let to_addr = if let Some(to) = to { - let addr = resolve_ens(provider, to).await?; - tx.set_to(addr.to_ethers()); - Some(addr) + tx.set_to(to.to_ethers()); + Some(to) } else { None }; - Ok(Self { to: to_addr, chain, tx, func: None, etherscan_api_key: None, provider }) + + alloy_tx.to = to_addr; + + Ok(Self { to: to_addr, chain, tx, alloy_tx, func: None, etherscan_api_key: None, provider }) } /// Set gas for tx pub fn set_gas(&mut self, v: U256) -> &mut Self { self.tx.set_gas(v.to_ethers()); + self.alloy_tx.gas = Some(v); self } @@ -93,6 +110,7 @@ impl<'a, M: Middleware> TxBuilder<'a, M> { /// Set gas price pub fn set_gas_price(&mut self, v: U256) -> &mut Self { self.tx.set_gas_price(v.to_ethers()); + self.alloy_tx.gas_price = Some(v); self } @@ -109,6 +127,11 @@ impl<'a, M: Middleware> TxBuilder<'a, M> { if let TypedTransaction::Eip1559(tx) = &mut self.tx { tx.max_priority_fee_per_gas = Some(v.to_ethers()) } + + if let Some(2) = self.alloy_tx.transaction_type.map(|v| v.to::()) { + self.alloy_tx.max_priority_fee_per_gas = Some(v); + } + self } @@ -123,6 +146,7 @@ impl<'a, M: Middleware> TxBuilder<'a, M> { /// Set value pub fn set_value(&mut self, v: U256) -> &mut Self { self.tx.set_value(v.to_ethers()); + self.alloy_tx.value = Some(v); self } @@ -137,6 +161,7 @@ impl<'a, M: Middleware> TxBuilder<'a, M> { /// Set nonce pub fn set_nonce(&mut self, v: U256) -> &mut Self { self.tx.set_nonce(v.to_ethers()); + self.alloy_tx.nonce = Some(v.to::()); self } @@ -163,7 +188,8 @@ impl<'a, M: Middleware> TxBuilder<'a, M> { } pub fn set_data(&mut self, v: Vec) -> &mut Self { - self.tx.set_data(v.into()); + self.tx.set_data(v.clone().into()); + self.alloy_tx.input = TransactionInput::new(Bytes::from(v.clone())); self } @@ -215,9 +241,10 @@ impl<'a, M: Middleware> TxBuilder<'a, M> { &mut self, sig: &str, args: Vec, - ) -> Result<&mut TxBuilder<'a, M>> { + ) -> Result<&mut TxBuilder<'a, P>> { let (data, func) = self.create_args(sig, args).await?; - self.tx.set_data(data.into()); + self.tx.set_data(data.clone().into()); + self.alloy_tx.input = TransactionInput::new(Bytes::from(data)); self.func = Some(func); Ok(self) } @@ -226,7 +253,7 @@ impl<'a, M: Middleware> TxBuilder<'a, M> { pub async fn args( &mut self, value: Option<(&str, Vec)>, - ) -> Result<&mut TxBuilder<'a, M>> { + ) -> Result<&mut TxBuilder<'a, P>> { if let Some((sig, args)) = value { return self.set_args(sig, args).await } @@ -238,30 +265,22 @@ impl<'a, M: Middleware> TxBuilder<'a, M> { (self.tx, self.func) } - /// Non-consuming build: peek into the tx content - pub fn peek(&self) -> TxBuilderPeekOutput { - (&self.tx, &self.func) + /// Consuming build: returns alloy transaction and optional function call + pub fn build_alloy(self) -> TxBuilderAlloyOutput { + (self.alloy_tx, self.func) } -} -async fn resolve_ens>( - provider: &M, - addr: T, -) -> Result
{ - let from_addr = match addr.into() { - NameOrAddress::Name(ref ens_name) => provider.resolve_name(ens_name).await, - NameOrAddress::Address(addr) => Ok(addr), + pub fn peek(&self) -> TxBuilderPeekOutput { + (&self.alloy_tx, &self.func) } - .map_err(|x| eyre!("Failed to resolve ENS name: {x}"))?; - Ok(from_addr.to_alloy()) } -async fn resolve_name_args(args: &[String], provider: &M) -> Vec { +async fn resolve_name_args(args: &[String], provider: &P) -> Vec { join_all(args.iter().map(|arg| async { if arg.contains('.') { - let addr = provider.resolve_name(arg).await; + let addr = NameOrAddress::Name(arg.to_string()).resolve(provider).await; match addr { - Ok(addr) => format!("{addr:?}"), + Ok(addr) => addr.to_string(), Err(_) => arg.to_string(), } } else { @@ -275,63 +294,22 @@ async fn resolve_name_args(args: &[String], provider: &M) -> Vec< mod tests { use crate::TxBuilder; use alloy_primitives::{Address, U256}; - use async_trait::async_trait; - use ethers_core::types::{transaction::eip2718::TypedTransaction, NameOrAddress, H160}; - use ethers_providers::{JsonRpcClient, Middleware, ProviderError}; + use ethers_core::types::{transaction::eip2718::TypedTransaction, NameOrAddress}; use foundry_common::types::ToEthers; use foundry_config::NamedChain; - use serde::{de::DeserializeOwned, Serialize}; - use std::str::FromStr; - - const ADDR_1: &str = "0000000000000000000000000000000000000001"; - const ADDR_2: &str = "0000000000000000000000000000000000000002"; - - #[derive(Debug)] - struct MyProvider {} - - #[cfg_attr(target_arch = "wasm32", async_trait(?Send))] - #[cfg_attr(not(target_arch = "wasm32"), async_trait)] - impl JsonRpcClient for MyProvider { - type Error = ProviderError; - - async fn request( - &self, - _method: &str, - _params: T, - ) -> Result { - Err(ProviderError::CustomError("There is no request".to_string())) - } - } - #[cfg_attr(target_arch = "wasm32", async_trait(?Send))] - #[cfg_attr(not(target_arch = "wasm32"), async_trait)] - impl Middleware for MyProvider { - type Error = ProviderError; - type Provider = MyProvider; - type Inner = MyProvider; - - fn inner(&self) -> &Self::Inner { - self - } - async fn resolve_name(&self, ens_name: &str) -> Result { - match ens_name { - "a.eth" => Ok(H160::from_str(ADDR_1).unwrap()), - "b.eth" => Ok(H160::from_str(ADDR_2).unwrap()), - _ => unreachable!("don't know how to resolve {ens_name}"), - } - } - } + const ADDR_1: Address = Address::with_last_byte(1); + const ADDR_2: Address = Address::with_last_byte(2); + #[tokio::test(flavor = "multi_thread")] async fn builder_new_non_legacy() -> eyre::Result<()> { - let provider = MyProvider {}; + // Instanciate a local provider although it'll do nothing. + let provider = foundry_common::provider::alloy::get_http_provider("http://localhost:8545"); let builder = - TxBuilder::new(&provider, "a.eth", Some("b.eth"), NamedChain::Mainnet, false).await?; + TxBuilder::new(&provider, ADDR_1, Some(ADDR_2), NamedChain::Mainnet, false).await?; let (tx, args) = builder.build(); - assert_eq!(*tx.from().unwrap(), Address::from_str(ADDR_1).unwrap().to_ethers()); - assert_eq!( - *tx.to().unwrap(), - NameOrAddress::Address(Address::from_str(ADDR_2).unwrap().to_ethers()) - ); + assert_eq!(*tx.from().unwrap(), ADDR_1.to_ethers()); + assert_eq!(*tx.to().unwrap(), NameOrAddress::Address(ADDR_2.to_ethers())); assert_eq!(args, None); match tx { @@ -345,9 +323,9 @@ mod tests { #[tokio::test(flavor = "multi_thread")] async fn builder_new_legacy() -> eyre::Result<()> { - let provider = MyProvider {}; + let provider = foundry_common::provider::alloy::get_http_provider("http://localhost:8545"); let builder = - TxBuilder::new(&provider, "a.eth", Some("b.eth"), NamedChain::Mainnet, true).await?; + TxBuilder::new(&provider, ADDR_1, Some(ADDR_2), NamedChain::Mainnet, true).await?; // don't check anything other than the tx type - the rest is covered in the non-legacy case let (tx, _) = builder.build(); match tx { @@ -361,9 +339,9 @@ mod tests { #[tokio::test(flavor = "multi_thread")] async fn builder_fields() -> eyre::Result<()> { - let provider = MyProvider {}; + let provider = foundry_common::provider::alloy::get_http_provider("http://localhost:8545"); let mut builder = - TxBuilder::new(&provider, "a.eth", Some("b.eth"), NamedChain::Mainnet, false) + TxBuilder::new(&provider, ADDR_1, Some(ADDR_2), NamedChain::Mainnet, false) .await .unwrap(); builder @@ -385,9 +363,9 @@ mod tests { #[tokio::test(flavor = "multi_thread")] async fn builder_args() -> eyre::Result<()> { - let provider = MyProvider {}; + let provider = foundry_common::provider::alloy::get_http_provider("http://localhost:8545"); let mut builder = - TxBuilder::new(&provider, "a.eth", Some("b.eth"), NamedChain::Mainnet, false) + TxBuilder::new(&provider, ADDR_1, Some(ADDR_2), NamedChain::Mainnet, false) .await .unwrap(); builder.args(Some(("what_a_day(int)", vec![String::from("31337")]))).await?; From e482bee3818630496baeec6dd6c7940f5eed9701 Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Mon, 18 Mar 2024 18:16:16 +0400 Subject: [PATCH 05/63] DocumentMut --- crates/cast/bin/tx.rs | 8 ++------ crates/config/src/fix.rs | 8 ++++---- crates/config/src/lib.rs | 6 +++--- crates/config/src/utils.rs | 6 +++--- 4 files changed, 12 insertions(+), 16 deletions(-) diff --git a/crates/cast/bin/tx.rs b/crates/cast/bin/tx.rs index 769d321f5e9e..49724602ec7c 100644 --- a/crates/cast/bin/tx.rs +++ b/crates/cast/bin/tx.rs @@ -46,12 +46,8 @@ pub async fn build_tx, T: Into, ) -> Result { let from = from.into().resolve(provider).await?; - let to = if let Some(to) = to { - Some(to.into().resolve(provider).await?) - } else { - None - }; - + let to = if let Some(to) = to { Some(to.into().resolve(provider).await?) } else { None }; + let mut builder = TxBuilder::new(provider, from, to, chain, tx.legacy).await?; builder .etherscan_api_key(etherscan_api_key) diff --git a/crates/config/src/fix.rs b/crates/config/src/fix.rs index a0ce9fbc1b0b..dc43fd25500b 100644 --- a/crates/config/src/fix.rs +++ b/crates/config/src/fix.rs @@ -10,7 +10,7 @@ use std::{ /// A convenience wrapper around a TOML document and the path it was read from struct TomlFile { - doc: toml_edit::Document, + doc: toml_edit::DocumentMut, path: PathBuf, } @@ -21,11 +21,11 @@ impl TomlFile { Ok(Self { doc, path }) } - fn doc(&self) -> &toml_edit::Document { + fn doc(&self) -> &toml_edit::DocumentMut { &self.doc } - fn doc_mut(&mut self) -> &mut toml_edit::Document { + fn doc_mut(&mut self) -> &mut toml_edit::DocumentMut { &mut self.doc } @@ -39,7 +39,7 @@ impl TomlFile { } impl Deref for TomlFile { - type Target = toml_edit::Document; + type Target = toml_edit::DocumentMut; fn deref(&self) -> &Self::Target { self.doc() } diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs index 4f27b58b8edd..fa1d4e139d33 100644 --- a/crates/config/src/lib.rs +++ b/crates/config/src/lib.rs @@ -1215,7 +1215,7 @@ impl Config { /// [Self::get_config_path()] and if the closure returns `true`. pub fn update_at(root: impl Into, f: F) -> eyre::Result<()> where - F: FnOnce(&Config, &mut toml_edit::Document) -> bool, + F: FnOnce(&Config, &mut toml_edit::DocumentMut) -> bool, { let config = Self::load_with_root(root).sanitized(); config.update(|doc| f(&config, doc)) @@ -1227,14 +1227,14 @@ impl Config { /// [Self::get_config_path()] and if the closure returns `true` pub fn update(&self, f: F) -> eyre::Result<()> where - F: FnOnce(&mut toml_edit::Document) -> bool, + F: FnOnce(&mut toml_edit::DocumentMut) -> bool, { let file_path = self.get_config_path(); if !file_path.exists() { return Ok(()) } let contents = fs::read_to_string(&file_path)?; - let mut doc = contents.parse::()?; + let mut doc = contents.parse::()?; if f(&mut doc) { fs::write(file_path, doc.to_string())?; } diff --git a/crates/config/src/utils.rs b/crates/config/src/utils.rs index d0d6f8e06663..cb23500088b4 100644 --- a/crates/config/src/utils.rs +++ b/crates/config/src/utils.rs @@ -14,7 +14,7 @@ use std::{ path::{Path, PathBuf}, str::FromStr, }; -use toml_edit::{Document, Item}; +use toml_edit::{DocumentMut, Item}; /// Loads the config for the current project workspace pub fn load_config() -> Config { @@ -216,9 +216,9 @@ pub fn get_available_profiles(toml_path: impl AsRef) -> eyre::Result) -> eyre::Result { +fn read_toml(path: impl AsRef) -> eyre::Result { let path = path.as_ref().to_owned(); - let doc: Document = std::fs::read_to_string(path)?.parse()?; + let doc: DocumentMut = std::fs::read_to_string(path)?.parse()?; Ok(doc) } From 953f91540645ed6c3813f0dbc3d3db0782d72cbc Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Mon, 18 Mar 2024 20:02:29 +0400 Subject: [PATCH 06/63] wip --- crates/cast/src/lib.rs | 48 ++++------- crates/common/src/fmt/ui.rs | 130 ++++++++++++++---------------- crates/common/src/transactions.rs | 11 +-- 3 files changed, 80 insertions(+), 109 deletions(-) diff --git a/crates/cast/src/lib.rs b/crates/cast/src/lib.rs index eefe80fa31aa..41b93a629230 100644 --- a/crates/cast/src/lib.rs +++ b/crates/cast/src/lib.rs @@ -320,7 +320,7 @@ where /// # Ok(()) /// # } /// ``` - pub async fn block>( + pub async fn block>( &self, block: T, full: bool, @@ -328,45 +328,27 @@ where to_json: bool, ) -> Result { let block = block.into(); - let block = if full { - let block = self - .provider - .get_block_with_txs(block) - .await? - .ok_or_else(|| eyre::eyre!("block {:?} not found", block))?; - if let Some(ref field) = field { - get_pretty_block_attr(&block, field) - .unwrap_or_else(|| format!("{field} is not a valid block field")) - } else if to_json { - serde_json::to_value(&block).unwrap().to_string() - } else { - block.pretty() + if let Some(field) = field { + if field == "transactions" && !full { + eyre::bail!("use --full to view transactions") } + } + + let block = self.alloy_provider.get_block(block, full).await?.ok_or_else(|| eyre::eyre!("block {:?} not found", block))?; + + let block = if let Some(ref field) = field { + get_pretty_block_attr(&block, field) + .unwrap_or_else(|| format!("{field} is not a valid block field")) + } else if to_json { + serde_json::to_value(&block).unwrap().to_string() } else { - let block = self - .provider - .get_block(block) - .await? - .ok_or_else(|| eyre::eyre!("block {:?} not found", block))?; - - if let Some(ref field) = field { - if field == "transactions" { - "use --full to view transactions".to_string() - } else { - get_pretty_block_attr(&block, field) - .unwrap_or_else(|| format!("{field} is not a valid block field")) - } - } else if to_json { - serde_json::to_value(&block).unwrap().to_string() - } else { - block.pretty() - } + block.pretty() }; Ok(block) } - async fn block_field_as_num>(&self, block: T, field: String) -> Result { + async fn block_field_as_num>(&self, block: T, field: String) -> Result { let block = block.into(); let block_field = Cast::block( self, diff --git a/crates/common/src/fmt/ui.rs b/crates/common/src/fmt/ui.rs index 5549f36abc5f..198e395331a7 100644 --- a/crates/common/src/fmt/ui.rs +++ b/crates/common/src/fmt/ui.rs @@ -2,7 +2,7 @@ use crate::TransactionReceiptWithRevertReason; use alloy_primitives::*; -use ethers_core::types::{Block, Log, OtherFields, Transaction, TransactionReceipt, TxHash}; +use alloy_rpc_types::{other::OtherFields, Block, BlockTransactions, Log, Transaction, TransactionReceipt}; use serde::Deserialize; /// length of the name column for pretty formatting `{:>20}{value}` @@ -65,7 +65,7 @@ impl UIfmt for bool { } } -impl UIfmt for U256 { +impl UIfmt for Uint { fn pretty(&self) -> String { self.to_string() } @@ -119,12 +119,6 @@ impl UIfmt for [u8] { } } -impl UIfmt for U64 { - fn pretty(&self) -> String { - self.to_string() - } -} - impl UIfmt for TransactionReceipt { fn pretty(&self) -> String { let Self { @@ -138,8 +132,8 @@ impl UIfmt for TransactionReceipt { gas_used, contract_address, logs, - status, - root, + status_code, + state_root, logs_bloom, transaction_type, effective_gas_price, @@ -172,8 +166,8 @@ type {}", gas_used.pretty(), serde_json::to_string(logs).unwrap(), logs_bloom.pretty(), - root.pretty(), - status.pretty(), + state_root.pretty(), + status_code.pretty(), transaction_hash.pretty(), transaction_index.pretty(), transaction_type.pretty() @@ -218,7 +212,7 @@ transactionIndex: {}", } } -impl UIfmt for Block { +impl UIfmt for Block { fn pretty(&self) -> String { format!( " @@ -230,15 +224,12 @@ transactions {}", } } -impl UIfmt for Block { +impl UIfmt for BlockTransactions { fn pretty(&self) -> String { - format!( - " -{} -transactions: {}", - pretty_block_basics(self), - self.transactions.pretty() - ) + match self { + BlockTransactions::Hashes(hashes) => hashes.pretty(), + BlockTransactions::Full(transactions) => transactions.pretty(), + } } } @@ -286,11 +277,11 @@ value {}{}", self.hash.pretty(), self.input.pretty(), self.nonce.pretty(), - to_bytes(self.r).pretty(), - to_bytes(self.s).pretty(), + self.signature.map(|s| s.r.to_be_bytes()).pretty(), + self.signature.map(|s| s.s.to_be_bytes()).pretty(), self.to.pretty(), self.transaction_index.pretty(), - self.v.pretty(), + self.signature.map(|s| s.v).pretty(), self.value.pretty(), self.other.pretty() ) @@ -385,11 +376,11 @@ pub fn get_pretty_tx_attr(transaction: &Transaction, attr: &str) -> Option Some(transaction.hash.pretty()), "input" => Some(transaction.input.pretty()), "nonce" => Some(transaction.nonce.pretty()), - "s" => Some(to_bytes(transaction.s).pretty()), - "r" => Some(to_bytes(transaction.r).pretty()), + "s" => transaction.signature.map(|s| s.s.pretty()), + "r" => transaction.signature.map(|s| s.r.pretty()), "to" => Some(transaction.to.pretty()), "transactionIndex" | "transaction_index" => Some(transaction.transaction_index.pretty()), - "v" => Some(transaction.v.pretty()), + "v" => transaction.signature.map(|s| s.v.pretty()), "value" => Some(transaction.value.pretty()), other => { if let Some(value) = transaction.other.get(other) { @@ -418,8 +409,8 @@ pub fn get_pretty_tx_receipt_attr( "gasUsed" | "gas_used" => Some(receipt.receipt.gas_used.pretty()), "logs" => Some(receipt.receipt.logs.pretty()), "logsBloom" | "logs_bloom" => Some(receipt.receipt.logs_bloom.pretty()), - "root" => Some(receipt.receipt.root.pretty()), - "status" => Some(receipt.receipt.status.pretty()), + "root" | "stateRoot" | "state_root "=> Some(receipt.receipt.state_root.pretty()), + "status" | "statusCode" | "status_code" => Some(receipt.receipt.status_code.pretty()), "transactionHash" | "transaction_hash" => Some(receipt.receipt.transaction_hash.pretty()), "transactionIndex" | "transaction_index" => { Some(receipt.receipt.transaction_index.pretty()) @@ -431,28 +422,27 @@ pub fn get_pretty_tx_receipt_attr( } /// Returns the `UiFmt::pretty()` formatted attribute of the given block -pub fn get_pretty_block_attr(block: &Block, attr: &str) -> Option { +pub fn get_pretty_block_attr(block: &Block, attr: &str) -> Option { match attr { - "baseFeePerGas" | "base_fee_per_gas" => Some(block.base_fee_per_gas.pretty()), - "difficulty" => Some(block.difficulty.pretty()), - "extraData" | "extra_data" => Some(block.extra_data.pretty()), - "gasLimit" | "gas_limit" => Some(block.gas_limit.pretty()), - "gasUsed" | "gas_used" => Some(block.gas_used.pretty()), - "hash" => Some(block.hash.pretty()), - "logsBloom" | "logs_bloom" => Some(block.logs_bloom.pretty()), - "miner" | "author" => Some(block.author.pretty()), - "mixHash" | "mix_hash" => Some(block.mix_hash.pretty()), - "nonce" => Some(block.nonce.pretty()), - "number" => Some(block.number.pretty()), - "parentHash" | "parent_hash" => Some(block.parent_hash.pretty()), - "transactionsRoot" | "transactions_root" => Some(block.transactions_root.pretty()), - "receiptsRoot" | "receipts_root" => Some(block.receipts_root.pretty()), - "sealFields" | "seal_fields" => Some(block.seal_fields.pretty()), - "sha3Uncles" | "sha_3_uncles" => Some(block.uncles_hash.pretty()), + "baseFeePerGas" | "base_fee_per_gas" => Some(block.header.base_fee_per_gas.pretty()), + "difficulty" => Some(block.header.difficulty.pretty()), + "extraData" | "extra_data" => Some(block.header.extra_data.pretty()), + "gasLimit" | "gas_limit" => Some(block.header.gas_limit.pretty()), + "gasUsed" | "gas_used" => Some(block.header.gas_used.pretty()), + "hash" => Some(block.header.hash.pretty()), + "logsBloom" | "logs_bloom" => Some(block.header.logs_bloom.pretty()), + "miner" | "author" => Some(block.header.miner.pretty()), + "mixHash" | "mix_hash" => Some(block.header.mix_hash.pretty()), + "nonce" => Some(block.header.nonce.pretty()), + "number" => Some(block.header.number.pretty()), + "parentHash" | "parent_hash" => Some(block.header.parent_hash.pretty()), + "transactionsRoot" | "transactions_root" => Some(block.header.transactions_root.pretty()), + "receiptsRoot" | "receipts_root" => Some(block.header.receipts_root.pretty()), + "sha3Uncles" | "sha_3_uncles" => Some(block.header.uncles_hash.pretty()), "size" => Some(block.size.pretty()), - "stateRoot" | "state_root" => Some(block.state_root.pretty()), - "timestamp" => Some(block.timestamp.pretty()), - "totalDifficulty" | "total_difficult" => Some(block.total_difficulty.pretty()), + "stateRoot" | "state_root" => Some(block.header.state_root.pretty()), + "timestamp" => Some(block.header.timestamp.pretty()), + "totalDifficulty" | "total_difficult" => Some(block.header.total_difficulty.pretty()), other => { if let Some(value) = block.other.get(other) { let val = EthValue::from(value.clone()); @@ -463,7 +453,7 @@ pub fn get_pretty_block_attr(block: &Block, attr: &str) -> Option(block: &Block) -> String { +fn pretty_block_basics(block: &Block) -> String { format!( " baseFeePerGas {} @@ -480,34 +470,32 @@ number {} parentHash {} transactionsRoot {} receiptsRoot {} -sealFields {} sha3Uncles {} size {} stateRoot {} timestamp {} withdrawalsRoot {} totalDifficulty {}{}", - block.base_fee_per_gas.pretty(), - block.difficulty.pretty(), - block.extra_data.pretty(), - block.gas_limit.pretty(), - block.gas_used.pretty(), - block.hash.pretty(), - block.logs_bloom.pretty(), - block.author.pretty(), - block.mix_hash.pretty(), - block.nonce.pretty(), - block.number.pretty(), - block.parent_hash.pretty(), - block.transactions_root.pretty(), - block.receipts_root.pretty(), - block.seal_fields.pretty(), - block.uncles_hash.pretty(), + block.header.base_fee_per_gas.pretty(), + block.header.difficulty.pretty(), + block.header.extra_data.pretty(), + block.header.gas_limit.pretty(), + block.header.gas_used.pretty(), + block.header.hash.pretty(), + block.header.logs_bloom.pretty(), + block.header.miner.pretty(), + block.header.mix_hash.pretty(), + block.header.nonce.pretty(), + block.header.number.pretty(), + block.header.parent_hash.pretty(), + block.header.transactions_root.pretty(), + block.header.receipts_root.pretty(), + block.header.uncles_hash.pretty(), block.size.pretty(), - block.state_root.pretty(), - block.timestamp.pretty(), - block.withdrawals_root.pretty(), - block.total_difficulty.pretty(), + block.header.state_root.pretty(), + block.header.timestamp.pretty(), + block.header.withdrawals_root.pretty(), + block.header.total_difficulty.pretty(), block.other.pretty() ) } diff --git a/crates/common/src/transactions.rs b/crates/common/src/transactions.rs index b337147d6171..99ede40b84a5 100644 --- a/crates/common/src/transactions.rs +++ b/crates/common/src/transactions.rs @@ -1,5 +1,6 @@ //! wrappers for transactions -use ethers_core::types::{BlockId, TransactionReceipt}; +use alloy_providers::tmp::TempProvider; +use alloy_rpc_types::TransactionReceipt; use ethers_providers::Middleware; use eyre::Result; use serde::{Deserialize, Serialize}; @@ -19,23 +20,23 @@ pub struct TransactionReceiptWithRevertReason { impl TransactionReceiptWithRevertReason { /// Returns if the status of the transaction is 0 (failure) pub fn is_failure(&self) -> Option { - self.receipt.status.map(|status| status.as_u64() == 0) + self.receipt.status_code.map(|status| status.is_zero()) } /// Updates the revert reason field using `eth_call` and returns an Err variant if the revert /// reason was not successfully updated - pub async fn update_revert_reason(&mut self, provider: &M) -> Result<()> { + pub async fn update_revert_reason(&mut self, provider: &P) -> Result<()> { self.revert_reason = self.fetch_revert_reason(provider).await?; Ok(()) } - async fn fetch_revert_reason(&self, provider: &M) -> Result> { + async fn fetch_revert_reason(&self, provider: &P) -> Result> { if let Some(false) | None = self.is_failure() { return Ok(None) } if let Some(ref transaction) = provider - .get_transaction(self.receipt.transaction_hash) + .get_transaction_by_hash(self.receipt.transaction_hash) .await .map_err(|_| eyre::eyre!("unable to fetch transaction"))? { From 435be40e087c5d620173953877f4e39f845f043e Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Mon, 18 Mar 2024 23:22:32 +0400 Subject: [PATCH 07/63] wip --- crates/common/src/transactions.rs | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/crates/common/src/transactions.rs b/crates/common/src/transactions.rs index 99ede40b84a5..72cf4583e41b 100644 --- a/crates/common/src/transactions.rs +++ b/crates/common/src/transactions.rs @@ -35,20 +35,18 @@ impl TransactionReceiptWithRevertReason { return Ok(None) } - if let Some(ref transaction) = provider - .get_transaction_by_hash(self.receipt.transaction_hash) + let transaction = provider + .get_transaction_by_hash(self.receipt.transaction_hash.unwrap()) .await - .map_err(|_| eyre::eyre!("unable to fetch transaction"))? - { - if let Some(block_hash) = self.receipt.block_hash { - match provider.call(&transaction.into(), Some(BlockId::Hash(block_hash))).await { - Err(e) => return Ok(extract_revert_reason(e.to_string())), - Ok(_) => eyre::bail!("no revert reason as transaction succeeded"), - } + .map_err(|_| eyre::eyre!("unable to fetch transaction"))?; + + if let Some(block_hash) = self.receipt.block_hash { + match provider.call(transaction.into(), Some(BlockId::Hash(block_hash))).await { + Err(e) => return Ok(extract_revert_reason(e.to_string())), + Ok(_) => eyre::bail!("no revert reason as transaction succeeded"), } - eyre::bail!("unable to fetch block_hash") } - Err(eyre::eyre!("transaction does not exist")) + eyre::bail!("unable to fetch block_hash") } } From d286ae0ec2d987264297d6ffcb4aa944891cd9eb Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Tue, 19 Mar 2024 01:55:11 +0400 Subject: [PATCH 08/63] wip: bump alloy --- Cargo.lock | 203 ++++++++++++++++++---------- Cargo.toml | 65 +++++---- clippy.toml | 2 +- crates/anvil/Cargo.toml | 5 +- crates/anvil/core/Cargo.toml | 2 +- crates/cast/Cargo.toml | 8 +- crates/cast/src/lib.rs | 12 +- crates/cheatcodes/Cargo.toml | 4 +- crates/common/Cargo.toml | 10 +- crates/common/src/ens.rs | 7 +- crates/common/src/fmt/ui.rs | 11 +- crates/common/src/provider/alloy.rs | 14 +- crates/common/src/transactions.rs | 19 ++- crates/common/src/types.rs | 71 +--------- crates/evm/core/Cargo.toml | 10 +- crates/evm/core/src/fork/backend.rs | 12 +- crates/evm/core/src/fork/init.rs | 5 +- crates/evm/core/src/opts.rs | 2 +- 18 files changed, 254 insertions(+), 208 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index caf71c148257..8494184a9c57 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -90,10 +90,9 @@ dependencies = [ [[package]] name = "alloy-consensus" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=9ac2c90#9ac2c90d58a9994d4b61c879e33c6af2739a2b4f" +source = "git+https://github.com/klkvr/alloy?rev=47e349f#47e349f303db95f1eabced5901fc5b76e6d267c4" dependencies = [ "alloy-eips", - "alloy-network", "alloy-primitives", "alloy-rlp", "c-kzg", @@ -104,15 +103,18 @@ dependencies = [ [[package]] name = "alloy-contract" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=9ac2c90#9ac2c90d58a9994d4b61c879e33c6af2739a2b4f" +source = "git+https://github.com/klkvr/alloy?rev=47e349f#47e349f303db95f1eabced5901fc5b76e6d267c4" dependencies = [ "alloy-dyn-abi", "alloy-json-abi", + "alloy-network", "alloy-primitives", - "alloy-providers", - "alloy-rpc-types", + "alloy-provider", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=47e349f)", "alloy-sol-types", "alloy-transport", + "futures", + "futures-util", "thiserror", ] @@ -124,7 +126,7 @@ checksum = "2919acdad13336bc5dc26b636cdd6892c2f27fb0d4a58320a00c2713cf6a4e9a" dependencies = [ "alloy-json-abi", "alloy-primitives", - "alloy-sol-type-parser", + "alloy-sol-type-parser 0.6.4 (registry+https://github.com/rust-lang/crates.io-index)", "alloy-sol-types", "arbitrary", "const-hex", @@ -140,32 +142,30 @@ dependencies = [ [[package]] name = "alloy-eips" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=9ac2c90#9ac2c90d58a9994d4b61c879e33c6af2739a2b4f" +source = "git+https://github.com/klkvr/alloy?rev=47e349f#47e349f303db95f1eabced5901fc5b76e6d267c4" dependencies = [ "alloy-primitives", "alloy-rlp", "serde", - "thiserror", ] [[package]] name = "alloy-genesis" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=9ac2c90#9ac2c90d58a9994d4b61c879e33c6af2739a2b4f" +source = "git+https://github.com/klkvr/alloy?rev=47e349f#47e349f303db95f1eabced5901fc5b76e6d267c4" dependencies = [ "alloy-primitives", - "alloy-rpc-types", + "alloy-serde", "serde", ] [[package]] name = "alloy-json-abi" version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24ed0f2a6c3a1c947b4508522a53a190dba8f94dcd4e3e1a5af945a498e78f2f" +source = "git+https://github.com/alloy-rs/core?rev=6ace151#6ace1519942ac3053a000eaa6792ed6fa0a45a88" dependencies = [ "alloy-primitives", - "alloy-sol-type-parser", + "alloy-sol-type-parser 0.6.4 (git+https://github.com/alloy-rs/core?rev=6ace151)", "serde", "serde_json", ] @@ -173,7 +173,7 @@ dependencies = [ [[package]] name = "alloy-json-rpc" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=9ac2c90#9ac2c90d58a9994d4b61c879e33c6af2739a2b4f" +source = "git+https://github.com/klkvr/alloy?rev=47e349f#47e349f303db95f1eabced5901fc5b76e6d267c4" dependencies = [ "alloy-primitives", "serde", @@ -184,20 +184,24 @@ dependencies = [ [[package]] name = "alloy-network" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=9ac2c90#9ac2c90d58a9994d4b61c879e33c6af2739a2b4f" +source = "git+https://github.com/klkvr/alloy?rev=47e349f#47e349f303db95f1eabced5901fc5b76e6d267c4" dependencies = [ + "alloy-consensus", "alloy-eips", "alloy-json-rpc", "alloy-primitives", - "alloy-rlp", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=47e349f)", + "alloy-signer", + "async-trait", + "futures-utils-wasm", "serde", + "thiserror", ] [[package]] name = "alloy-primitives" version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "600d34d8de81e23b6d909c094e23b3d357e01ca36b78a8c5424c501eedbe86f0" +source = "git+https://github.com/alloy-rs/core?rev=6ace151#6ace1519942ac3053a000eaa6792ed6fa0a45a88" dependencies = [ "alloy-rlp", "arbitrary", @@ -221,25 +225,26 @@ dependencies = [ ] [[package]] -name = "alloy-providers" +name = "alloy-provider" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=9ac2c90#9ac2c90d58a9994d4b61c879e33c6af2739a2b4f" +source = "git+https://github.com/klkvr/alloy?rev=47e349f#47e349f303db95f1eabced5901fc5b76e6d267c4" dependencies = [ + "alloy-json-rpc", "alloy-network", "alloy-primitives", "alloy-rpc-client", - "alloy-rpc-trace-types", - "alloy-rpc-types", + "alloy-rpc-trace-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=47e349f)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=47e349f)", "alloy-transport", "alloy-transport-http", "async-stream", "async-trait", "auto_impl", + "dashmap", "futures", "lru", "reqwest", - "serde", - "thiserror", + "serde_json", "tokio", "tracing", ] @@ -247,7 +252,7 @@ dependencies = [ [[package]] name = "alloy-pubsub" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=9ac2c90#9ac2c90d58a9994d4b61c879e33c6af2739a2b4f" +source = "git+https://github.com/klkvr/alloy?rev=47e349f#47e349f303db95f1eabced5901fc5b76e6d267c4" dependencies = [ "alloy-json-rpc", "alloy-primitives", @@ -287,7 +292,7 @@ dependencies = [ [[package]] name = "alloy-rpc-client" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=9ac2c90#9ac2c90d58a9994d4b61c879e33c6af2739a2b4f" +source = "git+https://github.com/klkvr/alloy?rev=47e349f#47e349f303db95f1eabced5901fc5b76e6d267c4" dependencies = [ "alloy-json-rpc", "alloy-transport", @@ -304,15 +309,41 @@ dependencies = [ "url", ] +[[package]] +name = "alloy-rpc-trace-types" +version = "0.1.0" +source = "git+https://github.com/klkvr/alloy?rev=47e349f#47e349f303db95f1eabced5901fc5b76e6d267c4" +dependencies = [ + "alloy-primitives", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=47e349f)", + "alloy-serde", + "serde", + "serde_json", +] + [[package]] name = "alloy-rpc-trace-types" version = "0.1.0" source = "git+https://github.com/alloy-rs/alloy?rev=9ac2c90#9ac2c90d58a9994d4b61c879e33c6af2739a2b4f" dependencies = [ "alloy-primitives", - "alloy-rpc-types", + "alloy-rpc-types 0.1.0 (git+https://github.com/alloy-rs/alloy?rev=9ac2c90)", + "serde", + "serde_json", +] + +[[package]] +name = "alloy-rpc-types" +version = "0.1.0" +source = "git+https://github.com/klkvr/alloy?rev=47e349f#47e349f303db95f1eabced5901fc5b76e6d267c4" +dependencies = [ + "alloy-primitives", + "alloy-rlp", + "alloy-serde", + "itertools 0.12.1", "serde", "serde_json", + "thiserror", ] [[package]] @@ -328,16 +359,41 @@ dependencies = [ "thiserror", ] +[[package]] +name = "alloy-serde" +version = "0.1.0" +source = "git+https://github.com/klkvr/alloy?rev=47e349f#47e349f303db95f1eabced5901fc5b76e6d267c4" +dependencies = [ + "alloy-primitives", + "serde", + "serde_json", +] + [[package]] name = "alloy-signer" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=9ac2c90#9ac2c90d58a9994d4b61c879e33c6af2739a2b4f" +source = "git+https://github.com/klkvr/alloy?rev=47e349f#47e349f303db95f1eabced5901fc5b76e6d267c4" dependencies = [ - "alloy-network", + "alloy-dyn-abi", "alloy-primitives", "alloy-sol-types", "async-trait", "auto_impl", + "elliptic-curve", + "k256", + "thiserror", +] + +[[package]] +name = "alloy-signer-wallet" +version = "0.1.0" +source = "git+https://github.com/klkvr/alloy?rev=47e349f#47e349f303db95f1eabced5901fc5b76e6d267c4" +dependencies = [ + "alloy-consensus", + "alloy-network", + "alloy-primitives", + "alloy-signer", + "async-trait", "coins-bip32", "coins-bip39", "elliptic-curve", @@ -350,8 +406,7 @@ dependencies = [ [[package]] name = "alloy-sol-macro" version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e86ec0a47740b20bc5613b8712d0d321d031c4efc58e9645af96085d5cccfc27" +source = "git+https://github.com/alloy-rs/core?rev=6ace151#6ace1519942ac3053a000eaa6792ed6fa0a45a88" dependencies = [ "alloy-json-abi", "const-hex", @@ -376,11 +431,18 @@ dependencies = [ "winnow 0.6.5", ] +[[package]] +name = "alloy-sol-type-parser" +version = "0.6.4" +source = "git+https://github.com/alloy-rs/core?rev=6ace151#6ace1519942ac3053a000eaa6792ed6fa0a45a88" +dependencies = [ + "winnow 0.6.5", +] + [[package]] name = "alloy-sol-types" version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad09ec5853fa700d12d778ad224dcdec636af424d29fad84fb9a2f16a5b0ef09" +source = "git+https://github.com/alloy-rs/core?rev=6ace151#6ace1519942ac3053a000eaa6792ed6fa0a45a88" dependencies = [ "alloy-json-abi", "alloy-primitives", @@ -392,11 +454,12 @@ dependencies = [ [[package]] name = "alloy-transport" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=9ac2c90#9ac2c90d58a9994d4b61c879e33c6af2739a2b4f" +source = "git+https://github.com/klkvr/alloy?rev=47e349f#47e349f303db95f1eabced5901fc5b76e6d267c4" dependencies = [ "alloy-json-rpc", "base64 0.22.0", "futures-util", + "futures-utils-wasm", "serde", "serde_json", "thiserror", @@ -409,7 +472,7 @@ dependencies = [ [[package]] name = "alloy-transport-http" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=9ac2c90#9ac2c90d58a9994d4b61c879e33c6af2739a2b4f" +source = "git+https://github.com/klkvr/alloy?rev=47e349f#47e349f303db95f1eabced5901fc5b76e6d267c4" dependencies = [ "alloy-json-rpc", "alloy-transport", @@ -422,7 +485,7 @@ dependencies = [ [[package]] name = "alloy-transport-ipc" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=9ac2c90#9ac2c90d58a9994d4b61c879e33c6af2739a2b4f" +source = "git+https://github.com/klkvr/alloy?rev=47e349f#47e349f303db95f1eabced5901fc5b76e6d267c4" dependencies = [ "alloy-json-rpc", "alloy-pubsub", @@ -440,7 +503,7 @@ dependencies = [ [[package]] name = "alloy-transport-ws" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=9ac2c90#9ac2c90d58a9994d4b61c879e33c6af2739a2b4f" +source = "git+https://github.com/klkvr/alloy?rev=47e349f#47e349f303db95f1eabced5901fc5b76e6d267c4" dependencies = [ "alloy-pubsub", "alloy-transport", @@ -545,11 +608,12 @@ dependencies = [ "alloy-genesis", "alloy-network", "alloy-primitives", - "alloy-providers", + "alloy-provider", "alloy-rlp", - "alloy-rpc-trace-types", - "alloy-rpc-types", + "alloy-rpc-trace-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=47e349f)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=47e349f)", "alloy-signer", + "alloy-signer-wallet", "alloy-sol-types", "alloy-transport", "anvil-core", @@ -609,8 +673,8 @@ dependencies = [ "alloy-network", "alloy-primitives", "alloy-rlp", - "alloy-rpc-trace-types", - "alloy-rpc-types", + "alloy-rpc-trace-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=47e349f)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=47e349f)", "anvil-core", "bytes", "c-kzg", @@ -1252,9 +1316,9 @@ dependencies = [ [[package]] name = "c-kzg" -version = "0.4.2" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94a4bc5367b6284358d2a6a6a1dc2d92ec4b86034561c3b9d3341909752fd848" +checksum = "3130f3d8717cc02e668a896af24984d5d5d4e8bf12e278e982e0f1bd88a0f9af" dependencies = [ "blst", "cc", @@ -1311,9 +1375,9 @@ dependencies = [ "alloy-dyn-abi", "alloy-json-abi", "alloy-primitives", - "alloy-providers", + "alloy-provider", "alloy-rlp", - "alloy-rpc-types", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=47e349f)", "alloy-signer", "async-trait", "chrono", @@ -1395,7 +1459,7 @@ dependencies = [ "alloy-dyn-abi", "alloy-json-abi", "alloy-primitives", - "alloy-rpc-types", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=47e349f)", "clap", "criterion", "dirs 5.0.1", @@ -2969,7 +3033,7 @@ dependencies = [ "alloy-dyn-abi", "alloy-json-abi", "alloy-primitives", - "alloy-rpc-types", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=47e349f)", "anvil", "async-trait", "axum", @@ -3085,7 +3149,7 @@ dependencies = [ "alloy-dyn-abi", "alloy-json-abi", "alloy-primitives", - "alloy-rpc-types", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=47e349f)", "async-recursion", "clap", "const-hex", @@ -3183,9 +3247,9 @@ dependencies = [ "alloy-genesis", "alloy-json-abi", "alloy-primitives", - "alloy-providers", - "alloy-rpc-types", - "alloy-signer", + "alloy-provider", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=47e349f)", + "alloy-signer-wallet", "alloy-sol-types", "base64 0.22.0", "const-hex", @@ -3264,11 +3328,12 @@ dependencies = [ "alloy-json-abi", "alloy-json-rpc", "alloy-primitives", - "alloy-providers", + "alloy-provider", "alloy-pubsub", "alloy-rpc-client", - "alloy-rpc-types", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=47e349f)", "alloy-signer", + "alloy-signer-wallet", "alloy-sol-types", "alloy-transport", "alloy-transport-http", @@ -3434,9 +3499,10 @@ dependencies = [ "alloy-genesis", "alloy-json-abi", "alloy-primitives", - "alloy-providers", - "alloy-rpc-types", + "alloy-provider", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=47e349f)", "alloy-sol-types", + "alloy-transport", "arrayvec", "auto_impl", "const-hex", @@ -3757,6 +3823,12 @@ dependencies = [ "slab", ] +[[package]] +name = "futures-utils-wasm" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42012b0f064e01aa58b545fe3727f90f7dd4020f4a3ea735b50344965f5a57e9" + [[package]] name = "fxhash" version = "0.2.1" @@ -6332,8 +6404,7 @@ dependencies = [ [[package]] name = "revm" version = "7.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "217d21144d329f21d5245b8e6a46e0d6d0a527d9917d7a087f225b161e529169" +source = "git+https://github.com/bluealloy/revm?rev=5aff229a#5aff229a1046f410e13e5512df036707144668cc" dependencies = [ "auto_impl", "cfg-if", @@ -6350,8 +6421,8 @@ version = "0.1.0" source = "git+https://github.com/paradigmxyz/evm-inspectors?rev=ba0b6ab#ba0b6ab695802c752601f17f5c941b62a067ad64" dependencies = [ "alloy-primitives", - "alloy-rpc-trace-types", - "alloy-rpc-types", + "alloy-rpc-trace-types 0.1.0 (git+https://github.com/alloy-rs/alloy?rev=9ac2c90)", + "alloy-rpc-types 0.1.0 (git+https://github.com/alloy-rs/alloy?rev=9ac2c90)", "alloy-sol-types", "anstyle", "colorchoice", @@ -6364,8 +6435,7 @@ dependencies = [ [[package]] name = "revm-interpreter" version = "3.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "776848391ed76d5103ca1aa1632cd21b521e2870afb30b63723da862d69efd0f" +source = "git+https://github.com/bluealloy/revm?rev=5aff229a#5aff229a1046f410e13e5512df036707144668cc" dependencies = [ "revm-primitives", "serde", @@ -6374,8 +6444,7 @@ dependencies = [ [[package]] name = "revm-precompile" version = "5.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3fd1856a7cb09197a02669d779e1afb5a627b0888a24814ba2b6a1ad4c3ff8d" +source = "git+https://github.com/bluealloy/revm?rev=5aff229a#5aff229a1046f410e13e5512df036707144668cc" dependencies = [ "aurora-engine-modexp", "c-kzg", @@ -6391,8 +6460,7 @@ dependencies = [ [[package]] name = "revm-primitives" version = "3.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a4d7d3e793e907dc0797a9d3b43abfdf5226d133855214db9bd27d4cee33ebd" +source = "git+https://github.com/bluealloy/revm?rev=5aff229a#5aff229a1046f410e13e5512df036707144668cc" dependencies = [ "alloy-primitives", "auto_impl", @@ -7491,8 +7559,7 @@ dependencies = [ [[package]] name = "syn-solidity" version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb3d0961cd53c23ea94eeec56ba940f636f6394788976e9f16ca5ee0aca7464a" +source = "git+https://github.com/alloy-rs/core?rev=6ace151#6ace1519942ac3053a000eaa6792ed6fa0a45a88" dependencies = [ "paste", "proc-macro2", diff --git a/Cargo.toml b/Cargo.toml index 62ef0bd35d13..ced4e1104524 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,7 +28,7 @@ resolver = "2" [workspace.package] version = "0.2.0" edition = "2021" -rust-version = "1.75" # Remember to update clippy.toml as well +rust-version = "1.76" # Remember to update clippy.toml as well authors = ["Foundry Contributors"] license = "MIT OR Apache-2.0" homepage = "https://github.com/foundry-rs/foundry" @@ -159,28 +159,29 @@ ethers-middleware = { version = "2.0.14", default-features = false } ethers-solc = { version = "2.0.14", default-features = false } ## alloy -alloy-consensus = { git = "https://github.com/alloy-rs/alloy", rev = "9ac2c90", default-features = false } -alloy-contract = { git = "https://github.com/alloy-rs/alloy", rev = "9ac2c90", default-features = false } -alloy-eips = { git = "https://github.com/alloy-rs/alloy", rev = "9ac2c90", default-features = false } -alloy-genesis = { git = "https://github.com/alloy-rs/alloy", rev = "9ac2c90", default-features = false } -alloy-json-rpc = { git = "https://github.com/alloy-rs/alloy", rev = "9ac2c90", default-features = false } -alloy-network = { git = "https://github.com/alloy-rs/alloy", rev = "9ac2c90", default-features = false } -alloy-node-bindings = { git = "https://github.com/alloy-rs/alloy", rev = "9ac2c90", default-features = false } -alloy-providers = { git = "https://github.com/alloy-rs/alloy", rev = "9ac2c90", default-features = false } -alloy-pubsub = { git = "https://github.com/alloy-rs/alloy", rev = "9ac2c90", default-features = false } -alloy-rpc-client = { git = "https://github.com/alloy-rs/alloy", rev = "9ac2c90", default-features = false } -alloy-rpc-trace-types = { git = "https://github.com/alloy-rs/alloy", rev = "9ac2c90", default-features = false } -alloy-rpc-types = { git = "https://github.com/alloy-rs/alloy", rev = "9ac2c90", default-features = false } -alloy-signer = { git = "https://github.com/alloy-rs/alloy", rev = "9ac2c90", default-features = false } -alloy-transport = { git = "https://github.com/alloy-rs/alloy", rev = "9ac2c90", default-features = false } -alloy-transport-http = { git = "https://github.com/alloy-rs/alloy", rev = "9ac2c90", default-features = false } -alloy-transport-ipc = { git = "https://github.com/alloy-rs/alloy", rev = "9ac2c90", default-features = false } -alloy-transport-ws = { git = "https://github.com/alloy-rs/alloy", rev = "9ac2c90", default-features = false } -alloy-primitives = { version = "0.6.3", features = ["getrandom"] } -alloy-dyn-abi = "0.6.3" -alloy-json-abi = "0.6.3" -alloy-sol-types = "0.6.3" -syn-solidity = "0.6.3" +alloy-consensus = { git = "https://github.com/klkvr/alloy", rev = "47e349f" } +alloy-contract = { git = "https://github.com/klkvr/alloy", rev = "47e349f" } +alloy-eips = { git = "https://github.com/klkvr/alloy", rev = "47e349f" } +alloy-genesis = { git = "https://github.com/klkvr/alloy", rev = "47e349f" } +alloy-json-rpc = { git = "https://github.com/klkvr/alloy", rev = "47e349f" } +alloy-network = { git = "https://github.com/klkvr/alloy", rev = "47e349f" } +alloy-node-bindings = { git = "https://github.com/klkvr/alloy", rev = "47e349f" } +alloy-provider = { git = "https://github.com/klkvr/alloy", rev = "47e349f" } +alloy-pubsub = { git = "https://github.com/klkvr/alloy", rev = "47e349f" } +alloy-rpc-client = { git = "https://github.com/klkvr/alloy", rev = "47e349f" } +alloy-rpc-trace-types = { git = "https://github.com/klkvr/alloy", rev = "47e349f" } +alloy-rpc-types = { git = "https://github.com/klkvr/alloy", rev = "47e349f" } +alloy-signer = { git = "https://github.com/klkvr/alloy", rev = "47e349f" } +alloy-signer-wallet = { git = "https://github.com/klkvr/alloy", rev = "47e349f" } +alloy-transport = { git = "https://github.com/klkvr/alloy", rev = "47e349f" } +alloy-transport-http = { git = "https://github.com/klkvr/alloy", rev = "47e349f" } +alloy-transport-ipc = { git = "https://github.com/klkvr/alloy", rev = "47e349f" } +alloy-transport-ws = { git = "https://github.com/klkvr/alloy", rev = "47e349f" } +alloy-primitives = { version = "0.6.4", features = ["getrandom"] } +alloy-dyn-abi = "0.6.4" +alloy-json-abi = "0.6.4" +alloy-sol-types = "0.6.4" +syn-solidity = "0.6.4" alloy-chains = "0.1" alloy-rlp = "0.3.3" @@ -189,7 +190,10 @@ solang-parser = "=0.3.3" ## misc arrayvec = "0.7" base64 = "0.22" -chrono = { version = "0.4", default-features = false, features = ["clock", "std"] } +chrono = { version = "0.4", default-features = false, features = [ + "clock", + "std", +] } color-eyre = "0.6" derive_more = "0.99" evm-disassembler = "0.5" @@ -214,8 +218,11 @@ hyper = "0.14" tower = "0.4" tower-http = "0.4" -# [patch.crates-io] -# revm = { path = "../../danipopes/revm/crates/revm" } -# revm-interpreter = { path = "../../danipopes/revm/crates/interpreter" } -# revm-primitives = { path = "../../danipopes/revm/crates/primitives" } -# revm-precompile = { path = "../../danipopes/revm/crates/precompile" } +[patch.crates-io] +revm = { git = "https://github.com/bluealloy/revm", rev = "5aff229a" } +revm-interpreter = { git = "https://github.com/bluealloy/revm", rev = "5aff229a" } +revm-primitives = { git = "https://github.com/bluealloy/revm", rev = "5aff229a" } +revm-precompile = { git = "https://github.com/bluealloy/revm", rev = "5aff229a" } +alloy-primitives = { git = "https://github.com/alloy-rs/core", rev = "6ace151" } +alloy-json-abi = { git = "https://github.com/alloy-rs/core", rev = "6ace151" } +alloy-sol-types = { git = "https://github.com/alloy-rs/core", rev = "6ace151" } \ No newline at end of file diff --git a/clippy.toml b/clippy.toml index cc4ad18b1872..472818efed9b 100644 --- a/clippy.toml +++ b/clippy.toml @@ -1 +1 @@ -msrv = "1.75" +msrv = "1.76" diff --git a/crates/anvil/Cargo.toml b/crates/anvil/Cargo.toml index 430c9e906bdf..8bccc9d2733f 100644 --- a/crates/anvil/Cargo.toml +++ b/crates/anvil/Cargo.toml @@ -43,12 +43,13 @@ alloy-primitives = { workspace = true, features = ["serde"] } alloy-consensus = { workspace = true, features = ["k256", "kzg"] } alloy-network.workspace = true alloy-rlp.workspace = true -alloy-signer = { workspace = true, features = ["eip712", "mnemonic"] } +alloy-signer = { workspace = true, features = ["eip712"] } +alloy-signer-wallet = { workspace = true, features = ["mnemonic"] } alloy-sol-types = { workspace = true, features = ["std"] } alloy-dyn-abi = { workspace = true, features = ["std", "eip712"] } alloy-rpc-types.workspace = true alloy-rpc-trace-types.workspace = true -alloy-providers.workspace = true +alloy-provider.workspace = true alloy-transport.workspace = true alloy-chains.workspace = true alloy-genesis.workspace = true diff --git a/crates/anvil/core/Cargo.toml b/crates/anvil/core/Cargo.toml index 6b6041ce54ab..50faf7472d72 100644 --- a/crates/anvil/core/Cargo.toml +++ b/crates/anvil/core/Cargo.toml @@ -26,7 +26,7 @@ alloy-dyn-abi = { workspace = true, features = ["std", "eip712"] } serde = { workspace = true, optional = true } serde_json.workspace = true bytes = "1.4" -c-kzg = { version = "0.4.2", features = ["serde"] } +c-kzg = { version = "1", features = ["serde"] } # trie hash-db = { version = "0.15", default-features = false } diff --git a/crates/cast/Cargo.toml b/crates/cast/Cargo.toml index 1f5cbadba89c..849b5a6c71cf 100644 --- a/crates/cast/Cargo.toml +++ b/crates/cast/Cargo.toml @@ -15,7 +15,11 @@ name = "cast" path = "bin/main.rs" [build-dependencies] -vergen = { workspace = true, default-features = false, features = ["build", "git", "gitcl"] } +vergen = { workspace = true, default-features = false, features = [ + "build", + "git", + "gitcl", +] } [dependencies] # lib @@ -30,7 +34,7 @@ alloy-dyn-abi.workspace = true alloy-json-abi.workspace = true alloy-primitives.workspace = true alloy-rlp.workspace = true -alloy-providers.workspace = true +alloy-provider.workspace = true alloy-rpc-types.workspace = true alloy-signer.workspace = true alloy-contract.workspace = true diff --git a/crates/cast/src/lib.rs b/crates/cast/src/lib.rs index 41b93a629230..f2edcc88933e 100644 --- a/crates/cast/src/lib.rs +++ b/crates/cast/src/lib.rs @@ -334,7 +334,11 @@ where } } - let block = self.alloy_provider.get_block(block, full).await?.ok_or_else(|| eyre::eyre!("block {:?} not found", block))?; + let block = self + .alloy_provider + .get_block(block, full) + .await? + .ok_or_else(|| eyre::eyre!("block {:?} not found", block))?; let block = if let Some(ref field) = field { get_pretty_block_attr(&block, field) @@ -348,7 +352,11 @@ where Ok(block) } - async fn block_field_as_num>(&self, block: T, field: String) -> Result { + async fn block_field_as_num>( + &self, + block: T, + field: String, + ) -> Result { let block = block.into(); let block_field = Cast::block( self, diff --git a/crates/cheatcodes/Cargo.toml b/crates/cheatcodes/Cargo.toml index 57b39966e034..ddd4a9c4d120 100644 --- a/crates/cheatcodes/Cargo.toml +++ b/crates/cheatcodes/Cargo.toml @@ -24,9 +24,9 @@ alloy-json-abi.workspace = true alloy-primitives.workspace = true alloy-genesis.workspace = true alloy-sol-types.workspace = true -alloy-providers.workspace = true +alloy-provider.workspace = true alloy-rpc-types.workspace = true -alloy-signer = { workspace = true, features = ["mnemonic", "keystore"] } +alloy-signer-wallet = { workspace = true, features = ["mnemonic", "keystore"] } parking_lot = "0.12" eyre.workspace = true diff --git a/crates/common/Cargo.toml b/crates/common/Cargo.toml index 4e23f07ebcba..3ae826ed2a14 100644 --- a/crates/common/Cargo.toml +++ b/crates/common/Cargo.toml @@ -21,12 +21,18 @@ ethers-signers.workspace = true alloy-dyn-abi = { workspace = true, features = ["arbitrary", "eip712"] } alloy-json-abi.workspace = true -alloy-primitives = { workspace = true, features = ["serde", "getrandom", "arbitrary", "rlp"] } +alloy-primitives = { workspace = true, features = [ + "serde", + "getrandom", + "arbitrary", + "rlp", +] } alloy-rpc-types.workspace = true alloy-rpc-client.workspace = true -alloy-providers.workspace = true +alloy-provider.workspace = true alloy-transport.workspace = true alloy-signer.workspace = true +alloy-signer-wallet.workspace = true alloy-transport-http.workspace = true alloy-transport-ws.workspace = true alloy-transport-ipc.workspace = true diff --git a/crates/common/src/ens.rs b/crates/common/src/ens.rs index 896416f472bb..4182518ae3cb 100644 --- a/crates/common/src/ens.rs +++ b/crates/common/src/ens.rs @@ -1,7 +1,7 @@ //! ENS Name resolving utilities. #![allow(missing_docs)] use alloy_primitives::{address, keccak256, Address, B256}; -use alloy_providers::tmp::TempProvider; +use alloy_provider::{Network, Provider}; use alloy_sol_types::sol; use std::str::FromStr; @@ -36,10 +36,7 @@ pub enum NameOrAddress { impl NameOrAddress { /// Resolves the name to an Ethereum Address. - pub async fn resolve( - &self, - provider: &P, - ) -> Result { + pub async fn resolve>(&self, provider: &P) -> Result { let name = match self { NameOrAddress::Name(name) => name.clone(), NameOrAddress::Address(addr) => return Ok(*addr), diff --git a/crates/common/src/fmt/ui.rs b/crates/common/src/fmt/ui.rs index 198e395331a7..3cf423b44a3d 100644 --- a/crates/common/src/fmt/ui.rs +++ b/crates/common/src/fmt/ui.rs @@ -2,7 +2,9 @@ use crate::TransactionReceiptWithRevertReason; use alloy_primitives::*; -use alloy_rpc_types::{other::OtherFields, Block, BlockTransactions, Log, Transaction, TransactionReceipt}; +use alloy_rpc_types::{ + other::OtherFields, Block, BlockTransactions, Log, Transaction, TransactionReceipt, +}; use serde::Deserialize; /// length of the name column for pretty formatting `{:>20}{value}` @@ -229,6 +231,7 @@ impl UIfmt for BlockTransactions { match self { BlockTransactions::Hashes(hashes) => hashes.pretty(), BlockTransactions::Full(transactions) => transactions.pretty(), + BlockTransactions::Uncle => String::new(), } } } @@ -277,8 +280,8 @@ value {}{}", self.hash.pretty(), self.input.pretty(), self.nonce.pretty(), - self.signature.map(|s| s.r.to_be_bytes()).pretty(), - self.signature.map(|s| s.s.to_be_bytes()).pretty(), + self.signature.map(|s| s.r.to_be_bytes_vec()).pretty(), + self.signature.map(|s| s.s.to_be_bytes_vec()).pretty(), self.to.pretty(), self.transaction_index.pretty(), self.signature.map(|s| s.v).pretty(), @@ -409,7 +412,7 @@ pub fn get_pretty_tx_receipt_attr( "gasUsed" | "gas_used" => Some(receipt.receipt.gas_used.pretty()), "logs" => Some(receipt.receipt.logs.pretty()), "logsBloom" | "logs_bloom" => Some(receipt.receipt.logs_bloom.pretty()), - "root" | "stateRoot" | "state_root "=> Some(receipt.receipt.state_root.pretty()), + "root" | "stateRoot" | "state_root " => Some(receipt.receipt.state_root.pretty()), "status" | "statusCode" | "status_code" => Some(receipt.receipt.status_code.pretty()), "transactionHash" | "transaction_hash" => Some(receipt.receipt.transaction_hash.pretty()), "transactionIndex" | "transaction_index" => { diff --git a/crates/common/src/provider/alloy.rs b/crates/common/src/provider/alloy.rs index 54c9085a15ee..47ec14a7b072 100644 --- a/crates/common/src/provider/alloy.rs +++ b/crates/common/src/provider/alloy.rs @@ -4,7 +4,9 @@ use crate::{ provider::runtime_transport::RuntimeTransportBuilder, ALCHEMY_FREE_TIER_CUPS, REQUEST_TIMEOUT, }; use alloy_primitives::U256; -use alloy_providers::tmp::{Provider, TempProvider}; +use alloy_provider::{ + network::Ethereum, Network, Provider, ProviderBuilder as AlloyProviderBuilder, RootProvider, +}; use alloy_rpc_client::ClientBuilder; use ethers_middleware::gas_oracle::{GasCategory, GasOracle, Polygon}; use eyre::{Result, WrapErr}; @@ -25,7 +27,7 @@ use super::{ }; /// Helper type alias for a retry provider -pub type RetryProvider = Provider>; +pub type RetryProvider = RootProvider>; /// Helper type alias for a rpc url pub type RpcUrl = String; @@ -239,8 +241,10 @@ impl ProviderBuilder { .build(); let client = ClientBuilder::default().layer(retry_layer).transport(transport, false); - // todo: provider polling interval - Ok(Provider::new_with_client(client)) + let provider = + AlloyProviderBuilder::<_, Ethereum>::new().provider(RootProvider::new(client)); + + Ok(provider) } } @@ -250,7 +254,7 @@ impl ProviderBuilder { /// - polygon /// /// Fallback is the default [`Provider::estimate_eip1559_fees`] implementation -pub async fn estimate_eip1559_fees( +pub async fn estimate_eip1559_fees>( provider: &P, chain: Option, ) -> Result<(U256, U256)> { diff --git a/crates/common/src/transactions.rs b/crates/common/src/transactions.rs index 72cf4583e41b..a218a5c9d5dc 100644 --- a/crates/common/src/transactions.rs +++ b/crates/common/src/transactions.rs @@ -1,7 +1,6 @@ //! wrappers for transactions -use alloy_providers::tmp::TempProvider; -use alloy_rpc_types::TransactionReceipt; -use ethers_providers::Middleware; +use alloy_provider::{network::Ethereum, Network, Provider}; +use alloy_rpc_types::{BlockId, TransactionReceipt}; use eyre::Result; use serde::{Deserialize, Serialize}; @@ -25,23 +24,29 @@ impl TransactionReceiptWithRevertReason { /// Updates the revert reason field using `eth_call` and returns an Err variant if the revert /// reason was not successfully updated - pub async fn update_revert_reason(&mut self, provider: &P) -> Result<()> { + pub async fn update_revert_reason>( + &mut self, + provider: &P, + ) -> Result<()> { self.revert_reason = self.fetch_revert_reason(provider).await?; Ok(()) } - async fn fetch_revert_reason(&self, provider: &P) -> Result> { + async fn fetch_revert_reason>( + &self, + provider: &P, + ) -> Result> { if let Some(false) | None = self.is_failure() { return Ok(None) } let transaction = provider - .get_transaction_by_hash(self.receipt.transaction_hash.unwrap()) + .get_transaction_by_hash(self.receipt.transaction_hash) .await .map_err(|_| eyre::eyre!("unable to fetch transaction"))?; if let Some(block_hash) = self.receipt.block_hash { - match provider.call(transaction.into(), Some(BlockId::Hash(block_hash))).await { + match provider.call(&transaction.into(), Some(BlockId::Hash(block_hash.into()))).await { Err(e) => return Ok(extract_revert_reason(e.to_string())), Ok(_) => eyre::bail!("no revert reason as transaction succeeded"), } diff --git a/crates/common/src/types.rs b/crates/common/src/types.rs index 85b7e87ba568..4e4558951ea4 100644 --- a/crates/common/src/types.rs +++ b/crates/common/src/types.rs @@ -1,12 +1,13 @@ //! Temporary utility conversion traits between ethers-rs and alloy types. -use alloy_primitives::{Address, Bloom, Bytes, B256, B64, I256, U128, U256, U64}; +use alloy_primitives::{Address, Bloom, Bytes, B256, B64, I256, U128, U256, U64, U8}; use alloy_rpc_types::{ other::OtherFields, request::{TransactionInput, TransactionRequest as CallRequest}, AccessList, AccessListItem, BlockNumberOrTag, Signature, Transaction, }; -use alloy_signer::{LocalWallet, Signer}; +use alloy_signer::Signer; +use alloy_signer_wallet::LocalWallet; use ethers_core::types::{ transaction::eip2930::{ AccessList as EthersAccessList, AccessListItem as EthersAccessListItem, @@ -105,43 +106,7 @@ impl ToAlloy for u64 { } } -impl ToAlloy for ethers_core::types::Transaction { - type To = Transaction; - - fn to_alloy(self) -> Self::To { - Transaction { - hash: self.hash.to_alloy(), - nonce: U64::from(self.nonce.as_u64()), - block_hash: self.block_hash.map(ToAlloy::to_alloy), - block_number: self.block_number.map(|b| U256::from(b.as_u64())), - transaction_index: self.transaction_index.map(|b| U256::from(b.as_u64())), - from: self.from.to_alloy(), - to: self.to.map(ToAlloy::to_alloy), - value: self.value.to_alloy(), - gas_price: self.gas_price.map(|a| U128::from(a.as_u128())), - gas: self.gas.to_alloy(), - max_fee_per_gas: self.max_fee_per_gas.map(|f| U128::from(f.as_u128())), - max_priority_fee_per_gas: self - .max_priority_fee_per_gas - .map(|f| U128::from(f.as_u128())), - max_fee_per_blob_gas: None, - input: self.input.0.into(), - signature: Some(Signature { - r: self.r.to_alloy(), - s: self.s.to_alloy(), - v: U256::from(self.v.as_u64()), - y_parity: None, - }), - chain_id: self.chain_id.map(|c| U64::from(c.as_u64())), - blob_versioned_hashes: Vec::new(), - access_list: self.access_list.map(|a| a.0.into_iter().map(ToAlloy::to_alloy).collect()), - transaction_type: self.transaction_type.map(|t| t.to_alloy()), - other: Default::default(), - } - } -} - -impl ToEthers for alloy_signer::LocalWallet { +impl ToEthers for alloy_signer_wallet::LocalWallet { type To = ethers_signers::LocalWallet; fn to_ethers(self) -> Self::To { @@ -161,34 +126,6 @@ impl ToEthers for Vec { } } -/// Converts from a [TransactionRequest] to a [CallRequest]. -pub fn to_call_request_from_tx_request(tx: TransactionRequest) -> CallRequest { - CallRequest { - from: tx.from.map(|f| f.to_alloy()), - to: match tx.to { - Some(to) => match to { - ethers_core::types::NameOrAddress::Address(addr) => Some(addr.to_alloy()), - ethers_core::types::NameOrAddress::Name(_) => None, - }, - None => None, - }, - gas_price: tx.gas_price.map(|g| g.to_alloy()), - max_fee_per_gas: None, - max_priority_fee_per_gas: None, - gas: tx.gas.map(|g| g.to_alloy()), - value: tx.value.map(|v| v.to_alloy()), - input: TransactionInput::maybe_input(tx.data.map(|b| b.0.into())), - nonce: tx.nonce.map(|n| U64::from(n.as_u64())), - chain_id: tx.chain_id.map(|c| c.to_alloy()), - access_list: None, - max_fee_per_blob_gas: None, - blob_versioned_hashes: None, - transaction_type: None, - sidecar: None, - other: OtherFields::default(), - } -} - impl ToAlloy for EthersAccessList { type To = AccessList; fn to_alloy(self) -> Self::To { diff --git a/crates/evm/core/Cargo.toml b/crates/evm/core/Cargo.toml index 7e4ea3c218d2..cf922cbce492 100644 --- a/crates/evm/core/Cargo.toml +++ b/crates/evm/core/Cargo.toml @@ -19,9 +19,15 @@ foundry-macros.workspace = true alloy-dyn-abi = { workspace = true, features = ["arbitrary", "eip712"] } alloy-json-abi.workspace = true -alloy-primitives = { workspace = true, features = ["serde", "getrandom", "arbitrary", "rlp"] } +alloy-primitives = { workspace = true, features = [ + "serde", + "getrandom", + "arbitrary", + "rlp", +] } alloy-genesis.workspace = true -alloy-providers.workspace = true +alloy-provider.workspace = true +alloy-transport.workspace = true alloy-rpc-types.workspace = true alloy-sol-types.workspace = true diff --git a/crates/evm/core/src/fork/backend.rs b/crates/evm/core/src/fork/backend.rs index 8e720a2505d2..b10cda95a6b6 100644 --- a/crates/evm/core/src/fork/backend.rs +++ b/crates/evm/core/src/fork/backend.rs @@ -4,7 +4,7 @@ use crate::{ fork::{cache::FlushJsonBlockCacheDB, BlockchainDb}, }; use alloy_primitives::{keccak256, Address, Bytes, B256, U256}; -use alloy_providers::tmp::TempProvider; +use alloy_provider::Provider; use alloy_rpc_types::{Block, BlockId, Transaction}; use eyre::WrapErr; use foundry_common::NON_ARCHIVE_NODE_WARNING; @@ -97,9 +97,9 @@ pub struct BackendHandler

{ block_id: Option, } -impl

BackendHandler

+impl BackendHandler

where - P: TempProvider + Clone + 'static, + P: Provider + Clone + 'static, { fn new( provider: P, @@ -285,7 +285,7 @@ where impl

Future for BackendHandler

where - P: TempProvider + Clone + Unpin + 'static, + P: Provider + Clone + Unpin + 'static, { type Output = (); @@ -531,7 +531,7 @@ impl SharedBackend { pin_block: Option, ) -> Self where - P: TempProvider + Unpin + 'static + Clone, + P: Provider + Unpin + 'static + Clone, { let (shared, handler) = Self::new(provider, db, pin_block); @@ -560,7 +560,7 @@ impl SharedBackend { pin_block: Option, ) -> (Self, BackendHandler

) where - P: TempProvider + Clone + 'static, + P: Provider + Clone + 'static, { let (backend, backend_rx) = channel(1); let cache = Arc::new(FlushJsonBlockCacheDB(Arc::clone(db.cache()))); diff --git a/crates/evm/core/src/fork/init.rs b/crates/evm/core/src/fork/init.rs index abde7cb22dea..e6597ca8f982 100644 --- a/crates/evm/core/src/fork/init.rs +++ b/crates/evm/core/src/fork/init.rs @@ -1,6 +1,7 @@ use crate::utils::apply_chain_and_block_specific_env_changes; use alloy_primitives::{Address, U256}; -use alloy_providers::tmp::TempProvider; +use alloy_provider::{Network, Provider}; +use alloy_transport::Transport; use alloy_rpc_types::{Block, BlockNumberOrTag}; use eyre::WrapErr; use foundry_common::NON_ARCHIVE_NODE_WARNING; @@ -10,7 +11,7 @@ use revm::primitives::{BlockEnv, CfgEnv, Env, TxEnv}; /// Initializes a REVM block environment based on a forked /// ethereum provider. // todo(onbjerg): these bounds needed cus of the bounds in `Provider`, can simplify? -pub async fn environment( +pub async fn environment>( provider: &P, memory_limit: u64, gas_price: Option, diff --git a/crates/evm/core/src/opts.rs b/crates/evm/core/src/opts.rs index 89fdcf4e3869..92cfdcd9b131 100644 --- a/crates/evm/core/src/opts.rs +++ b/crates/evm/core/src/opts.rs @@ -1,7 +1,7 @@ use super::fork::environment; use crate::fork::CreateFork; use alloy_primitives::{Address, B256, U256}; -use alloy_providers::tmp::TempProvider; +use alloy_provider::Provider; use alloy_rpc_types::Block; use eyre::WrapErr; use foundry_common::{ From 04ca1053729c1112d460558b22801016fa2884cb Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Tue, 19 Mar 2024 03:49:48 +0400 Subject: [PATCH 09/63] wip --- Cargo.lock | 1 + crates/anvil/core/src/eth/transaction/mod.rs | 4 +- .../core/src/eth/transaction/optimism.rs | 11 +++-- crates/cheatcodes/Cargo.toml | 1 + crates/cheatcodes/src/error.rs | 3 +- crates/cheatcodes/src/evm/fork.rs | 6 +-- crates/cheatcodes/src/evm/mock.rs | 4 +- crates/cheatcodes/src/fs.rs | 4 +- crates/cheatcodes/src/inspector.rs | 28 ++++++------ crates/cheatcodes/src/script.rs | 3 +- crates/cheatcodes/src/test/expect.rs | 6 +-- crates/cheatcodes/src/utils.rs | 7 +-- crates/cli/src/utils/mod.rs | 2 +- crates/common/src/ens.rs | 5 ++- crates/evm/core/src/fork/backend.rs | 45 ++++++++++++------- crates/evm/core/src/fork/init.rs | 2 +- crates/evm/core/src/fork/multi.rs | 8 +++- crates/evm/core/src/utils.rs | 1 + 18 files changed, 83 insertions(+), 58 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8494184a9c57..82d270d1af85 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3249,6 +3249,7 @@ dependencies = [ "alloy-primitives", "alloy-provider", "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=47e349f)", + "alloy-signer", "alloy-signer-wallet", "alloy-sol-types", "base64 0.22.0", diff --git a/crates/anvil/core/src/eth/transaction/mod.rs b/crates/anvil/core/src/eth/transaction/mod.rs index 72a88c54712c..471c747c7bfe 100644 --- a/crates/anvil/core/src/eth/transaction/mod.rs +++ b/crates/anvil/core/src/eth/transaction/mod.rs @@ -8,8 +8,8 @@ use alloy_consensus::{ BlobTransactionSidecar, ReceiptWithBloom, TxEip1559, TxEip2930, TxEip4844, TxEip4844Variant, TxEip4844WithSidecar, TxLegacy, }; -use alloy_network::{Signed, Transaction, TxKind}; -use alloy_primitives::{Address, Bloom, Bytes, Log, Signature, TxHash, B256, U128, U256, U64}; +use alloy_consensus::{Transaction, Signed}; +use alloy_primitives::{Address, Bloom, Bytes, Log, Signatureigned, TxHash, B256, U128, U256, U64}; use alloy_rlp::{Decodable, Encodable}; use alloy_rpc_types::{ request::TransactionRequest, AccessList, Signature as RpcSignature, diff --git a/crates/anvil/core/src/eth/transaction/optimism.rs b/crates/anvil/core/src/eth/transaction/optimism.rs index 86edc810a537..bcbcec22014a 100644 --- a/crates/anvil/core/src/eth/transaction/optimism.rs +++ b/crates/anvil/core/src/eth/transaction/optimism.rs @@ -1,6 +1,5 @@ -use alloy_consensus::TxType; -use alloy_network::{Transaction, TxKind}; -use alloy_primitives::{Address, Bytes, ChainId, Signature, B256, U256}; +use alloy_consensus::{Transaction, TxType}; +use alloy_primitives::{Address, Bytes, ChainId, Signature, TxKind, B256, U256}; use alloy_rlp::{ length_of_length, Decodable, Encodable, Error as DecodeError, Header as RlpHeader, }; @@ -158,7 +157,7 @@ impl Transaction for DepositTransactionRequest { u64::MAX } - fn decode_signed(buf: &mut &[u8]) -> alloy_rlp::Result> + fn decode_signed(buf: &mut &[u8]) -> alloy_rlp::Result> where Self: Sized, { @@ -189,11 +188,11 @@ impl Transaction for DepositTransactionRequest { &mut self.input } - fn into_signed(self, signature: Signature) -> alloy_network::Signed + fn into_signed(self, signature: Signature) -> alloy_consensus::Signed where Self: Sized, { - alloy_network::Signed::new_unchecked(self.clone(), signature, self.signature_hash()) + alloy_consensus::Signed::new_unchecked(self.clone(), signature, self.signature_hash()) } fn set_chain_id(&mut self, _chain_id: ChainId) {} diff --git a/crates/cheatcodes/Cargo.toml b/crates/cheatcodes/Cargo.toml index ddd4a9c4d120..fe39ef4600f9 100644 --- a/crates/cheatcodes/Cargo.toml +++ b/crates/cheatcodes/Cargo.toml @@ -26,6 +26,7 @@ alloy-genesis.workspace = true alloy-sol-types.workspace = true alloy-provider.workspace = true alloy-rpc-types.workspace = true +alloy-signer.workspace = true alloy-signer-wallet = { workspace = true, features = ["mnemonic", "keystore"] } parking_lot = "0.12" diff --git a/crates/cheatcodes/src/error.rs b/crates/cheatcodes/src/error.rs index 8b5f8102d8e3..4aeec84d9e4d 100644 --- a/crates/cheatcodes/src/error.rs +++ b/crates/cheatcodes/src/error.rs @@ -1,6 +1,7 @@ use crate::Vm; use alloy_primitives::{Address, Bytes}; -use alloy_signer::{Error as SignerError, WalletError}; +use alloy_signer::{Error as SignerError}; +use alloy_signer_wallet::WalletError; use alloy_sol_types::SolError; use foundry_common::errors::FsPathError; use foundry_config::UnresolvedEnvVarError; diff --git a/crates/cheatcodes/src/evm/fork.rs b/crates/cheatcodes/src/evm/fork.rs index f5402a0d38d2..4ff2bb4ae098 100644 --- a/crates/cheatcodes/src/evm/fork.rs +++ b/crates/cheatcodes/src/evm/fork.rs @@ -1,6 +1,6 @@ use crate::{Cheatcode, Cheatcodes, CheatsCtxt, DatabaseExt, Result, Vm::*}; use alloy_primitives::{B256, U256}; -use alloy_providers::tmp::TempProvider; +use alloy_provider::Provider; use alloy_rpc_types::Filter; use alloy_sol_types::SolValue; use eyre::WrapErr; @@ -225,7 +225,7 @@ impl Cheatcode for rpcCall { let method: &'static str = Box::new(method.clone()).leak(); let params_json: serde_json::Value = serde_json::from_str(params)?; let result = RuntimeOrHandle::new() - .block_on(provider.raw_request(method, params_json)) + .block_on(provider.raw_request(method.into(), params_json)) .map_err(|err| fmt_err!("{method:?}: {err}"))?; let result_as_tokens = crate::json::json_value_to_token(&result) @@ -268,7 +268,7 @@ impl Cheatcode for eth_getLogsCall { // todo: handle the errors somehow let logs = RuntimeOrHandle::new() - .block_on(provider.get_logs(filter)) + .block_on(provider.get_logs(&filter)) .wrap_err("failed to get logs")?; let eth_logs = logs diff --git a/crates/cheatcodes/src/evm/mock.rs b/crates/cheatcodes/src/evm/mock.rs index 645c14c58c82..6a266a4108fb 100644 --- a/crates/cheatcodes/src/evm/mock.rs +++ b/crates/cheatcodes/src/evm/mock.rs @@ -94,9 +94,9 @@ impl Cheatcode for mockCallRevert_1Call { fn mock_call( state: &mut Cheatcodes, callee: &Address, - cdata: &Vec, + cdata: &Bytes, value: Option<&U256>, - rdata: &Vec, + rdata: &Bytes, ret_type: InstructionResult, ) { state.mocked_calls.entry(*callee).or_default().insert( diff --git a/crates/cheatcodes/src/fs.rs b/crates/cheatcodes/src/fs.rs index 3e345db94a97..ee5cf35a7fd3 100644 --- a/crates/cheatcodes/src/fs.rs +++ b/crates/cheatcodes/src/fs.rs @@ -365,8 +365,8 @@ fn ffi(state: &Cheatcodes, input: &[String]) -> Result { }; Ok(FfiResult { exitCode: output.status.code().unwrap_or(69), - stdout: encoded_stdout, - stderr: output.stderr, + stdout: encoded_stdout.into(), + stderr: output.stderr.into(), }) } diff --git a/crates/cheatcodes/src/inspector.rs b/crates/cheatcodes/src/inspector.rs index bf39684b4955..2fa06d24cd7c 100644 --- a/crates/cheatcodes/src/inspector.rs +++ b/crates/cheatcodes/src/inspector.rs @@ -433,9 +433,9 @@ impl Inspector for Cheatcodes { oldBalance: old_balance, newBalance: old_balance + value, value, - data: vec![], + data: Bytes::new(), reverted: false, - deployedCode: vec![], + deployedCode: Bytes::new(), storageAccesses: vec![], depth: ecx.journaled_state.depth(), }; @@ -540,9 +540,9 @@ impl Inspector for Cheatcodes { oldBalance: balance, newBalance: balance, value: U256::ZERO, - data: vec![], + data: Bytes::new(), reverted: false, - deployedCode: vec![], + deployedCode: Bytes::new(), storageAccesses: vec![], depth: ecx.journaled_state.depth(), }; @@ -696,7 +696,7 @@ impl Inspector for Cheatcodes { if let Some(storage_recorded_logs) = &mut self.recorded_logs { storage_recorded_logs.push(Vm::Log { topics: log.data.topics().to_vec(), - data: log.data.data.to_vec(), + data: log.data.data.clone(), emitter: log.address, }); } @@ -924,9 +924,9 @@ impl Inspector for Cheatcodes { oldBalance: old_balance, newBalance: U256::ZERO, // updated on call_end value: call.transfer.value, - data: call.input.to_vec(), + data: call.input.clone(), reverted: false, - deployedCode: vec![], + deployedCode: Bytes::new(), storageAccesses: vec![], // updated on step depth: ecx.journaled_state.depth(), }]); @@ -1335,9 +1335,9 @@ impl Inspector for Cheatcodes { oldBalance: U256::ZERO, // updated on create_end newBalance: U256::ZERO, // updated on create_end value: call.value, - data: call.init_code.to_vec(), + data: call.init_code.clone(), reverted: false, - deployedCode: vec![], // updated on create_end + deployedCode: Bytes::new(), // updated on create_end storageAccesses: vec![], // updated on create_end depth, }]); @@ -1533,10 +1533,10 @@ fn apply_create2_deployer( oldBalance: U256::ZERO, // updated on create_end newBalance: U256::ZERO, // updated on create_end value: call.value, - data: calldata, + data: calldata.into(), reverted: false, - deployedCode: vec![], // updated on create_end - storageAccesses: vec![], // updated on create_end + deployedCode: Bytes::new(), // updated on create_end + storageAccesses: vec![], // updated on create_end depth: ecx.journaled_state.depth(), }]) } @@ -1672,8 +1672,8 @@ fn append_storage_access( oldBalance: U256::ZERO, newBalance: U256::ZERO, value: U256::ZERO, - data: vec![], - deployedCode: vec![], + data: Bytes::new(), + deployedCode: Bytes::new(), depth: entry.depth, }; last.push(resume_record); diff --git a/crates/cheatcodes/src/script.rs b/crates/cheatcodes/src/script.rs index ff4e3a14841a..60bad56f71fb 100644 --- a/crates/cheatcodes/src/script.rs +++ b/crates/cheatcodes/src/script.rs @@ -2,7 +2,8 @@ use crate::{Cheatcode, CheatsCtxt, DatabaseExt, Result, Vm::*}; use alloy_primitives::{Address, U256}; -use alloy_signer::{LocalWallet, Signer}; +use alloy_signer::Signer; +use alloy_signer_wallet::LocalWallet; use foundry_config::Config; use foundry_wallets::{multi_wallet::MultiWallet, WalletSigner}; use parking_lot::Mutex; diff --git a/crates/cheatcodes/src/test/expect.rs b/crates/cheatcodes/src/test/expect.rs index 02c747adb2ff..2fdc99476e4b 100644 --- a/crates/cheatcodes/src/test/expect.rs +++ b/crates/cheatcodes/src/test/expect.rs @@ -25,7 +25,7 @@ const DUMMY_CREATE_ADDRESS: Address = address!("00000000000000000000000000000000 /// This then allows us to customize the matching behavior for each call data on the /// `ExpectedCallData` struct and track how many times we've actually seen the call on the second /// element of the tuple. -pub type ExpectedCallTracker = HashMap, (ExpectedCallData, u64)>>; +pub type ExpectedCallTracker = HashMap>; #[derive(Clone, Debug)] pub struct ExpectedCallData { @@ -318,7 +318,7 @@ impl Cheatcode for expectSafeMemoryCallCall { fn expect_call( state: &mut Cheatcodes, target: &Address, - calldata: &Vec, + calldata: &Bytes, value: Option<&U256>, mut gas: Option, mut min_gas: Option, @@ -351,7 +351,7 @@ fn expect_call( "counted expected calls can only bet set once" ); expecteds.insert( - calldata.to_vec(), + calldata.clone(), (ExpectedCallData { value: value.copied(), gas, min_gas, count, call_type }, 0), ); } diff --git a/crates/cheatcodes/src/utils.rs b/crates/cheatcodes/src/utils.rs index 525120d7de8f..cca792e3f48d 100644 --- a/crates/cheatcodes/src/utils.rs +++ b/crates/cheatcodes/src/utils.rs @@ -2,13 +2,14 @@ use crate::{Cheatcode, Cheatcodes, CheatsCtxt, DatabaseExt, Result, Vm::*}; use alloy_primitives::{keccak256, B256, U256}; -use alloy_signer::{ +use alloy_signer_wallet::{ coins_bip39::{ ChineseSimplified, ChineseTraditional, Czech, English, French, Italian, Japanese, Korean, Portuguese, Spanish, Wordlist, }, - LocalWallet, MnemonicBuilder, Signer, SignerSync, + LocalWallet, MnemonicBuilder, }; +use alloy_signer::{Signer, SignerSync}; use alloy_sol_types::SolValue; use foundry_evm_core::constants::DEFAULT_CREATE2_DEPLOYER; use k256::{ @@ -160,7 +161,7 @@ pub(super) fn sign(private_key: &U256, digest: &B256) -> Result { // The `ecrecover` precompile does not use EIP-155. No chain ID is needed. let wallet = parse_wallet(private_key)?; - let sig = wallet.sign_hash_sync(*digest)?; + let sig = wallet.sign_hash_sync(digest)?; let recovered = sig.recover_address_from_prehash(digest)?; assert_eq!(recovered, wallet.address()); diff --git a/crates/cli/src/utils/mod.rs b/crates/cli/src/utils/mod.rs index 23e0c7ff7da8..735fb25230ea 100644 --- a/crates/cli/src/utils/mod.rs +++ b/crates/cli/src/utils/mod.rs @@ -76,7 +76,7 @@ pub fn subscriber() { } pub fn abi_to_solidity(abi: &JsonAbi, name: &str) -> Result { - let s = abi.to_sol(name); + let s = abi.to_sol(name, None); let s = forge_fmt::format(&s)?; Ok(s) } diff --git a/crates/common/src/ens.rs b/crates/common/src/ens.rs index 4182518ae3cb..302defa78293 100644 --- a/crates/common/src/ens.rs +++ b/crates/common/src/ens.rs @@ -36,7 +36,10 @@ pub enum NameOrAddress { impl NameOrAddress { /// Resolves the name to an Ethereum Address. - pub async fn resolve>(&self, provider: &P) -> Result { + pub async fn resolve>( + &self, + provider: &P, + ) -> Result { let name = match self { NameOrAddress::Name(name) => name.clone(), NameOrAddress::Address(addr) => return Ok(*addr), diff --git a/crates/evm/core/src/fork/backend.rs b/crates/evm/core/src/fork/backend.rs index b10cda95a6b6..ca783f332c43 100644 --- a/crates/evm/core/src/fork/backend.rs +++ b/crates/evm/core/src/fork/backend.rs @@ -3,9 +3,10 @@ use crate::{ backend::{DatabaseError, DatabaseResult}, fork::{cache::FlushJsonBlockCacheDB, BlockchainDb}, }; -use alloy_primitives::{keccak256, Address, Bytes, B256, U256}; -use alloy_provider::Provider; +use alloy_primitives::{keccak256, Address, Bytes, B256, U256, U64}; +use alloy_provider::{network::Ethereum, Network, Provider}; use alloy_rpc_types::{Block, BlockId, Transaction}; +use alloy_transport::Transport; use eyre::WrapErr; use foundry_common::NON_ARCHIVE_NODE_WARNING; use futures::{ @@ -21,6 +22,7 @@ use revm::{ use rustc_hash::FxHashMap; use std::{ collections::{hash_map::Entry, HashMap, VecDeque}, + marker::PhantomData, pin::Pin, sync::{ mpsc::{channel as oneshot_channel, Sender as OneshotSender}, @@ -31,7 +33,7 @@ use std::{ // Various future/request type aliases type AccountFuture = - Pin, Address)> + Send>>; + Pin, Address)> + Send>>; type StorageFuture = Pin, Address, U256)> + Send>>; type BlockHashFuture = Pin, u64)> + Send>>; type FullBlockFuture = @@ -76,8 +78,9 @@ enum BackendRequest { /// This handler will remain active as long as it is reachable (request channel still open) and /// requests are in progress. #[must_use = "futures do nothing unless polled"] -pub struct BackendHandler

{ +pub struct BackendHandler { provider: P, + transport: PhantomData, /// Stores all the data. db: BlockchainDb, /// Requests currently in progress @@ -97,9 +100,10 @@ pub struct BackendHandler

{ block_id: Option, } -impl BackendHandler

+impl BackendHandler where - P: Provider + Clone + 'static, + T: Transport + Clone, + P: Provider + Clone + Unpin + 'static, { fn new( provider: P, @@ -117,6 +121,7 @@ where queued_requests: Default::default(), incoming: rx, block_id, + transport: PhantomData, } } @@ -197,7 +202,7 @@ where let fut = Box::pin(async move { let balance = provider.get_balance(address, block_id); let nonce = provider.get_transaction_count(address, block_id); - let code = provider.get_code_at(address, block_id); + let code = provider.get_code_at(address, block_id.unwrap_or_default()); let resp = tokio::try_join!(balance, nonce, code).map_err(Into::into); (resp, address) }); @@ -283,9 +288,10 @@ where } } -impl

Future for BackendHandler

+impl Future for BackendHandler where - P: Provider + Clone + Unpin + 'static, + T: Transport + Clone + Unpin, + P: Provider + Clone + Unpin + 'static, { type Output = (); @@ -512,9 +518,14 @@ impl SharedBackend { /// dropped. /// /// NOTE: this should be called with `Arc` - pub async fn spawn_backend

(provider: P, db: BlockchainDb, pin_block: Option) -> Self + pub async fn spawn_backend( + provider: P, + db: BlockchainDb, + pin_block: Option, + ) -> Self where - P: TempProvider + Unpin + 'static + Clone, + T: Transport + Clone + Unpin, + P: Provider + Unpin + 'static + Clone, { let (shared, handler) = Self::new(provider, db, pin_block); // spawn the provider handler to a task @@ -525,13 +536,14 @@ impl SharedBackend { /// Same as `Self::spawn_backend` but spawns the `BackendHandler` on a separate `std::thread` in /// its own `tokio::Runtime` - pub fn spawn_backend_thread

( + pub fn spawn_backend_thread( provider: P, db: BlockchainDb, pin_block: Option, ) -> Self where - P: Provider + Unpin + 'static + Clone, + T: Transport + Clone + Unpin, + P: Provider + Unpin + 'static + Clone, { let (shared, handler) = Self::new(provider, db, pin_block); @@ -554,13 +566,14 @@ impl SharedBackend { } /// Returns a new `SharedBackend` and the `BackendHandler` - pub fn new

( + pub fn new( provider: P, db: BlockchainDb, pin_block: Option, - ) -> (Self, BackendHandler

) + ) -> (Self, BackendHandler) where - P: Provider + Clone + 'static, + T: Transport + Clone + Unpin, + P: Provider + Unpin + 'static + Clone, { let (backend, backend_rx) = channel(1); let cache = Arc::new(FlushJsonBlockCacheDB(Arc::clone(db.cache()))); diff --git a/crates/evm/core/src/fork/init.rs b/crates/evm/core/src/fork/init.rs index e6597ca8f982..decc00c3aa84 100644 --- a/crates/evm/core/src/fork/init.rs +++ b/crates/evm/core/src/fork/init.rs @@ -1,8 +1,8 @@ use crate::utils::apply_chain_and_block_specific_env_changes; use alloy_primitives::{Address, U256}; use alloy_provider::{Network, Provider}; -use alloy_transport::Transport; use alloy_rpc_types::{Block, BlockNumberOrTag}; +use alloy_transport::Transport; use eyre::WrapErr; use foundry_common::NON_ARCHIVE_NODE_WARNING; diff --git a/crates/evm/core/src/fork/multi.rs b/crates/evm/core/src/fork/multi.rs index 4e1cb66e5ff4..6ed49ca27f72 100644 --- a/crates/evm/core/src/fork/multi.rs +++ b/crates/evm/core/src/fork/multi.rs @@ -4,7 +4,11 @@ //! concurrently active pairs at once. use crate::fork::{BackendHandler, BlockchainDb, BlockchainDbMeta, CreateFork, SharedBackend}; -use foundry_common::provider::alloy::{ProviderBuilder, RetryProvider}; +use foundry_common::provider::{ + alloy::{ProviderBuilder, RetryProvider}, + runtime_transport::RuntimeTransport, + tower::RetryBackoffService, +}; use foundry_config::Config; use futures::{ channel::mpsc::{channel, Receiver, Sender}, @@ -167,7 +171,7 @@ impl MultiFork { } } -type Handler = BackendHandler>; +type Handler = BackendHandler, Arc>; type CreateFuture = Pin> + Send>>; diff --git a/crates/evm/core/src/utils.rs b/crates/evm/core/src/utils.rs index 7ef8bb47f2d4..fea2ab4f8ef5 100644 --- a/crates/evm/core/src/utils.rs +++ b/crates/evm/core/src/utils.rs @@ -76,6 +76,7 @@ pub fn configure_tx_env(env: &mut revm::primitives::Env, tx: &Transaction) { .access_list .clone() .unwrap_or_default() + .0 .into_iter() .map(|item| { ( From f9fcfd423dab44276e4abd05ececb1c5e4caaa57 Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Wed, 20 Mar 2024 01:22:25 +0400 Subject: [PATCH 10/63] wip --- Cargo.lock | 83 ++++---- Cargo.toml | 36 ++-- crates/anvil/core/src/eth/transaction/mod.rs | 4 +- crates/cast/Cargo.toml | 4 +- crates/cast/src/lib.rs | 188 +++++++++---------- crates/cast/src/tx.rs | 120 +++++------- crates/cheatcodes/src/error.rs | 2 +- crates/cheatcodes/src/inspector.rs | 8 +- crates/cheatcodes/src/utils.rs | 2 +- crates/common/src/ens.rs | 3 +- crates/common/src/transactions.rs | 7 +- crates/common/src/types.rs | 6 +- 12 files changed, 214 insertions(+), 249 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 82d270d1af85..85652ade08de 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -90,7 +90,7 @@ dependencies = [ [[package]] name = "alloy-consensus" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=47e349f#47e349f303db95f1eabced5901fc5b76e6d267c4" +source = "git+https://github.com/klkvr/alloy?rev=de65254#de6525468ab75f40f94db793da2b54ecc52d2d2c" dependencies = [ "alloy-eips", "alloy-primitives", @@ -103,14 +103,14 @@ dependencies = [ [[package]] name = "alloy-contract" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=47e349f#47e349f303db95f1eabced5901fc5b76e6d267c4" +source = "git+https://github.com/klkvr/alloy?rev=de65254#de6525468ab75f40f94db793da2b54ecc52d2d2c" dependencies = [ "alloy-dyn-abi", "alloy-json-abi", "alloy-network", "alloy-primitives", "alloy-provider", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=47e349f)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=de65254)", "alloy-sol-types", "alloy-transport", "futures", @@ -142,7 +142,7 @@ dependencies = [ [[package]] name = "alloy-eips" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=47e349f#47e349f303db95f1eabced5901fc5b76e6d267c4" +source = "git+https://github.com/klkvr/alloy?rev=de65254#de6525468ab75f40f94db793da2b54ecc52d2d2c" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -152,7 +152,7 @@ dependencies = [ [[package]] name = "alloy-genesis" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=47e349f#47e349f303db95f1eabced5901fc5b76e6d267c4" +source = "git+https://github.com/klkvr/alloy?rev=de65254#de6525468ab75f40f94db793da2b54ecc52d2d2c" dependencies = [ "alloy-primitives", "alloy-serde", @@ -173,7 +173,7 @@ dependencies = [ [[package]] name = "alloy-json-rpc" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=47e349f#47e349f303db95f1eabced5901fc5b76e6d267c4" +source = "git+https://github.com/klkvr/alloy?rev=de65254#de6525468ab75f40f94db793da2b54ecc52d2d2c" dependencies = [ "alloy-primitives", "serde", @@ -184,13 +184,13 @@ dependencies = [ [[package]] name = "alloy-network" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=47e349f#47e349f303db95f1eabced5901fc5b76e6d267c4" +source = "git+https://github.com/klkvr/alloy?rev=de65254#de6525468ab75f40f94db793da2b54ecc52d2d2c" dependencies = [ "alloy-consensus", "alloy-eips", "alloy-json-rpc", "alloy-primitives", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=47e349f)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=de65254)", "alloy-signer", "async-trait", "futures-utils-wasm", @@ -227,14 +227,15 @@ dependencies = [ [[package]] name = "alloy-provider" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=47e349f#47e349f303db95f1eabced5901fc5b76e6d267c4" +source = "git+https://github.com/klkvr/alloy?rev=de65254#de6525468ab75f40f94db793da2b54ecc52d2d2c" dependencies = [ "alloy-json-rpc", "alloy-network", "alloy-primitives", + "alloy-pubsub", "alloy-rpc-client", - "alloy-rpc-trace-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=47e349f)", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=47e349f)", + "alloy-rpc-trace-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=de65254)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=de65254)", "alloy-transport", "alloy-transport-http", "async-stream", @@ -252,7 +253,7 @@ dependencies = [ [[package]] name = "alloy-pubsub" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=47e349f#47e349f303db95f1eabced5901fc5b76e6d267c4" +source = "git+https://github.com/klkvr/alloy?rev=de65254#de6525468ab75f40f94db793da2b54ecc52d2d2c" dependencies = [ "alloy-json-rpc", "alloy-primitives", @@ -292,9 +293,11 @@ dependencies = [ [[package]] name = "alloy-rpc-client" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=47e349f#47e349f303db95f1eabced5901fc5b76e6d267c4" +source = "git+https://github.com/klkvr/alloy?rev=de65254#de6525468ab75f40f94db793da2b54ecc52d2d2c" dependencies = [ "alloy-json-rpc", + "alloy-primitives", + "alloy-pubsub", "alloy-transport", "alloy-transport-http", "futures", @@ -312,11 +315,10 @@ dependencies = [ [[package]] name = "alloy-rpc-trace-types" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=47e349f#47e349f303db95f1eabced5901fc5b76e6d267c4" +source = "git+https://github.com/alloy-rs/alloy?rev=9ac2c90#9ac2c90d58a9994d4b61c879e33c6af2739a2b4f" dependencies = [ "alloy-primitives", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=47e349f)", - "alloy-serde", + "alloy-rpc-types 0.1.0 (git+https://github.com/alloy-rs/alloy?rev=9ac2c90)", "serde", "serde_json", ] @@ -324,10 +326,11 @@ dependencies = [ [[package]] name = "alloy-rpc-trace-types" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=9ac2c90#9ac2c90d58a9994d4b61c879e33c6af2739a2b4f" +source = "git+https://github.com/klkvr/alloy?rev=de65254#de6525468ab75f40f94db793da2b54ecc52d2d2c" dependencies = [ "alloy-primitives", - "alloy-rpc-types 0.1.0 (git+https://github.com/alloy-rs/alloy?rev=9ac2c90)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=de65254)", + "alloy-serde", "serde", "serde_json", ] @@ -335,11 +338,10 @@ dependencies = [ [[package]] name = "alloy-rpc-types" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=47e349f#47e349f303db95f1eabced5901fc5b76e6d267c4" +source = "git+https://github.com/alloy-rs/alloy?rev=9ac2c90#9ac2c90d58a9994d4b61c879e33c6af2739a2b4f" dependencies = [ "alloy-primitives", "alloy-rlp", - "alloy-serde", "itertools 0.12.1", "serde", "serde_json", @@ -349,10 +351,11 @@ dependencies = [ [[package]] name = "alloy-rpc-types" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=9ac2c90#9ac2c90d58a9994d4b61c879e33c6af2739a2b4f" +source = "git+https://github.com/klkvr/alloy?rev=de65254#de6525468ab75f40f94db793da2b54ecc52d2d2c" dependencies = [ "alloy-primitives", "alloy-rlp", + "alloy-serde", "itertools 0.12.1", "serde", "serde_json", @@ -362,7 +365,7 @@ dependencies = [ [[package]] name = "alloy-serde" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=47e349f#47e349f303db95f1eabced5901fc5b76e6d267c4" +source = "git+https://github.com/klkvr/alloy?rev=de65254#de6525468ab75f40f94db793da2b54ecc52d2d2c" dependencies = [ "alloy-primitives", "serde", @@ -372,7 +375,7 @@ dependencies = [ [[package]] name = "alloy-signer" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=47e349f#47e349f303db95f1eabced5901fc5b76e6d267c4" +source = "git+https://github.com/klkvr/alloy?rev=de65254#de6525468ab75f40f94db793da2b54ecc52d2d2c" dependencies = [ "alloy-dyn-abi", "alloy-primitives", @@ -387,7 +390,7 @@ dependencies = [ [[package]] name = "alloy-signer-wallet" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=47e349f#47e349f303db95f1eabced5901fc5b76e6d267c4" +source = "git+https://github.com/klkvr/alloy?rev=de65254#de6525468ab75f40f94db793da2b54ecc52d2d2c" dependencies = [ "alloy-consensus", "alloy-network", @@ -454,7 +457,7 @@ dependencies = [ [[package]] name = "alloy-transport" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=47e349f#47e349f303db95f1eabced5901fc5b76e6d267c4" +source = "git+https://github.com/klkvr/alloy?rev=de65254#de6525468ab75f40f94db793da2b54ecc52d2d2c" dependencies = [ "alloy-json-rpc", "base64 0.22.0", @@ -472,7 +475,7 @@ dependencies = [ [[package]] name = "alloy-transport-http" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=47e349f#47e349f303db95f1eabced5901fc5b76e6d267c4" +source = "git+https://github.com/klkvr/alloy?rev=de65254#de6525468ab75f40f94db793da2b54ecc52d2d2c" dependencies = [ "alloy-json-rpc", "alloy-transport", @@ -485,7 +488,7 @@ dependencies = [ [[package]] name = "alloy-transport-ipc" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=47e349f#47e349f303db95f1eabced5901fc5b76e6d267c4" +source = "git+https://github.com/klkvr/alloy?rev=de65254#de6525468ab75f40f94db793da2b54ecc52d2d2c" dependencies = [ "alloy-json-rpc", "alloy-pubsub", @@ -503,7 +506,7 @@ dependencies = [ [[package]] name = "alloy-transport-ws" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=47e349f#47e349f303db95f1eabced5901fc5b76e6d267c4" +source = "git+https://github.com/klkvr/alloy?rev=de65254#de6525468ab75f40f94db793da2b54ecc52d2d2c" dependencies = [ "alloy-pubsub", "alloy-transport", @@ -610,8 +613,8 @@ dependencies = [ "alloy-primitives", "alloy-provider", "alloy-rlp", - "alloy-rpc-trace-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=47e349f)", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=47e349f)", + "alloy-rpc-trace-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=de65254)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=de65254)", "alloy-signer", "alloy-signer-wallet", "alloy-sol-types", @@ -673,8 +676,8 @@ dependencies = [ "alloy-network", "alloy-primitives", "alloy-rlp", - "alloy-rpc-trace-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=47e349f)", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=47e349f)", + "alloy-rpc-trace-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=de65254)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=de65254)", "anvil-core", "bytes", "c-kzg", @@ -1374,11 +1377,13 @@ dependencies = [ "alloy-contract", "alloy-dyn-abi", "alloy-json-abi", + "alloy-json-rpc", "alloy-primitives", "alloy-provider", "alloy-rlp", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=47e349f)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=de65254)", "alloy-signer", + "alloy-transport", "async-trait", "chrono", "clap", @@ -1459,7 +1464,7 @@ dependencies = [ "alloy-dyn-abi", "alloy-json-abi", "alloy-primitives", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=47e349f)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=de65254)", "clap", "criterion", "dirs 5.0.1", @@ -3033,7 +3038,7 @@ dependencies = [ "alloy-dyn-abi", "alloy-json-abi", "alloy-primitives", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=47e349f)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=de65254)", "anvil", "async-trait", "axum", @@ -3149,7 +3154,7 @@ dependencies = [ "alloy-dyn-abi", "alloy-json-abi", "alloy-primitives", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=47e349f)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=de65254)", "async-recursion", "clap", "const-hex", @@ -3248,7 +3253,7 @@ dependencies = [ "alloy-json-abi", "alloy-primitives", "alloy-provider", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=47e349f)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=de65254)", "alloy-signer", "alloy-signer-wallet", "alloy-sol-types", @@ -3332,7 +3337,7 @@ dependencies = [ "alloy-provider", "alloy-pubsub", "alloy-rpc-client", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=47e349f)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=de65254)", "alloy-signer", "alloy-signer-wallet", "alloy-sol-types", @@ -3501,7 +3506,7 @@ dependencies = [ "alloy-json-abi", "alloy-primitives", "alloy-provider", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=47e349f)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=de65254)", "alloy-sol-types", "alloy-transport", "arrayvec", diff --git a/Cargo.toml b/Cargo.toml index ced4e1104524..0431b2ae891c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -159,24 +159,24 @@ ethers-middleware = { version = "2.0.14", default-features = false } ethers-solc = { version = "2.0.14", default-features = false } ## alloy -alloy-consensus = { git = "https://github.com/klkvr/alloy", rev = "47e349f" } -alloy-contract = { git = "https://github.com/klkvr/alloy", rev = "47e349f" } -alloy-eips = { git = "https://github.com/klkvr/alloy", rev = "47e349f" } -alloy-genesis = { git = "https://github.com/klkvr/alloy", rev = "47e349f" } -alloy-json-rpc = { git = "https://github.com/klkvr/alloy", rev = "47e349f" } -alloy-network = { git = "https://github.com/klkvr/alloy", rev = "47e349f" } -alloy-node-bindings = { git = "https://github.com/klkvr/alloy", rev = "47e349f" } -alloy-provider = { git = "https://github.com/klkvr/alloy", rev = "47e349f" } -alloy-pubsub = { git = "https://github.com/klkvr/alloy", rev = "47e349f" } -alloy-rpc-client = { git = "https://github.com/klkvr/alloy", rev = "47e349f" } -alloy-rpc-trace-types = { git = "https://github.com/klkvr/alloy", rev = "47e349f" } -alloy-rpc-types = { git = "https://github.com/klkvr/alloy", rev = "47e349f" } -alloy-signer = { git = "https://github.com/klkvr/alloy", rev = "47e349f" } -alloy-signer-wallet = { git = "https://github.com/klkvr/alloy", rev = "47e349f" } -alloy-transport = { git = "https://github.com/klkvr/alloy", rev = "47e349f" } -alloy-transport-http = { git = "https://github.com/klkvr/alloy", rev = "47e349f" } -alloy-transport-ipc = { git = "https://github.com/klkvr/alloy", rev = "47e349f" } -alloy-transport-ws = { git = "https://github.com/klkvr/alloy", rev = "47e349f" } +alloy-consensus = { git = "https://github.com/klkvr/alloy", rev = "de65254" } +alloy-contract = { git = "https://github.com/klkvr/alloy", rev = "de65254" } +alloy-eips = { git = "https://github.com/klkvr/alloy", rev = "de65254" } +alloy-genesis = { git = "https://github.com/klkvr/alloy", rev = "de65254" } +alloy-json-rpc = { git = "https://github.com/klkvr/alloy", rev = "de65254" } +alloy-network = { git = "https://github.com/klkvr/alloy", rev = "de65254" } +alloy-node-bindings = { git = "https://github.com/klkvr/alloy", rev = "de65254" } +alloy-provider = { git = "https://github.com/klkvr/alloy", rev = "de65254" } +alloy-pubsub = { git = "https://github.com/klkvr/alloy", rev = "de65254" } +alloy-rpc-client = { git = "https://github.com/klkvr/alloy", rev = "de65254" } +alloy-rpc-trace-types = { git = "https://github.com/klkvr/alloy", rev = "de65254" } +alloy-rpc-types = { git = "https://github.com/klkvr/alloy", rev = "de65254" } +alloy-signer = { git = "https://github.com/klkvr/alloy", rev = "de65254" } +alloy-signer-wallet = { git = "https://github.com/klkvr/alloy", rev = "de65254" } +alloy-transport = { git = "https://github.com/klkvr/alloy", rev = "de65254" } +alloy-transport-http = { git = "https://github.com/klkvr/alloy", rev = "de65254" } +alloy-transport-ipc = { git = "https://github.com/klkvr/alloy", rev = "de65254" } +alloy-transport-ws = { git = "https://github.com/klkvr/alloy", rev = "de65254" } alloy-primitives = { version = "0.6.4", features = ["getrandom"] } alloy-dyn-abi = "0.6.4" alloy-json-abi = "0.6.4" diff --git a/crates/anvil/core/src/eth/transaction/mod.rs b/crates/anvil/core/src/eth/transaction/mod.rs index 471c747c7bfe..72a88c54712c 100644 --- a/crates/anvil/core/src/eth/transaction/mod.rs +++ b/crates/anvil/core/src/eth/transaction/mod.rs @@ -8,8 +8,8 @@ use alloy_consensus::{ BlobTransactionSidecar, ReceiptWithBloom, TxEip1559, TxEip2930, TxEip4844, TxEip4844Variant, TxEip4844WithSidecar, TxLegacy, }; -use alloy_consensus::{Transaction, Signed}; -use alloy_primitives::{Address, Bloom, Bytes, Log, Signatureigned, TxHash, B256, U128, U256, U64}; +use alloy_network::{Signed, Transaction, TxKind}; +use alloy_primitives::{Address, Bloom, Bytes, Log, Signature, TxHash, B256, U128, U256, U64}; use alloy_rlp::{Decodable, Encodable}; use alloy_rpc_types::{ request::TransactionRequest, AccessList, Signature as RpcSignature, diff --git a/crates/cast/Cargo.toml b/crates/cast/Cargo.toml index 849b5a6c71cf..4341d3d7b8d2 100644 --- a/crates/cast/Cargo.toml +++ b/crates/cast/Cargo.toml @@ -34,8 +34,10 @@ alloy-dyn-abi.workspace = true alloy-json-abi.workspace = true alloy-primitives.workspace = true alloy-rlp.workspace = true -alloy-provider.workspace = true +alloy-provider = { workspace = true, features = ["pubsub"] } +alloy-transport.workspace = true alloy-rpc-types.workspace = true +alloy-json-rpc.workspace = true alloy-signer.workspace = true alloy-contract.workspace = true alloy-consensus.workspace = true diff --git a/crates/cast/src/lib.rs b/crates/cast/src/lib.rs index f2edcc88933e..9da806ba67e3 100644 --- a/crates/cast/src/lib.rs +++ b/crates/cast/src/lib.rs @@ -1,19 +1,20 @@ +use alloy_consensus::TxEnvelope; use alloy_dyn_abi::{DynSolType, DynSolValue, FunctionExt}; use alloy_json_abi::ContractObject; use alloy_primitives::{ utils::{keccak256, ParseUnits, Unit}, - Address, Bytes, Keccak256, B256, I256, U256, U64, + Address, Bytes, Keccak256, TxHash, B256, I256, U256, U64, +}; +use alloy_provider::{ + network::{eip2718::Decodable2718, Ethereum}, + PendingTransaction, PendingTransactionBuilder, Provider, }; -use alloy_providers::tmp::TempProvider; use alloy_rlp::Decodable; -use alloy_rpc_types::{BlockId as AlloyBlockId, BlockNumberOrTag}; +use alloy_rpc_types::{BlockId, BlockNumberOrTag, Filter}; +use alloy_transport::Transport; use base::{Base, NumberWithBase, ToBase}; use chrono::DateTime; -use ethers_core::{ - types::{transaction::eip2718::TypedTransaction, BlockId, Filter, Signature, H256}, - utils::rlp, -}; -use ethers_providers::{Middleware, PendingTransaction, PubsubClient}; +use ethers_core::types::transaction::eip2718::TypedTransaction; use evm_disassembler::{disassemble_bytes, disassemble_str, format_operations}; use eyre::{Context, ContextCompat, Result}; use foundry_block_explorers::Client; @@ -26,13 +27,15 @@ use foundry_config::Chain; use futures::{future::Either, FutureExt, StreamExt}; use rayon::prelude::*; use std::{ + borrow::Cow, io, + marker::PhantomData, path::PathBuf, str::FromStr, sync::atomic::{AtomicBool, Ordering}, }; use tokio::signal::ctrl_c; -pub use tx::{TxBuilder, TxBuilderAlloyOutput, TxBuilderOutput, TxBuilderPeekOutput}; +pub use tx::{TxBuilder, TxBuilderOutput, TxBuilderPeekOutput}; use foundry_common::abi::encode_function_args_packed; pub use foundry_evm::*; @@ -51,14 +54,15 @@ use rlp_converter::Item; // TODO: CastContract with common contract initializers? Same for CastProviders? -pub struct Cast { - provider: M, - alloy_provider: P, +pub struct Cast { + provider: P, + transport: PhantomData, } -impl Cast +impl Cast where - M::Error: 'static, + T: Transport + Clone, + P: Provider, { /// Creates a new Cast instance from the provided client /// @@ -76,8 +80,8 @@ where /// # Ok(()) /// # } /// ``` - pub fn new(provider: M, alloy_provider: P) -> Self { - Self { provider, alloy_provider } + pub fn new(provider: P) -> Self { + Self { provider, transport: PhantomData } } /// Makes a read-only call to the specified address @@ -109,11 +113,11 @@ where /// ``` pub async fn call<'a>( &self, - builder_output: TxBuilderAlloyOutput, - block: Option, + builder_output: TxBuilderOutput, + block: Option, ) -> Result { let (tx, func) = builder_output; - let res = self.alloy_provider.call(tx.clone(), block).await?; + let res = self.provider.call(&tx, block).await?; let mut decoded = vec![]; @@ -126,7 +130,9 @@ where if res.is_empty() { // check that the recipient is a contract that can be called if let Some(addr) = tx.to { - if let Ok(code) = self.alloy_provider.get_code_at(addr, block).await { + if let Ok(code) = + self.provider.get_code_at(addr, block.unwrap_or_default()).await + { if code.is_empty() { eyre::bail!("contract {addr:?} does not have any code") } @@ -177,11 +183,11 @@ where pub async fn access_list( &self, builder_output: TxBuilderPeekOutput<'_>, - block: Option, + block: Option, to_json: bool, ) -> Result { let (tx, _) = builder_output; - let access_list = self.alloy_provider.create_access_list(tx.clone(), block).await?; + let access_list = self.provider.create_access_list(&tx, block).await?; let res = if to_json { serde_json::to_string(&access_list)? } else { @@ -202,8 +208,8 @@ where Ok(res) } - pub async fn balance(&self, who: Address, block: Option) -> Result { - Ok(self.alloy_provider.get_balance(who, block).await?) + pub async fn balance(&self, who: Address, block: Option) -> Result { + Ok(self.provider.get_balance(who, block).await?) } /// Sends a transaction to the specified address @@ -234,12 +240,9 @@ where /// # Ok(()) /// # } /// ``` - pub async fn send<'a>( - &self, - builder_output: TxBuilderOutput, - ) -> Result> { + pub async fn send<'a>(&self, builder_output: TxBuilderOutput) -> Result { let (tx, _) = builder_output; - let res = self.provider.send_transaction(tx, None).await?; + let res = self.provider.send_transaction(tx).await?.register().await?; Ok::<_, eyre::Error>(res) } @@ -260,13 +263,13 @@ where /// # Ok(()) /// # } /// ``` - pub async fn publish(&self, mut raw_tx: String) -> Result> { + pub async fn publish(&self, mut raw_tx: String) -> Result { raw_tx = match raw_tx.strip_prefix("0x") { Some(s) => s.to_string(), None => raw_tx, }; - let tx = Bytes::from(hex::decode(raw_tx)?); - let res = self.provider.send_raw_transaction(tx.0.into()).await?; + let tx = hex::decode(raw_tx)?; + let res = self.provider.send_raw_transaction(&tx).await?.register().await?; Ok::<_, eyre::Error>(res) } @@ -301,7 +304,7 @@ where pub async fn estimate(&self, builder_output: TxBuilderPeekOutput<'_>) -> Result { let (tx, _) = builder_output; - let res = self.alloy_provider.estimate_gas(tx.clone(), None).await?; + let res = self.provider.estimate_gas(&tx, None).await?; Ok::<_, eyre::Error>(res) } @@ -320,22 +323,22 @@ where /// # Ok(()) /// # } /// ``` - pub async fn block>( + pub async fn block>( &self, - block: T, + block: B, full: bool, field: Option, to_json: bool, ) -> Result { let block = block.into(); - if let Some(field) = field { + if let Some(ref field) = field { if field == "transactions" && !full { eyre::bail!("use --full to view transactions") } } let block = self - .alloy_provider + .provider .get_block(block, full) .await? .ok_or_else(|| eyre::eyre!("block {:?} not found", block))?; @@ -352,11 +355,7 @@ where Ok(block) } - async fn block_field_as_num>( - &self, - block: T, - field: String, - ) -> Result { + async fn block_field_as_num>(&self, block: B, field: String) -> Result { let block = block.into(); let block_field = Cast::block( self, @@ -376,18 +375,18 @@ where Ok(ret) } - pub async fn base_fee>(&self, block: T) -> Result { + pub async fn base_fee>(&self, block: B) -> Result { Cast::block_field_as_num(self, block, String::from("baseFeePerGas")).await } - pub async fn age>(&self, block: T) -> Result { + pub async fn age>(&self, block: B) -> Result { let timestamp_str = Cast::block_field_as_num(self, block, String::from("timestamp")).await?.to_string(); let datetime = DateTime::from_timestamp(timestamp_str.parse::().unwrap(), 0).unwrap(); Ok(datetime.format("%a %b %e %H:%M:%S %Y").to_string()) } - pub async fn timestamp>(&self, block: T) -> Result { + pub async fn timestamp>(&self, block: B) -> Result { Cast::block_field_as_num(self, block, "timestamp".to_string()).await } @@ -455,15 +454,15 @@ where } pub async fn chain_id(&self) -> Result { - Ok(U256::from(self.alloy_provider.get_chain_id().await?)) + Ok(U256::from(self.provider.get_chain_id().await?)) } pub async fn block_number(&self) -> Result { - Ok(U64::from(self.alloy_provider.get_block_number().await?)) + Ok(U64::from(self.provider.get_block_number().await?)) } pub async fn gas_price(&self) -> Result { - Ok(self.alloy_provider.get_gas_price().await?) + Ok(self.provider.get_gas_price().await?) } /// # Example @@ -483,8 +482,8 @@ where /// # Ok(()) /// # } /// ``` - pub async fn nonce(&self, who: Address, block: Option) -> Result { - Ok(self.alloy_provider.get_transaction_count(who, block).await?.to()) + pub async fn nonce(&self, who: Address, block: Option) -> Result { + Ok(self.provider.get_transaction_count(who, block).await?.to()) } /// # Example @@ -504,14 +503,10 @@ where /// # Ok(()) /// # } /// ``` - pub async fn implementation( - &self, - who: Address, - block: Option, - ) -> Result { + pub async fn implementation(&self, who: Address, block: Option) -> Result { let slot = B256::from_str("0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc")?; - let value = self.alloy_provider.get_storage_at(who, slot.into(), block).await?; + let value = self.provider.get_storage_at(who, slot.into(), block).await?; let addr = Address::from_word(value.into()); Ok(format!("{addr:?}")) } @@ -533,10 +528,10 @@ where /// # Ok(()) /// # } /// ``` - pub async fn admin(&self, who: Address, block: Option) -> Result { + pub async fn admin(&self, who: Address, block: Option) -> Result { let slot = B256::from_str("0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103")?; - let value = self.alloy_provider.get_storage_at(who, slot.into(), block).await?; + let value = self.provider.get_storage_at(who, slot.into(), block).await?; let addr = Address::from_word(value.into()); Ok(format!("{addr:?}")) } @@ -583,14 +578,14 @@ where pub async fn code( &self, who: Address, - block: Option, + block: Option, disassemble: bool, ) -> Result { if disassemble { - let code = self.alloy_provider.get_code_at(who, block).await?.to_vec(); + let code = self.provider.get_code_at(who, block.unwrap_or_default()).await?.to_vec(); Ok(format_operations(disassemble_bytes(code)?)?) } else { - Ok(format!("{}", self.alloy_provider.get_code_at(who, block).await?)) + Ok(format!("{}", self.provider.get_code_at(who, block.unwrap_or_default()).await?)) } } @@ -611,8 +606,8 @@ where /// # Ok(()) /// # } /// ``` - pub async fn codesize(&self, who: Address, block: Option) -> Result { - let code = self.alloy_provider.get_code_at(who, block).await?.to_vec(); + pub async fn codesize(&self, who: Address, block: Option) -> Result { + let code = self.provider.get_code_at(who, block.unwrap_or_default()).await?.to_vec(); Ok(format!("{}", code.len())) } @@ -638,12 +633,8 @@ where raw: bool, to_json: bool, ) -> Result { - let tx_hash = H256::from_str(&tx_hash).wrap_err("invalid tx hash")?; - let tx = self - .provider - .get_transaction(tx_hash) - .await? - .ok_or_else(|| eyre::eyre!("tx not found: {:?}", tx_hash))?; + let tx_hash = TxHash::from_str(&tx_hash).wrap_err("invalid tx hash")?; + let tx = self.provider.get_transaction_by_hash(tx_hash).await?; Ok(if raw { format!("0x{}", hex::encode(tx.rlp())) @@ -677,14 +668,14 @@ where &self, tx_hash: String, field: Option, - confs: usize, + confs: u64, cast_async: bool, to_json: bool, ) -> Result { - let tx_hash = H256::from_str(&tx_hash).wrap_err("invalid tx hash")?; + let tx_hash = TxHash::from_str(&tx_hash).wrap_err("invalid tx hash")?; let mut receipt: TransactionReceiptWithRevertReason = - match self.provider.get_transaction_receipt(tx_hash).await? { + match self.provider.get_transaction_receipt(tx_hash.into()).await? { Some(r) => r, None => { // if the async flag is provided, immediately exit if no tx is found, otherwise @@ -692,13 +683,10 @@ where if cast_async { eyre::bail!("tx not found: {:?}", tx_hash) } else { - let tx = PendingTransaction::new(tx_hash, self.provider.provider()); - tx.confirmations(confs).await?.ok_or_else(|| { - eyre::eyre!( - "tx not found, might have been dropped from mempool: {:?}", - tx_hash - ) - })? + PendingTransactionBuilder::new(self.provider.root(), tx_hash.into()) + .with_confirmations(confs) + .get_receipt() + .await? } } } @@ -736,12 +724,14 @@ where /// # Ok(()) /// # } /// ``` - pub async fn rpc(&self, method: &str, params: T) -> Result + pub async fn rpc(&self, method: &str, params: V) -> Result where - T: std::fmt::Debug + serde::Serialize + Send + Sync + Clone, + V: alloy_json_rpc::RpcParam, { - let method = Box::new(method.to_string()).leak(); - let res = self.alloy_provider.raw_request::(method, params).await?; + let res = self + .provider + .raw_request::(Cow::Owned(method.to_string()), params) + .await?; Ok(serde_json::to_string(&res)?) } @@ -769,11 +759,11 @@ where &self, from: Address, slot: B256, - block: Option, + block: Option, ) -> Result { Ok(format!( "{:?}", - B256::from(self.alloy_provider.get_storage_at(from, slot.into(), block).await?) + B256::from(self.provider.get_storage_at(from, slot.into(), block).await?) )) } @@ -829,14 +819,13 @@ where /// ``` pub async fn convert_block_number( &self, - block: Option, + block: Option, ) -> Result, eyre::Error> { match block { Some(block) => match block { - AlloyBlockId::Number(block_number) => Ok(Some(block_number)), - AlloyBlockId::Hash(hash) => { - let block = - self.alloy_provider.get_block_by_hash(hash.block_hash, false).await?; + BlockId::Number(block_number) => Ok(Some(block_number)), + BlockId::Hash(hash) => { + let block = self.provider.get_block_by_hash(hash.block_hash, false).await?; Ok(block .map(|block| block.header.number.unwrap().to::()) .map(BlockNumberOrTag::from)) @@ -872,21 +861,18 @@ where filter: Filter, output: &mut dyn io::Write, to_json: bool, - ) -> Result<()> - where - ::Provider: PubsubClient, - { + ) -> Result<()> { // Initialize the subscription stream for logs - let mut subscription = self.provider.subscribe_logs(&filter).await?; + let mut subscription = self.provider.subscribe_logs(&filter).await?.into_stream(); // Check if a to_block is specified, if so, subscribe to blocks let mut block_subscription = if filter.get_to_block().is_some() { - Some(self.provider.subscribe_blocks().await?) + Some(self.provider.subscribe_blocks().await?.into_stream()) } else { None }; - let to_block_number = filter.get_to_block(); + let to_block_number = filter.get_to_block().map(U256::from); // If output should be JSON, start with an opening bracket if to_json { @@ -904,7 +890,7 @@ where Either::Right(futures::future::pending()) } => { if let (Some(block), Some(to_block)) = (block, to_block_number) { - if block.number.map_or(false, |bn| bn > to_block) { + if block.header.number.map_or(false, |bn| bn > to_block) { break; } } @@ -2012,10 +1998,10 @@ impl SimpleCast { /// let tx = "0x02f8f582a86a82058d8459682f008508351050808303fd84948e42f2f4101563bf679975178e880fd87d3efd4e80b884659ac74b00000000000000000000000080f0c1c49891dcfdd40b6e0f960f84e6042bcb6f000000000000000000000000b97ef9ef8734c71904d8002f8b6bc66dd9c48a6e00000000000000000000000000000000000000000000000000000000007ff4e20000000000000000000000000000000000000000000000000000000000000064c001a05d429597befe2835396206781b199122f2e8297327ed4a05483339e7a8b2022aa04c23a7f70fb29dda1b4ee342fb10a625e9b8ddc6a603fb4e170d4f6f37700cb8"; /// let (tx, sig) = Cast::decode_raw_transaction(&tx)?; /// # Ok::<(), eyre::Report>(()) - pub fn decode_raw_transaction(tx: &str) -> Result<(TypedTransaction, Signature)> { + pub fn decode_raw_transaction(tx: &str) -> Result { let tx_hex = hex::decode(strip_0x(tx))?; - let tx_rlp = rlp::Rlp::new(tx_hex.as_slice()); - Ok(TypedTransaction::decode_signed(&tx_rlp)?) + let tx = TxEnvelope::decode_2718(&mut tx_hex.as_slice())?; + Ok(tx) } } diff --git a/crates/cast/src/tx.rs b/crates/cast/src/tx.rs index a2f209b5c399..294ebd19e0e9 100644 --- a/crates/cast/src/tx.rs +++ b/crates/cast/src/tx.rs @@ -1,11 +1,14 @@ +use std::marker::PhantomData; + use crate::errors::FunctionSignatureError; use alloy_json_abi::Function; use alloy_primitives::{Address, Bytes, U256, U64}; -use alloy_providers::tmp::TempProvider; -use alloy_rpc_types::request::{TransactionInput, TransactionRequest as AlloyTransactionRequest}; -use ethers_core::types::{ - transaction::eip2718::TypedTransaction, Eip1559TransactionRequest, TransactionRequest, +use alloy_provider::{ + network::{Ethereum, TransactionBuilder}, + Provider, }; +use alloy_rpc_types::request::{TransactionInput, TransactionRequest}; +use alloy_transport::Transport; use eyre::Result; use foundry_common::{ abi::{encode_function_args, get_func, get_func_etherscan}, @@ -15,9 +18,8 @@ use foundry_common::{ use foundry_config::Chain; use futures::future::join_all; -pub type TxBuilderOutput = (TypedTransaction, Option); -pub type TxBuilderAlloyOutput = (AlloyTransactionRequest, Option); -pub type TxBuilderPeekOutput<'a> = (&'a AlloyTransactionRequest, &'a Option); +pub type TxBuilderOutput = (TransactionRequest, Option); +pub type TxBuilderPeekOutput<'a> = (&'a TransactionRequest, &'a Option); /// Transaction builder /// @@ -39,17 +41,17 @@ pub type TxBuilderPeekOutput<'a> = (&'a AlloyTransactionRequest, &'a Option { +pub struct TxBuilder<'a, P, T> { to: Option

, chain: Chain, - tx: TypedTransaction, - alloy_tx: AlloyTransactionRequest, + tx: TransactionRequest, func: Option, etherscan_api_key: Option, provider: &'a P, + transport: PhantomData, } -impl<'a, P: TempProvider> TxBuilder<'a, P> { +impl<'a, T: Transport + Clone, P: Provider> TxBuilder<'a, P, T> { /// Create a new TxBuilder /// `provider` - provider to use /// `from` - 'from' field. Could be an ENS name @@ -62,40 +64,28 @@ impl<'a, P: TempProvider> TxBuilder<'a, P> { to: Option
, chain: impl Into, legacy: bool, - ) -> Result> { + ) -> Result { let chain = chain.into(); - let (mut tx, mut alloy_tx): (TypedTransaction, AlloyTransactionRequest) = if chain - .is_legacy() || - legacy - { - ( - TransactionRequest::new().from(from.to_ethers()).chain_id(chain.id()).into(), - AlloyTransactionRequest::default().from(from).transaction_type(0), - ) - } else { - ( - Eip1559TransactionRequest::new().from(from.to_ethers()).chain_id(chain.id()).into(), - AlloyTransactionRequest::default().from(from).transaction_type(2), - ) - }; - - let to_addr = if let Some(to) = to { - tx.set_to(to.to_ethers()); - Some(to) - } else { - None - }; - - alloy_tx.to = to_addr; - - Ok(Self { to: to_addr, chain, tx, alloy_tx, func: None, etherscan_api_key: None, provider }) + let tx = TransactionRequest::default() + .from(from) + .transaction_type(if chain.is_legacy() || legacy { 0 } else { 2 }) + .to(to); + + Ok(Self { + to, + chain, + tx, + func: None, + etherscan_api_key: None, + provider, + transport: PhantomData, + }) } /// Set gas for tx pub fn set_gas(&mut self, v: U256) -> &mut Self { - self.tx.set_gas(v.to_ethers()); - self.alloy_tx.gas = Some(v); + self.tx.set_gas_limit(v); self } @@ -109,8 +99,7 @@ impl<'a, P: TempProvider> TxBuilder<'a, P> { /// Set gas price pub fn set_gas_price(&mut self, v: U256) -> &mut Self { - self.tx.set_gas_price(v.to_ethers()); - self.alloy_tx.gas_price = Some(v); + self.tx.set_gas_price(v); self } @@ -124,12 +113,8 @@ impl<'a, P: TempProvider> TxBuilder<'a, P> { /// Set priority gas price pub fn set_priority_gas_price(&mut self, v: U256) -> &mut Self { - if let TypedTransaction::Eip1559(tx) = &mut self.tx { - tx.max_priority_fee_per_gas = Some(v.to_ethers()) - } - - if let Some(2) = self.alloy_tx.transaction_type.map(|v| v.to::()) { - self.alloy_tx.max_priority_fee_per_gas = Some(v); + if let Some(2) = self.tx.transaction_type.map(|v| v.to::()) { + self.tx.set_max_priority_fee_per_gas(v); } self @@ -145,8 +130,7 @@ impl<'a, P: TempProvider> TxBuilder<'a, P> { /// Set value pub fn set_value(&mut self, v: U256) -> &mut Self { - self.tx.set_value(v.to_ethers()); - self.alloy_tx.value = Some(v); + self.tx.set_value(v); self } @@ -159,14 +143,13 @@ impl<'a, P: TempProvider> TxBuilder<'a, P> { } /// Set nonce - pub fn set_nonce(&mut self, v: U256) -> &mut Self { - self.tx.set_nonce(v.to_ethers()); - self.alloy_tx.nonce = Some(v.to::()); + pub fn set_nonce(&mut self, v: U64) -> &mut Self { + self.tx.set_nonce(v); self } /// Set nonce, if `v` is not None - pub fn nonce(&mut self, v: Option) -> &mut Self { + pub fn nonce(&mut self, v: Option) -> &mut Self { if let Some(value) = v { self.set_nonce(value); } @@ -187,9 +170,8 @@ impl<'a, P: TempProvider> TxBuilder<'a, P> { self } - pub fn set_data(&mut self, v: Vec) -> &mut Self { - self.tx.set_data(v.clone().into()); - self.alloy_tx.input = TransactionInput::new(Bytes::from(v.clone())); + pub fn set_data(&mut self, v: Bytes) -> &mut Self { + self.tx.set_input(v); self } @@ -237,23 +219,15 @@ impl<'a, P: TempProvider> TxBuilder<'a, P> { /// (`0xcdba2fd40000000000000000000000000000000000000000000000000000000000007a69`) /// * only function name (`do`) - in this case, etherscan lookup is performed on `tx.to`'s /// contract - pub async fn set_args( - &mut self, - sig: &str, - args: Vec, - ) -> Result<&mut TxBuilder<'a, P>> { + pub async fn set_args(&mut self, sig: &str, args: Vec) -> Result<&mut Self> { let (data, func) = self.create_args(sig, args).await?; - self.tx.set_data(data.clone().into()); - self.alloy_tx.input = TransactionInput::new(Bytes::from(data)); + self.tx.set_input(data.into()); self.func = Some(func); Ok(self) } /// Set function arguments, if `value` is not None - pub async fn args( - &mut self, - value: Option<(&str, Vec)>, - ) -> Result<&mut TxBuilder<'a, P>> { + pub async fn args(&mut self, value: Option<(&str, Vec)>) -> Result<&mut Self> { if let Some((sig, args)) = value { return self.set_args(sig, args).await } @@ -265,17 +239,15 @@ impl<'a, P: TempProvider> TxBuilder<'a, P> { (self.tx, self.func) } - /// Consuming build: returns alloy transaction and optional function call - pub fn build_alloy(self) -> TxBuilderAlloyOutput { - (self.alloy_tx, self.func) - } - pub fn peek(&self) -> TxBuilderPeekOutput { - (&self.alloy_tx, &self.func) + (&self.tx, &self.func) } } -async fn resolve_name_args(args: &[String], provider: &P) -> Vec { +async fn resolve_name_args>( + args: &[String], + provider: &P, +) -> Vec { join_all(args.iter().map(|arg| async { if arg.contains('.') { let addr = NameOrAddress::Name(arg.to_string()).resolve(provider).await; diff --git a/crates/cheatcodes/src/error.rs b/crates/cheatcodes/src/error.rs index 4aeec84d9e4d..508e7173ee77 100644 --- a/crates/cheatcodes/src/error.rs +++ b/crates/cheatcodes/src/error.rs @@ -1,6 +1,6 @@ use crate::Vm; use alloy_primitives::{Address, Bytes}; -use alloy_signer::{Error as SignerError}; +use alloy_signer::Error as SignerError; use alloy_signer_wallet::WalletError; use alloy_sol_types::SolError; use foundry_common::errors::FsPathError; diff --git a/crates/cheatcodes/src/inspector.rs b/crates/cheatcodes/src/inspector.rs index 2fa06d24cd7c..d95fdb2422e7 100644 --- a/crates/cheatcodes/src/inspector.rs +++ b/crates/cheatcodes/src/inspector.rs @@ -1337,8 +1337,8 @@ impl Inspector for Cheatcodes { value: call.value, data: call.init_code.clone(), reverted: false, - deployedCode: Bytes::new(), // updated on create_end - storageAccesses: vec![], // updated on create_end + deployedCode: Bytes::new(), // updated on create_end + storageAccesses: vec![], // updated on create_end depth, }]); } @@ -1535,8 +1535,8 @@ fn apply_create2_deployer( value: call.value, data: calldata.into(), reverted: false, - deployedCode: Bytes::new(), // updated on create_end - storageAccesses: vec![], // updated on create_end + deployedCode: Bytes::new(), // updated on create_end + storageAccesses: vec![], // updated on create_end depth: ecx.journaled_state.depth(), }]) } diff --git a/crates/cheatcodes/src/utils.rs b/crates/cheatcodes/src/utils.rs index cca792e3f48d..bf344ee48846 100644 --- a/crates/cheatcodes/src/utils.rs +++ b/crates/cheatcodes/src/utils.rs @@ -2,6 +2,7 @@ use crate::{Cheatcode, Cheatcodes, CheatsCtxt, DatabaseExt, Result, Vm::*}; use alloy_primitives::{keccak256, B256, U256}; +use alloy_signer::{Signer, SignerSync}; use alloy_signer_wallet::{ coins_bip39::{ ChineseSimplified, ChineseTraditional, Czech, English, French, Italian, Japanese, Korean, @@ -9,7 +10,6 @@ use alloy_signer_wallet::{ }, LocalWallet, MnemonicBuilder, }; -use alloy_signer::{Signer, SignerSync}; use alloy_sol_types::SolValue; use foundry_evm_core::constants::DEFAULT_CREATE2_DEPLOYER; use k256::{ diff --git a/crates/common/src/ens.rs b/crates/common/src/ens.rs index 302defa78293..5d60ea7859fe 100644 --- a/crates/common/src/ens.rs +++ b/crates/common/src/ens.rs @@ -3,6 +3,7 @@ use alloy_primitives::{address, keccak256, Address, B256}; use alloy_provider::{Network, Provider}; use alloy_sol_types::sol; +use alloy_transport::Transport; use std::str::FromStr; // ENS Registry and Resolver contracts. @@ -36,7 +37,7 @@ pub enum NameOrAddress { impl NameOrAddress { /// Resolves the name to an Ethereum Address. - pub async fn resolve>( + pub async fn resolve>( &self, provider: &P, ) -> Result { diff --git a/crates/common/src/transactions.rs b/crates/common/src/transactions.rs index a218a5c9d5dc..1a62c49261c3 100644 --- a/crates/common/src/transactions.rs +++ b/crates/common/src/transactions.rs @@ -1,6 +1,7 @@ //! wrappers for transactions -use alloy_provider::{network::Ethereum, Network, Provider}; +use alloy_provider::{network::Ethereum, Provider}; use alloy_rpc_types::{BlockId, TransactionReceipt}; +use alloy_transport::Transport; use eyre::Result; use serde::{Deserialize, Serialize}; @@ -24,7 +25,7 @@ impl TransactionReceiptWithRevertReason { /// Updates the revert reason field using `eth_call` and returns an Err variant if the revert /// reason was not successfully updated - pub async fn update_revert_reason>( + pub async fn update_revert_reason>( &mut self, provider: &P, ) -> Result<()> { @@ -32,7 +33,7 @@ impl TransactionReceiptWithRevertReason { Ok(()) } - async fn fetch_revert_reason>( + async fn fetch_revert_reason>( &self, provider: &P, ) -> Result> { diff --git a/crates/common/src/types.rs b/crates/common/src/types.rs index 4e4558951ea4..bc40026312ab 100644 --- a/crates/common/src/types.rs +++ b/crates/common/src/types.rs @@ -1,10 +1,8 @@ //! Temporary utility conversion traits between ethers-rs and alloy types. -use alloy_primitives::{Address, Bloom, Bytes, B256, B64, I256, U128, U256, U64, U8}; +use alloy_primitives::{Address, Bloom, Bytes, B256, B64, I256, U256, U64}; use alloy_rpc_types::{ - other::OtherFields, - request::{TransactionInput, TransactionRequest as CallRequest}, - AccessList, AccessListItem, BlockNumberOrTag, Signature, Transaction, + AccessList, AccessListItem, BlockNumberOrTag, }; use alloy_signer::Signer; use alloy_signer_wallet::LocalWallet; From d1ace73cab3bce8ce60c671df3dff86db66f9c70 Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Wed, 20 Mar 2024 21:45:01 +0400 Subject: [PATCH 11/63] wip --- Cargo.lock | 82 +++++++++++++++------------- Cargo.toml | 36 ++++++------ crates/anvil/src/config.rs | 2 +- crates/anvil/src/eth/backend/fork.rs | 2 +- crates/anvil/tests/it/api.rs | 2 +- crates/anvil/tests/it/fork.rs | 2 +- crates/anvil/tests/it/genesis.rs | 2 +- crates/anvil/tests/it/wsapi.rs | 2 +- crates/cast/bin/cmd/access_list.rs | 2 +- crates/cast/bin/cmd/call.rs | 11 ++-- crates/cast/bin/cmd/estimate.rs | 8 +-- crates/cast/bin/cmd/find_block.rs | 36 ++++++------ crates/cast/bin/cmd/logs.rs | 18 +++--- crates/cast/bin/cmd/mktx.rs | 2 +- crates/cast/bin/cmd/rpc.rs | 5 +- crates/cast/bin/cmd/run.rs | 2 +- crates/cast/bin/cmd/send.rs | 17 ++---- crates/cast/bin/cmd/storage.rs | 7 +-- crates/cast/bin/tx.rs | 2 +- crates/cast/src/lib.rs | 6 +- crates/cast/src/tx.rs | 4 +- crates/cheatcodes/src/inspector.rs | 4 +- crates/cli/Cargo.toml | 2 + crates/cli/src/opts/transaction.rs | 4 +- crates/cli/src/utils/mod.rs | 10 ++-- crates/common/src/fmt/ui.rs | 4 +- crates/evm/core/src/utils.rs | 2 +- 27 files changed, 138 insertions(+), 138 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 85652ade08de..0d7b65b638ea 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -90,7 +90,7 @@ dependencies = [ [[package]] name = "alloy-consensus" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=de65254#de6525468ab75f40f94db793da2b54ecc52d2d2c" +source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" dependencies = [ "alloy-eips", "alloy-primitives", @@ -103,14 +103,14 @@ dependencies = [ [[package]] name = "alloy-contract" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=de65254#de6525468ab75f40f94db793da2b54ecc52d2d2c" +source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" dependencies = [ "alloy-dyn-abi", "alloy-json-abi", "alloy-network", "alloy-primitives", "alloy-provider", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=de65254)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=376583d)", "alloy-sol-types", "alloy-transport", "futures", @@ -142,7 +142,7 @@ dependencies = [ [[package]] name = "alloy-eips" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=de65254#de6525468ab75f40f94db793da2b54ecc52d2d2c" +source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -152,7 +152,7 @@ dependencies = [ [[package]] name = "alloy-genesis" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=de65254#de6525468ab75f40f94db793da2b54ecc52d2d2c" +source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" dependencies = [ "alloy-primitives", "alloy-serde", @@ -173,7 +173,7 @@ dependencies = [ [[package]] name = "alloy-json-rpc" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=de65254#de6525468ab75f40f94db793da2b54ecc52d2d2c" +source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" dependencies = [ "alloy-primitives", "serde", @@ -184,13 +184,13 @@ dependencies = [ [[package]] name = "alloy-network" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=de65254#de6525468ab75f40f94db793da2b54ecc52d2d2c" +source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" dependencies = [ "alloy-consensus", "alloy-eips", "alloy-json-rpc", "alloy-primitives", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=de65254)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=376583d)", "alloy-signer", "async-trait", "futures-utils-wasm", @@ -227,15 +227,15 @@ dependencies = [ [[package]] name = "alloy-provider" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=de65254#de6525468ab75f40f94db793da2b54ecc52d2d2c" +source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" dependencies = [ "alloy-json-rpc", "alloy-network", "alloy-primitives", "alloy-pubsub", "alloy-rpc-client", - "alloy-rpc-trace-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=de65254)", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=de65254)", + "alloy-rpc-trace-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=376583d)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=376583d)", "alloy-transport", "alloy-transport-http", "async-stream", @@ -253,7 +253,7 @@ dependencies = [ [[package]] name = "alloy-pubsub" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=de65254#de6525468ab75f40f94db793da2b54ecc52d2d2c" +source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" dependencies = [ "alloy-json-rpc", "alloy-primitives", @@ -293,7 +293,7 @@ dependencies = [ [[package]] name = "alloy-rpc-client" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=de65254#de6525468ab75f40f94db793da2b54ecc52d2d2c" +source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" dependencies = [ "alloy-json-rpc", "alloy-primitives", @@ -315,10 +315,11 @@ dependencies = [ [[package]] name = "alloy-rpc-trace-types" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=9ac2c90#9ac2c90d58a9994d4b61c879e33c6af2739a2b4f" +source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" dependencies = [ "alloy-primitives", - "alloy-rpc-types 0.1.0 (git+https://github.com/alloy-rs/alloy?rev=9ac2c90)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=376583d)", + "alloy-serde", "serde", "serde_json", ] @@ -326,11 +327,10 @@ dependencies = [ [[package]] name = "alloy-rpc-trace-types" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=de65254#de6525468ab75f40f94db793da2b54ecc52d2d2c" +source = "git+https://github.com/alloy-rs/alloy?rev=9ac2c90#9ac2c90d58a9994d4b61c879e33c6af2739a2b4f" dependencies = [ "alloy-primitives", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=de65254)", - "alloy-serde", + "alloy-rpc-types 0.1.0 (git+https://github.com/alloy-rs/alloy?rev=9ac2c90)", "serde", "serde_json", ] @@ -338,10 +338,13 @@ dependencies = [ [[package]] name = "alloy-rpc-types" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=9ac2c90#9ac2c90d58a9994d4b61c879e33c6af2739a2b4f" +source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" dependencies = [ + "alloy-consensus", + "alloy-eips", "alloy-primitives", "alloy-rlp", + "alloy-serde", "itertools 0.12.1", "serde", "serde_json", @@ -351,11 +354,10 @@ dependencies = [ [[package]] name = "alloy-rpc-types" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=de65254#de6525468ab75f40f94db793da2b54ecc52d2d2c" +source = "git+https://github.com/alloy-rs/alloy?rev=9ac2c90#9ac2c90d58a9994d4b61c879e33c6af2739a2b4f" dependencies = [ "alloy-primitives", "alloy-rlp", - "alloy-serde", "itertools 0.12.1", "serde", "serde_json", @@ -365,7 +367,7 @@ dependencies = [ [[package]] name = "alloy-serde" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=de65254#de6525468ab75f40f94db793da2b54ecc52d2d2c" +source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" dependencies = [ "alloy-primitives", "serde", @@ -375,7 +377,7 @@ dependencies = [ [[package]] name = "alloy-signer" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=de65254#de6525468ab75f40f94db793da2b54ecc52d2d2c" +source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" dependencies = [ "alloy-dyn-abi", "alloy-primitives", @@ -390,7 +392,7 @@ dependencies = [ [[package]] name = "alloy-signer-wallet" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=de65254#de6525468ab75f40f94db793da2b54ecc52d2d2c" +source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" dependencies = [ "alloy-consensus", "alloy-network", @@ -457,7 +459,7 @@ dependencies = [ [[package]] name = "alloy-transport" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=de65254#de6525468ab75f40f94db793da2b54ecc52d2d2c" +source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" dependencies = [ "alloy-json-rpc", "base64 0.22.0", @@ -475,7 +477,7 @@ dependencies = [ [[package]] name = "alloy-transport-http" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=de65254#de6525468ab75f40f94db793da2b54ecc52d2d2c" +source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" dependencies = [ "alloy-json-rpc", "alloy-transport", @@ -488,7 +490,7 @@ dependencies = [ [[package]] name = "alloy-transport-ipc" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=de65254#de6525468ab75f40f94db793da2b54ecc52d2d2c" +source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" dependencies = [ "alloy-json-rpc", "alloy-pubsub", @@ -506,7 +508,7 @@ dependencies = [ [[package]] name = "alloy-transport-ws" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=de65254#de6525468ab75f40f94db793da2b54ecc52d2d2c" +source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" dependencies = [ "alloy-pubsub", "alloy-transport", @@ -613,8 +615,8 @@ dependencies = [ "alloy-primitives", "alloy-provider", "alloy-rlp", - "alloy-rpc-trace-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=de65254)", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=de65254)", + "alloy-rpc-trace-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=376583d)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=376583d)", "alloy-signer", "alloy-signer-wallet", "alloy-sol-types", @@ -676,8 +678,8 @@ dependencies = [ "alloy-network", "alloy-primitives", "alloy-rlp", - "alloy-rpc-trace-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=de65254)", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=de65254)", + "alloy-rpc-trace-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=376583d)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=376583d)", "anvil-core", "bytes", "c-kzg", @@ -1381,7 +1383,7 @@ dependencies = [ "alloy-primitives", "alloy-provider", "alloy-rlp", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=de65254)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=376583d)", "alloy-signer", "alloy-transport", "async-trait", @@ -1464,7 +1466,7 @@ dependencies = [ "alloy-dyn-abi", "alloy-json-abi", "alloy-primitives", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=de65254)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=376583d)", "clap", "criterion", "dirs 5.0.1", @@ -3038,7 +3040,7 @@ dependencies = [ "alloy-dyn-abi", "alloy-json-abi", "alloy-primitives", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=de65254)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=376583d)", "anvil", "async-trait", "axum", @@ -3154,7 +3156,7 @@ dependencies = [ "alloy-dyn-abi", "alloy-json-abi", "alloy-primitives", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=de65254)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=376583d)", "async-recursion", "clap", "const-hex", @@ -3253,7 +3255,7 @@ dependencies = [ "alloy-json-abi", "alloy-primitives", "alloy-provider", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=de65254)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=376583d)", "alloy-signer", "alloy-signer-wallet", "alloy-sol-types", @@ -3298,6 +3300,8 @@ dependencies = [ "alloy-dyn-abi", "alloy-json-abi", "alloy-primitives", + "alloy-provider", + "alloy-transport", "clap", "color-eyre", "dotenvy", @@ -3337,7 +3341,7 @@ dependencies = [ "alloy-provider", "alloy-pubsub", "alloy-rpc-client", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=de65254)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=376583d)", "alloy-signer", "alloy-signer-wallet", "alloy-sol-types", @@ -3506,7 +3510,7 @@ dependencies = [ "alloy-json-abi", "alloy-primitives", "alloy-provider", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=de65254)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=376583d)", "alloy-sol-types", "alloy-transport", "arrayvec", diff --git a/Cargo.toml b/Cargo.toml index 0431b2ae891c..da43711b8bf2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -159,24 +159,24 @@ ethers-middleware = { version = "2.0.14", default-features = false } ethers-solc = { version = "2.0.14", default-features = false } ## alloy -alloy-consensus = { git = "https://github.com/klkvr/alloy", rev = "de65254" } -alloy-contract = { git = "https://github.com/klkvr/alloy", rev = "de65254" } -alloy-eips = { git = "https://github.com/klkvr/alloy", rev = "de65254" } -alloy-genesis = { git = "https://github.com/klkvr/alloy", rev = "de65254" } -alloy-json-rpc = { git = "https://github.com/klkvr/alloy", rev = "de65254" } -alloy-network = { git = "https://github.com/klkvr/alloy", rev = "de65254" } -alloy-node-bindings = { git = "https://github.com/klkvr/alloy", rev = "de65254" } -alloy-provider = { git = "https://github.com/klkvr/alloy", rev = "de65254" } -alloy-pubsub = { git = "https://github.com/klkvr/alloy", rev = "de65254" } -alloy-rpc-client = { git = "https://github.com/klkvr/alloy", rev = "de65254" } -alloy-rpc-trace-types = { git = "https://github.com/klkvr/alloy", rev = "de65254" } -alloy-rpc-types = { git = "https://github.com/klkvr/alloy", rev = "de65254" } -alloy-signer = { git = "https://github.com/klkvr/alloy", rev = "de65254" } -alloy-signer-wallet = { git = "https://github.com/klkvr/alloy", rev = "de65254" } -alloy-transport = { git = "https://github.com/klkvr/alloy", rev = "de65254" } -alloy-transport-http = { git = "https://github.com/klkvr/alloy", rev = "de65254" } -alloy-transport-ipc = { git = "https://github.com/klkvr/alloy", rev = "de65254" } -alloy-transport-ws = { git = "https://github.com/klkvr/alloy", rev = "de65254" } +alloy-consensus = { git = "https://github.com/klkvr/alloy", rev = "376583d" } +alloy-contract = { git = "https://github.com/klkvr/alloy", rev = "376583d" } +alloy-eips = { git = "https://github.com/klkvr/alloy", rev = "376583d" } +alloy-genesis = { git = "https://github.com/klkvr/alloy", rev = "376583d" } +alloy-json-rpc = { git = "https://github.com/klkvr/alloy", rev = "376583d" } +alloy-network = { git = "https://github.com/klkvr/alloy", rev = "376583d" } +alloy-node-bindings = { git = "https://github.com/klkvr/alloy", rev = "376583d" } +alloy-provider = { git = "https://github.com/klkvr/alloy", rev = "376583d" } +alloy-pubsub = { git = "https://github.com/klkvr/alloy", rev = "376583d" } +alloy-rpc-client = { git = "https://github.com/klkvr/alloy", rev = "376583d" } +alloy-rpc-trace-types = { git = "https://github.com/klkvr/alloy", rev = "376583d" } +alloy-rpc-types = { git = "https://github.com/klkvr/alloy", rev = "376583d" } +alloy-signer = { git = "https://github.com/klkvr/alloy", rev = "376583d" } +alloy-signer-wallet = { git = "https://github.com/klkvr/alloy", rev = "376583d" } +alloy-transport = { git = "https://github.com/klkvr/alloy", rev = "376583d" } +alloy-transport-http = { git = "https://github.com/klkvr/alloy", rev = "376583d" } +alloy-transport-ipc = { git = "https://github.com/klkvr/alloy", rev = "376583d" } +alloy-transport-ws = { git = "https://github.com/klkvr/alloy", rev = "376583d" } alloy-primitives = { version = "0.6.4", features = ["getrandom"] } alloy-dyn-abi = "0.6.4" alloy-json-abi = "0.6.4" diff --git a/crates/anvil/src/config.rs b/crates/anvil/src/config.rs index 354bf2c589d9..7a03e22eb2d7 100644 --- a/crates/anvil/src/config.rs +++ b/crates/anvil/src/config.rs @@ -17,7 +17,7 @@ use crate::{ }; use alloy_genesis::Genesis; use alloy_primitives::{hex, utils::Unit, U256}; -use alloy_providers::tmp::TempProvider; +use alloy_provider::Provider; use alloy_rpc_types::BlockNumberOrTag; use alloy_signer::{ coins_bip39::{English, Mnemonic}, diff --git a/crates/anvil/src/eth/backend/fork.rs b/crates/anvil/src/eth/backend/fork.rs index 04ea0c70f5f1..cb4f66871442 100644 --- a/crates/anvil/src/eth/backend/fork.rs +++ b/crates/anvil/src/eth/backend/fork.rs @@ -2,7 +2,7 @@ use crate::eth::{backend::db::Db, error::BlockchainError}; use alloy_primitives::{Address, Bytes, StorageValue, B256, U256, U64}; -use alloy_providers::tmp::TempProvider; +use alloy_provider::Provider; use alloy_rpc_trace_types::{ geth::{GethDebugTracingOptions, GethTrace}, parity::LocalizedTransactionTrace as Trace, diff --git a/crates/anvil/tests/it/api.rs b/crates/anvil/tests/it/api.rs index 216e9581389b..28eaf83d46d5 100644 --- a/crates/anvil/tests/it/api.rs +++ b/crates/anvil/tests/it/api.rs @@ -5,7 +5,7 @@ use crate::{ utils::ethers_http_provider, }; use alloy_primitives::{Address as rAddress, B256, U256 as rU256}; -use alloy_providers::tmp::TempProvider; +use alloy_provider::Provider; use alloy_rpc_types::{ request::{TransactionInput as CallInput, TransactionRequest as CallRequest}, state::{AccountOverride, StateOverride}, diff --git a/crates/anvil/tests/it/fork.rs b/crates/anvil/tests/it/fork.rs index 39946383e105..e8a63c944d3a 100644 --- a/crates/anvil/tests/it/fork.rs +++ b/crates/anvil/tests/it/fork.rs @@ -5,7 +5,7 @@ use crate::{ utils::{self, ethers_http_provider}, }; use alloy_primitives::{address, U256 as rU256}; -use alloy_providers::tmp::TempProvider; +use alloy_provider::Provider; use alloy_rpc_types::{ request::{TransactionInput, TransactionRequest as CallRequest}, BlockNumberOrTag, diff --git a/crates/anvil/tests/it/genesis.rs b/crates/anvil/tests/it/genesis.rs index f5f5fec9cc7d..bc5af367f5aa 100644 --- a/crates/anvil/tests/it/genesis.rs +++ b/crates/anvil/tests/it/genesis.rs @@ -4,7 +4,7 @@ use std::str::FromStr; use alloy_genesis::Genesis; use alloy_primitives::{Address, U256, U64}; -use alloy_providers::tmp::TempProvider; +use alloy_provider::Provider; use anvil::{spawn, NodeConfig}; #[tokio::test(flavor = "multi_thread")] diff --git a/crates/anvil/tests/it/wsapi.rs b/crates/anvil/tests/it/wsapi.rs index c2073f5617f7..ce0c4d6a4387 100644 --- a/crates/anvil/tests/it/wsapi.rs +++ b/crates/anvil/tests/it/wsapi.rs @@ -1,6 +1,6 @@ //! general eth api tests with websocket provider -use alloy_providers::tmp::TempProvider; +use alloy_provider::Provider; use anvil::{spawn, NodeConfig}; use ethers::types::U256; use foundry_common::types::ToAlloy; diff --git a/crates/cast/bin/cmd/access_list.rs b/crates/cast/bin/cmd/access_list.rs index 8e63984cc34a..88a6fb783c6a 100644 --- a/crates/cast/bin/cmd/access_list.rs +++ b/crates/cast/bin/cmd/access_list.rs @@ -1,5 +1,5 @@ use alloy_primitives::Address; -use alloy_providers::tmp::TempProvider; +use alloy_provider::Provider; use alloy_rpc_types::BlockId; use cast::{Cast, TxBuilder}; use clap::Parser; diff --git a/crates/cast/bin/cmd/call.rs b/crates/cast/bin/cmd/call.rs index 6f92d35076a9..044e2658d9b8 100644 --- a/crates/cast/bin/cmd/call.rs +++ b/crates/cast/bin/cmd/call.rs @@ -1,6 +1,7 @@ use alloy_primitives::U256; -use alloy_providers::tmp::TempProvider; +use alloy_provider::{network::Ethereum, Provider}; use alloy_rpc_types::BlockId; +use alloy_transport::Transport; use cast::{Cast, TxBuilder}; use clap::Parser; use eyre::{Result, WrapErr}; @@ -203,8 +204,8 @@ impl CallArgs { } /// fills the builder from create arg -async fn fill_create( - builder: &mut TxBuilder<'_, P>, +async fn fill_create, T: Transport + Clone>( + builder: &mut TxBuilder<'_, P, T>, value: Option, code: String, sig: Option, @@ -225,8 +226,8 @@ async fn fill_create( } /// fills the builder from args -async fn fill_tx( - builder: &mut TxBuilder<'_, P>, +async fn fill_tx, T: Transport + Clone>( + builder: &mut TxBuilder<'_, P, T>, value: Option, sig: Option, args: Vec, diff --git a/crates/cast/bin/cmd/estimate.rs b/crates/cast/bin/cmd/estimate.rs index 70934403f07b..cd3d38757a46 100644 --- a/crates/cast/bin/cmd/estimate.rs +++ b/crates/cast/bin/cmd/estimate.rs @@ -81,9 +81,7 @@ impl EstimateArgs { let figment = Figment::from(Config::figment()).merge(etherscan).merge(rpc); let config = Config::try_from(figment)?; - let alloy_provider = utils::get_alloy_provider(&config)?; - - let provider = utils::get_provider(&config)?; + let provider = utils::get_alloy_provider(&config)?; let chain = utils::get_chain(config.chain, &provider).await?; let api_key = config.get_etherscan_api_key(Some(chain)); @@ -110,7 +108,7 @@ impl EstimateArgs { data.append(&mut sigdata); } - builder.set_data(data); + builder.set_data(data.into()); } _ => { let sig = sig.ok_or_else(|| eyre::eyre!("Function signature must be provided."))?; @@ -119,7 +117,7 @@ impl EstimateArgs { }; let builder_output = builder.peek(); - let gas = Cast::new(&provider, &alloy_provider).estimate(builder_output).await?; + let gas = Cast::new(&provider).estimate(builder_output).await?; println!("{gas}"); Ok(()) } diff --git a/crates/cast/bin/cmd/find_block.rs b/crates/cast/bin/cmd/find_block.rs index f0ee9616b831..6d0305d88a83 100644 --- a/crates/cast/bin/cmd/find_block.rs +++ b/crates/cast/bin/cmd/find_block.rs @@ -1,4 +1,5 @@ use alloy_primitives::{U256, U64}; +use alloy_provider::Provider; use cast::Cast; use clap::Parser; use ethers_providers::Middleware; @@ -22,52 +23,51 @@ impl FindBlockArgs { pub async fn run(self) -> Result<()> { let FindBlockArgs { timestamp, rpc } = self; - let ts_target = U256::from(timestamp); + let ts_target = timestamp; let config = Config::from(&rpc); - let provider = utils::get_provider(&config)?; - let alloy_provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_alloy_provider(&config)?; let last_block_num = provider.get_block_number().await?; - let cast_provider = Cast::new(provider, alloy_provider); + let cast_provider = Cast::new(provider); let res = join!(cast_provider.timestamp(last_block_num), cast_provider.timestamp(1)); - let ts_block_latest = res.0?; - let ts_block_1 = res.1?; + let ts_block_latest: u64 = res.0?.to(); + let ts_block_1: u64 = res.1?.to(); let block_num = if ts_block_latest < ts_target { // If the most recent block's timestamp is below the target, return it - last_block_num.to_alloy() + last_block_num } else if ts_block_1 > ts_target { // If the target timestamp is below block 1's timestamp, return that - U64::from(1_u64) + 1 } else { // Otherwise, find the block that is closest to the timestamp - let mut low_block = U64::from(1_u64); // block 0 has a timestamp of 0: https://github.com/ethereum/go-ethereum/issues/17042#issuecomment-559414137 - let mut high_block = last_block_num.to_alloy(); - let mut matching_block: Option = None; + let mut low_block = 1_u64; // block 0 has a timestamp of 0: https://github.com/ethereum/go-ethereum/issues/17042#issuecomment-559414137 + let mut high_block = last_block_num; + let mut matching_block = None; while high_block > low_block && matching_block.is_none() { // Get timestamp of middle block (this approach approach to avoids overflow) let high_minus_low_over_2 = high_block .checked_sub(low_block) .ok_or_else(|| eyre::eyre!("unexpected underflow")) .unwrap() - .checked_div(U64::from(2_u64)) + .checked_div(2_u64) .unwrap(); let mid_block = high_block.checked_sub(high_minus_low_over_2).unwrap(); - let ts_mid_block = cast_provider.timestamp(mid_block.to_ethers()).await?; + let ts_mid_block = cast_provider.timestamp(mid_block).await?.to::(); // Check if we've found a match or should keep searching if ts_mid_block == ts_target { matching_block = Some(mid_block) - } else if high_block.checked_sub(low_block).unwrap() == U64::from(1_u64) { + } else if high_block.checked_sub(low_block).unwrap() == 1_u64 { // The target timestamp is in between these blocks. This rounds to the // highest block if timestamp is equidistant between blocks let res = join!( - cast_provider.timestamp(high_block.to_ethers()), - cast_provider.timestamp(low_block.to_ethers()) + cast_provider.timestamp(high_block), + cast_provider.timestamp(low_block) ); - let ts_high = res.0.unwrap(); - let ts_low = res.1.unwrap(); + let ts_high: u64 = res.0.unwrap().to(); + let ts_low: u64 = res.1.unwrap().to(); let high_diff = ts_high.checked_sub(ts_target).unwrap(); let low_diff = ts_target.checked_sub(ts_low).unwrap(); let is_low = low_diff < high_diff; diff --git a/crates/cast/bin/cmd/logs.rs b/crates/cast/bin/cmd/logs.rs index 3ee86a4bce3e..771ee090d3f1 100644 --- a/crates/cast/bin/cmd/logs.rs +++ b/crates/cast/bin/cmd/logs.rs @@ -1,17 +1,19 @@ -use alloy_rpc_types::BlockId; +use alloy_rpc_types::{BlockId, BlockNumberOrTag, FilterBlockOption}; use cast::Cast; use clap::Parser; use ethers_core::{ abi::{ token::{LenientTokenizer, StrictTokenizer, Tokenizer}, - Address, Event, HumanReadableParser, ParamType, RawTopicFilter, Token, Topic, TopicFilter, + Event, HumanReadableParser, ParamType, RawTopicFilter, Token, Topic, TopicFilter, }, - types::{BlockNumber, Filter, FilterBlockOption, NameOrAddress, ValueOrArray, H256, U256}, + types::{ValueOrArray, H256, U256}, }; +use alloy_rpc_types::Filter; use ethers_providers::Middleware; use eyre::{Result, WrapErr}; use foundry_cli::{opts::EthereumOpts, utils}; use foundry_common::types::ToEthers; +use foundry_common::ens::NameOrAddress; use foundry_config::Config; use itertools::Itertools; use std::{io, str::FromStr}; @@ -75,10 +77,9 @@ impl LogsArgs { } = self; let config = Config::from(ð); - let provider = utils::get_provider(&config)?; - let alloy_provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_alloy_provider(&config)?; - let cast = Cast::new(&provider, alloy_provider); + let cast = Cast::new(provider); let address = match address { Some(address) => { @@ -115,8 +116,8 @@ impl LogsArgs { /// successful, `topics_or_args` is parsed as indexed inputs and converted to topics. Otherwise, /// `sig_or_topic` is prepended to `topics_or_args` and used as raw topics. fn build_filter( - from_block: Option, - to_block: Option, + from_block: Option, + to_block: Option, address: Option
, sig_or_topic: Option, topics_or_args: Vec, @@ -133,7 +134,6 @@ fn build_filter( }, None => TopicFilter::default(), }; - // Convert from TopicFilter to Filter let topics = vec![topic_filter.topic0, topic_filter.topic1, topic_filter.topic2, topic_filter.topic3] diff --git a/crates/cast/bin/cmd/mktx.rs b/crates/cast/bin/cmd/mktx.rs index 99dacb2860f5..8f6db7d47ad8 100644 --- a/crates/cast/bin/cmd/mktx.rs +++ b/crates/cast/bin/cmd/mktx.rs @@ -77,7 +77,7 @@ impl MakeTxArgs { tx::validate_to_address(&code, &to)?; let config = Config::from(ð); - let provider = utils::get_provider(&config)?; + let provider = utils::get_alloy_provider(&config)?; let chain = utils::get_chain(config.chain, &provider).await?; let api_key = config.get_etherscan_api_key(Some(chain)); diff --git a/crates/cast/bin/cmd/rpc.rs b/crates/cast/bin/cmd/rpc.rs index dd42faf3c312..bd0a55ce4258 100644 --- a/crates/cast/bin/cmd/rpc.rs +++ b/crates/cast/bin/cmd/rpc.rs @@ -38,8 +38,7 @@ impl RpcArgs { let RpcArgs { raw, method, params, rpc } = self; let config = Config::from(&rpc); - let provider = utils::get_provider(&config)?; - let alloy_provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_alloy_provider(&config)?; let params = if raw { if params.is_empty() { @@ -54,7 +53,7 @@ impl RpcArgs { } else { serde_json::Value::Array(params.into_iter().map(value_or_string).collect()) }; - println!("{}", Cast::new(provider, alloy_provider).rpc(&method, params).await?); + println!("{}", Cast::new(provider).rpc(&method, params).await?); Ok(()) } } diff --git a/crates/cast/bin/cmd/run.rs b/crates/cast/bin/cmd/run.rs index 8de966906791..90225e136871 100644 --- a/crates/cast/bin/cmd/run.rs +++ b/crates/cast/bin/cmd/run.rs @@ -1,5 +1,5 @@ use alloy_primitives::U256; -use alloy_providers::tmp::TempProvider; +use alloy_provider::Provider; use alloy_rpc_types::BlockTransactions; use cast::revm::primitives::EnvWithHandlerCfg; use clap::Parser; diff --git a/crates/cast/bin/cmd/send.rs b/crates/cast/bin/cmd/send.rs index 72904e59c903..f42247ac0841 100644 --- a/crates/cast/bin/cmd/send.rs +++ b/crates/cast/bin/cmd/send.rs @@ -1,6 +1,6 @@ use crate::tx; use alloy_primitives::Address; -use alloy_providers::tmp::TempProvider; +use alloy_provider::Provider; use cast::Cast; use clap::Parser; use ethers_middleware::SignerMiddleware; @@ -112,7 +112,7 @@ impl SendTxArgs { tx::validate_to_address(&code, &to)?; let config = Config::from(ð); - let provider = utils::get_provider(&config)?; + let provider = utils::get_alloy_provider(&config)?; let alloy_provider = utils::get_alloy_provider(&config)?; let chain = utils::get_chain(config.chain, &provider).await?; let api_key = config.get_etherscan_api_key(Some(chain)); @@ -132,15 +132,15 @@ impl SendTxArgs { if unlocked { // only check current chain id if it was specified in the config if let Some(config_chain) = config.chain { - let current_chain_id = provider.get_chainid().await?.as_u64(); + let current_chain_id = provider.get_chain_id().await?.to(); let config_chain_id = config_chain.id(); // switch chain if current chain id is not the same as the one specified in the // config if config_chain_id != current_chain_id { cli_warn!("Switching to chain {}", config_chain); provider - .request( - "wallet_switchEthereumChain", + .raw_request( + "wallet_switchEthereumChain".into(), [serde_json::json!({ "chainId": format!("0x{:x}", config_chain_id), })], @@ -150,12 +150,7 @@ impl SendTxArgs { } if resend { - tx.nonce = Some( - provider - .get_transaction_count(config.sender.to_ethers(), None) - .await? - .to_alloy(), - ); + tx.nonce = Some(provider.get_transaction_count(config.sender, None).await?); } cast_send( diff --git a/crates/cast/bin/cmd/storage.rs b/crates/cast/bin/cmd/storage.rs index 1c652ad5a8c2..7a64506578b7 100644 --- a/crates/cast/bin/cmd/storage.rs +++ b/crates/cast/bin/cmd/storage.rs @@ -1,6 +1,6 @@ use crate::opts::parse_slot; use alloy_primitives::{Address, B256, U256}; -use alloy_providers::tmp::TempProvider; +use alloy_provider::Provider; use alloy_rpc_types::BlockId; use cast::Cast; use clap::Parser; @@ -80,19 +80,18 @@ impl StorageArgs { let Self { address, slot, block, build, .. } = self; let provider = utils::get_alloy_provider(&config)?; - let ethers_provider = utils::get_provider(&config)?; let address = address.resolve(&provider).await?; // Slot was provided, perform a simple RPC call if let Some(slot) = slot { - let cast = Cast::new(ethers_provider, provider); + let cast = Cast::new(provider); println!("{}", cast.storage(address, slot, block).await?); return Ok(()); } // No slot was provided // Get deployed bytecode at given address - let address_code = provider.get_code_at(address, block).await?; + let address_code = provider.get_code_at(address, block.unwrap_or_default()).await?; if address_code.is_empty() { eyre::bail!("Provided address has no deployed code and thus no storage"); } diff --git a/crates/cast/bin/tx.rs b/crates/cast/bin/tx.rs index 49724602ec7c..1592366137c6 100644 --- a/crates/cast/bin/tx.rs +++ b/crates/cast/bin/tx.rs @@ -1,5 +1,5 @@ use alloy_primitives::Address; -use alloy_providers::tmp::TempProvider; +use alloy_provider::Provider; use cast::{TxBuilder, TxBuilderOutput}; use eyre::Result; use foundry_cli::opts::TransactionOpts; diff --git a/crates/cast/src/lib.rs b/crates/cast/src/lib.rs index 9da806ba67e3..7143c87af2e6 100644 --- a/crates/cast/src/lib.rs +++ b/crates/cast/src/lib.rs @@ -6,10 +6,10 @@ use alloy_primitives::{ Address, Bytes, Keccak256, TxHash, B256, I256, U256, U64, }; use alloy_provider::{ - network::{eip2718::Decodable2718, Ethereum}, + network::{eip2718::Decodable2718, Ethereum, eip2718::Encodable2718}, PendingTransaction, PendingTransactionBuilder, Provider, }; -use alloy_rlp::Decodable; +use alloy_rlp::{Decodable, Encodable}; use alloy_rpc_types::{BlockId, BlockNumberOrTag, Filter}; use alloy_transport::Transport; use base::{Base, NumberWithBase, ToBase}; @@ -637,7 +637,7 @@ where let tx = self.provider.get_transaction_by_hash(tx_hash).await?; Ok(if raw { - format!("0x{}", hex::encode(tx.rlp())) + format!("0x{}", hex::encode(TxEnvelope::try_from(tx)?.encoded_2718())) } else if let Some(field) = field { get_pretty_tx_attr(&tx, field.as_str()) .ok_or_else(|| eyre::eyre!("invalid tx field: {}", field.to_string()))? diff --git a/crates/cast/src/tx.rs b/crates/cast/src/tx.rs index 294ebd19e0e9..7f87ee7277f7 100644 --- a/crates/cast/src/tx.rs +++ b/crates/cast/src/tx.rs @@ -143,13 +143,13 @@ impl<'a, T: Transport + Clone, P: Provider> TxBuilder<'a, P, T> { } /// Set nonce - pub fn set_nonce(&mut self, v: U64) -> &mut Self { + pub fn set_nonce(&mut self, v: u64) -> &mut Self { self.tx.set_nonce(v); self } /// Set nonce, if `v` is not None - pub fn nonce(&mut self, v: Option) -> &mut Self { + pub fn nonce(&mut self, v: Option) -> &mut Self { if let Some(value) = v { self.set_nonce(value); } diff --git a/crates/cheatcodes/src/inspector.rs b/crates/cheatcodes/src/inspector.rs index d95fdb2422e7..10ff4dfa3230 100644 --- a/crates/cheatcodes/src/inspector.rs +++ b/crates/cheatcodes/src/inspector.rs @@ -856,7 +856,7 @@ impl Inspector for Cheatcodes { to: Some(call.contract), value: Some(call.transfer.value), input: TransactionInput::new(call.input.clone()), - nonce: Some(U64::from(account.info.nonce)), + nonce: Some(account.info.nonce), gas: if is_fixed_gas_limit { Some(U256::from(call.gas_limit)) } else { @@ -1265,7 +1265,7 @@ impl Inspector for Cheatcodes { to, value: Some(call.value), input: TransactionInput::new(bytecode), - nonce: Some(U64::from(nonce)), + nonce: Some(nonce), gas: if is_fixed_gas_limit { Some(U256::from(call.gas_limit)) } else { diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index aad365bb52b0..810c1bbbc41d 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -22,6 +22,8 @@ foundry-compilers = { workspace = true, features = ["full"] } alloy-dyn-abi.workspace = true alloy-json-abi.workspace = true alloy-primitives.workspace = true +alloy-provider.workspace = true +alloy-transport.workspace = true ethers-core.workspace = true ethers-providers.workspace = true diff --git a/crates/cli/src/opts/transaction.rs b/crates/cli/src/opts/transaction.rs index 84173eaaf4b3..81d6107bdea0 100644 --- a/crates/cli/src/opts/transaction.rs +++ b/crates/cli/src/opts/transaction.rs @@ -1,5 +1,5 @@ use crate::utils::parse_ether_value; -use alloy_primitives::U256; +use alloy_primitives::{U256, U64}; use clap::Parser; use serde::Serialize; @@ -38,7 +38,7 @@ pub struct TransactionOpts { /// Nonce for the transaction. #[arg(long)] - pub nonce: Option, + pub nonce: Option, /// Send a legacy transaction instead of an EIP1559 transaction. /// diff --git a/crates/cli/src/utils/mod.rs b/crates/cli/src/utils/mod.rs index 735fb25230ea..4f7aeb2051f1 100644 --- a/crates/cli/src/utils/mod.rs +++ b/crates/cli/src/utils/mod.rs @@ -1,5 +1,7 @@ use alloy_json_abi::JsonAbi; use alloy_primitives::{utils::format_units, U256}; +use alloy_provider::{network::Ethereum, Provider}; +use alloy_transport::Transport; use ethers_core::types::TransactionReceipt; use ethers_providers::Middleware; use eyre::{ContextCompat, Result}; @@ -141,14 +143,14 @@ pub fn get_alloy_provider_builder( Ok(builder) } -pub async fn get_chain(chain: Option, provider: M) -> Result +pub async fn get_chain(chain: Option, provider: P) -> Result where - M: Middleware, - M::Error: 'static, + P: Provider, + T: Transport + Clone, { match chain { Some(chain) => Ok(chain), - None => Ok(Chain::from_id(provider.get_chainid().await?.as_u64())), + None => Ok(Chain::from_id(provider.get_chain_id().await?.to())), } } diff --git a/crates/common/src/fmt/ui.rs b/crates/common/src/fmt/ui.rs index 3cf423b44a3d..d93caa10e489 100644 --- a/crates/common/src/fmt/ui.rs +++ b/crates/common/src/fmt/ui.rs @@ -279,7 +279,7 @@ value {}{}", self.gas_price.pretty(), self.hash.pretty(), self.input.pretty(), - self.nonce.pretty(), + self.nonce.to_string(), self.signature.map(|s| s.r.to_be_bytes_vec()).pretty(), self.signature.map(|s| s.s.to_be_bytes_vec()).pretty(), self.to.pretty(), @@ -378,7 +378,7 @@ pub fn get_pretty_tx_attr(transaction: &Transaction, attr: &str) -> Option Some(transaction.gas_price.pretty()), "hash" => Some(transaction.hash.pretty()), "input" => Some(transaction.input.pretty()), - "nonce" => Some(transaction.nonce.pretty()), + "nonce" => Some(transaction.nonce.to_string()), "s" => transaction.signature.map(|s| s.s.pretty()), "r" => transaction.signature.map(|s| s.r.pretty()), "to" => Some(transaction.to.pretty()), diff --git a/crates/evm/core/src/utils.rs b/crates/evm/core/src/utils.rs index fea2ab4f8ef5..ad11165267aa 100644 --- a/crates/evm/core/src/utils.rs +++ b/crates/evm/core/src/utils.rs @@ -71,7 +71,7 @@ pub fn configure_tx_env(env: &mut revm::primitives::Env, tx: &Transaction) { env.tx.gas_limit = tx.gas.to(); env.tx.gas_price = tx.gas_price.unwrap_or_default().to(); env.tx.gas_priority_fee = tx.max_priority_fee_per_gas.map(|g| g.to()); - env.tx.nonce = Some(tx.nonce.to()); + env.tx.nonce = Some(tx.nonce); env.tx.access_list = tx .access_list .clone() From 2a723a47db9881a72d0b35baf198a83cfe1cb02e Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Wed, 20 Mar 2024 23:50:00 +0400 Subject: [PATCH 12/63] [wip] migrate to alloy providers and signers (#7425) wip --- Cargo.lock | 739 ++++++++++++++++++---------- Cargo.toml | 40 +- crates/cast/Cargo.toml | 5 +- crates/cast/bin/cmd/wallet/list.rs | 2 +- crates/cast/bin/cmd/wallet/mod.rs | 11 +- crates/cast/src/lib.rs | 1 + crates/cli/Cargo.toml | 2 +- crates/forge/Cargo.toml | 2 +- crates/script/src/lib.rs | 2 +- crates/wallets/Cargo.toml | 16 +- crates/wallets/src/error.rs | 7 +- crates/wallets/src/multi_wallet.rs | 12 +- crates/wallets/src/utils.rs | 42 +- crates/wallets/src/wallet.rs | 7 +- crates/wallets/src/wallet_signer.rs | 124 ++--- 15 files changed, 594 insertions(+), 418 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0d7b65b638ea..783a88469423 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -96,7 +96,7 @@ dependencies = [ "alloy-primitives", "alloy-rlp", "c-kzg", - "sha2 0.10.8", + "sha2", "thiserror", ] @@ -408,6 +408,52 @@ dependencies = [ "thiserror", ] +[[package]] +name = "alloy-signer-aws" +version = "0.1.0" +source = "git+https://github.com/alloy-rs/alloy?rev=9ac2c90#9ac2c90d58a9994d4b61c879e33c6af2739a2b4f" +dependencies = [ + "alloy-primitives", + "alloy-signer", + "async-trait", + "aws-sdk-kms", + "k256", + "spki", + "thiserror", + "tracing", +] + +[[package]] +name = "alloy-signer-ledger" +version = "0.1.0" +source = "git+https://github.com/alloy-rs/alloy?rev=9ac2c90#9ac2c90d58a9994d4b61c879e33c6af2739a2b4f" +dependencies = [ + "alloy-primitives", + "alloy-signer", + "async-trait", + "coins-ledger", + "futures-util", + "semver 1.0.22", + "thiserror", + "tracing", +] + +[[package]] +name = "alloy-signer-trezor" +version = "0.1.0" +source = "git+https://github.com/alloy-rs/alloy?rev=9ac2c90#9ac2c90d58a9994d4b61c879e33c6af2739a2b4f" +dependencies = [ + "alloy-consensus", + "alloy-network", + "alloy-primitives", + "alloy-signer", + "async-trait", + "semver 1.0.22", + "thiserror", + "tracing", + "trezor-client", +] + [[package]] name = "alloy-sol-macro" version = "0.6.4" @@ -513,7 +559,7 @@ dependencies = [ "alloy-pubsub", "alloy-transport", "futures", - "http", + "http 0.2.12", "serde_json", "tokio", "tokio-tungstenite", @@ -1030,6 +1076,319 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" +[[package]] +name = "aws-config" +version = "1.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f4084d18094aec9f79d509f4cb6ccf6b613c5037e32f32e74312e52b836e366" +dependencies = [ + "aws-credential-types", + "aws-runtime", + "aws-sdk-sso", + "aws-sdk-ssooidc", + "aws-sdk-sts", + "aws-smithy-async", + "aws-smithy-http", + "aws-smithy-json", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-types", + "aws-types", + "bytes", + "fastrand", + "hex", + "http 0.2.12", + "hyper", + "ring 0.17.8", + "time", + "tokio", + "tracing", + "zeroize", +] + +[[package]] +name = "aws-credential-types" +version = "1.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa8587ae17c8e967e4b05a62d495be2fb7701bec52a97f7acfe8a29f938384c8" +dependencies = [ + "aws-smithy-async", + "aws-smithy-runtime-api", + "aws-smithy-types", + "zeroize", +] + +[[package]] +name = "aws-runtime" +version = "1.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b13dc54b4b49f8288532334bba8f87386a40571c47c37b1304979b556dc613c8" +dependencies = [ + "aws-credential-types", + "aws-sigv4", + "aws-smithy-async", + "aws-smithy-http", + "aws-smithy-runtime-api", + "aws-smithy-types", + "aws-types", + "bytes", + "fastrand", + "http 0.2.12", + "http-body", + "percent-encoding", + "pin-project-lite", + "tracing", + "uuid 1.7.0", +] + +[[package]] +name = "aws-sdk-kms" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffff97eef0a66fb565564d27cb108cc85409aa31cd6c8e22afed7abe5ccbd403" +dependencies = [ + "aws-credential-types", + "aws-runtime", + "aws-smithy-async", + "aws-smithy-http", + "aws-smithy-json", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-types", + "aws-types", + "bytes", + "http 0.2.12", + "once_cell", + "regex-lite", + "tracing", +] + +[[package]] +name = "aws-sdk-sso" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5cc34f5925899739a3f125bd3f7d37d081234a3df218feb9c9d337fd4c70e72" +dependencies = [ + "aws-credential-types", + "aws-runtime", + "aws-smithy-async", + "aws-smithy-http", + "aws-smithy-json", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-types", + "aws-types", + "bytes", + "http 0.2.12", + "once_cell", + "regex-lite", + "tracing", +] + +[[package]] +name = "aws-sdk-ssooidc" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7327cddd32b1a6f2aaeaadb1336b671a7975e96a999d3b1bcf5aa47932dc6ddb" +dependencies = [ + "aws-credential-types", + "aws-runtime", + "aws-smithy-async", + "aws-smithy-http", + "aws-smithy-json", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-types", + "aws-types", + "bytes", + "http 0.2.12", + "once_cell", + "regex-lite", + "tracing", +] + +[[package]] +name = "aws-sdk-sts" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c11981cdb80e8e205e22beb6630a8bdec380a1256bd29efaab34aaebd07cfb9" +dependencies = [ + "aws-credential-types", + "aws-runtime", + "aws-smithy-async", + "aws-smithy-http", + "aws-smithy-json", + "aws-smithy-query", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-types", + "aws-smithy-xml", + "aws-types", + "http 0.2.12", + "once_cell", + "regex-lite", + "tracing", +] + +[[package]] +name = "aws-sigv4" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11d6f29688a4be9895c0ba8bef861ad0c0dac5c15e9618b9b7a6c233990fc263" +dependencies = [ + "aws-credential-types", + "aws-smithy-http", + "aws-smithy-runtime-api", + "aws-smithy-types", + "bytes", + "form_urlencoded", + "hex", + "hmac", + "http 0.2.12", + "http 1.1.0", + "once_cell", + "percent-encoding", + "sha2", + "time", + "tracing", +] + +[[package]] +name = "aws-smithy-async" +version = "1.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26ea8fa03025b2face2b3038a63525a10891e3d8829901d502e5384a0d8cd46" +dependencies = [ + "futures-util", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "aws-smithy-http" +version = "0.60.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f10fa66956f01540051b0aa7ad54574640f748f9839e843442d99b970d3aff9" +dependencies = [ + "aws-smithy-runtime-api", + "aws-smithy-types", + "bytes", + "bytes-utils", + "futures-core", + "http 0.2.12", + "http-body", + "once_cell", + "percent-encoding", + "pin-project-lite", + "pin-utils", + "tracing", +] + +[[package]] +name = "aws-smithy-json" +version = "0.60.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4683df9469ef09468dad3473d129960119a0d3593617542b7d52086c8486f2d6" +dependencies = [ + "aws-smithy-types", +] + +[[package]] +name = "aws-smithy-query" +version = "0.60.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2fbd61ceb3fe8a1cb7352e42689cec5335833cd9f94103a61e98f9bb61c64bb" +dependencies = [ + "aws-smithy-types", + "urlencoding", +] + +[[package]] +name = "aws-smithy-runtime" +version = "1.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec81002d883e5a7fd2bb063d6fb51c4999eb55d404f4fff3dd878bf4733b9f01" +dependencies = [ + "aws-smithy-async", + "aws-smithy-http", + "aws-smithy-runtime-api", + "aws-smithy-types", + "bytes", + "fastrand", + "h2", + "http 0.2.12", + "http-body", + "hyper", + "hyper-rustls", + "once_cell", + "pin-project-lite", + "pin-utils", + "rustls", + "tokio", + "tracing", +] + +[[package]] +name = "aws-smithy-runtime-api" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9acb931e0adaf5132de878f1398d83f8677f90ba70f01f65ff87f6d7244be1c5" +dependencies = [ + "aws-smithy-async", + "aws-smithy-types", + "bytes", + "http 0.2.12", + "http 1.1.0", + "pin-project-lite", + "tokio", + "tracing", + "zeroize", +] + +[[package]] +name = "aws-smithy-types" +version = "1.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abe14dceea1e70101d38fbf2a99e6a34159477c0fb95e68e05c66bd7ae4c3729" +dependencies = [ + "base64-simd", + "bytes", + "bytes-utils", + "http 0.2.12", + "http-body", + "itoa", + "num-integer", + "pin-project-lite", + "pin-utils", + "ryu", + "serde", + "time", +] + +[[package]] +name = "aws-smithy-xml" +version = "0.60.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872c68cf019c0e4afc5de7753c4f7288ce4b71663212771bf5e4542eb9346ca9" +dependencies = [ + "xmlparser", +] + +[[package]] +name = "aws-types" +version = "1.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dbf2f3da841a8930f159163175cf6a3d16ddde517c1b0fba7aa776822800f40" +dependencies = [ + "aws-credential-types", + "aws-smithy-async", + "aws-smithy-runtime-api", + "aws-smithy-types", + "http 0.2.12", + "rustc_version 0.4.0", + "tracing", +] + [[package]] name = "axum" version = "0.6.20" @@ -1042,7 +1401,7 @@ dependencies = [ "bitflags 1.3.2", "bytes", "futures-util", - "http", + "http 0.2.12", "http-body", "hyper", "itoa", @@ -1074,7 +1433,7 @@ dependencies = [ "async-trait", "bytes", "futures-util", - "http", + "http 0.2.12", "http-body", "mime", "rustversion", @@ -1121,6 +1480,16 @@ version = "0.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9475866fec1451be56a3c2400fd081ff546538961565ccb5b7142cbd22bc7a51" +[[package]] +name = "base64-simd" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "339abbe78e73178762e23bea9dfd08e697eb3f3301cd4be981c0f78ba5859195" +dependencies = [ + "outref", + "vsimd", +] + [[package]] name = "base64ct" version = "1.6.0" @@ -1183,15 +1552,6 @@ dependencies = [ "wyz", ] -[[package]] -name = "block-buffer" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4" -dependencies = [ - "generic-array", -] - [[package]] name = "block-buffer" version = "0.10.4" @@ -1235,7 +1595,7 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f5353f36341f7451062466f0b755b96ac3a9547e4d7f6b70d603fc721a7d7896" dependencies = [ - "sha2 0.10.8", + "sha2", "tinyvec", ] @@ -1298,6 +1658,16 @@ dependencies = [ "serde", ] +[[package]] +name = "bytes-utils" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dafe3a8757b027e2be6e4e5601ed563c55989fcf1546e933c66c8eb3a058d35" +dependencies = [ + "bytes", + "either", +] + [[package]] name = "bzip2" version = "0.4.4" @@ -1387,6 +1757,7 @@ dependencies = [ "alloy-signer", "alloy-transport", "async-trait", + "aws-sdk-kms", "chrono", "clap", "clap_complete", @@ -1419,8 +1790,6 @@ dependencies = [ "rayon", "regex", "rpassword", - "rusoto_core", - "rusoto_kms", "semver 1.0.22", "serde", "serde_json", @@ -1506,7 +1875,6 @@ dependencies = [ "android-tzdata", "iana-time-zone", "num-traits", - "serde", "windows-targets 0.52.4", ] @@ -1642,10 +2010,10 @@ dependencies = [ "bs58", "coins-core", "digest 0.10.7", - "hmac 0.12.1", + "hmac", "k256", "serde", - "sha2 0.10.8", + "sha2", "thiserror", ] @@ -1657,11 +2025,11 @@ checksum = "3db8fba409ce3dc04f7d804074039eb68b960b0829161f8e06c95fea3f122528" dependencies = [ "bitvec", "coins-bip32", - "hmac 0.12.1", + "hmac", "once_cell", "pbkdf2 0.12.2", "rand 0.8.5", - "sha2 0.10.8", + "sha2", "thiserror", ] @@ -1680,7 +2048,7 @@ dependencies = [ "ripemd", "serde", "serde_derive", - "sha2 0.10.8", + "sha2", "sha3", "thiserror", ] @@ -2001,16 +2369,6 @@ dependencies = [ "typenum", ] -[[package]] -name = "crypto-mac" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1d1a86f49236c215f271d40892d5fc950490551400b02ef360692c29815c714" -dependencies = [ - "generic-array", - "subtle", -] - [[package]] name = "ctr" version = "0.9.2" @@ -2202,7 +2560,7 @@ version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ - "block-buffer 0.10.4", + "block-buffer", "const-oid", "crypto-common", "subtle", @@ -2458,16 +2816,16 @@ dependencies = [ "ctr", "digest 0.10.7", "hex", - "hmac 0.12.1", + "hmac", "pbkdf2 0.11.0", "rand 0.8.5", "scrypt", "serde", "serde_json", - "sha2 0.10.8", + "sha2", "sha3", "thiserror", - "uuid", + "uuid 0.8.2", ] [[package]] @@ -2719,7 +3077,7 @@ dependencies = [ "futures-timer", "futures-util", "hashers", - "http", + "http 0.2.12", "instant", "jsonwebtoken", "once_cell", @@ -2749,23 +3107,14 @@ dependencies = [ "async-trait", "coins-bip32", "coins-bip39", - "coins-ledger", "const-hex", "elliptic-curve", "eth-keystore", "ethers-core", - "futures-executor", - "futures-util", - "home", "rand 0.8.5", - "rusoto_core", - "rusoto_kms", - "semver 1.0.22", - "sha2 0.10.8", - "spki", + "sha2", "thiserror", "tracing", - "trezor-client", ] [[package]] @@ -2783,7 +3132,7 @@ dependencies = [ "futures-util", "glob", "home", - "md-5 0.10.6", + "md-5", "num_cpus", "once_cell", "path-slash", @@ -2793,7 +3142,7 @@ dependencies = [ "semver 1.0.22", "serde", "serde_json", - "sha2 0.10.8", + "sha2", "solang-parser", "svm-rs", "svm-rs-builds 0.2.3", @@ -3398,7 +3747,7 @@ dependencies = [ "futures-util", "home", "itertools 0.12.1", - "md-5 0.10.6", + "md-5", "memmap2 0.9.4", "once_cell", "path-slash", @@ -3408,7 +3757,7 @@ dependencies = [ "semver 1.0.22", "serde", "serde_json", - "sha2 0.10.8", + "sha2", "solang-parser", "svm-rs", "svm-rs-builds 0.3.5", @@ -3653,20 +4002,22 @@ name = "foundry-wallets" version = "0.2.0" dependencies = [ "alloy-primitives", + "alloy-signer", + "alloy-signer-aws", + "alloy-signer-ledger", + "alloy-signer-trezor", + "alloy-sol-types", "async-trait", + "aws-config", + "aws-sdk-kms", "clap", "const-hex", "derive_builder", - "ethers-core", - "ethers-providers", - "ethers-signers", "eyre", "foundry-common", "foundry-config", "itertools 0.12.1", "rpassword", - "rusoto_core", - "rusoto_kms", "serde", "thiserror", "tokio", @@ -4160,7 +4511,7 @@ dependencies = [ "futures-core", "futures-sink", "futures-util", - "http", + "http 0.2.12", "indexmap", "slab", "tokio", @@ -4281,16 +4632,6 @@ dependencies = [ "rusb", ] -[[package]] -name = "hmac" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a2a2320eb7ec0ebe8da8f744d7812d9fc4cb4d09344ac01898dbcb6a20ae69b" -dependencies = [ - "crypto-mac", - "digest 0.9.0", -] - [[package]] name = "hmac" version = "0.12.1" @@ -4334,6 +4675,17 @@ dependencies = [ "itoa", ] +[[package]] +name = "http" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21b9ddb458710bc376481b842f5da65cdf31522de232c1ca8146abce2a358258" +dependencies = [ + "bytes", + "fnv", + "itoa", +] + [[package]] name = "http-body" version = "0.4.6" @@ -4341,7 +4693,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7ceab25649e9960c0311ea418d17bee82c0dcec1bd053b5f9a66e265a693bed2" dependencies = [ "bytes", - "http", + "http 0.2.12", "pin-project-lite", ] @@ -4380,7 +4732,7 @@ dependencies = [ "futures-core", "futures-util", "h2", - "http", + "http 0.2.12", "http-body", "httparse", "httpdate", @@ -4393,21 +4745,6 @@ dependencies = [ "want", ] -[[package]] -name = "hyper-rustls" -version = "0.23.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1788965e61b367cd03a62950836d5cd41560c3577d90e40e0819373194d1661c" -dependencies = [ - "http", - "hyper", - "log", - "rustls 0.20.9", - "rustls-native-certs", - "tokio", - "tokio-rustls 0.23.4", -] - [[package]] name = "hyper-rustls" version = "0.24.2" @@ -4415,11 +4752,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec3efd23720e2049821a693cbc7e65ea87c72f1c58ff2f9522ff332b1491e590" dependencies = [ "futures-util", - "http", + "http 0.2.12", "hyper", - "rustls 0.21.10", + "log", + "rustls", + "rustls-native-certs", "tokio", - "tokio-rustls 0.24.1", + "tokio-rustls", ] [[package]] @@ -4755,7 +5094,7 @@ dependencies = [ "ecdsa", "elliptic-curve", "once_cell", - "sha2 0.10.8", + "sha2", "signature", ] @@ -4955,17 +5294,6 @@ version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94" -[[package]] -name = "md-5" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b5a279bb9607f9f53c22d496eade00d138d1bdcccd07d74650387cf94942a15" -dependencies = [ - "block-buffer 0.9.0", - "digest 0.9.0", - "opaque-debug", -] - [[package]] name = "md-5" version = "0.10.6" @@ -5374,12 +5702,6 @@ version = "11.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ab1bc2a289d34bd04a330323ac98a1b4bc82c9d9fcb1e66b63caa84da26b575" -[[package]] -name = "opaque-debug" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" - [[package]] name = "open-fastrlp" version = "0.1.4" @@ -5466,6 +5788,12 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" +[[package]] +name = "outref" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4030760ffd992bef45b0ae3f10ce1aba99e33464c90d14dd7c039884963ddc7a" + [[package]] name = "overload" version = "0.1.1" @@ -5487,7 +5815,7 @@ dependencies = [ "ecdsa", "elliptic-curve", "primeorder", - "sha2 0.10.8", + "sha2", ] [[package]] @@ -5614,9 +5942,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "83a0692ec44e4cf1ef28ca317f14f8f07da2d95ec3fa01f86e4467b725e60917" dependencies = [ "digest 0.10.7", - "hmac 0.12.1", + "hmac", "password-hash", - "sha2 0.10.8", + "sha2", ] [[package]] @@ -5626,7 +5954,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2" dependencies = [ "digest 0.10.7", - "hmac 0.12.1", + "hmac", ] [[package]] @@ -5718,7 +6046,7 @@ checksum = "934cd7631c050f4674352a6e835d5f6711ffbfb9345c2fc0107155ac495ae293" dependencies = [ "once_cell", "pest", - "sha2 0.10.8", + "sha2", ] [[package]] @@ -6354,6 +6682,12 @@ dependencies = [ "regex-syntax 0.8.2", ] +[[package]] +name = "regex-lite" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30b661b2f27137bdbc16f00eda72866a92bb28af1753ffbd56744fb6e2e9cd8e" + [[package]] name = "regex-syntax" version = "0.6.29" @@ -6378,10 +6712,10 @@ dependencies = [ "futures-core", "futures-util", "h2", - "http", + "http 0.2.12", "http-body", "hyper", - "hyper-rustls 0.24.2", + "hyper-rustls", "hyper-tls", "ipnet", "js-sys", @@ -6391,7 +6725,7 @@ dependencies = [ "once_cell", "percent-encoding", "pin-project-lite", - "rustls 0.21.10", + "rustls", "rustls-native-certs", "rustls-pemfile", "serde", @@ -6401,7 +6735,7 @@ dependencies = [ "system-configuration", "tokio", "tokio-native-tls", - "tokio-rustls 0.24.1", + "tokio-rustls", "tower-service", "url", "wasm-bindgen", @@ -6463,7 +6797,7 @@ dependencies = [ "revm-primitives", "ripemd", "secp256k1", - "sha2 0.10.8", + "sha2", "substrate-bn", ] @@ -6491,7 +6825,7 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" dependencies = [ - "hmac 0.12.1", + "hmac", "subtle", ] @@ -6618,89 +6952,6 @@ dependencies = [ "libusb1-sys", ] -[[package]] -name = "rusoto_core" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1db30db44ea73551326269adcf7a2169428a054f14faf9e1768f2163494f2fa2" -dependencies = [ - "async-trait", - "base64 0.13.1", - "bytes", - "crc32fast", - "futures", - "http", - "hyper", - "hyper-rustls 0.23.2", - "lazy_static", - "log", - "rusoto_credential", - "rusoto_signature", - "rustc_version 0.4.0", - "serde", - "serde_json", - "tokio", - "xml-rs", -] - -[[package]] -name = "rusoto_credential" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee0a6c13db5aad6047b6a44ef023dbbc21a056b6dab5be3b79ce4283d5c02d05" -dependencies = [ - "async-trait", - "chrono", - "dirs-next", - "futures", - "hyper", - "serde", - "serde_json", - "shlex", - "tokio", - "zeroize", -] - -[[package]] -name = "rusoto_kms" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e1fc19cfcfd9f6b2f96e36d5b0dddda9004d2cbfc2d17543e3b9f10cc38fce8" -dependencies = [ - "async-trait", - "bytes", - "futures", - "rusoto_core", - "serde", - "serde_json", -] - -[[package]] -name = "rusoto_signature" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5ae95491c8b4847931e291b151127eccd6ff8ca13f33603eb3d0035ecb05272" -dependencies = [ - "base64 0.13.1", - "bytes", - "chrono", - "digest 0.9.0", - "futures", - "hex", - "hmac 0.11.0", - "http", - "hyper", - "log", - "md-5 0.9.1", - "percent-encoding", - "pin-project-lite", - "rusoto_credential", - "rustc_version 0.4.0", - "serde", - "sha2 0.9.9", - "tokio", -] - [[package]] name = "rustc-demangle" version = "0.1.23" @@ -6750,18 +7001,6 @@ dependencies = [ "windows-sys 0.52.0", ] -[[package]] -name = "rustls" -version = "0.20.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b80e3dec595989ea8510028f30c408a4630db12c9cbb8de34203b89d6577e99" -dependencies = [ - "log", - "ring 0.16.20", - "sct", - "webpki", -] - [[package]] name = "rustls" version = "0.21.10" @@ -6939,10 +7178,10 @@ version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f9e24d2b632954ded8ab2ef9fea0a0c769ea56ea98bddbafbad22caeeadf45d" dependencies = [ - "hmac 0.12.1", + "hmac", "pbkdf2 0.11.0", "salsa20", - "sha2 0.10.8", + "sha2", ] [[package]] @@ -7186,19 +7425,6 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ae1a47186c03a32177042e55dbc5fd5aee900b8e0069a8d70fba96a9375cd012" -[[package]] -name = "sha2" -version = "0.9.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d58a1e1bf39749807d89cf2d98ac2dfa0ff1cb3faa38fbb64dd88ac8013d800" -dependencies = [ - "block-buffer 0.9.0", - "cfg-if", - "cpufeatures", - "digest 0.9.0", - "opaque-debug", -] - [[package]] name = "sha2" version = "0.10.8" @@ -7512,7 +7738,7 @@ dependencies = [ "semver 1.0.22", "serde", "serde_json", - "sha2 0.10.8", + "sha2", "thiserror", "url", "zip", @@ -7831,24 +8057,13 @@ dependencies = [ "tokio", ] -[[package]] -name = "tokio-rustls" -version = "0.23.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c43ee83903113e03984cb9e5cebe6c04a5116269e900e3ddba8f068a62adda59" -dependencies = [ - "rustls 0.20.9", - "tokio", - "webpki", -] - [[package]] name = "tokio-rustls" version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c28327cf380ac148141087fbfb9de9d7bd4e84ab5d2c28fbc911d753de8a7081" dependencies = [ - "rustls 0.21.10", + "rustls", "tokio", ] @@ -7873,10 +8088,10 @@ dependencies = [ "futures-util", "log", "native-tls", - "rustls 0.21.10", + "rustls", "tokio", "tokio-native-tls", - "tokio-rustls 0.24.1", + "tokio-rustls", "tungstenite", "webpki-roots", ] @@ -8005,7 +8220,7 @@ dependencies = [ "bytes", "futures-core", "futures-util", - "http", + "http 0.2.12", "http-body", "http-range-header", "httpdate", @@ -8175,12 +8390,12 @@ dependencies = [ "byteorder", "bytes", "data-encoding", - "http", + "http 0.2.12", "httparse", "log", "native-tls", "rand 0.8.5", - "rustls 0.21.10", + "rustls", "sha1", "thiserror", "url", @@ -8304,6 +8519,12 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "urlencoding" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da" + [[package]] name = "utf-8" version = "0.7.6" @@ -8326,6 +8547,12 @@ dependencies = [ "serde", ] +[[package]] +name = "uuid" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f00cc9702ca12d3c81455259621e676d0f7251cec66a21e98fe2e9a37db93b2a" + [[package]] name = "valuable" version = "0.1.0" @@ -8356,6 +8583,12 @@ version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" +[[package]] +name = "vsimd" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64" + [[package]] name = "wait-timeout" version = "0.2.0" @@ -8520,16 +8753,6 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "webpki" -version = "0.22.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed63aea5ce73d0ff405984102c42de94fc55a6b75765d621c65262469b3c9b53" -dependencies = [ - "ring 0.17.8", - "untrusted 0.9.0", -] - [[package]] name = "webpki-roots" version = "0.25.4" @@ -8852,10 +9075,10 @@ dependencies = [ ] [[package]] -name = "xml-rs" -version = "0.8.19" +name = "xmlparser" +version = "0.13.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fcb9cbac069e033553e8bb871be2fbdffcab578eb25bd0f7c508cedc6dcd75a" +checksum = "66fee0b777b0f5ac1c69bb06d361268faafa61cd4682ae064a171c16c433e9e4" [[package]] name = "yansi" @@ -8922,7 +9145,7 @@ dependencies = [ "crc32fast", "crossbeam-utils", "flate2", - "hmac 0.12.1", + "hmac", "pbkdf2 0.11.0", "sha1", "time", diff --git a/Cargo.toml b/Cargo.toml index da43711b8bf2..8e450f885034 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -104,9 +104,6 @@ codegen-units = 1 [profile.release.package] mdbook.opt-level = 1 protobuf.opt-level = 1 -rusoto_core.opt-level = 1 -rusoto_credential.opt-level = 1 -rusoto_kms.opt-level = 1 toml_edit.opt-level = 1 trezor-client.opt-level = 1 @@ -159,29 +156,30 @@ ethers-middleware = { version = "2.0.14", default-features = false } ethers-solc = { version = "2.0.14", default-features = false } ## alloy -alloy-consensus = { git = "https://github.com/klkvr/alloy", rev = "376583d" } -alloy-contract = { git = "https://github.com/klkvr/alloy", rev = "376583d" } -alloy-eips = { git = "https://github.com/klkvr/alloy", rev = "376583d" } -alloy-genesis = { git = "https://github.com/klkvr/alloy", rev = "376583d" } -alloy-json-rpc = { git = "https://github.com/klkvr/alloy", rev = "376583d" } -alloy-network = { git = "https://github.com/klkvr/alloy", rev = "376583d" } -alloy-node-bindings = { git = "https://github.com/klkvr/alloy", rev = "376583d" } -alloy-provider = { git = "https://github.com/klkvr/alloy", rev = "376583d" } -alloy-pubsub = { git = "https://github.com/klkvr/alloy", rev = "376583d" } -alloy-rpc-client = { git = "https://github.com/klkvr/alloy", rev = "376583d" } -alloy-rpc-trace-types = { git = "https://github.com/klkvr/alloy", rev = "376583d" } -alloy-rpc-types = { git = "https://github.com/klkvr/alloy", rev = "376583d" } -alloy-signer = { git = "https://github.com/klkvr/alloy", rev = "376583d" } -alloy-signer-wallet = { git = "https://github.com/klkvr/alloy", rev = "376583d" } -alloy-transport = { git = "https://github.com/klkvr/alloy", rev = "376583d" } -alloy-transport-http = { git = "https://github.com/klkvr/alloy", rev = "376583d" } -alloy-transport-ipc = { git = "https://github.com/klkvr/alloy", rev = "376583d" } -alloy-transport-ws = { git = "https://github.com/klkvr/alloy", rev = "376583d" } +alloy-consensus = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } +alloy-contract = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } +alloy-eips = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } +alloy-genesis = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } +alloy-json-rpc = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } +alloy-network = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } +alloy-node-bindings = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } +alloy-provider = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } +alloy-pubsub = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } +alloy-rpc-client = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } +alloy-rpc-trace-types = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } +alloy-rpc-types = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } +alloy-signer = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } +alloy-signer-wallet = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } +alloy-transport = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } +alloy-transport-http = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } +alloy-transport-ipc = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } +alloy-transport-ws = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } alloy-primitives = { version = "0.6.4", features = ["getrandom"] } alloy-dyn-abi = "0.6.4" alloy-json-abi = "0.6.4" alloy-sol-types = "0.6.4" syn-solidity = "0.6.4" + alloy-chains = "0.1" alloy-rlp = "0.3.3" diff --git a/crates/cast/Cargo.toml b/crates/cast/Cargo.toml index 4341d3d7b8d2..407aa008cec7 100644 --- a/crates/cast/Cargo.toml +++ b/crates/cast/Cargo.toml @@ -56,8 +56,7 @@ serde_json.workspace = true serde.workspace = true # aws -rusoto_core = { version = "0.48", default-features = false } -rusoto_kms = { version = "0.48", default-features = false } +aws-sdk-kms = { version = "1", default-features = false } # bin foundry-cli.workspace = true @@ -91,7 +90,7 @@ criterion = "0.5" [features] default = ["rustls"] rustls = ["foundry-cli/rustls", "foundry-wallets/rustls"] -openssl = ["foundry-cli/openssl", "foundry-wallets/openssl"] +openssl = ["foundry-cli/openssl"] asm-keccak = ["alloy-primitives/asm-keccak"] [[bench]] diff --git a/crates/cast/bin/cmd/wallet/list.rs b/crates/cast/bin/cmd/wallet/list.rs index 2790366a37c7..0a9a5a8f2567 100644 --- a/crates/cast/bin/cmd/wallet/list.rs +++ b/crates/cast/bin/cmd/wallet/list.rs @@ -61,7 +61,7 @@ impl ListArgs { .available_senders(self.max_senders.unwrap()) .await? .iter() - .for_each(|sender| println!("{} ({})", sender.to_alloy(), $label)); + .for_each(|sender| println!("{} ({})", sender, $label)); } } Err(e) => { diff --git a/crates/cast/bin/cmd/wallet/mod.rs b/crates/cast/bin/cmd/wallet/mod.rs index 931ecefa483a..944fc1247cac 100644 --- a/crates/cast/bin/cmd/wallet/mod.rs +++ b/crates/cast/bin/cmd/wallet/mod.rs @@ -1,3 +1,4 @@ +use alloy_dyn_abi::TypedData; use alloy_primitives::{Address, Signature}; use alloy_signer::{ coins_bip39::{English, Mnemonic}, @@ -7,7 +8,7 @@ use clap::Parser; use ethers_core::types::transaction::eip712::TypedData; use ethers_signers::Signer; use eyre::{Context, Result}; -use foundry_common::{fs, types::ToAlloy}; +use foundry_common::fs; use foundry_config::Config; use foundry_wallets::{RawWalletOpts, WalletOpts, WalletSigner}; use rand::thread_rng; @@ -258,7 +259,7 @@ impl WalletSubcommands { .signer() .await?; let addr = wallet.address(); - println!("{}", addr.to_alloy().to_checksum(None)); + println!("{}", addr.to_checksum(None)); } WalletSubcommands::Sign { message, data, from_file, no_hash, wallet } => { let wallet = wallet.signer().await?; @@ -270,11 +271,11 @@ impl WalletSubcommands { // data is a json string serde_json::from_str(&message)? }; - wallet.sign_typed_data(&typed_data).await? + wallet.sign_typed_data(&typed_data, typed_data.domain()).await? } else if no_hash { - wallet.sign_hash(&message.parse()?).await? + wallet.sign_hash(message.parse()?).await? } else { - wallet.sign_message(Self::hex_str_to_bytes(&message)?).await? + wallet.sign_message(&Self::hex_str_to_bytes(&message)?).await? }; println!("0x{sig}"); } diff --git a/crates/cast/src/lib.rs b/crates/cast/src/lib.rs index 7143c87af2e6..500634868a0c 100644 --- a/crates/cast/src/lib.rs +++ b/crates/cast/src/lib.rs @@ -39,6 +39,7 @@ pub use tx::{TxBuilder, TxBuilderOutput, TxBuilderPeekOutput}; use foundry_common::abi::encode_function_args_packed; pub use foundry_evm::*; +pub use tx::{TxBuilder, TxBuilderOutput}; pub use rusoto_core::{ credential::ChainProvider as AwsChainProvider, region::Region as AwsRegion, request::HttpClient as AwsHttpClient, Client as AwsClient, diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index 810c1bbbc41d..b20c8acb5b77 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -50,4 +50,4 @@ tempfile = "3.7" [features] default = ["rustls"] rustls = ["ethers-providers/rustls", "foundry-wallets/rustls"] -openssl = ["ethers-providers/openssl", "foundry-compilers/openssl", "foundry-wallets/openssl"] +openssl = ["ethers-providers/openssl", "foundry-compilers/openssl"] diff --git a/crates/forge/Cargo.toml b/crates/forge/Cargo.toml index 46e9ffd38a44..8e8c7c2b1268 100644 --- a/crates/forge/Cargo.toml +++ b/crates/forge/Cargo.toml @@ -108,7 +108,7 @@ rustls = [ "reqwest/rustls-tls", "reqwest/rustls-tls-native-roots", ] -openssl = ["foundry-cli/openssl", "reqwest/default-tls", "foundry-wallets/openssl"] +openssl = ["foundry-cli/openssl", "reqwest/default-tls"] asm-keccak = ["alloy-primitives/asm-keccak"] [[bench]] diff --git a/crates/script/src/lib.rs b/crates/script/src/lib.rs index 010b5bbe970d..6af8faf61cb7 100644 --- a/crates/script/src/lib.rs +++ b/crates/script/src/lib.rs @@ -299,7 +299,7 @@ impl ScriptArgs { .wallets .private_keys()? .filter(|pks| pks.len() == 1) - .map(|pks| pks.first().unwrap().address().to_alloy()); + .map(|pks| pks.first().unwrap().address()); Ok(maybe_sender) } diff --git a/crates/wallets/Cargo.toml b/crates/wallets/Cargo.toml index 1ef26972dbd4..01b60b579ba9 100644 --- a/crates/wallets/Cargo.toml +++ b/crates/wallets/Cargo.toml @@ -11,13 +11,14 @@ repository.workspace = true [dependencies] alloy-primitives.workspace = true +alloy-signer = { workspace = true, features = ["eip712"] } +alloy-signer-aws.workspace = true +alloy-signer-ledger.workspace = true +alloy-signer-trezor.workspace = true +alloy-sol-types.workspace = true -ethers-core.workspace = true -ethers-providers.workspace = true -ethers-signers = { workspace = true, features = ["aws", "ledger", "trezor"] } - -rusoto_core = { version = "0.48", default-features = false } -rusoto_kms = { version = "0.48", default-features = false } +aws-sdk-kms = { version = "1", default-features = false } +aws-config = "1" foundry-config.workspace = true foundry-common.workspace = true @@ -38,5 +39,4 @@ tokio = { version = "1", features = ["macros"] } [features] default = ["rustls"] -rustls = ["ethers-providers/rustls", "rusoto_core/rustls"] -openssl = ["ethers-providers/openssl"] +rustls = ["aws-sdk-kms/rustls"] diff --git a/crates/wallets/src/error.rs b/crates/wallets/src/error.rs index 6588f5e22cc1..1ec2ae89f032 100644 --- a/crates/wallets/src/error.rs +++ b/crates/wallets/src/error.rs @@ -1,4 +1,7 @@ -use ethers_signers::{AwsSignerError, LedgerError, TrezorError, WalletError}; +use alloy_signer::{k256::ecdsa, WalletError}; +use alloy_signer_aws::AwsSignerError; +use alloy_signer_ledger::LedgerError; +use alloy_signer_trezor::TrezorError; use hex::FromHexError; #[derive(Debug, thiserror::Error)] @@ -23,6 +26,8 @@ pub enum WalletSignerError { Io(#[from] std::io::Error), #[error(transparent)] InvalidHex(#[from] FromHexError), + #[error(transparent)] + Ecdsa(#[from] ecdsa::Error), #[error("{0} cannot sign raw hashes")] CannotSignRawHash(&'static str), } diff --git a/crates/wallets/src/multi_wallet.rs b/crates/wallets/src/multi_wallet.rs index d9673985a11f..9f4305ea067d 100644 --- a/crates/wallets/src/multi_wallet.rs +++ b/crates/wallets/src/multi_wallet.rs @@ -3,11 +3,10 @@ use crate::{ wallet_signer::{PendingSigner, WalletSigner}, }; use alloy_primitives::Address; +use alloy_signer::Signer; use clap::Parser; use derive_builder::Builder; -use ethers_signers::Signer; use eyre::Result; -use foundry_common::types::ToAlloy; use foundry_config::Config; use serde::Serialize; use std::{collections::HashMap, iter::repeat, path::PathBuf}; @@ -24,15 +23,14 @@ pub struct MultiWallet { impl MultiWallet { pub fn new(pending_signers: Vec, signers: Vec) -> Self { - let signers = - signers.into_iter().map(|signer| (signer.address().to_alloy(), signer)).collect(); + let signers = signers.into_iter().map(|signer| (signer.address(), signer)).collect(); Self { pending_signers, signers } } fn maybe_unlock_pending(&mut self) -> Result<()> { for pending in self.pending_signers.drain(..) { let signer = pending.unlock()?; - self.signers.insert(signer.address().to_alloy(), signer); + self.signers.insert(signer.address(), signer); } Ok(()) } @@ -48,7 +46,7 @@ impl MultiWallet { } pub fn add_signer(&mut self, signer: WalletSigner) { - self.signers.insert(signer.address().to_alloy(), signer); + self.signers.insert(signer.address(), signer); } } @@ -386,7 +384,7 @@ impl MultiWalletOpts { .collect::>(); for key in aws_keys { - let aws_signer = WalletSigner::from_aws(&key).await?; + let aws_signer = WalletSigner::from_aws(key).await?; wallets.push(aws_signer) } diff --git a/crates/wallets/src/utils.rs b/crates/wallets/src/utils.rs index a10903313034..d146be299283 100644 --- a/crates/wallets/src/utils.rs +++ b/crates/wallets/src/utils.rs @@ -1,39 +1,35 @@ use crate::{error::PrivateKeyError, PendingSigner, WalletSigner}; -use ethers_signers::{HDPath as LedgerHDPath, LocalWallet, TrezorHDPath, WalletError}; +use alloy_primitives::B256; +use alloy_signer::LocalWallet; +use alloy_signer_ledger::HDPath as LedgerHDPath; +use alloy_signer_trezor::TrezorHDPath; use eyre::{Context, Result}; use foundry_config::Config; use std::{ fs, path::{Path, PathBuf}, - str::FromStr, }; +fn ensure_pk_not_env(pk: &str) -> Result<()> { + if !pk.starts_with("0x") && std::env::var(pk).is_ok() { + return Err(PrivateKeyError::ExistsAsEnvVar(pk.to_string()).into()); + } + Ok(()) +} + /// Validates and sanitizes user inputs, returning configured [WalletSigner]. pub fn create_private_key_signer(private_key: &str) -> Result { let privk = private_key.trim().strip_prefix("0x").unwrap_or(private_key); - match LocalWallet::from_str(privk) { + + let Ok(private_key) = hex::decode(privk) else { + ensure_pk_not_env(privk)?; + eyre::bail!("Failed to decode private key") + }; + + match LocalWallet::from_bytes(&B256::from_slice(&private_key)) { Ok(pk) => Ok(WalletSigner::Local(pk)), Err(err) => { - // helper closure to check if pk was meant to be an env var, this usually happens if - // `$` is missing - let ensure_not_env = |pk: &str| { - // check if pk was meant to be an env var - if !pk.starts_with("0x") && std::env::var(pk).is_ok() { - // SAFETY: at this point we know the user actually wanted to use an env var - // and most likely forgot the `$` anchor, so the - // `private_key` here is an unresolved env var - return Err(PrivateKeyError::ExistsAsEnvVar(pk.to_string())) - } - Ok(()) - }; - match err { - WalletError::HexError(err) => { - ensure_not_env(private_key)?; - return Err(PrivateKeyError::InvalidHex(err).into()); - } - WalletError::EcdsaError(_) => ensure_not_env(private_key)?, - _ => {} - }; + ensure_pk_not_env(privk)?; eyre::bail!("Failed to create wallet from private key: {err}") } } diff --git a/crates/wallets/src/wallet.rs b/crates/wallets/src/wallet.rs index cd7359f2e2ce..3f0afd27a37b 100644 --- a/crates/wallets/src/wallet.rs +++ b/crates/wallets/src/wallet.rs @@ -1,9 +1,8 @@ use crate::{raw_wallet::RawWalletOpts, utils, wallet_signer::WalletSigner}; use alloy_primitives::Address; +use alloy_signer::Signer; use clap::Parser; -use ethers_signers::Signer; use eyre::Result; -use foundry_common::types::ToAlloy; use serde::Serialize; /// The wallet options can either be: @@ -95,7 +94,7 @@ impl WalletOpts { .await? } else if self.aws { let key_id = std::env::var("AWS_KMS_KEY_ID")?; - WalletSigner::from_aws(&key_id).await? + WalletSigner::from_aws(key_id).await? } else if let Some(raw_wallet) = self.raw.signer()? { raw_wallet } else if let Some(path) = utils::maybe_get_keystore_path( @@ -139,7 +138,7 @@ of the unlocked account you want to use, or provide the --from flag with the add if let Some(from) = self.from { from } else if let Ok(signer) = self.signer().await { - signer.address().to_alloy() + signer.address() } else { Address::ZERO } diff --git a/crates/wallets/src/wallet_signer.rs b/crates/wallets/src/wallet_signer.rs index d71fbe1af7ff..d0e0535897de 100644 --- a/crates/wallets/src/wallet_signer.rs +++ b/crates/wallets/src/wallet_signer.rs @@ -1,19 +1,15 @@ use crate::error::WalletSignerError; -use alloy_primitives::B256; -use async_trait::async_trait; -use ethers_core::types::{ - transaction::{eip2718::TypedTransaction, eip712::Eip712}, - Signature, -}; -use ethers_signers::{ - coins_bip39::English, AwsSigner, HDPath as LedgerHDPath, Ledger, LocalWallet, MnemonicBuilder, - Signer, Trezor, TrezorHDPath, +use alloy_primitives::{Address, ChainId, B256}; +use alloy_signer::{ + coins_bip39::English, LocalWallet, MnemonicBuilder, SignableTx, Signature, Signer, }; -use rusoto_core::{ - credential::ChainProvider as AwsChainProvider, region::Region as AwsRegion, - request::HttpClient as AwsHttpClient, Client as AwsClient, -}; -use rusoto_kms::KmsClient; +use alloy_signer_aws::AwsSigner; +use alloy_signer_ledger::{HDPath as LedgerHDPath, LedgerSigner}; +use alloy_signer_trezor::{TrezorHDPath, TrezorSigner}; +use alloy_sol_types::{Eip712Domain, SolStruct}; +use async_trait::async_trait; +use aws_config::BehaviorVersion; +use aws_sdk_kms::Client as AwsClient; use std::path::PathBuf; pub type Result = std::result::Result; @@ -24,36 +20,34 @@ pub enum WalletSigner { /// Wrapper around local wallet. e.g. private key, mnemonic Local(LocalWallet), /// Wrapper around Ledger signer. - Ledger(Ledger), + Ledger(LedgerSigner), /// Wrapper around Trezor signer. - Trezor(Trezor), + Trezor(TrezorSigner), /// Wrapper around AWS KMS signer. Aws(AwsSigner), } impl WalletSigner { pub async fn from_ledger_path(path: LedgerHDPath) -> Result { - let ledger = Ledger::new(path, 1).await?; + let ledger = LedgerSigner::new(path, None).await?; Ok(Self::Ledger(ledger)) } pub async fn from_trezor_path(path: TrezorHDPath) -> Result { // cached to ~/.ethers-rs/trezor/cache/trezor.session - let trezor = Trezor::new(path, 1, None).await?; + let trezor = TrezorSigner::new(path, None).await?; Ok(Self::Trezor(trezor)) } - pub async fn from_aws(key_id: &str) -> Result { - let client = - AwsClient::new_with(AwsChainProvider::default(), AwsHttpClient::new().unwrap()); + pub async fn from_aws(key_id: String) -> Result { + let config = aws_config::load_defaults(BehaviorVersion {}).await; + let client = AwsClient::new(&config); - let kms = KmsClient::new_with_client(client, AwsRegion::default()); - - Ok(Self::Aws(AwsSigner::new(kms, key_id, 1).await?)) + Ok(Self::Aws(AwsSigner::new(client, key_id, None).await?)) } pub fn from_private_key(private_key: impl AsRef<[u8]>) -> Result { - let wallet = LocalWallet::from_bytes(private_key.as_ref())?; + let wallet = LocalWallet::from_bytes(&B256::from_slice(private_key.as_ref()))?; Ok(Self::Local(wallet)) } @@ -63,7 +57,7 @@ impl WalletSigner { /// - the result for Ledger signers includes addresses available for both LedgerLive and Legacy /// derivation paths /// - for Local and AWS signers the result contains a single address - pub async fn available_senders(&self, max: usize) -> Result> { + pub async fn available_senders(&self, max: usize) -> Result> { let mut senders = Vec::new(); match self { WalletSigner::Local(local) => { @@ -136,78 +130,40 @@ macro_rules! delegate { #[async_trait] impl Signer for WalletSigner { - type Error = WalletSignerError; - - async fn sign_message>(&self, message: S) -> Result { - delegate!(self, inner => inner.sign_message(message).await.map_err(Into::into)) + /// Signs the given hash. + async fn sign_hash(&self, hash: B256) -> alloy_signer::Result { + delegate!(self, inner => inner.sign_hash(hash)).await } - async fn sign_transaction(&self, message: &TypedTransaction) -> Result { - delegate!(self, inner => inner.sign_transaction(message).await.map_err(Into::into)) + async fn sign_message(&self, message: &[u8]) -> alloy_signer::Result { + delegate!(self, inner => inner.sign_message(message)).await } - async fn sign_typed_data(&self, payload: &T) -> Result { - delegate!(self, inner => inner.sign_typed_data(payload).await.map_err(Into::into)) + async fn sign_transaction(&self, tx: &mut SignableTx) -> alloy_signer::Result { + delegate!(self, inner => inner.sign_transaction(tx)).await } - fn address(&self) -> ethers_core::types::Address { + fn address(&self) -> Address { delegate!(self, inner => inner.address()) } - fn chain_id(&self) -> u64 { + fn chain_id(&self) -> Option { delegate!(self, inner => inner.chain_id()) } - fn with_chain_id>(self, chain_id: T) -> Self { - match self { - Self::Local(inner) => Self::Local(inner.with_chain_id(chain_id)), - Self::Ledger(inner) => Self::Ledger(inner.with_chain_id(chain_id)), - Self::Trezor(inner) => Self::Trezor(inner.with_chain_id(chain_id)), - Self::Aws(inner) => Self::Aws(inner.with_chain_id(chain_id)), - } - } -} - -#[async_trait] -impl Signer for &WalletSigner { - type Error = WalletSignerError; - - async fn sign_message>(&self, message: S) -> Result { - (*self).sign_message(message).await + fn set_chain_id(&mut self, chain_id: Option) { + delegate!(self, inner => inner.set_chain_id(chain_id)) } - async fn sign_transaction(&self, message: &TypedTransaction) -> Result { - (*self).sign_transaction(message).await - } - - async fn sign_typed_data(&self, payload: &T) -> Result { - (*self).sign_typed_data(payload).await - } - - fn address(&self) -> ethers_core::types::Address { - (*self).address() - } - - fn chain_id(&self) -> u64 { - (*self).chain_id() - } - - fn with_chain_id>(self, chain_id: T) -> Self { - let _ = chain_id; - self - } -} - -impl WalletSigner { - pub async fn sign_hash(&self, hash: &B256) -> Result { - match self { - // TODO: AWS can sign hashes but utilities aren't exposed in ethers-signers. - // TODO: Implement with alloy-signer. - Self::Aws(_aws) => Err(WalletSignerError::CannotSignRawHash("AWS")), - Self::Ledger(_) => Err(WalletSignerError::CannotSignRawHash("Ledger")), - Self::Local(wallet) => wallet.sign_hash(hash.0.into()).map_err(Into::into), - Self::Trezor(_) => Err(WalletSignerError::CannotSignRawHash("Trezor")), - } + async fn sign_typed_data( + &self, + payload: &T, + domain: &Eip712Domain, + ) -> alloy_signer::Result + where + Self: Sized, + { + delegate!(self, inner => inner.sign_typed_data(payload, domain)).await } } From 20ce3883548646ee8b25b6e3cf6ca39f26b3b201 Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Thu, 21 Mar 2024 00:01:51 +0400 Subject: [PATCH 13/63] fix wallets after alloy bump --- Cargo.lock | 47 +++++++++++++++++------------ Cargo.toml | 3 ++ crates/cast/bin/cmd/logs.rs | 6 ++-- crates/cast/src/lib.rs | 7 +++-- crates/common/src/fmt/ui.rs | 7 ----- crates/common/src/provider/alloy.rs | 2 +- crates/common/src/types.rs | 9 ++---- crates/wallets/Cargo.toml | 3 ++ crates/wallets/src/error.rs | 3 +- crates/wallets/src/utils.rs | 2 +- crates/wallets/src/wallet_signer.rs | 23 +++++++++----- 11 files changed, 62 insertions(+), 50 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 783a88469423..980a9d860ebd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -390,29 +390,12 @@ dependencies = [ ] [[package]] -name = "alloy-signer-wallet" +name = "alloy-signer-aws" version = "0.1.0" source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" dependencies = [ "alloy-consensus", "alloy-network", - "alloy-primitives", - "alloy-signer", - "async-trait", - "coins-bip32", - "coins-bip39", - "elliptic-curve", - "eth-keystore", - "k256", - "rand 0.8.5", - "thiserror", -] - -[[package]] -name = "alloy-signer-aws" -version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=9ac2c90#9ac2c90d58a9994d4b61c879e33c6af2739a2b4f" -dependencies = [ "alloy-primitives", "alloy-signer", "async-trait", @@ -426,8 +409,10 @@ dependencies = [ [[package]] name = "alloy-signer-ledger" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=9ac2c90#9ac2c90d58a9994d4b61c879e33c6af2739a2b4f" +source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" dependencies = [ + "alloy-consensus", + "alloy-network", "alloy-primitives", "alloy-signer", "async-trait", @@ -441,7 +426,7 @@ dependencies = [ [[package]] name = "alloy-signer-trezor" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=9ac2c90#9ac2c90d58a9994d4b61c879e33c6af2739a2b4f" +source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" dependencies = [ "alloy-consensus", "alloy-network", @@ -454,6 +439,25 @@ dependencies = [ "trezor-client", ] +[[package]] +name = "alloy-signer-wallet" +version = "0.1.0" +source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" +dependencies = [ + "alloy-consensus", + "alloy-network", + "alloy-primitives", + "alloy-signer", + "async-trait", + "coins-bip32", + "coins-bip39", + "elliptic-curve", + "eth-keystore", + "k256", + "rand 0.8.5", + "thiserror", +] + [[package]] name = "alloy-sol-macro" version = "0.6.4" @@ -4001,11 +4005,14 @@ dependencies = [ name = "foundry-wallets" version = "0.2.0" dependencies = [ + "alloy-consensus", + "alloy-network", "alloy-primitives", "alloy-signer", "alloy-signer-aws", "alloy-signer-ledger", "alloy-signer-trezor", + "alloy-signer-wallet", "alloy-sol-types", "async-trait", "aws-config", diff --git a/Cargo.toml b/Cargo.toml index 8e450f885034..a6c247a40469 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -170,6 +170,9 @@ alloy-rpc-trace-types = { git = "https://github.com/klkvr/alloy", rev = "376583d alloy-rpc-types = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } alloy-signer = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } alloy-signer-wallet = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } +alloy-signer-aws = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } +alloy-signer-ledger = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } +alloy-signer-trezor = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } alloy-transport = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } alloy-transport-http = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } alloy-transport-ipc = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } diff --git a/crates/cast/bin/cmd/logs.rs b/crates/cast/bin/cmd/logs.rs index 771ee090d3f1..13b6f0e5dfb6 100644 --- a/crates/cast/bin/cmd/logs.rs +++ b/crates/cast/bin/cmd/logs.rs @@ -1,4 +1,4 @@ -use alloy_rpc_types::{BlockId, BlockNumberOrTag, FilterBlockOption}; +use alloy_rpc_types::{BlockId, BlockNumberOrTag, Filter, FilterBlockOption}; use cast::Cast; use clap::Parser; use ethers_core::{ @@ -8,12 +8,10 @@ use ethers_core::{ }, types::{ValueOrArray, H256, U256}, }; -use alloy_rpc_types::Filter; use ethers_providers::Middleware; use eyre::{Result, WrapErr}; use foundry_cli::{opts::EthereumOpts, utils}; -use foundry_common::types::ToEthers; -use foundry_common::ens::NameOrAddress; +use foundry_common::{ens::NameOrAddress, types::ToEthers}; use foundry_config::Config; use itertools::Itertools; use std::{io, str::FromStr}; diff --git a/crates/cast/src/lib.rs b/crates/cast/src/lib.rs index 500634868a0c..081aa1c1a859 100644 --- a/crates/cast/src/lib.rs +++ b/crates/cast/src/lib.rs @@ -6,7 +6,10 @@ use alloy_primitives::{ Address, Bytes, Keccak256, TxHash, B256, I256, U256, U64, }; use alloy_provider::{ - network::{eip2718::Decodable2718, Ethereum, eip2718::Encodable2718}, + network::{ + eip2718::{Decodable2718, Encodable2718}, + Ethereum, + }, PendingTransaction, PendingTransactionBuilder, Provider, }; use alloy_rlp::{Decodable, Encodable}; @@ -39,12 +42,12 @@ pub use tx::{TxBuilder, TxBuilderOutput, TxBuilderPeekOutput}; use foundry_common::abi::encode_function_args_packed; pub use foundry_evm::*; -pub use tx::{TxBuilder, TxBuilderOutput}; pub use rusoto_core::{ credential::ChainProvider as AwsChainProvider, region::Region as AwsRegion, request::HttpClient as AwsHttpClient, Client as AwsClient, }; pub use rusoto_kms::KmsClient; +pub use tx::{TxBuilder, TxBuilderOutput}; pub mod base; pub mod errors; diff --git a/crates/common/src/fmt/ui.rs b/crates/common/src/fmt/ui.rs index d93caa10e489..fa564933f592 100644 --- a/crates/common/src/fmt/ui.rs +++ b/crates/common/src/fmt/ui.rs @@ -361,13 +361,6 @@ mod temp_ethers { with_alloy!(Address, Bloom, H64, H256, I256, U256, U64); } -/// Convert a U256 to bytes -pub fn to_bytes(uint: ethers_core::types::U256) -> [u8; 32] { - let mut buffer: [u8; 32] = [0; 32]; - uint.to_big_endian(&mut buffer); - buffer -} - /// Returns the `UiFmt::pretty()` formatted attribute of the transactions pub fn get_pretty_tx_attr(transaction: &Transaction, attr: &str) -> Option { match attr { diff --git a/crates/common/src/provider/alloy.rs b/crates/common/src/provider/alloy.rs index 47ec14a7b072..bc8ab8871dec 100644 --- a/crates/common/src/provider/alloy.rs +++ b/crates/common/src/provider/alloy.rs @@ -5,7 +5,7 @@ use crate::{ }; use alloy_primitives::U256; use alloy_provider::{ - network::Ethereum, Network, Provider, ProviderBuilder as AlloyProviderBuilder, RootProvider, + network::Ethereum, Provider, ProviderBuilder as AlloyProviderBuilder, RootProvider, }; use alloy_rpc_client::ClientBuilder; use ethers_middleware::gas_oracle::{GasCategory, GasOracle, Polygon}; diff --git a/crates/common/src/types.rs b/crates/common/src/types.rs index bc40026312ab..bcfed539ff00 100644 --- a/crates/common/src/types.rs +++ b/crates/common/src/types.rs @@ -1,17 +1,14 @@ //! Temporary utility conversion traits between ethers-rs and alloy types. use alloy_primitives::{Address, Bloom, Bytes, B256, B64, I256, U256, U64}; -use alloy_rpc_types::{ - AccessList, AccessListItem, BlockNumberOrTag, -}; -use alloy_signer::Signer; +use alloy_rpc_types::{AccessList, AccessListItem, BlockNumberOrTag}; use alloy_signer_wallet::LocalWallet; use ethers_core::types::{ transaction::eip2930::{ AccessList as EthersAccessList, AccessListItem as EthersAccessListItem, }, - BlockNumber, Bloom as EthersBloom, Bytes as EthersBytes, TransactionRequest, H160, H256, H64, - I256 as EthersI256, U256 as EthersU256, U64 as EthersU64, + BlockNumber, Bloom as EthersBloom, Bytes as EthersBytes, H160, H256, H64, I256 as EthersI256, + U256 as EthersU256, U64 as EthersU64, }; /// Conversion trait to easily convert from Ethers types to Alloy types. diff --git a/crates/wallets/Cargo.toml b/crates/wallets/Cargo.toml index 01b60b579ba9..72bb6b8886b2 100644 --- a/crates/wallets/Cargo.toml +++ b/crates/wallets/Cargo.toml @@ -12,9 +12,12 @@ repository.workspace = true [dependencies] alloy-primitives.workspace = true alloy-signer = { workspace = true, features = ["eip712"] } +alloy-signer-wallet = { workspace = true, features = ["mnemonic", "keystore"] } alloy-signer-aws.workspace = true alloy-signer-ledger.workspace = true alloy-signer-trezor.workspace = true +alloy-network.workspace = true +alloy-consensus.workspace = true alloy-sol-types.workspace = true aws-sdk-kms = { version = "1", default-features = false } diff --git a/crates/wallets/src/error.rs b/crates/wallets/src/error.rs index 1ec2ae89f032..b9a5e34f592a 100644 --- a/crates/wallets/src/error.rs +++ b/crates/wallets/src/error.rs @@ -1,7 +1,8 @@ -use alloy_signer::{k256::ecdsa, WalletError}; +use alloy_signer::k256::ecdsa; use alloy_signer_aws::AwsSignerError; use alloy_signer_ledger::LedgerError; use alloy_signer_trezor::TrezorError; +use alloy_signer_wallet::WalletError; use hex::FromHexError; #[derive(Debug, thiserror::Error)] diff --git a/crates/wallets/src/utils.rs b/crates/wallets/src/utils.rs index d146be299283..082d5b16366a 100644 --- a/crates/wallets/src/utils.rs +++ b/crates/wallets/src/utils.rs @@ -1,8 +1,8 @@ use crate::{error::PrivateKeyError, PendingSigner, WalletSigner}; use alloy_primitives::B256; -use alloy_signer::LocalWallet; use alloy_signer_ledger::HDPath as LedgerHDPath; use alloy_signer_trezor::TrezorHDPath; +use alloy_signer_wallet::LocalWallet; use eyre::{Context, Result}; use foundry_config::Config; use std::{ diff --git a/crates/wallets/src/wallet_signer.rs b/crates/wallets/src/wallet_signer.rs index d0e0535897de..332a21823da8 100644 --- a/crates/wallets/src/wallet_signer.rs +++ b/crates/wallets/src/wallet_signer.rs @@ -1,11 +1,12 @@ use crate::error::WalletSignerError; +use alloy_consensus::SignableTransaction; +use alloy_network::TxSigner; use alloy_primitives::{Address, ChainId, B256}; -use alloy_signer::{ - coins_bip39::English, LocalWallet, MnemonicBuilder, SignableTx, Signature, Signer, -}; +use alloy_signer::{Signature, Signer}; use alloy_signer_aws::AwsSigner; use alloy_signer_ledger::{HDPath as LedgerHDPath, LedgerSigner}; use alloy_signer_trezor::{TrezorHDPath, TrezorSigner}; +use alloy_signer_wallet::{coins_bip39::English, LocalWallet, MnemonicBuilder}; use alloy_sol_types::{Eip712Domain, SolStruct}; use async_trait::async_trait; use aws_config::BehaviorVersion; @@ -131,7 +132,7 @@ macro_rules! delegate { #[async_trait] impl Signer for WalletSigner { /// Signs the given hash. - async fn sign_hash(&self, hash: B256) -> alloy_signer::Result { + async fn sign_hash(&self, hash: &B256) -> alloy_signer::Result { delegate!(self, inner => inner.sign_hash(hash)).await } @@ -139,10 +140,6 @@ impl Signer for WalletSigner { delegate!(self, inner => inner.sign_message(message)).await } - async fn sign_transaction(&self, tx: &mut SignableTx) -> alloy_signer::Result { - delegate!(self, inner => inner.sign_transaction(tx)).await - } - fn address(&self) -> Address { delegate!(self, inner => inner.address()) } @@ -167,6 +164,16 @@ impl Signer for WalletSigner { } } +#[async_trait] +impl TxSigner for WalletSigner { + async fn sign_transaction( + &self, + tx: &mut dyn SignableTransaction, + ) -> alloy_signer::Result { + delegate!(self, inner => inner.sign_transaction(tx)).await + } +} + /// Signers that require user action to be obtained. #[derive(Debug, Clone)] pub enum PendingSigner { From 12fee31ed6d46491d19156b32f6633ccbf686f6f Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Thu, 21 Mar 2024 06:41:05 +0400 Subject: [PATCH 14/63] clean up deps --- Cargo.lock | 12 +- crates/anvil/src/config.rs | 4 +- crates/cast/Cargo.toml | 6 +- crates/cast/bin/cmd/access_list.rs | 41 ++----- crates/cast/bin/cmd/call.rs | 29 +++-- crates/cast/bin/cmd/estimate.rs | 6 +- crates/cast/bin/cmd/find_block.rs | 3 - crates/cast/bin/cmd/logs.rs | 29 ++--- crates/cast/bin/cmd/mktx.rs | 28 ++--- crates/cast/bin/cmd/send.rs | 51 ++++---- crates/cast/bin/cmd/storage.rs | 9 +- crates/cast/bin/cmd/wallet/list.rs | 2 +- crates/cast/bin/cmd/wallet/mod.rs | 19 ++- crates/cast/bin/cmd/wallet/vanity.rs | 3 +- crates/cast/bin/main.rs | 171 +++++++++++---------------- crates/cast/bin/opts.rs | 43 ++++--- crates/cast/bin/tx.rs | 16 ++- crates/cast/src/lib.rs | 31 +++-- crates/cast/src/tx.rs | 27 +++-- crates/cheatcodes/src/env.rs | 2 +- crates/cheatcodes/src/evm.rs | 1 - crates/cheatcodes/src/fs.rs | 6 +- crates/cheatcodes/src/inspector.rs | 2 +- crates/cheatcodes/src/script.rs | 1 - crates/cheatcodes/src/utils.rs | 2 +- crates/cli/Cargo.toml | 5 +- crates/cli/src/utils/mod.rs | 1 - crates/common/Cargo.toml | 1 - crates/common/src/abi.rs | 2 +- crates/common/src/ens.rs | 82 +++++++++---- crates/common/src/fmt/ui.rs | 55 +++++---- crates/evm/core/src/fork/backend.rs | 2 +- crates/verify/src/lib.rs | 2 +- crates/wallets/Cargo.toml | 1 + crates/wallets/src/multi_wallet.rs | 4 +- crates/wallets/src/wallet.rs | 2 +- crates/wallets/src/wallet_signer.rs | 8 ++ 37 files changed, 343 insertions(+), 366 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 980a9d860ebd..4c448b52cbb1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1754,11 +1754,13 @@ dependencies = [ "alloy-dyn-abi", "alloy-json-abi", "alloy-json-rpc", + "alloy-network", "alloy-primitives", "alloy-provider", "alloy-rlp", "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=376583d)", "alloy-signer", + "alloy-signer-wallet", "alloy-transport", "async-trait", "aws-sdk-kms", @@ -1770,12 +1772,8 @@ dependencies = [ "const-hex", "criterion", "dunce", - "eth-keystore", "ethers-contract", "ethers-core", - "ethers-middleware", - "ethers-providers", - "ethers-signers", "evm-disassembler", "evmole", "eyre", @@ -3659,7 +3657,6 @@ dependencies = [ "color-eyre", "dotenvy", "ethers-core", - "ethers-providers", "eyre", "forge-fmt", "foundry-common", @@ -3695,7 +3692,6 @@ dependencies = [ "alloy-pubsub", "alloy-rpc-client", "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=376583d)", - "alloy-signer", "alloy-signer-wallet", "alloy-sol-types", "alloy-transport", @@ -4006,6 +4002,7 @@ name = "foundry-wallets" version = "0.2.0" dependencies = [ "alloy-consensus", + "alloy-dyn-abi", "alloy-network", "alloy-primitives", "alloy-signer", @@ -8094,10 +8091,8 @@ checksum = "212d5dcb2a1ce06d81107c3d0ffa3121fe974b73f068c8282cb1c32328113b6c" dependencies = [ "futures-util", "log", - "native-tls", "rustls", "tokio", - "tokio-native-tls", "tokio-rustls", "tungstenite", "webpki-roots", @@ -8400,7 +8395,6 @@ dependencies = [ "http 0.2.12", "httparse", "log", - "native-tls", "rand 0.8.5", "rustls", "sha1", diff --git a/crates/anvil/src/config.rs b/crates/anvil/src/config.rs index 7a03e22eb2d7..f7ac3e65e2e0 100644 --- a/crates/anvil/src/config.rs +++ b/crates/anvil/src/config.rs @@ -1218,7 +1218,9 @@ pub fn anvil_tmp_dir() -> Option { /// /// This fetches the "latest" block and checks whether the `Block` is fully populated (`hash` field /// is present). This prevents edge cases where anvil forks the "latest" block but `eth_getBlockByNumber` still returns a pending block, -async fn find_latest_fork_block(provider: P) -> Result { +async fn find_latest_fork_block, T: Transport + Clone>( + provider: P, +) -> Result { let mut num = provider.get_block_number().await?; // walk back from the head of the chain, but at most 2 blocks, which should be more than enough diff --git a/crates/cast/Cargo.toml b/crates/cast/Cargo.toml index 407aa008cec7..f1d9f7925f9f 100644 --- a/crates/cast/Cargo.toml +++ b/crates/cast/Cargo.toml @@ -39,11 +39,12 @@ alloy-transport.workspace = true alloy-rpc-types.workspace = true alloy-json-rpc.workspace = true alloy-signer.workspace = true +alloy-signer-wallet = { workspace = true, features = ["mnemonic", "keystore"] } alloy-contract.workspace = true alloy-consensus.workspace = true +alloy-network.workspace = true ethers-core.workspace = true -ethers-providers.workspace = true chrono.workspace = true evm-disassembler.workspace = true @@ -62,9 +63,6 @@ aws-sdk-kms = { version = "1", default-features = false } foundry-cli.workspace = true ethers-contract.workspace = true -ethers-middleware.workspace = true -ethers-signers.workspace = true -eth-keystore = "0.5" clap = { version = "4", features = ["derive", "env", "unicode", "wrap_help"] } clap_complete = "4" diff --git a/crates/cast/bin/cmd/access_list.rs b/crates/cast/bin/cmd/access_list.rs index 88a6fb783c6a..25195f457698 100644 --- a/crates/cast/bin/cmd/access_list.rs +++ b/crates/cast/bin/cmd/access_list.rs @@ -1,9 +1,10 @@ +use alloy_network::Ethereum; use alloy_primitives::Address; use alloy_provider::Provider; use alloy_rpc_types::BlockId; +use alloy_transport::Transport; use cast::{Cast, TxBuilder}; use clap::Parser; -use ethers_providers::Middleware; use eyre::{Result, WrapErr}; use foundry_cli::{ opts::{EthereumOpts, TransactionOpts}, @@ -61,41 +62,26 @@ impl AccessListArgs { let AccessListArgs { to, sig, args, data, tx, eth, block, json: to_json } = self; let config = Config::from(ð); - let provider = utils::get_provider(&config)?; - let alloy_provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_alloy_provider(&config)?; let chain = utils::get_chain(config.chain, &provider).await?; let sender = eth.wallet.sender().await; let to = match to { Some(NameOrAddress::Name(name)) => { - Some(NameOrAddress::Name(name).resolve(&alloy_provider).await?) + Some(NameOrAddress::Name(name).resolve(&provider).await?) } Some(NameOrAddress::Address(addr)) => Some(addr), None => None, }; - access_list( - &provider, - alloy_provider, - sender, - to, - sig, - args, - data, - tx, - chain, - block, - to_json, - ) - .await?; + access_list(&provider, sender, to, sig, args, data, tx, chain, block, to_json).await?; Ok(()) } } #[allow(clippy::too_many_arguments)] -async fn access_list( - provider: M, - alloy_provider: P, +async fn access_list, T: Transport + Clone>( + provider: P, from: Address, to: Option
, sig: Option, @@ -105,16 +91,13 @@ async fn access_list( chain: Chain, block: Option, to_json: bool, -) -> Result<()> -where - M::Error: 'static, -{ - let mut builder = TxBuilder::new(&alloy_provider, from, to, chain, tx.legacy).await?; +) -> Result<()> { + let mut builder = TxBuilder::new(&provider, from, to, chain, tx.legacy).await?; builder .gas(tx.gas_limit) .gas_price(tx.gas_price) .priority_gas_price(tx.priority_gas_price) - .nonce(tx.nonce); + .nonce(tx.nonce.map(|n| n.to())); builder.value(tx.value); @@ -123,12 +106,12 @@ where } if let Some(data) = data { // Note: `sig+args` and `data` are mutually exclusive - builder.set_data(hex::decode(data).wrap_err("Expected hex encoded function data")?); + builder.set_data(hex::decode(data).wrap_err("Expected hex encoded function data")?.into()); } let builder_output = builder.peek(); - let cast = Cast::new(&provider, &alloy_provider); + let cast = Cast::new(&provider); let access_list: String = cast.access_list(builder_output, block, to_json).await?; diff --git a/crates/cast/bin/cmd/call.rs b/crates/cast/bin/cmd/call.rs index 044e2658d9b8..0f57be7747de 100644 --- a/crates/cast/bin/cmd/call.rs +++ b/crates/cast/bin/cmd/call.rs @@ -1,3 +1,5 @@ +use alloy_consensus::Transaction; +use alloy_network::TransactionBuilder; use alloy_primitives::U256; use alloy_provider::{network::Ethereum, Provider}; use alloy_rpc_types::BlockId; @@ -9,7 +11,7 @@ use foundry_cli::{ opts::{EthereumOpts, TransactionOpts}, utils::{self, handle_traces, parse_ether_value, TraceResult}, }; -use foundry_common::{ens::NameOrAddress, types::ToAlloy}; +use foundry_common::ens::NameOrAddress; use foundry_compilers::EvmVersion; use foundry_config::{find_project_root_path, Config}; use foundry_evm::{executors::TracingExecutor, opts::EvmOpts}; @@ -112,27 +114,26 @@ impl CallArgs { } = self; let config = Config::from(ð); - let provider = utils::get_provider(&config)?; - let alloy_provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_alloy_provider(&config)?; let chain = utils::get_chain(config.chain, &provider).await?; let sender = eth.wallet.sender().await; let to = match to { Some(NameOrAddress::Name(name)) => { - Some(NameOrAddress::Name(name).resolve(&alloy_provider).await?) + Some(NameOrAddress::Name(name).resolve(&provider).await?) } Some(NameOrAddress::Address(addr)) => Some(addr), None => None, }; - let mut builder = TxBuilder::new(&alloy_provider, sender, to, chain, tx.legacy).await?; + let mut builder = TxBuilder::new(&provider, sender, to, chain, tx.legacy).await?; builder .gas(tx.gas_limit) .etherscan_api_key(config.get_etherscan_api_key(Some(chain))) .gas_price(tx.gas_price) .priority_gas_price(tx.priority_gas_price) - .nonce(tx.nonce); + .nonce(tx.nonce.map(|n| n.to())); match command { Some(CallSubcommands::Create { code, sig, args, value }) => { @@ -182,11 +183,13 @@ impl CallArgs { let (tx, _) = builder.build(); + let tx = tx.build_unsigned()?; + let trace = TraceResult::from(executor.call_raw_committing( sender, - tx.to_addr().copied().expect("an address to be here").to_alloy(), - tx.data().cloned().unwrap_or_default().to_vec().into(), - tx.value().copied().unwrap_or_default().to_alloy(), + tx.to().to().expect("an address to be here"), + tx.input().to_vec().into(), + tx.value(), )?); handle_traces(trace, &config, chain, labels, debug).await?; @@ -196,8 +199,8 @@ impl CallArgs { } }; - let builder_output = builder.build_alloy(); - println!("{}", Cast::new(provider, alloy_provider).call(builder_output, block).await?); + let builder_output = builder.build(); + println!("{}", Cast::new(provider).call(builder_output, block).await?); Ok(()) } @@ -220,7 +223,7 @@ async fn fill_create, T: Transport + Clone>( data.append(&mut sigdata); } - builder.set_data(data); + builder.set_data(data.into()); Ok(()) } @@ -241,7 +244,7 @@ async fn fill_tx, T: Transport + Clone>( if let Some(data) = data { // Note: `sig+args` and `data` are mutually exclusive - builder.set_data(hex::decode(data).wrap_err("Expected hex encoded function data")?); + builder.set_data(hex::decode(data).wrap_err("Expected hex encoded function data")?.into()); } Ok(()) diff --git a/crates/cast/bin/cmd/estimate.rs b/crates/cast/bin/cmd/estimate.rs index cd3d38757a46..2876d07189b5 100644 --- a/crates/cast/bin/cmd/estimate.rs +++ b/crates/cast/bin/cmd/estimate.rs @@ -85,16 +85,16 @@ impl EstimateArgs { let chain = utils::get_chain(config.chain, &provider).await?; let api_key = config.get_etherscan_api_key(Some(chain)); - let from = from.resolve(&alloy_provider).await?; + let from = from.resolve(&provider).await?; let to = match to { Some(NameOrAddress::Name(name)) => { - Some(NameOrAddress::Name(name).resolve(&alloy_provider).await?) + Some(NameOrAddress::Name(name).resolve(&provider).await?) } Some(NameOrAddress::Address(addr)) => Some(addr), None => None, }; - let mut builder = TxBuilder::new(&alloy_provider, from, to, chain, false).await?; + let mut builder = TxBuilder::new(&provider, from, to, chain, false).await?; builder.etherscan_api_key(api_key); match command { diff --git a/crates/cast/bin/cmd/find_block.rs b/crates/cast/bin/cmd/find_block.rs index 6d0305d88a83..48c23a9613f4 100644 --- a/crates/cast/bin/cmd/find_block.rs +++ b/crates/cast/bin/cmd/find_block.rs @@ -1,11 +1,8 @@ -use alloy_primitives::{U256, U64}; use alloy_provider::Provider; use cast::Cast; use clap::Parser; -use ethers_providers::Middleware; use eyre::Result; use foundry_cli::{opts::RpcOpts, utils}; -use foundry_common::types::{ToAlloy, ToEthers}; use foundry_config::Config; use futures::join; diff --git a/crates/cast/bin/cmd/logs.rs b/crates/cast/bin/cmd/logs.rs index 13b6f0e5dfb6..20c545819217 100644 --- a/crates/cast/bin/cmd/logs.rs +++ b/crates/cast/bin/cmd/logs.rs @@ -1,4 +1,5 @@ -use alloy_rpc_types::{BlockId, BlockNumberOrTag, Filter, FilterBlockOption}; +use alloy_primitives::Address; +use alloy_rpc_types::{BlockId, BlockNumberOrTag, Filter, FilterBlockOption, FilterSet}; use cast::Cast; use clap::Parser; use ethers_core::{ @@ -6,12 +7,11 @@ use ethers_core::{ token::{LenientTokenizer, StrictTokenizer, Tokenizer}, Event, HumanReadableParser, ParamType, RawTopicFilter, Token, Topic, TopicFilter, }, - types::{ValueOrArray, H256, U256}, + types::{H256, U256}, }; -use ethers_providers::Middleware; use eyre::{Result, WrapErr}; use foundry_cli::{opts::EthereumOpts, utils}; -use foundry_common::{ens::NameOrAddress, types::ToEthers}; +use foundry_common::{ens::NameOrAddress, types::ToAlloy}; use foundry_config::Config; use itertools::Itertools; use std::{io, str::FromStr}; @@ -77,21 +77,15 @@ impl LogsArgs { let config = Config::from(ð); let provider = utils::get_alloy_provider(&config)?; - let cast = Cast::new(provider); + let cast = Cast::new(&provider); let address = match address { - Some(address) => { - let address = match address { - NameOrAddress::Name(name) => provider.resolve_name(&name).await?, - NameOrAddress::Address(address) => address, - }; - Some(address) - } + Some(address) => Some(address.resolve(&provider).await?), None => None, }; - let from_block = cast.convert_block_number(from_block).await?.map(ToEthers::to_ethers); - let to_block = cast.convert_block_number(to_block).await?.map(ToEthers::to_ethers); + let from_block = cast.convert_block_number(from_block).await?; + let to_block = cast.convert_block_number(to_block).await?; let filter = build_filter(from_block, to_block, address, sig_or_topic, topics_or_args)?; @@ -137,15 +131,16 @@ fn build_filter( vec![topic_filter.topic0, topic_filter.topic1, topic_filter.topic2, topic_filter.topic3] .into_iter() .map(|topic| match topic { - Topic::Any => None, - Topic::This(topic) => Some(ValueOrArray::Value(Some(topic))), + Topic::Any => vec![], + Topic::This(topic) => vec![topic.to_alloy()], _ => unreachable!(), }) + .map(FilterSet::from) .collect::>(); let filter = Filter { block_option, - address: address.map(ValueOrArray::Value), + address: address.map(|a| vec![a]).unwrap_or_default().into(), topics: [topics[0].clone(), topics[1].clone(), topics[2].clone(), topics[3].clone()], }; diff --git a/crates/cast/bin/cmd/mktx.rs b/crates/cast/bin/cmd/mktx.rs index 8f6db7d47ad8..969355c1bc15 100644 --- a/crates/cast/bin/cmd/mktx.rs +++ b/crates/cast/bin/cmd/mktx.rs @@ -1,14 +1,14 @@ use crate::tx; +use alloy_network::{eip2718::Encodable2718, EthereumSigner, TransactionBuilder}; +use alloy_provider::Provider; +use alloy_signer::Signer; use clap::Parser; -use ethers_middleware::MiddlewareBuilder; -use ethers_providers::Middleware; -use ethers_signers::Signer; use eyre::Result; use foundry_cli::{ opts::{EthereumOpts, TransactionOpts}, utils::{self, get_alloy_provider}, }; -use foundry_common::{ens::NameOrAddress, types::ToAlloy}; +use foundry_common::ens::NameOrAddress; use foundry_config::Config; use std::str::FromStr; @@ -85,25 +85,21 @@ impl MakeTxArgs { let signer = eth.wallet.signer().await?; let from = signer.address(); - tx::validate_from_address(eth.wallet.from, from.to_alloy())?; + tx::validate_from_address(eth.wallet.from, from)?; if resend { - tx.nonce = Some(provider.get_transaction_count(from, None).await?.to_alloy()); + tx.nonce = Some(provider.get_transaction_count(from, None).await?); } - let provider = provider.with_signer(signer); - let alloy_provider = get_alloy_provider(&config)?; + let provider = get_alloy_provider(&config)?; - let (mut tx, _) = - tx::build_tx(&alloy_provider, from.to_alloy(), to, code, sig, args, tx, chain, api_key) - .await?; + let (tx, _) = + tx::build_tx(&provider, from, to, code, sig, args, tx, chain, api_key).await?; - // Fill nonce, gas limit, gas price, and max priority fee per gas if needed - provider.fill_transaction(&mut tx, None).await?; + let tx = tx.build::(&signer.into()).await?; - let signature = provider.sign_transaction(&tx, from).await?; - let signed_tx = tx.rlp_signed(&signature); - println!("{signed_tx}"); + let signed_tx = hex::encode(tx.encoded_2718()); + println!("0x{signed_tx}"); Ok(()) } diff --git a/crates/cast/bin/cmd/send.rs b/crates/cast/bin/cmd/send.rs index f42247ac0841..4bc48c3afd5e 100644 --- a/crates/cast/bin/cmd/send.rs +++ b/crates/cast/bin/cmd/send.rs @@ -1,21 +1,17 @@ use crate::tx; +use alloy_network::{Ethereum, EthereumSigner}; use alloy_primitives::Address; -use alloy_provider::Provider; +use alloy_provider::{Provider, ProviderBuilder}; +use alloy_signer::Signer; +use alloy_transport::Transport; use cast::Cast; use clap::Parser; -use ethers_middleware::SignerMiddleware; -use ethers_providers::Middleware; -use ethers_signers::Signer; use eyre::Result; use foundry_cli::{ opts::{EthereumOpts, TransactionOpts}, utils, }; -use foundry_common::{ - cli_warn, - ens::NameOrAddress, - types::{ToAlloy, ToEthers}, -}; +use foundry_common::{cli_warn, ens::NameOrAddress}; use foundry_config::{Chain, Config}; use std::str::FromStr; @@ -40,7 +36,7 @@ pub struct SendTxArgs { /// The number of confirmations until the receipt is fetched. #[arg(long, default_value = "1")] - confirmations: usize, + confirmations: u64, /// Print the transaction receipt as JSON. #[arg(long, short, help_heading = "Display options")] @@ -113,13 +109,12 @@ impl SendTxArgs { let config = Config::from(ð); let provider = utils::get_alloy_provider(&config)?; - let alloy_provider = utils::get_alloy_provider(&config)?; let chain = utils::get_chain(config.chain, &provider).await?; let api_key = config.get_etherscan_api_key(Some(chain)); let to = match to { Some(NameOrAddress::Name(name)) => { - Some(NameOrAddress::Name(name).resolve(&alloy_provider).await?) + Some(NameOrAddress::Name(name).resolve(&provider).await?) } Some(NameOrAddress::Address(addr)) => Some(addr), None => None, @@ -132,7 +127,7 @@ impl SendTxArgs { if unlocked { // only check current chain id if it was specified in the config if let Some(config_chain) = config.chain { - let current_chain_id = provider.get_chain_id().await?.to(); + let current_chain_id: u64 = provider.get_chain_id().await?.to(); let config_chain_id = config_chain.id(); // switch chain if current chain id is not the same as the one specified in the // config @@ -155,7 +150,6 @@ impl SendTxArgs { cast_send( provider, - alloy_provider, config.sender, to, code, @@ -178,18 +172,18 @@ impl SendTxArgs { let signer = eth.wallet.signer().await?; let from = signer.address(); - tx::validate_from_address(eth.wallet.from, from.to_alloy())?; + tx::validate_from_address(eth.wallet.from, from)?; if resend { - tx.nonce = Some(provider.get_transaction_count(from, None).await?.to_alloy()); + tx.nonce = Some(provider.get_transaction_count(from, None).await?); } - let provider = SignerMiddleware::new_with_provider_chain(provider, signer).await?; + let signer = EthereumSigner::from(signer); + let provider = ProviderBuilder::<_, Ethereum>::new().signer(signer).provider(provider); cast_send( provider, - alloy_provider, - from.to_alloy(), + from, to, code, sig, @@ -207,9 +201,8 @@ impl SendTxArgs { } #[allow(clippy::too_many_arguments)] -async fn cast_send( - provider: M, - alloy_provider: P, +async fn cast_send, T: Transport + Clone>( + provider: P, from: Address, to: Option
, code: Option, @@ -219,20 +212,16 @@ async fn cast_send( chain: Chain, etherscan_api_key: Option, cast_async: bool, - confs: usize, + confs: u64, to_json: bool, -) -> Result<()> -where - M::Error: 'static, -{ +) -> Result<()> { let builder_output = - tx::build_tx(&alloy_provider, from, to, code, sig, args, tx, chain, etherscan_api_key) - .await?; + tx::build_tx(&provider, from, to, code, sig, args, tx, chain, etherscan_api_key).await?; - let cast = Cast::new(provider, alloy_provider); + let cast = Cast::new(provider); let pending_tx = cast.send(builder_output).await?; - let tx_hash = *pending_tx; + let tx_hash = pending_tx.inner().tx_hash(); if cast_async { println!("{tx_hash:#x}"); diff --git a/crates/cast/bin/cmd/storage.rs b/crates/cast/bin/cmd/storage.rs index 7a64506578b7..970186634ef5 100644 --- a/crates/cast/bin/cmd/storage.rs +++ b/crates/cast/bin/cmd/storage.rs @@ -1,7 +1,8 @@ use crate::opts::parse_slot; use alloy_primitives::{Address, B256, U256}; -use alloy_provider::Provider; +use alloy_provider::{network::Ethereum, Provider}; use alloy_rpc_types::BlockId; +use alloy_transport::Transport; use cast::Cast; use clap::Parser; use comfy_table::{presets::ASCII_MARKDOWN, Table}; @@ -118,7 +119,7 @@ impl StorageArgs { eyre::bail!("You must provide an Etherscan API key if you're fetching a remote contract's storage."); } - let chain = utils::get_chain(config.chain, ðers_provider).await?; + let chain = utils::get_chain(config.chain, &provider).await?; let api_key = config.get_etherscan_api_key(Some(chain)).unwrap_or_default(); let client = Client::new(chain, api_key)?; let source = find_source(client, address).await?; @@ -203,7 +204,7 @@ impl StorageValue { } } -async fn fetch_and_print_storage( +async fn fetch_and_print_storage, T: Transport + Clone>( provider: P, address: Address, block: Option, @@ -220,7 +221,7 @@ async fn fetch_and_print_storage( } } -async fn fetch_storage_slots( +async fn fetch_storage_slots, T: Transport + Clone>( provider: P, address: Address, block: Option, diff --git a/crates/cast/bin/cmd/wallet/list.rs b/crates/cast/bin/cmd/wallet/list.rs index 0a9a5a8f2567..d4ca3f013437 100644 --- a/crates/cast/bin/cmd/wallet/list.rs +++ b/crates/cast/bin/cmd/wallet/list.rs @@ -1,7 +1,7 @@ use clap::Parser; use eyre::Result; -use foundry_common::{fs, types::ToAlloy}; +use foundry_common::fs; use foundry_config::Config; use foundry_wallets::multi_wallet::MultiWalletOptsBuilder; diff --git a/crates/cast/bin/cmd/wallet/mod.rs b/crates/cast/bin/cmd/wallet/mod.rs index 944fc1247cac..c595332d958f 100644 --- a/crates/cast/bin/cmd/wallet/mod.rs +++ b/crates/cast/bin/cmd/wallet/mod.rs @@ -1,12 +1,11 @@ use alloy_dyn_abi::TypedData; use alloy_primitives::{Address, Signature}; -use alloy_signer::{ +use alloy_signer::Signer; +use alloy_signer_wallet::{ coins_bip39::{English, Mnemonic}, - LocalWallet, MnemonicBuilder, Signer as AlloySigner, + LocalWallet, MnemonicBuilder, }; use clap::Parser; -use ethers_core::types::transaction::eip712::TypedData; -use ethers_signers::Signer; use eyre::{Context, Result}; use foundry_common::fs; use foundry_config::Config; @@ -271,13 +270,13 @@ impl WalletSubcommands { // data is a json string serde_json::from_str(&message)? }; - wallet.sign_typed_data(&typed_data, typed_data.domain()).await? + wallet.sign_dynamic_typed_data(&typed_data).await? } else if no_hash { - wallet.sign_hash(message.parse()?).await? + wallet.sign_hash(&hex::decode(&message)?[..].try_into()?).await? } else { wallet.sign_message(&Self::hex_str_to_bytes(&message)?).await? }; - println!("0x{sig}"); + println!("0x{}", hex::encode(sig.as_bytes())); } WalletSubcommands::Verify { message, signature, address } => { let recovered_address = Self::recover_address_from_message(&message, &signature)?; @@ -336,11 +335,11 @@ flag to set your key via: }; let mut rng = thread_rng(); - eth_keystore::encrypt_key( - &dir, + let (wallet, _) = LocalWallet::encrypt_keystore( + dir, &mut rng, private_key, - &password, + password, Some(&account_name), )?; let address = wallet.address(); diff --git a/crates/cast/bin/cmd/wallet/vanity.rs b/crates/cast/bin/cmd/wallet/vanity.rs index c3485ddfa96f..28ada95b11cb 100644 --- a/crates/cast/bin/cmd/wallet/vanity.rs +++ b/crates/cast/bin/cmd/wallet/vanity.rs @@ -1,5 +1,6 @@ use alloy_primitives::Address; -use alloy_signer::{k256::ecdsa::SigningKey, utils::secret_key_to_address, LocalWallet, Signer}; +use alloy_signer::{k256::ecdsa::SigningKey, utils::secret_key_to_address}; +use alloy_signer_wallet::LocalWallet; use clap::{builder::TypedValueParser, Parser}; use eyre::Result; use rayon::iter::{self, ParallelIterator}; diff --git a/crates/cast/bin/main.rs b/crates/cast/bin/main.rs index 27fe5a72f25f..884c0a684c79 100644 --- a/crates/cast/bin/main.rs +++ b/crates/cast/bin/main.rs @@ -2,15 +2,16 @@ extern crate tracing; use alloy_primitives::{keccak256, Address, B256}; +use alloy_provider::Provider; +use alloy_rpc_types::{BlockId, BlockNumberOrTag::Latest}; use cast::{Cast, SimpleCast, TxBuilder}; use clap::{CommandFactory, Parser}; use clap_complete::generate; -use ethers_core::types::{BlockId, BlockNumber::Latest}; -use ethers_providers::Middleware; use eyre::Result; use foundry_cli::{handler, prompt, stdin, utils}; use foundry_common::{ abi::get_event, + ens::{lookup_address, resolve_name}, fmt::format_tokens, fs, selectors::{ @@ -18,7 +19,6 @@ use foundry_common::{ import_selectors, parse_signatures, pretty_calldata, ParsedSignatures, SelectorImportData, SelectorType, }, - types::{ToAlloy, ToEthers}, }; use foundry_config::Config; use std::time::Instant; @@ -200,27 +200,22 @@ async fn main() -> Result<()> { CastSubcommand::AccessList(cmd) => cmd.run().await?, CastSubcommand::Age { block, rpc } => { let config = Config::from(&rpc); - let provider = utils::get_provider(&config)?; - let alloy_provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_alloy_provider(&config)?; println!( "{}", - Cast::new(provider, alloy_provider) - .age(block.unwrap_or(BlockId::Number(Latest))) - .await? + Cast::new(provider).age(block.unwrap_or(BlockId::Number(Latest))).await? ); } CastSubcommand::Balance { block, who, ether, rpc, erc20 } => { let config = Config::from(&rpc); - let provider = utils::get_provider(&config)?; - let alloy_provider = utils::get_alloy_provider(&config)?; - let account_addr = who.resolve(&alloy_provider).await?; + let provider = utils::get_alloy_provider(&config)?; + let account_addr = who.resolve(&provider).await?; match erc20 { Some(token) => { let chain = utils::get_chain(config.chain, &provider).await?; let mut builder = - TxBuilder::new(&alloy_provider, Address::ZERO, Some(token), chain, true) - .await?; + TxBuilder::new(&provider, Address::ZERO, Some(token), chain, true).await?; builder .set_args( @@ -228,15 +223,11 @@ async fn main() -> Result<()> { vec![format!("{account_addr:#x}")], ) .await?; - let builder_output = builder.build_alloy(); - println!( - "{}", - Cast::new(&provider, &alloy_provider).call(builder_output, block).await? - ); + let builder_output = builder.build(); + println!("{}", Cast::new(&provider).call(builder_output, block).await?); } None => { - let value = - Cast::new(&provider, &alloy_provider).balance(account_addr, block).await?; + let value = Cast::new(&provider).balance(account_addr, block).await?; if ether { println!("{}", SimpleCast::from_wei(&value.to_string(), "eth")?); } else { @@ -247,74 +238,60 @@ async fn main() -> Result<()> { } CastSubcommand::BaseFee { block, rpc } => { let config = Config::from(&rpc); - let provider = utils::get_provider(&config)?; - let alloy_provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_alloy_provider(&config)?; println!( "{}", - Cast::new(provider, alloy_provider) - .base_fee(block.unwrap_or(BlockId::Number(Latest))) - .await? + Cast::new(provider).base_fee(block.unwrap_or(BlockId::Number(Latest))).await? ); } CastSubcommand::Block { block, full, field, json, rpc } => { let config = Config::from(&rpc); - let provider = utils::get_provider(&config)?; - let alloy_provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_alloy_provider(&config)?; println!( "{}", - Cast::new(provider, alloy_provider) + Cast::new(provider) .block(block.unwrap_or(BlockId::Number(Latest)), full, field, json) .await? ); } CastSubcommand::BlockNumber { rpc } => { let config = Config::from(&rpc); - let provider = utils::get_provider(&config)?; - let alloy_provider = utils::get_alloy_provider(&config)?; - println!("{}", Cast::new(provider, alloy_provider).block_number().await?); + let provider = utils::get_alloy_provider(&config)?; + println!("{}", Cast::new(provider).block_number().await?); } CastSubcommand::Chain { rpc } => { let config = Config::from(&rpc); - let provider = utils::get_provider(&config)?; - let alloy_provider = utils::get_alloy_provider(&config)?; - println!("{}", Cast::new(provider, alloy_provider).chain().await?); + let provider = utils::get_alloy_provider(&config)?; + println!("{}", Cast::new(provider).chain().await?); } CastSubcommand::ChainId { rpc } => { let config = Config::from(&rpc); - let provider = utils::get_provider(&config)?; - let alloy_provider = utils::get_alloy_provider(&config)?; - println!("{}", Cast::new(provider, alloy_provider).chain_id().await?); + let provider = utils::get_alloy_provider(&config)?; + println!("{}", Cast::new(provider).chain_id().await?); } CastSubcommand::Client { rpc } => { let config = Config::from(&rpc); - let provider = utils::get_provider(&config)?; - println!("{}", provider.client_version().await?); + let provider = utils::get_alloy_provider(&config)?; + println!("{}", provider.get_client_version().await?); } CastSubcommand::Code { block, who, disassemble, rpc } => { let config = Config::from(&rpc); - let provider = utils::get_provider(&config)?; - let alloy_provider = utils::get_alloy_provider(&config)?; - let who = who.resolve(&alloy_provider).await?; - println!( - "{}", - Cast::new(provider, alloy_provider).code(who, block, disassemble).await? - ); + let provider = utils::get_alloy_provider(&config)?; + let who = who.resolve(&provider).await?; + println!("{}", Cast::new(provider).code(who, block, disassemble).await?); } CastSubcommand::Codesize { block, who, rpc } => { let config = Config::from(&rpc); - let provider = utils::get_provider(&config)?; - let alloy_provider = utils::get_alloy_provider(&config)?; - let who = who.resolve(&alloy_provider).await?; - println!("{}", Cast::new(provider, alloy_provider).codesize(who, block).await?); + let provider = utils::get_alloy_provider(&config)?; + let who = who.resolve(&provider).await?; + println!("{}", Cast::new(provider).codesize(who, block).await?); } CastSubcommand::ComputeAddress { address, nonce, rpc } => { let config = Config::from(&rpc); - let provider = utils::get_provider(&config)?; - let alloy_provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_alloy_provider(&config)?; let address: Address = stdin::unwrap_line(address)?.parse()?; - let computed = - Cast::new(&provider, alloy_provider).compute_address(address, nonce).await?; + let computed = Cast::new(provider).compute_address(address, nonce).await?; println!("Computed Address: {}", computed.to_checksum(None)); } CastSubcommand::Disassemble { bytecode } => { @@ -346,40 +323,35 @@ async fn main() -> Result<()> { CastSubcommand::FindBlock(cmd) => cmd.run().await?, CastSubcommand::GasPrice { rpc } => { let config = Config::from(&rpc); - let provider = utils::get_provider(&config)?; - let alloy_provider = utils::get_alloy_provider(&config)?; - println!("{}", Cast::new(provider, alloy_provider).gas_price().await?); + let provider = utils::get_alloy_provider(&config)?; + println!("{}", Cast::new(provider).gas_price().await?); } CastSubcommand::Index { key_type, key, slot_number } => { println!("{}", SimpleCast::index(&key_type, &key, &slot_number)?); } CastSubcommand::Implementation { block, who, rpc } => { let config = Config::from(&rpc); - let provider = utils::get_provider(&config)?; - let alloy_provider = utils::get_alloy_provider(&config)?; - let who = who.resolve(&alloy_provider).await?; - println!("{}", Cast::new(provider, alloy_provider).implementation(who, block).await?); + let provider = utils::get_alloy_provider(&config)?; + let who = who.resolve(&provider).await?; + println!("{}", Cast::new(provider).implementation(who, block).await?); } CastSubcommand::Admin { block, who, rpc } => { let config = Config::from(&rpc); - let provider = utils::get_provider(&config)?; - let alloy_provider = utils::get_alloy_provider(&config)?; - let who = who.resolve(&alloy_provider).await?; - println!("{}", Cast::new(provider, alloy_provider).admin(who, block).await?); + let provider = utils::get_alloy_provider(&config)?; + let who = who.resolve(&provider).await?; + println!("{}", Cast::new(provider).admin(who, block).await?); } CastSubcommand::Nonce { block, who, rpc } => { let config = Config::from(&rpc); - let provider = utils::get_provider(&config)?; - let alloy_provider = utils::get_alloy_provider(&config)?; - let who = who.resolve(&alloy_provider).await?; - println!("{}", Cast::new(provider, alloy_provider).nonce(who, block).await?); + let provider = utils::get_alloy_provider(&config)?; + let who = who.resolve(&provider).await?; + println!("{}", Cast::new(provider).nonce(who, block).await?); } CastSubcommand::Proof { address, slots, rpc, block } => { let config = Config::from(&rpc); - let provider = utils::get_provider(&config)?; - let value = provider - .get_proof(address, slots.into_iter().map(|s| s.to_ethers()).collect(), block) - .await?; + let provider = utils::get_alloy_provider(&config)?; + let address = address.resolve(&provider).await?; + let value = provider.get_proof(address, slots.into_iter().collect(), block).await?; println!("{}", serde_json::to_string(&value)?); } CastSubcommand::Rpc(cmd) => cmd.run().await?, @@ -391,27 +363,24 @@ async fn main() -> Result<()> { CastSubcommand::MakeTx(cmd) => cmd.run().await?, CastSubcommand::PublishTx { raw_tx, cast_async, rpc } => { let config = Config::from(&rpc); - let provider = utils::get_provider(&config)?; - let alloy_provider = utils::get_alloy_provider(&config)?; - let cast = Cast::new(&provider, alloy_provider); + let provider = utils::get_alloy_provider(&config)?; + let cast = Cast::new(&provider); let pending_tx = cast.publish(raw_tx).await?; - let tx_hash = *pending_tx; + let tx_hash = pending_tx.inner().tx_hash(); if cast_async { println!("{tx_hash:#x}"); } else { - let receipt = - pending_tx.await?.ok_or_else(|| eyre::eyre!("tx {tx_hash} not found"))?; + let receipt = pending_tx.get_receipt().await?; println!("{}", serde_json::json!(receipt)); } } CastSubcommand::Receipt { tx_hash, field, json, cast_async, confirmations, rpc } => { let config = Config::from(&rpc); - let provider = utils::get_provider(&config)?; - let alloy_provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_alloy_provider(&config)?; println!( "{}", - Cast::new(provider, alloy_provider) + Cast::new(provider) .receipt(tx_hash, field, confirmations, cast_async, json) .await? ); @@ -420,16 +389,12 @@ async fn main() -> Result<()> { CastSubcommand::SendTx(cmd) => cmd.run().await?, CastSubcommand::Tx { tx_hash, field, raw, json, rpc } => { let config = Config::from(&rpc); - let provider = utils::get_provider(&config)?; - let alloy_provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_alloy_provider(&config)?; // Can use either --raw or specify raw as a field let raw = raw || field.as_ref().is_some_and(|f| f == "raw"); - println!( - "{}", - Cast::new(&provider, alloy_provider).transaction(tx_hash, field, raw, json).await? - ) + println!("{}", Cast::new(&provider).transaction(tx_hash, field, raw, json).await?) } // 4Byte @@ -490,12 +455,12 @@ async fn main() -> Result<()> { } CastSubcommand::LookupAddress { who, rpc, verify } => { let config = Config::from(&rpc); - let provider = utils::get_provider(&config)?; + let provider = utils::get_alloy_provider(&config)?; let who = stdin::unwrap_line(who)?; - let name = provider.lookup_address(who.to_ethers()).await?; + let name = lookup_address(who, &provider).await?; if verify { - let address = provider.resolve_name(&name).await?.to_alloy(); + let address = resolve_name(&name, &provider).await?; eyre::ensure!( address == who, "Forward lookup verification failed: got `{name:?}`, expected `{who:?}`" @@ -505,18 +470,18 @@ async fn main() -> Result<()> { } CastSubcommand::ResolveName { who, rpc, verify } => { let config = Config::from(&rpc); - let provider = utils::get_provider(&config)?; + let provider = utils::get_alloy_provider(&config)?; let who = stdin::unwrap_line(who)?; - let address = provider.resolve_name(&who).await?; + let address = resolve_name(&who, &provider).await?; if verify { - let name = provider.lookup_address(address).await?; + let name = lookup_address(address, &provider).await?; assert_eq!( name, who, "forward lookup verification failed. got {name}, expected {who}" ); } - println!("{}", address.to_alloy().to_checksum(None)); + println!("{}", address.to_checksum(None)); } // Misc @@ -578,16 +543,18 @@ async fn main() -> Result<()> { CastSubcommand::Logs(cmd) => cmd.run().await?, CastSubcommand::DecodeTransaction { tx } => { let tx = stdin::unwrap_line(tx)?; - let (tx, sig) = SimpleCast::decode_raw_transaction(&tx)?; + let tx = SimpleCast::decode_raw_transaction(&tx)?; + + todo!(); // Serialize tx, sig and construct a merged json string - let mut tx = serde_json::to_value(&tx)?; - let tx_map = tx.as_object_mut().unwrap(); - serde_json::to_value(sig)?.as_object().unwrap().iter().for_each(|(k, v)| { - tx_map.entry(k).or_insert(v.clone()); - }); + //let mut tx = serde_json::to_value(&tx)?; + //let tx_map = tx.as_object_mut().unwrap(); + //serde_json::to_value(sig)?.as_object().unwrap().iter().for_each(|(k, v)| { + // tx_map.entry(k).or_insert(v.clone()); + //}); - println!("{}", serde_json::to_string_pretty(&tx)?); + //println!("{}", serde_json::to_string_pretty(&tx)?); } }; Ok(()) diff --git a/crates/cast/bin/opts.rs b/crates/cast/bin/opts.rs index adda5087574f..9c23713d47e5 100644 --- a/crates/cast/bin/opts.rs +++ b/crates/cast/bin/opts.rs @@ -5,12 +5,11 @@ use crate::cmd::{ wallet::WalletSubcommands, }; use alloy_primitives::{Address, B256, U256}; -use alloy_rpc_types::BlockId as AlloyBlockId; +use alloy_rpc_types::BlockId; use clap::{Parser, Subcommand, ValueHint}; -use ethers_core::types::{BlockId, NameOrAddress}; use eyre::Result; use foundry_cli::opts::{EtherscanOpts, RpcOpts}; -use foundry_common::ens::NameOrAddress as EnsNameOrAddress; +use foundry_common::ens::NameOrAddress; use std::{path::PathBuf, str::FromStr}; const VERSION_MESSAGE: &str = concat!( @@ -425,7 +424,7 @@ pub enum CastSubcommand { /// The number of confirmations until the receipt is fetched #[arg(long, default_value = "1")] - confirmations: usize, + confirmations: u64, /// Exit immediately if the transaction was not found. #[arg(id = "async", long = "async", env = "CAST_ASYNC", alias = "cast-async")] @@ -527,11 +526,11 @@ pub enum CastSubcommand { /// /// Can also be the tags earliest, finalized, safe, latest, or pending. #[clap(long, short = 'B')] - block: Option, + block: Option, /// The address to get the nonce for. - #[clap(value_parser = EnsNameOrAddress::from_str)] - who: EnsNameOrAddress, + #[clap(value_parser = NameOrAddress::from_str)] + who: NameOrAddress, #[command(flatten)] rpc: RpcOpts, @@ -544,11 +543,11 @@ pub enum CastSubcommand { /// /// Can also be the tags earliest, finalized, safe, latest, or pending. #[clap(long, short = 'B')] - block: Option, + block: Option, /// The address to get the nonce for. - #[clap(value_parser = EnsNameOrAddress::from_str)] - who: EnsNameOrAddress, + #[clap(value_parser = NameOrAddress::from_str)] + who: NameOrAddress, #[command(flatten)] rpc: RpcOpts, @@ -624,11 +623,11 @@ pub enum CastSubcommand { /// /// Can also be the tags earliest, finalized, safe, latest, or pending. #[clap(long, short = 'B')] - block: Option, + block: Option, /// The account to query. - #[clap(value_parser = EnsNameOrAddress::from_str)] - who: EnsNameOrAddress, + #[clap(value_parser = NameOrAddress::from_str)] + who: NameOrAddress, /// Format the balance in ether. #[arg(long, short)] @@ -662,11 +661,11 @@ pub enum CastSubcommand { /// /// Can also be the tags earliest, finalized, safe, latest, or pending. #[clap(long, short = 'B')] - block: Option, + block: Option, /// The contract address. - #[clap(value_parser = EnsNameOrAddress::from_str)] - who: EnsNameOrAddress, + #[clap(value_parser = NameOrAddress::from_str)] + who: NameOrAddress, /// Disassemble bytecodes into individual opcodes. #[arg(long, short)] @@ -683,11 +682,11 @@ pub enum CastSubcommand { /// /// Can also be the tags earliest, finalized, safe, latest, or pending. #[clap(long, short = 'B')] - block: Option, + block: Option, /// The contract address. - #[clap(value_parser = EnsNameOrAddress::from_str)] - who: EnsNameOrAddress, + #[clap(value_parser = NameOrAddress::from_str)] + who: NameOrAddress, #[command(flatten)] rpc: RpcOpts, @@ -774,11 +773,11 @@ pub enum CastSubcommand { /// /// Can also be the tags earliest, finalized, safe, latest, or pending. #[clap(long, short = 'B')] - block: Option, + block: Option, /// The address to get the nonce for. - #[clap(value_parser = EnsNameOrAddress::from_str)] - who: EnsNameOrAddress, + #[clap(value_parser = NameOrAddress::from_str)] + who: NameOrAddress, #[command(flatten)] rpc: RpcOpts, diff --git a/crates/cast/bin/tx.rs b/crates/cast/bin/tx.rs index 1592366137c6..f08c1dde72b5 100644 --- a/crates/cast/bin/tx.rs +++ b/crates/cast/bin/tx.rs @@ -1,5 +1,6 @@ use alloy_primitives::Address; -use alloy_provider::Provider; +use alloy_provider::{network::Ethereum, Provider}; +use alloy_transport::Transport; use cast::{TxBuilder, TxBuilderOutput}; use eyre::Result; use foundry_cli::opts::TransactionOpts; @@ -34,10 +35,15 @@ pub fn validate_to_address(code: &Option, to: &Option) -> } #[allow(clippy::too_many_arguments)] -pub async fn build_tx, T: Into>( +pub async fn build_tx< + P: Provider, + T: Transport + Clone, + F: Into, + TO: Into, +>( provider: &P, from: F, - to: Option, + to: Option, code: Option, sig: Option, args: Vec, @@ -55,7 +61,7 @@ pub async fn build_tx, T: Into, T: Into(&self, builder_output: TxBuilderOutput) -> Result { + pub async fn send( + &self, + builder_output: TxBuilderOutput, + ) -> Result> { let (tx, _) = builder_output; - let res = self.provider.send_transaction(tx).await?.register().await?; + let res = self.provider.send_transaction(tx).await?; - Ok::<_, eyre::Error>(res) + Ok(res) } /// Publishes a raw transaction to the network @@ -267,15 +263,18 @@ where /// # Ok(()) /// # } /// ``` - pub async fn publish(&self, mut raw_tx: String) -> Result { + pub async fn publish( + &self, + mut raw_tx: String, + ) -> Result> { raw_tx = match raw_tx.strip_prefix("0x") { Some(s) => s.to_string(), None => raw_tx, }; let tx = hex::decode(raw_tx)?; - let res = self.provider.send_raw_transaction(&tx).await?.register().await?; + let res = self.provider.send_raw_transaction(&tx).await?; - Ok::<_, eyre::Error>(res) + Ok(res) } /// Estimates the gas cost of a transaction diff --git a/crates/cast/src/tx.rs b/crates/cast/src/tx.rs index 7f87ee7277f7..03c1da8900a1 100644 --- a/crates/cast/src/tx.rs +++ b/crates/cast/src/tx.rs @@ -2,18 +2,17 @@ use std::marker::PhantomData; use crate::errors::FunctionSignatureError; use alloy_json_abi::Function; -use alloy_primitives::{Address, Bytes, U256, U64}; +use alloy_primitives::{Address, Bytes, U256}; use alloy_provider::{ network::{Ethereum, TransactionBuilder}, Provider, }; -use alloy_rpc_types::request::{TransactionInput, TransactionRequest}; +use alloy_rpc_types::request::TransactionRequest; use alloy_transport::Transport; use eyre::Result; use foundry_common::{ abi::{encode_function_args, get_func, get_func_etherscan}, ens::NameOrAddress, - types::ToEthers, }; use foundry_config::Chain; use futures::future::join_all; @@ -265,9 +264,9 @@ async fn resolve_name_args>( #[cfg(test)] mod tests { use crate::TxBuilder; + use alloy_consensus::TypedTransaction; + use alloy_network::TransactionBuilder; use alloy_primitives::{Address, U256}; - use ethers_core::types::{transaction::eip2718::TypedTransaction, NameOrAddress}; - use foundry_common::types::ToEthers; use foundry_config::NamedChain; const ADDR_1: Address = Address::with_last_byte(1); @@ -280,10 +279,12 @@ mod tests { let builder = TxBuilder::new(&provider, ADDR_1, Some(ADDR_2), NamedChain::Mainnet, false).await?; let (tx, args) = builder.build(); - assert_eq!(*tx.from().unwrap(), ADDR_1.to_ethers()); - assert_eq!(*tx.to().unwrap(), NameOrAddress::Address(ADDR_2.to_ethers())); + assert_eq!(tx.from.unwrap(), ADDR_1); + assert_eq!(tx.to.unwrap(), ADDR_2); assert_eq!(args, None); + let tx = tx.build_unsigned().unwrap(); + match tx { TypedTransaction::Eip1559(_) => {} _ => { @@ -320,16 +321,16 @@ mod tests { .gas(Some(U256::from(12u32))) .gas_price(Some(U256::from(34u32))) .value(Some(U256::from(56u32))) - .nonce(Some(U256::from(78u32))); + .nonce(Some(78)); builder.etherscan_api_key(Some(String::from("what a lovely day"))); // not testing for this :-/ let (tx, _) = builder.build(); - assert_eq!(tx.gas().unwrap().as_u32(), 12); - assert_eq!(tx.gas_price().unwrap().as_u32(), 34); - assert_eq!(tx.value().unwrap().as_u32(), 56); - assert_eq!(tx.nonce().unwrap().as_u32(), 78); - assert_eq!(tx.chain_id().unwrap().as_u32(), 1); + assert_eq!(tx.gas, Some(12)); + assert_eq!(tx.gas_price, Some(34)); + assert_eq!(tx.value, Some(56)); + assert_eq!(tx.nonce, Some(78)); + assert_eq!(tx.chain_id, Some(1)); Ok(()) } diff --git a/crates/cheatcodes/src/env.rs b/crates/cheatcodes/src/env.rs index d6aaea149ee3..f8261d7a18f2 100644 --- a/crates/cheatcodes/src/env.rs +++ b/crates/cheatcodes/src/env.rs @@ -230,7 +230,7 @@ impl Cheatcode for envOr_12Call { impl Cheatcode for envOr_13Call { fn apply(&self, _state: &mut Cheatcodes) -> Result { let Self { name, delim, defaultValue } = self; - let default = defaultValue.iter().map(|vec| vec.clone().into()).collect::>(); + let default = defaultValue.iter().map(|vec| vec.clone()).collect::>(); env_array_default(name, delim, &default, &DynSolType::Bytes) } } diff --git a/crates/cheatcodes/src/evm.rs b/crates/cheatcodes/src/evm.rs index 601c97ad0046..b3aa0fdaf461 100644 --- a/crates/cheatcodes/src/evm.rs +++ b/crates/cheatcodes/src/evm.rs @@ -3,7 +3,6 @@ use crate::{Cheatcode, Cheatcodes, CheatsCtxt, Result, Vm::*}; use alloy_genesis::{Genesis, GenesisAccount}; use alloy_primitives::{Address, Bytes, B256, U256}; -use alloy_signer::Signer; use alloy_sol_types::SolValue; use foundry_common::fs::{read_json_file, write_json_file}; use foundry_evm_core::{ diff --git a/crates/cheatcodes/src/fs.rs b/crates/cheatcodes/src/fs.rs index ee5cf35a7fd3..d4e6beb94643 100644 --- a/crates/cheatcodes/src/fs.rs +++ b/crates/cheatcodes/src/fs.rs @@ -372,6 +372,8 @@ fn ffi(state: &Cheatcodes, input: &[String]) -> Result { #[cfg(test)] mod tests { + use alloy_primitives::Bytes; + use super::*; use crate::CheatsConfig; use std::{path::PathBuf, sync::Arc}; @@ -391,7 +393,7 @@ mod tests { let cheats = cheats(); let args = ["echo".to_string(), hex::encode(msg)]; let output = ffi(&cheats, &args).unwrap(); - assert_eq!(output.stdout, msg); + assert_eq!(output.stdout, Bytes::from(msg)); } #[test] @@ -400,7 +402,7 @@ mod tests { let cheats = cheats(); let args = ["echo".to_string(), msg.to_string()]; let output = ffi(&cheats, &args).unwrap(); - assert_eq!(output.stdout, msg.as_bytes()); + assert_eq!(output.stdout, Bytes::from(msg.as_bytes())); } #[test] diff --git a/crates/cheatcodes/src/inspector.rs b/crates/cheatcodes/src/inspector.rs index 10ff4dfa3230..c5d381079c8c 100644 --- a/crates/cheatcodes/src/inspector.rs +++ b/crates/cheatcodes/src/inspector.rs @@ -15,7 +15,7 @@ use crate::{ CheatsConfig, CheatsCtxt, Error, Result, Vm, Vm::AccountAccess, }; -use alloy_primitives::{Address, Bytes, Log, B256, U256, U64}; +use alloy_primitives::{Address, Bytes, Log, B256, U256}; use alloy_rpc_types::request::{TransactionInput, TransactionRequest}; use alloy_sol_types::{SolInterface, SolValue}; use foundry_common::{evm::Breakpoints, provider::alloy::RpcUrl}; diff --git a/crates/cheatcodes/src/script.rs b/crates/cheatcodes/src/script.rs index 60bad56f71fb..a28a8be490ca 100644 --- a/crates/cheatcodes/src/script.rs +++ b/crates/cheatcodes/src/script.rs @@ -2,7 +2,6 @@ use crate::{Cheatcode, CheatsCtxt, DatabaseExt, Result, Vm::*}; use alloy_primitives::{Address, U256}; -use alloy_signer::Signer; use alloy_signer_wallet::LocalWallet; use foundry_config::Config; use foundry_wallets::{multi_wallet::MultiWallet, WalletSigner}; diff --git a/crates/cheatcodes/src/utils.rs b/crates/cheatcodes/src/utils.rs index bf344ee48846..754b7c00d8e6 100644 --- a/crates/cheatcodes/src/utils.rs +++ b/crates/cheatcodes/src/utils.rs @@ -2,7 +2,7 @@ use crate::{Cheatcode, Cheatcodes, CheatsCtxt, DatabaseExt, Result, Vm::*}; use alloy_primitives::{keccak256, B256, U256}; -use alloy_signer::{Signer, SignerSync}; +use alloy_signer::SignerSync; use alloy_signer_wallet::{ coins_bip39::{ ChineseSimplified, ChineseTraditional, Czech, English, French, Italian, Japanese, Korean, diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index b20c8acb5b77..217240a5a873 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -26,7 +26,6 @@ alloy-provider.workspace = true alloy-transport.workspace = true ethers-core.workspace = true -ethers-providers.workspace = true clap = { version = "4", features = ["derive", "env", "unicode", "wrap_help"] } color-eyre.workspace = true @@ -49,5 +48,5 @@ tempfile = "3.7" [features] default = ["rustls"] -rustls = ["ethers-providers/rustls", "foundry-wallets/rustls"] -openssl = ["ethers-providers/openssl", "foundry-compilers/openssl"] +rustls = ["foundry-wallets/rustls"] +openssl = ["foundry-compilers/openssl"] diff --git a/crates/cli/src/utils/mod.rs b/crates/cli/src/utils/mod.rs index 4f7aeb2051f1..f5ed9f1f04a1 100644 --- a/crates/cli/src/utils/mod.rs +++ b/crates/cli/src/utils/mod.rs @@ -3,7 +3,6 @@ use alloy_primitives::{utils::format_units, U256}; use alloy_provider::{network::Ethereum, Provider}; use alloy_transport::Transport; use ethers_core::types::TransactionReceipt; -use ethers_providers::Middleware; use eyre::{ContextCompat, Result}; use foundry_common::types::ToAlloy; use foundry_config::{Chain, Config}; diff --git a/crates/common/Cargo.toml b/crates/common/Cargo.toml index 3ae826ed2a14..6390b53606f5 100644 --- a/crates/common/Cargo.toml +++ b/crates/common/Cargo.toml @@ -31,7 +31,6 @@ alloy-rpc-types.workspace = true alloy-rpc-client.workspace = true alloy-provider.workspace = true alloy-transport.workspace = true -alloy-signer.workspace = true alloy-signer-wallet.workspace = true alloy-transport-http.workspace = true alloy-transport-ws.workspace = true diff --git a/crates/common/src/abi.rs b/crates/common/src/abi.rs index 66a7c98910e2..768d6fbab3a0 100644 --- a/crates/common/src/abi.rs +++ b/crates/common/src/abi.rs @@ -194,7 +194,7 @@ pub fn find_source( } /// Helper function to coerce a value to a [DynSolValue] given a type string -fn coerce_value(ty: &str, arg: &str) -> Result { +pub fn coerce_value(ty: &str, arg: &str) -> Result { let ty = DynSolType::parse(ty)?; Ok(DynSolType::coerce_str(&ty, arg)?) } diff --git a/crates/common/src/ens.rs b/crates/common/src/ens.rs index 5d60ea7859fe..5e1726dff8a1 100644 --- a/crates/common/src/ens.rs +++ b/crates/common/src/ens.rs @@ -6,6 +6,8 @@ use alloy_sol_types::sol; use alloy_transport::Transport; use std::str::FromStr; +use self::EnsResolver::EnsResolverInstance; + // ENS Registry and Resolver contracts. sol! { #[sol(rpc)] @@ -20,12 +22,17 @@ sol! { contract EnsResolver { // Returns the address associated with the specified node. function addr(bytes32 node) view returns (address); + + // Returns the name associated with an ENS node, for reverse records. + function name(bytes32 node) view returns (string); } } /// ENS registry address (`0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e`) pub const ENS_ADDRESS: Address = address!("00000000000C2E074eC69A0dFb2997BA6C7d2e1e"); +pub const ENS_REVERSE_REGISTRAR_DOMAIN: &str = "addr.reverse"; + /// ENS name or Ethereum Address. #[derive(Clone, Debug, PartialEq, Eq)] pub enum NameOrAddress { @@ -41,26 +48,10 @@ impl NameOrAddress { &self, provider: &P, ) -> Result { - let name = match self { - NameOrAddress::Name(name) => name.clone(), - NameOrAddress::Address(addr) => return Ok(*addr), - }; - let node = namehash(&name); - let registry = EnsRegistry::new(ENS_ADDRESS, provider); - let resolver = registry - .resolver(node) - .call() - .await - .map_err(|err| EnsResolutionError::EnsRegistryResolutionFailed(err.to_string()))? - ._0; - let resolver = EnsResolver::new(resolver, provider); - let addr = resolver - .addr(node) - .call() - .await - .map_err(|err| EnsResolutionError::EnsResolutionFailed(err.to_string()))? - ._0; - Ok(addr) + match self { + NameOrAddress::Name(name) => resolve_name(name, provider).await, + NameOrAddress::Address(addr) => Ok(*addr), + } } } @@ -120,6 +111,57 @@ pub fn namehash(name: &str) -> B256 { .into() } +/// Returns the reverse-registrar name of an address. +pub fn reverse_address(addr: Address) -> String { + format!("{addr:?}.{ENS_REVERSE_REGISTRAR_DOMAIN}")[2..].to_string() +} + +pub async fn get_resolver>( + node: B256, + provider: &P, +) -> Result, EnsResolutionError> { + let registry = EnsRegistry::new(ENS_ADDRESS, provider); + let address = registry + .resolver(node) + .call() + .await + .map_err(|err| EnsResolutionError::EnsRegistryResolutionFailed(err.to_string()))? + ._0; + + Ok(EnsResolver::new(address, provider)) +} + +pub async fn resolve_name>( + name: &str, + provider: &P, +) -> Result { + let node = namehash(name); + let resolver = get_resolver(node, provider).await?; + let addr = resolver + .addr(node) + .call() + .await + .map_err(|err| EnsResolutionError::EnsResolutionFailed(err.to_string()))? + ._0; + + Ok(addr) +} + +pub async fn lookup_address>( + address: Address, + provider: &P, +) -> Result { + let node = namehash(&reverse_address(address)); + let resolver = get_resolver(node, provider).await?; + let name = resolver + .name(node) + .call() + .await + .map_err(|err| EnsResolutionError::EnsResolutionFailed(err.to_string()))? + ._0; + + Ok(name) +} #[cfg(test)] mod test { use super::*; diff --git a/crates/common/src/fmt/ui.rs b/crates/common/src/fmt/ui.rs index fa564933f592..ff41f69dca43 100644 --- a/crates/common/src/fmt/ui.rs +++ b/crates/common/src/fmt/ui.rs @@ -279,7 +279,7 @@ value {}{}", self.gas_price.pretty(), self.hash.pretty(), self.input.pretty(), - self.nonce.to_string(), + self.nonce, self.signature.map(|s| s.r.to_be_bytes_vec()).pretty(), self.signature.map(|s| s.s.to_be_bytes_vec()).pretty(), self.to.pretty(), @@ -578,7 +578,7 @@ txType 0 #[test] fn print_block_w_txs() { let block = r#"{"number":"0x3","hash":"0xda53da08ef6a3cbde84c33e51c04f68c3853b6a3731f10baa2324968eee63972","parentHash":"0x689c70c080ca22bc0e681694fa803c1aba16a69c8b6368fed5311d279eb9de90","mixHash":"0x0000000000000000000000000000000000000000000000000000000000000000","nonce":"0x0000000000000000","sha3Uncles":"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347","logsBloom":"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","transactionsRoot":"0x7270c1c4440180f2bd5215809ee3d545df042b67329499e1ab97eb759d31610d","stateRoot":"0x29f32984517a7d25607da485b23cefabfd443751422ca7e603395e1de9bc8a4b","receiptsRoot":"0x056b23fbba480696b65fe5a59b8f2148a1299103c4f57df839233af2cf4ca2d2","miner":"0x0000000000000000000000000000000000000000","difficulty":"0x0","totalDifficulty":"0x0","extraData":"0x","size":"0x3e8","gasLimit":"0x6691b7","gasUsed":"0x5208","timestamp":"0x5ecedbb9","transactions":[{"hash":"0xc3c5f700243de37ae986082fd2af88d2a7c2752a0c0f7b9d6ac47c729d45e067","nonce":"0x2","blockHash":"0xda53da08ef6a3cbde84c33e51c04f68c3853b6a3731f10baa2324968eee63972","blockNumber":"0x3","transactionIndex":"0x0","from":"0xfdcedc3bfca10ecb0890337fbdd1977aba84807a","to":"0xdca8ce283150ab773bcbeb8d38289bdb5661de1e","value":"0x0","gas":"0x15f90","gasPrice":"0x4a817c800","input":"0x","v":"0x25","r":"0x19f2694eb9113656dbea0b925e2e7ceb43df83e601c4116aee9c0dd99130be88","s":"0x73e5764b324a4f7679d890a198ba658ba1c8cd36983ff9797e10b1b89dbb448e"}],"uncles":[]}"#; - let block: Block = serde_json::from_str(block).unwrap(); + let block: Block = serde_json::from_str(block).unwrap(); let output ="\nblockHash 0xda53da08ef6a3cbde84c33e51c04f68c3853b6a3731f10baa2324968eee63972 blockNumber 3 from 0xFdCeDC3bFca10eCb0890337fbdD1977aba84807a @@ -593,7 +593,11 @@ to 0xdca8ce283150AB773BCbeB8d38289bdB5661dE1e transactionIndex 0 v 37 value 0".to_string(); - let generated = block.transactions[0].pretty(); + let txs = match block.transactions { + BlockTransactions::Full(txs) => txs, + _ => panic!("not full transactions"), + }; + let generated = txs[0].pretty(); assert_eq!(generated.as_str(), output.as_str()); } @@ -641,45 +645,40 @@ value 0".to_string(); #[test] fn test_pretty_tx_attr() { let block = r#"{"number":"0x3","hash":"0xda53da08ef6a3cbde84c33e51c04f68c3853b6a3731f10baa2324968eee63972","parentHash":"0x689c70c080ca22bc0e681694fa803c1aba16a69c8b6368fed5311d279eb9de90","mixHash":"0x0000000000000000000000000000000000000000000000000000000000000000","nonce":"0x0000000000000000","sha3Uncles":"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347","logsBloom":"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","transactionsRoot":"0x7270c1c4440180f2bd5215809ee3d545df042b67329499e1ab97eb759d31610d","stateRoot":"0x29f32984517a7d25607da485b23cefabfd443751422ca7e603395e1de9bc8a4b","receiptsRoot":"0x056b23fbba480696b65fe5a59b8f2148a1299103c4f57df839233af2cf4ca2d2","miner":"0x0000000000000000000000000000000000000000","difficulty":"0x0","totalDifficulty":"0x0","extraData":"0x","size":"0x3e8","gasLimit":"0x6691b7","gasUsed":"0x5208","timestamp":"0x5ecedbb9","transactions":[{"hash":"0xc3c5f700243de37ae986082fd2af88d2a7c2752a0c0f7b9d6ac47c729d45e067","nonce":"0x2","blockHash":"0xda53da08ef6a3cbde84c33e51c04f68c3853b6a3731f10baa2324968eee63972","blockNumber":"0x3","transactionIndex":"0x0","from":"0xfdcedc3bfca10ecb0890337fbdd1977aba84807a","to":"0xdca8ce283150ab773bcbeb8d38289bdb5661de1e","value":"0x0","gas":"0x15f90","gasPrice":"0x4a817c800","input":"0x","v":"0x25","r":"0x19f2694eb9113656dbea0b925e2e7ceb43df83e601c4116aee9c0dd99130be88","s":"0x73e5764b324a4f7679d890a198ba658ba1c8cd36983ff9797e10b1b89dbb448e"}],"uncles":[]}"#; - let block: Block = serde_json::from_str(block).unwrap(); - assert_eq!(None, get_pretty_tx_attr(&block.transactions[0], "")); - assert_eq!( - Some("3".to_string()), - get_pretty_tx_attr(&block.transactions[0], "blockNumber") - ); + let block: Block = serde_json::from_str(block).unwrap(); + let txs = match block.transactions { + BlockTransactions::Full(txes) => txes, + _ => panic!("not full transactions"), + }; + assert_eq!(None, get_pretty_tx_attr(&txs[0], "")); + assert_eq!(Some("3".to_string()), get_pretty_tx_attr(&txs[0], "blockNumber")); assert_eq!( Some("0xFdCeDC3bFca10eCb0890337fbdD1977aba84807a".to_string()), - get_pretty_tx_attr(&block.transactions[0], "from") - ); - assert_eq!(Some("90000".to_string()), get_pretty_tx_attr(&block.transactions[0], "gas")); - assert_eq!( - Some("20000000000".to_string()), - get_pretty_tx_attr(&block.transactions[0], "gasPrice") + get_pretty_tx_attr(&txs[0], "from") ); + assert_eq!(Some("90000".to_string()), get_pretty_tx_attr(&txs[0], "gas")); + assert_eq!(Some("20000000000".to_string()), get_pretty_tx_attr(&txs[0], "gasPrice")); assert_eq!( Some("0xc3c5f700243de37ae986082fd2af88d2a7c2752a0c0f7b9d6ac47c729d45e067".to_string()), - get_pretty_tx_attr(&block.transactions[0], "hash") + get_pretty_tx_attr(&txs[0], "hash") ); - assert_eq!(Some("0x".to_string()), get_pretty_tx_attr(&block.transactions[0], "input")); - assert_eq!(Some("2".to_string()), get_pretty_tx_attr(&block.transactions[0], "nonce")); + assert_eq!(Some("0x".to_string()), get_pretty_tx_attr(&txs[0], "input")); + assert_eq!(Some("2".to_string()), get_pretty_tx_attr(&txs[0], "nonce")); assert_eq!( Some("0x19f2694eb9113656dbea0b925e2e7ceb43df83e601c4116aee9c0dd99130be88".to_string()), - get_pretty_tx_attr(&block.transactions[0], "r") + get_pretty_tx_attr(&txs[0], "r") ); assert_eq!( Some("0x73e5764b324a4f7679d890a198ba658ba1c8cd36983ff9797e10b1b89dbb448e".to_string()), - get_pretty_tx_attr(&block.transactions[0], "s") + get_pretty_tx_attr(&txs[0], "s") ); assert_eq!( Some("0xdca8ce283150AB773BCbeB8d38289bdB5661dE1e".into()), - get_pretty_tx_attr(&block.transactions[0], "to") - ); - assert_eq!( - Some("0".to_string()), - get_pretty_tx_attr(&block.transactions[0], "transactionIndex") + get_pretty_tx_attr(&txs[0], "to") ); - assert_eq!(Some("37".to_string()), get_pretty_tx_attr(&block.transactions[0], "v")); - assert_eq!(Some("0".to_string()), get_pretty_tx_attr(&block.transactions[0], "value")); + assert_eq!(Some("0".to_string()), get_pretty_tx_attr(&txs[0], "transactionIndex")); + assert_eq!(Some("37".to_string()), get_pretty_tx_attr(&txs[0], "v")); + assert_eq!(Some("0".to_string()), get_pretty_tx_attr(&txs[0], "value")); } #[test] @@ -715,7 +714,7 @@ value 0".to_string(); } ); - let block: Block<()> = serde_json::from_value(json).unwrap(); + let block: Block = serde_json::from_value(json).unwrap(); assert_eq!(None, get_pretty_block_attr(&block, "")); assert_eq!(Some("7".to_string()), get_pretty_block_attr(&block, "baseFeePerGas")); diff --git a/crates/evm/core/src/fork/backend.rs b/crates/evm/core/src/fork/backend.rs index ca783f332c43..93f1187bb3b1 100644 --- a/crates/evm/core/src/fork/backend.rs +++ b/crates/evm/core/src/fork/backend.rs @@ -4,7 +4,7 @@ use crate::{ fork::{cache::FlushJsonBlockCacheDB, BlockchainDb}, }; use alloy_primitives::{keccak256, Address, Bytes, B256, U256, U64}; -use alloy_provider::{network::Ethereum, Network, Provider}; +use alloy_provider::{network::Ethereum, Provider}; use alloy_rpc_types::{Block, BlockId, Transaction}; use alloy_transport::Transport; use eyre::WrapErr; diff --git a/crates/verify/src/lib.rs b/crates/verify/src/lib.rs index be451d83fbb2..e06c4bb61e30 100644 --- a/crates/verify/src/lib.rs +++ b/crates/verify/src/lib.rs @@ -185,7 +185,7 @@ impl VerifyArgs { // If RPC is not set, the default chain is used let chain = match config.get_rpc_url() { Some(_) => { - let provider = utils::get_provider(&config)?; + let provider = utils::get_alloy_provider(&config)?; utils::get_chain(config.chain, provider).await? } None => config.chain.unwrap_or_default(), diff --git a/crates/wallets/Cargo.toml b/crates/wallets/Cargo.toml index 72bb6b8886b2..31ea5607ce96 100644 --- a/crates/wallets/Cargo.toml +++ b/crates/wallets/Cargo.toml @@ -19,6 +19,7 @@ alloy-signer-trezor.workspace = true alloy-network.workspace = true alloy-consensus.workspace = true alloy-sol-types.workspace = true +alloy-dyn-abi.workspace = true aws-sdk-kms = { version = "1", default-features = false } aws-config = "1" diff --git a/crates/wallets/src/multi_wallet.rs b/crates/wallets/src/multi_wallet.rs index 9f4305ea067d..c95bb8d0e2ae 100644 --- a/crates/wallets/src/multi_wallet.rs +++ b/crates/wallets/src/multi_wallet.rs @@ -397,7 +397,7 @@ impl MultiWalletOpts { #[cfg(test)] mod tests { use super::*; - use std::path::Path; + use std::{path::Path, str::FromStr}; #[test] fn parse_keystore_args() { @@ -437,7 +437,7 @@ mod tests { assert_eq!(unlocked.len(), 1); assert_eq!( unlocked[0].address(), - "ec554aeafe75601aaab43bd4621a22284db566c2".parse().unwrap() + Address::from_str("0xec554aeafe75601aaab43bd4621a22284db566c2").unwrap() ); } diff --git a/crates/wallets/src/wallet.rs b/crates/wallets/src/wallet.rs index 3f0afd27a37b..a4333b40d58f 100644 --- a/crates/wallets/src/wallet.rs +++ b/crates/wallets/src/wallet.rs @@ -175,7 +175,7 @@ mod tests { ]); let signer = wallet.signer().await.unwrap(); assert_eq!( - signer.address().to_alloy(), + signer.address(), Address::from_str("ec554aeafe75601aaab43bd4621a22284db566c2").unwrap() ); } diff --git a/crates/wallets/src/wallet_signer.rs b/crates/wallets/src/wallet_signer.rs index 332a21823da8..997489556c3f 100644 --- a/crates/wallets/src/wallet_signer.rs +++ b/crates/wallets/src/wallet_signer.rs @@ -1,5 +1,6 @@ use crate::error::WalletSignerError; use alloy_consensus::SignableTransaction; +use alloy_dyn_abi::TypedData; use alloy_network::TxSigner; use alloy_primitives::{Address, ChainId, B256}; use alloy_signer::{Signature, Signer}; @@ -162,6 +163,13 @@ impl Signer for WalletSigner { { delegate!(self, inner => inner.sign_typed_data(payload, domain)).await } + + async fn sign_dynamic_typed_data( + &self, + payload: &TypedData, + ) -> alloy_signer::Result { + delegate!(self, inner => inner.sign_dynamic_typed_data(payload)).await + } } #[async_trait] From 7b4e7a58466494de318fd09014fdd7a345326fb0 Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Fri, 22 Mar 2024 02:53:51 +0400 Subject: [PATCH 15/63] use serde on consensus types --- Cargo.lock | 90 +++++++++++++++-------------- Cargo.toml | 48 +++++++-------- crates/cast/Cargo.toml | 2 +- crates/cast/bin/cmd/call.rs | 2 +- crates/cast/bin/main.rs | 11 +--- crates/common/src/provider/alloy.rs | 12 ++-- crates/wallets/src/utils.rs | 2 +- crates/wallets/src/wallet_signer.rs | 2 +- 8 files changed, 83 insertions(+), 86 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 4c448b52cbb1..b99b4961aabf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -90,12 +90,14 @@ dependencies = [ [[package]] name = "alloy-consensus" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" +source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-eips", "alloy-primitives", "alloy-rlp", + "alloy-serde", "c-kzg", + "serde", "sha2", "thiserror", ] @@ -103,14 +105,14 @@ dependencies = [ [[package]] name = "alloy-contract" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" +source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-dyn-abi", "alloy-json-abi", "alloy-network", "alloy-primitives", "alloy-provider", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=376583d)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", "alloy-sol-types", "alloy-transport", "futures", @@ -142,7 +144,7 @@ dependencies = [ [[package]] name = "alloy-eips" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" +source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -152,7 +154,7 @@ dependencies = [ [[package]] name = "alloy-genesis" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" +source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-primitives", "alloy-serde", @@ -162,10 +164,10 @@ dependencies = [ [[package]] name = "alloy-json-abi" version = "0.6.4" -source = "git+https://github.com/alloy-rs/core?rev=6ace151#6ace1519942ac3053a000eaa6792ed6fa0a45a88" +source = "git+https://github.com/klkvr/core?rev=0473659#04736599a54c240ae1708746f45749d95907a192" dependencies = [ "alloy-primitives", - "alloy-sol-type-parser 0.6.4 (git+https://github.com/alloy-rs/core?rev=6ace151)", + "alloy-sol-type-parser 0.6.4 (git+https://github.com/klkvr/core?rev=0473659)", "serde", "serde_json", ] @@ -173,7 +175,7 @@ dependencies = [ [[package]] name = "alloy-json-rpc" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" +source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-primitives", "serde", @@ -184,13 +186,13 @@ dependencies = [ [[package]] name = "alloy-network" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" +source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-consensus", "alloy-eips", "alloy-json-rpc", "alloy-primitives", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=376583d)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", "alloy-signer", "async-trait", "futures-utils-wasm", @@ -201,7 +203,7 @@ dependencies = [ [[package]] name = "alloy-primitives" version = "0.6.4" -source = "git+https://github.com/alloy-rs/core?rev=6ace151#6ace1519942ac3053a000eaa6792ed6fa0a45a88" +source = "git+https://github.com/klkvr/core?rev=0473659#04736599a54c240ae1708746f45749d95907a192" dependencies = [ "alloy-rlp", "arbitrary", @@ -227,15 +229,15 @@ dependencies = [ [[package]] name = "alloy-provider" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" +source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-json-rpc", "alloy-network", "alloy-primitives", "alloy-pubsub", "alloy-rpc-client", - "alloy-rpc-trace-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=376583d)", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=376583d)", + "alloy-rpc-trace-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", "alloy-transport", "alloy-transport-http", "async-stream", @@ -253,7 +255,7 @@ dependencies = [ [[package]] name = "alloy-pubsub" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" +source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-json-rpc", "alloy-primitives", @@ -293,7 +295,7 @@ dependencies = [ [[package]] name = "alloy-rpc-client" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" +source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-json-rpc", "alloy-primitives", @@ -315,10 +317,10 @@ dependencies = [ [[package]] name = "alloy-rpc-trace-types" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" +source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-primitives", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=376583d)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", "alloy-serde", "serde", "serde_json", @@ -338,7 +340,7 @@ dependencies = [ [[package]] name = "alloy-rpc-types" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" +source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-consensus", "alloy-eips", @@ -367,7 +369,7 @@ dependencies = [ [[package]] name = "alloy-serde" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" +source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-primitives", "serde", @@ -377,7 +379,7 @@ dependencies = [ [[package]] name = "alloy-signer" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" +source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-dyn-abi", "alloy-primitives", @@ -392,7 +394,7 @@ dependencies = [ [[package]] name = "alloy-signer-aws" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" +source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-consensus", "alloy-network", @@ -409,7 +411,7 @@ dependencies = [ [[package]] name = "alloy-signer-ledger" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" +source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-consensus", "alloy-network", @@ -426,7 +428,7 @@ dependencies = [ [[package]] name = "alloy-signer-trezor" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" +source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-consensus", "alloy-network", @@ -442,7 +444,7 @@ dependencies = [ [[package]] name = "alloy-signer-wallet" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" +source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-consensus", "alloy-network", @@ -461,7 +463,7 @@ dependencies = [ [[package]] name = "alloy-sol-macro" version = "0.6.4" -source = "git+https://github.com/alloy-rs/core?rev=6ace151#6ace1519942ac3053a000eaa6792ed6fa0a45a88" +source = "git+https://github.com/klkvr/core?rev=0473659#04736599a54c240ae1708746f45749d95907a192" dependencies = [ "alloy-json-abi", "const-hex", @@ -489,7 +491,7 @@ dependencies = [ [[package]] name = "alloy-sol-type-parser" version = "0.6.4" -source = "git+https://github.com/alloy-rs/core?rev=6ace151#6ace1519942ac3053a000eaa6792ed6fa0a45a88" +source = "git+https://github.com/klkvr/core?rev=0473659#04736599a54c240ae1708746f45749d95907a192" dependencies = [ "winnow 0.6.5", ] @@ -497,7 +499,7 @@ dependencies = [ [[package]] name = "alloy-sol-types" version = "0.6.4" -source = "git+https://github.com/alloy-rs/core?rev=6ace151#6ace1519942ac3053a000eaa6792ed6fa0a45a88" +source = "git+https://github.com/klkvr/core?rev=0473659#04736599a54c240ae1708746f45749d95907a192" dependencies = [ "alloy-json-abi", "alloy-primitives", @@ -509,7 +511,7 @@ dependencies = [ [[package]] name = "alloy-transport" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" +source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-json-rpc", "base64 0.22.0", @@ -527,7 +529,7 @@ dependencies = [ [[package]] name = "alloy-transport-http" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" +source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-json-rpc", "alloy-transport", @@ -540,7 +542,7 @@ dependencies = [ [[package]] name = "alloy-transport-ipc" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" +source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-json-rpc", "alloy-pubsub", @@ -558,7 +560,7 @@ dependencies = [ [[package]] name = "alloy-transport-ws" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=376583d#376583dc4eb88e4cce0c5f84fe0db46866e678ed" +source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-pubsub", "alloy-transport", @@ -665,8 +667,8 @@ dependencies = [ "alloy-primitives", "alloy-provider", "alloy-rlp", - "alloy-rpc-trace-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=376583d)", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=376583d)", + "alloy-rpc-trace-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", "alloy-signer", "alloy-signer-wallet", "alloy-sol-types", @@ -728,8 +730,8 @@ dependencies = [ "alloy-network", "alloy-primitives", "alloy-rlp", - "alloy-rpc-trace-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=376583d)", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=376583d)", + "alloy-rpc-trace-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", "anvil-core", "bytes", "c-kzg", @@ -1758,7 +1760,7 @@ dependencies = [ "alloy-primitives", "alloy-provider", "alloy-rlp", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=376583d)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", "alloy-signer", "alloy-signer-wallet", "alloy-transport", @@ -1837,7 +1839,7 @@ dependencies = [ "alloy-dyn-abi", "alloy-json-abi", "alloy-primitives", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=376583d)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", "clap", "criterion", "dirs 5.0.1", @@ -3391,7 +3393,7 @@ dependencies = [ "alloy-dyn-abi", "alloy-json-abi", "alloy-primitives", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=376583d)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", "anvil", "async-trait", "axum", @@ -3507,7 +3509,7 @@ dependencies = [ "alloy-dyn-abi", "alloy-json-abi", "alloy-primitives", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=376583d)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", "async-recursion", "clap", "const-hex", @@ -3606,7 +3608,7 @@ dependencies = [ "alloy-json-abi", "alloy-primitives", "alloy-provider", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=376583d)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", "alloy-signer", "alloy-signer-wallet", "alloy-sol-types", @@ -3691,7 +3693,7 @@ dependencies = [ "alloy-provider", "alloy-pubsub", "alloy-rpc-client", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=376583d)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", "alloy-signer-wallet", "alloy-sol-types", "alloy-transport", @@ -3859,7 +3861,7 @@ dependencies = [ "alloy-json-abi", "alloy-primitives", "alloy-provider", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=376583d)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", "alloy-sol-types", "alloy-transport", "arrayvec", @@ -7799,7 +7801,7 @@ dependencies = [ [[package]] name = "syn-solidity" version = "0.6.4" -source = "git+https://github.com/alloy-rs/core?rev=6ace151#6ace1519942ac3053a000eaa6792ed6fa0a45a88" +source = "git+https://github.com/klkvr/core?rev=0473659#04736599a54c240ae1708746f45749d95907a192" dependencies = [ "paste", "proc-macro2", diff --git a/Cargo.toml b/Cargo.toml index a6c247a40469..635eba438a42 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -156,27 +156,27 @@ ethers-middleware = { version = "2.0.14", default-features = false } ethers-solc = { version = "2.0.14", default-features = false } ## alloy -alloy-consensus = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } -alloy-contract = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } -alloy-eips = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } -alloy-genesis = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } -alloy-json-rpc = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } -alloy-network = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } -alloy-node-bindings = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } -alloy-provider = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } -alloy-pubsub = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } -alloy-rpc-client = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } -alloy-rpc-trace-types = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } -alloy-rpc-types = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } -alloy-signer = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } -alloy-signer-wallet = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } -alloy-signer-aws = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } -alloy-signer-ledger = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } -alloy-signer-trezor = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } -alloy-transport = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } -alloy-transport-http = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } -alloy-transport-ipc = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } -alloy-transport-ws = { git = "https://github.com/klkvr/alloy", rev = "376583d", default-features = false } +alloy-consensus = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-contract = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-eips = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-genesis = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-json-rpc = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-network = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-node-bindings = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-provider = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-pubsub = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-rpc-client = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-rpc-trace-types = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-rpc-types = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-signer = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-signer-wallet = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-signer-aws = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-signer-ledger = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-signer-trezor = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-transport = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-transport-http = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-transport-ipc = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-transport-ws = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } alloy-primitives = { version = "0.6.4", features = ["getrandom"] } alloy-dyn-abi = "0.6.4" alloy-json-abi = "0.6.4" @@ -224,6 +224,6 @@ revm = { git = "https://github.com/bluealloy/revm", rev = "5aff229a" } revm-interpreter = { git = "https://github.com/bluealloy/revm", rev = "5aff229a" } revm-primitives = { git = "https://github.com/bluealloy/revm", rev = "5aff229a" } revm-precompile = { git = "https://github.com/bluealloy/revm", rev = "5aff229a" } -alloy-primitives = { git = "https://github.com/alloy-rs/core", rev = "6ace151" } -alloy-json-abi = { git = "https://github.com/alloy-rs/core", rev = "6ace151" } -alloy-sol-types = { git = "https://github.com/alloy-rs/core", rev = "6ace151" } \ No newline at end of file +alloy-primitives = { git = "https://github.com/klkvr/core", rev = "0473659" } +alloy-json-abi = { git = "https://github.com/klkvr/core", rev = "0473659" } +alloy-sol-types = { git = "https://github.com/klkvr/core", rev = "0473659" } diff --git a/crates/cast/Cargo.toml b/crates/cast/Cargo.toml index f1d9f7925f9f..65c8565dce0d 100644 --- a/crates/cast/Cargo.toml +++ b/crates/cast/Cargo.toml @@ -41,7 +41,7 @@ alloy-json-rpc.workspace = true alloy-signer.workspace = true alloy-signer-wallet = { workspace = true, features = ["mnemonic", "keystore"] } alloy-contract.workspace = true -alloy-consensus.workspace = true +alloy-consensus = { workspace = true, features = ["serde"] } alloy-network.workspace = true ethers-core.workspace = true diff --git a/crates/cast/bin/cmd/call.rs b/crates/cast/bin/cmd/call.rs index 0f57be7747de..22113e625ee1 100644 --- a/crates/cast/bin/cmd/call.rs +++ b/crates/cast/bin/cmd/call.rs @@ -187,7 +187,7 @@ impl CallArgs { let trace = TraceResult::from(executor.call_raw_committing( sender, - tx.to().to().expect("an address to be here"), + *tx.to().to().expect("an address to be here"), tx.input().to_vec().into(), tx.value(), )?); diff --git a/crates/cast/bin/main.rs b/crates/cast/bin/main.rs index 884c0a684c79..13286872f810 100644 --- a/crates/cast/bin/main.rs +++ b/crates/cast/bin/main.rs @@ -545,16 +545,7 @@ async fn main() -> Result<()> { let tx = stdin::unwrap_line(tx)?; let tx = SimpleCast::decode_raw_transaction(&tx)?; - todo!(); - - // Serialize tx, sig and construct a merged json string - //let mut tx = serde_json::to_value(&tx)?; - //let tx_map = tx.as_object_mut().unwrap(); - //serde_json::to_value(sig)?.as_object().unwrap().iter().for_each(|(k, v)| { - // tx_map.entry(k).or_insert(v.clone()); - //}); - - //println!("{}", serde_json::to_string_pretty(&tx)?); + println!("{}", serde_json::to_string_pretty(&tx)?); } }; Ok(()) diff --git a/crates/common/src/provider/alloy.rs b/crates/common/src/provider/alloy.rs index bc8ab8871dec..b025db896e6f 100644 --- a/crates/common/src/provider/alloy.rs +++ b/crates/common/src/provider/alloy.rs @@ -3,9 +3,8 @@ use crate::{ provider::runtime_transport::RuntimeTransportBuilder, ALCHEMY_FREE_TIER_CUPS, REQUEST_TIMEOUT, }; -use alloy_primitives::U256; use alloy_provider::{ - network::Ethereum, Provider, ProviderBuilder as AlloyProviderBuilder, RootProvider, + network::Ethereum, utils::Eip1559Estimation, Provider, ProviderBuilder as AlloyProviderBuilder, RootProvider }; use alloy_rpc_client::ClientBuilder; use ethers_middleware::gas_oracle::{GasCategory, GasOracle, Polygon}; @@ -257,7 +256,7 @@ impl ProviderBuilder { pub async fn estimate_eip1559_fees>( provider: &P, chain: Option, -) -> Result<(U256, U256)> { +) -> Result { let chain = if let Some(chain) = chain { chain } else { @@ -276,7 +275,12 @@ pub async fn estimate_eip1559_fees>( }; let estimator = Polygon::new(chain)?.category(GasCategory::Standard); let (a, b) = estimator.estimate_eip1559_fees().await?; - return Ok((a.to_alloy(), b.to_alloy())); + + let estimation = Eip1559Estimation { + max_fee_per_gas: a.to_alloy(), + max_priority_fee_per_gas: b.to_alloy(), + }; + return Ok(estimation) } _ => {} } diff --git a/crates/wallets/src/utils.rs b/crates/wallets/src/utils.rs index 082d5b16366a..08c95242af33 100644 --- a/crates/wallets/src/utils.rs +++ b/crates/wallets/src/utils.rs @@ -1,7 +1,7 @@ use crate::{error::PrivateKeyError, PendingSigner, WalletSigner}; use alloy_primitives::B256; use alloy_signer_ledger::HDPath as LedgerHDPath; -use alloy_signer_trezor::TrezorHDPath; +use alloy_signer_trezor::HDPath as TrezorHDPath; use alloy_signer_wallet::LocalWallet; use eyre::{Context, Result}; use foundry_config::Config; diff --git a/crates/wallets/src/wallet_signer.rs b/crates/wallets/src/wallet_signer.rs index 997489556c3f..5232f0a249e9 100644 --- a/crates/wallets/src/wallet_signer.rs +++ b/crates/wallets/src/wallet_signer.rs @@ -6,7 +6,7 @@ use alloy_primitives::{Address, ChainId, B256}; use alloy_signer::{Signature, Signer}; use alloy_signer_aws::AwsSigner; use alloy_signer_ledger::{HDPath as LedgerHDPath, LedgerSigner}; -use alloy_signer_trezor::{TrezorHDPath, TrezorSigner}; +use alloy_signer_trezor::{HDPath as TrezorHDPath, TrezorSigner}; use alloy_signer_wallet::{coins_bip39::English, LocalWallet, MnemonicBuilder}; use alloy_sol_types::{Eip712Domain, SolStruct}; use async_trait::async_trait; From 13144ef8dc568582aa9294321f804845cbd94f51 Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Fri, 22 Mar 2024 06:44:12 +0400 Subject: [PATCH 16/63] update TypedTransaction for anvil --- crates/anvil/core/src/eth/transaction/mod.rs | 271 ++++++++---------- .../core/src/eth/transaction/optimism.rs | 102 +------ crates/script/src/transaction.rs | 4 +- 3 files changed, 132 insertions(+), 245 deletions(-) diff --git a/crates/anvil/core/src/eth/transaction/mod.rs b/crates/anvil/core/src/eth/transaction/mod.rs index 72a88c54712c..a0eab8198639 100644 --- a/crates/anvil/core/src/eth/transaction/mod.rs +++ b/crates/anvil/core/src/eth/transaction/mod.rs @@ -5,12 +5,11 @@ use crate::eth::{ utils::eip_to_revm_access_list, }; use alloy_consensus::{ - BlobTransactionSidecar, ReceiptWithBloom, TxEip1559, TxEip2930, TxEip4844, TxEip4844Variant, - TxEip4844WithSidecar, TxLegacy, + BlobTransactionSidecar, ReceiptWithBloom, Signed, TxEip1559, TxEip2930, TxEip4844, TxEip4844Variant, TxEip4844WithSidecar, TxEnvelope, TxLegacy }; -use alloy_network::{Signed, Transaction, TxKind}; -use alloy_primitives::{Address, Bloom, Bytes, Log, Signature, TxHash, B256, U128, U256, U64}; -use alloy_rlp::{Decodable, Encodable}; +use alloy_eips::eip2718::Encodable2718; +use alloy_primitives::{Address, Bloom, Bytes, Log, Signature, TxHash, TxKind, B256, U128, U256, U64, U8}; +use alloy_rlp::{Decodable, Encodable, Header}; use alloy_rpc_types::{ request::TransactionRequest, AccessList, Signature as RpcSignature, Transaction as RpcTransaction, @@ -84,7 +83,7 @@ pub fn transaction_request_to_typed(tx: TransactionRequest) -> Option { Some(TypedTransactionRequest::Legacy(TxLegacy { - nonce: nonce.unwrap_or_default().to::(), + nonce: nonce.unwrap_or_default(), gas_price: gas_price.unwrap_or_default().to::(), gas_limit: gas.unwrap_or_default().to::(), value: value.unwrap_or(U256::ZERO), @@ -100,7 +99,7 @@ pub fn transaction_request_to_typed(tx: TransactionRequest) -> Option { Some(TypedTransactionRequest::EIP2930(TxEip2930 { - nonce: nonce.unwrap_or_default().to::(), + nonce: nonce.unwrap_or_default(), gas_price: gas_price.unwrap_or_default().to(), gas_limit: gas.unwrap_or_default().to::(), value: value.unwrap_or(U256::ZERO), @@ -120,7 +119,7 @@ pub fn transaction_request_to_typed(tx: TransactionRequest) -> Option { // Empty fields fall back to the canonical transaction schema. Some(TypedTransactionRequest::EIP1559(TxEip1559 { - nonce: nonce.unwrap_or_default().to::(), + nonce: nonce.unwrap_or_default(), max_fee_per_gas: max_fee_per_gas.unwrap_or_default().to::(), max_priority_fee_per_gas: max_priority_fee_per_gas.unwrap_or_default().to::(), gas_limit: gas.unwrap_or_default().to::(), @@ -137,7 +136,7 @@ pub fn transaction_request_to_typed(tx: TransactionRequest) -> Option { let tx = TxEip4844 { - nonce: nonce.unwrap_or_default().to::(), + nonce: nonce.unwrap_or_default(), max_fee_per_gas: max_fee_per_gas.unwrap_or_default().to::(), max_priority_fee_per_gas: max_priority_fee_per_gas.unwrap_or_default().to::(), max_fee_per_blob_gas: max_fee_per_blob_gas.unwrap_or_default().to::(), @@ -288,19 +287,19 @@ pub fn to_alloy_transaction_with_hash_and_sender( match transaction { TypedTransaction::Legacy(t) => RpcTransaction { hash, - nonce: U64::from(t.nonce), + nonce: t.tx().nonce, block_hash: None, block_number: None, transaction_index: None, from, to: None, - value: t.value, - gas_price: Some(U128::from(t.gas_price)), - max_fee_per_gas: Some(U128::from(t.gas_price)), - max_priority_fee_per_gas: Some(U128::from(t.gas_price)), - gas: U256::from(t.gas_limit), - input: t.input.clone(), - chain_id: t.chain_id.map(U64::from), + value: t.tx().value, + gas_price: Some(U256::from(t.tx().gas_price)), + max_fee_per_gas: Some(U256::from(t.tx().gas_price)), + max_priority_fee_per_gas: Some(U256::from(t.tx().gas_price)), + gas: U256::from(t.tx().gas_limit), + input: t.tx().input.clone(), + chain_id: t.tx().chain_id, signature: Some(RpcSignature { r: t.signature().r(), s: t.signature().s(), @@ -315,88 +314,88 @@ pub fn to_alloy_transaction_with_hash_and_sender( }, TypedTransaction::EIP2930(t) => RpcTransaction { hash, - nonce: U64::from(t.nonce), + nonce: t.tx().nonce, block_hash: None, block_number: None, transaction_index: None, from, to: None, - value: t.value, - gas_price: Some(U128::from(t.gas_price)), - max_fee_per_gas: Some(U128::from(t.gas_price)), - max_priority_fee_per_gas: Some(U128::from(t.gas_price)), - gas: U256::from(t.gas_limit), - input: t.input.clone(), - chain_id: Some(U64::from(t.chain_id)), + value: t.tx().value, + gas_price: Some(U256::from(t.tx().gas_price)), + max_fee_per_gas: Some(U256::from(t.tx().gas_price)), + max_priority_fee_per_gas: Some(U256::from(t.tx().gas_price)), + gas: U256::from(t.tx().gas_limit), + input: t.tx().input.clone(), + chain_id: Some(t.tx().chain_id), signature: Some(RpcSignature { r: t.signature().r(), s: t.signature().s(), v: U256::from(t.signature().v().y_parity_byte()), y_parity: Some(alloy_rpc_types::Parity::from(t.signature().v().y_parity())), }), - access_list: Some(from_eip_to_alloy_access_list(t.access_list.clone()).0), - transaction_type: Some(U64::from(1)), + access_list: Some(from_eip_to_alloy_access_list(t.tx().access_list.clone())), + transaction_type: Some(U8::from(1)), max_fee_per_blob_gas: None, blob_versioned_hashes: vec![], other: Default::default(), }, TypedTransaction::EIP1559(t) => RpcTransaction { hash, - nonce: U64::from(t.nonce), + nonce: t.tx().nonce, block_hash: None, block_number: None, transaction_index: None, from, to: None, - value: t.value, + value: t.tx().value, gas_price: None, - max_fee_per_gas: Some(U128::from(t.max_fee_per_gas)), - max_priority_fee_per_gas: Some(U128::from(t.max_priority_fee_per_gas)), - gas: U256::from(t.gas_limit), - input: t.input.clone(), - chain_id: Some(U64::from(t.chain_id)), + max_fee_per_gas: Some(U256::from(t.tx().max_fee_per_gas)), + max_priority_fee_per_gas: Some(U256::from(t.tx().max_priority_fee_per_gas)), + gas: U256::from(t.tx().gas_limit), + input: t.tx().input.clone(), + chain_id: Some(t.tx().chain_id), signature: Some(RpcSignature { r: t.signature().r(), s: t.signature().s(), v: U256::from(t.signature().v().y_parity_byte()), y_parity: Some(alloy_rpc_types::Parity::from(t.signature().v().y_parity())), }), - access_list: Some(from_eip_to_alloy_access_list(t.access_list.clone()).0), - transaction_type: Some(U64::from(2)), + access_list: Some(from_eip_to_alloy_access_list(t.tx().access_list.clone())), + transaction_type: Some(U8::from(2)), max_fee_per_blob_gas: None, blob_versioned_hashes: vec![], other: Default::default(), }, TypedTransaction::EIP4844(t) => RpcTransaction { hash, - nonce: U64::from(t.tx().tx().nonce), + nonce: t.tx().tx().nonce, block_hash: None, block_number: None, transaction_index: None, from, to: None, value: t.tx().tx().value, - gas_price: Some(U128::from(t.tx().tx().max_fee_per_gas)), - max_fee_per_gas: Some(U128::from(t.tx().tx().max_fee_per_gas)), - max_priority_fee_per_gas: Some(U128::from(t.tx().tx().max_priority_fee_per_gas)), + gas_price: Some(U256::from(t.tx().tx().max_fee_per_gas)), + max_fee_per_gas: Some(U256::from(t.tx().tx().max_fee_per_gas)), + max_priority_fee_per_gas: Some(U256::from(t.tx().tx().max_priority_fee_per_gas)), gas: U256::from(t.tx().tx().gas_limit), input: t.tx().tx().input.clone(), - chain_id: Some(U64::from(t.tx().tx().chain_id)), + chain_id: Some(t.tx().tx().chain_id), signature: Some(RpcSignature { r: t.signature().r(), s: t.signature().s(), v: U256::from(t.signature().v().y_parity_byte()), y_parity: Some(alloy_rpc_types::Parity::from(t.signature().v().y_parity())), }), - access_list: Some(from_eip_to_alloy_access_list(t.tx().tx().access_list.clone()).0), - transaction_type: Some(U64::from(3)), - max_fee_per_blob_gas: Some(U128::from(t.tx().tx().max_fee_per_blob_gas)), + access_list: Some(from_eip_to_alloy_access_list(t.tx().tx().access_list.clone())), + transaction_type: Some(U8::from(3)), + max_fee_per_blob_gas: Some(U256::from(t.tx().tx().max_fee_per_blob_gas)), blob_versioned_hashes: t.tx().tx().blob_versioned_hashes.clone(), other: Default::default(), }, TypedTransaction::Deposit(t) => RpcTransaction { hash, - nonce: U64::from(t.nonce), + nonce: t.nonce, block_hash: None, block_number: None, transaction_index: None, @@ -408,7 +407,7 @@ pub fn to_alloy_transaction_with_hash_and_sender( max_priority_fee_per_gas: None, gas: U256::from(t.gas_limit), input: t.input.clone().0.into(), - chain_id: t.chain_id().map(U64::from), + chain_id: t.chain_id().map(u64::from), signature: None, access_list: None, transaction_type: None, @@ -447,7 +446,7 @@ impl PendingTransaction { } } - pub fn nonce(&self) -> U256 { + pub fn nonce(&self) -> u64 { self.transaction.nonce() } @@ -472,7 +471,7 @@ impl PendingTransaction { let caller = *self.sender(); match &self.transaction.transaction { TypedTransaction::Legacy(tx) => { - let chain_id = tx.chain_id(); + let chain_id = tx.tx().chain_id; let TxLegacy { nonce, gas_price, gas_limit, value, to, input, .. } = tx.tx(); TxEnv { caller, @@ -590,7 +589,7 @@ impl PendingTransaction { transact_to: transact_to(kind), data: alloy_primitives::Bytes(input.0.clone()), chain_id, - nonce: Some(nonce.to::()), + nonce: Some(*nonce), value: *value, gas_price: U256::ZERO, gas_priority_fee: None, @@ -632,9 +631,9 @@ impl TypedTransaction { pub fn gas_price(&self) -> U256 { U256::from(match self { - TypedTransaction::Legacy(tx) => tx.gas_price, - TypedTransaction::EIP2930(tx) => tx.gas_price, - TypedTransaction::EIP1559(tx) => tx.max_fee_per_gas, + TypedTransaction::Legacy(tx) => tx.tx().gas_price, + TypedTransaction::EIP2930(tx) => tx.tx().gas_price, + TypedTransaction::EIP1559(tx) => tx.tx().max_fee_per_gas, TypedTransaction::EIP4844(tx) => tx.tx().tx().max_fee_per_blob_gas, TypedTransaction::Deposit(_) => 0, }) @@ -642,9 +641,9 @@ impl TypedTransaction { pub fn gas_limit(&self) -> U256 { U256::from(match self { - TypedTransaction::Legacy(tx) => tx.gas_limit, - TypedTransaction::EIP2930(tx) => tx.gas_limit, - TypedTransaction::EIP1559(tx) => tx.gas_limit, + TypedTransaction::Legacy(tx) => tx.tx().gas_limit, + TypedTransaction::EIP2930(tx) => tx.tx().gas_limit, + TypedTransaction::EIP1559(tx) => tx.tx().gas_limit, TypedTransaction::EIP4844(tx) => tx.tx().tx().gas_limit, TypedTransaction::Deposit(tx) => tx.gas_limit.to::(), }) @@ -652,9 +651,9 @@ impl TypedTransaction { pub fn value(&self) -> U256 { U256::from(match self { - TypedTransaction::Legacy(tx) => tx.value, - TypedTransaction::EIP2930(tx) => tx.value, - TypedTransaction::EIP1559(tx) => tx.value, + TypedTransaction::Legacy(tx) => tx.tx().value, + TypedTransaction::EIP2930(tx) => tx.tx().value, + TypedTransaction::EIP1559(tx) => tx.tx().value, TypedTransaction::EIP4844(tx) => tx.tx().tx().value, TypedTransaction::Deposit(tx) => tx.value, }) @@ -662,9 +661,9 @@ impl TypedTransaction { pub fn data(&self) -> &Bytes { match self { - TypedTransaction::Legacy(tx) => &tx.input, - TypedTransaction::EIP2930(tx) => &tx.input, - TypedTransaction::EIP1559(tx) => &tx.input, + TypedTransaction::Legacy(tx) => &tx.tx().input, + TypedTransaction::EIP2930(tx) => &tx.tx().input, + TypedTransaction::EIP1559(tx) => &tx.tx().input, TypedTransaction::EIP4844(tx) => &tx.tx().tx().input, TypedTransaction::Deposit(tx) => &tx.input, } @@ -691,50 +690,50 @@ impl TypedTransaction { match self { TypedTransaction::Legacy(t) => TransactionEssentials { kind: t.tx().to, - input: t.input.clone(), - nonce: U256::from(t.tx().nonce), + input: t.tx().input.clone(), + nonce: t.tx().nonce, gas_limit: U256::from(t.tx().gas_limit), gas_price: Some(U256::from(t.tx().gas_price)), max_fee_per_gas: None, max_priority_fee_per_gas: None, max_fee_per_blob_gas: None, blob_versioned_hashes: None, - value: t.value, + value: t.tx().value, chain_id: t.tx().chain_id, access_list: Default::default(), }, TypedTransaction::EIP2930(t) => TransactionEssentials { kind: t.tx().to, - input: t.input.clone(), - nonce: U256::from(t.tx().nonce), + input: t.tx().input.clone(), + nonce: t.tx().nonce, gas_limit: U256::from(t.tx().gas_limit), gas_price: Some(U256::from(t.tx().gas_price)), max_fee_per_gas: None, max_priority_fee_per_gas: None, max_fee_per_blob_gas: None, blob_versioned_hashes: None, - value: t.value, - chain_id: Some(t.chain_id), - access_list: to_alloy_access_list(t.access_list.clone()), + value: t.tx().value, + chain_id: Some(t.tx().chain_id), + access_list: to_alloy_access_list(t.tx().access_list.clone()), }, TypedTransaction::EIP1559(t) => TransactionEssentials { - kind: t.to, - input: t.input.clone(), - nonce: U256::from(t.nonce), - gas_limit: U256::from(t.gas_limit), + kind: t.tx().to, + input: t.tx().input.clone(), + nonce: t.tx().nonce, + gas_limit: U256::from(t.tx().gas_limit), gas_price: None, - max_fee_per_gas: Some(U256::from(t.max_fee_per_gas)), - max_priority_fee_per_gas: Some(U256::from(t.max_priority_fee_per_gas)), + max_fee_per_gas: Some(U256::from(t.tx().max_fee_per_gas)), + max_priority_fee_per_gas: Some(U256::from(t.tx().max_priority_fee_per_gas)), max_fee_per_blob_gas: None, blob_versioned_hashes: None, - value: t.value, - chain_id: Some(t.chain_id), - access_list: to_alloy_access_list(t.access_list.clone()), + value: t.tx().value, + chain_id: Some(t.tx().chain_id), + access_list: to_alloy_access_list(t.tx().access_list.clone()), }, TypedTransaction::EIP4844(t) => TransactionEssentials { kind: t.tx().tx().to, input: t.tx().tx().input.clone(), - nonce: U256::from(t.tx().tx().nonce), + nonce: t.tx().tx().nonce, gas_limit: U256::from(t.tx().tx().gas_limit), gas_price: Some(U256::from(t.tx().tx().max_fee_per_blob_gas)), max_fee_per_gas: Some(U256::from(t.tx().tx().max_fee_per_gas)), @@ -762,21 +761,21 @@ impl TypedTransaction { } } - pub fn nonce(&self) -> U256 { + pub fn nonce(&self) -> u64 { match self { - TypedTransaction::Legacy(t) => U256::from(t.nonce), - TypedTransaction::EIP2930(t) => U256::from(t.nonce), - TypedTransaction::EIP1559(t) => U256::from(t.nonce), - TypedTransaction::EIP4844(t) => U256::from(t.tx().tx().nonce), - TypedTransaction::Deposit(t) => U256::from(t.nonce), + TypedTransaction::Legacy(t) => t.tx().nonce, + TypedTransaction::EIP2930(t) => t.tx().nonce, + TypedTransaction::EIP1559(t) => t.tx().nonce, + TypedTransaction::EIP4844(t) => t.tx().tx().nonce, + TypedTransaction::Deposit(t) => t.nonce, } } pub fn chain_id(&self) -> Option { match self { - TypedTransaction::Legacy(t) => t.chain_id, - TypedTransaction::EIP2930(t) => Some(t.chain_id), - TypedTransaction::EIP1559(t) => Some(t.chain_id), + TypedTransaction::Legacy(t) => t.tx().chain_id, + TypedTransaction::EIP2930(t) => Some(t.tx().chain_id), + TypedTransaction::EIP1559(t) => Some(t.tx().chain_id), TypedTransaction::EIP4844(t) => Some(t.tx().tx().chain_id), TypedTransaction::Deposit(t) => t.chain_id(), } @@ -854,16 +853,16 @@ impl TypedTransaction { /// Returns what kind of transaction this is pub fn kind(&self) -> &TxKind { match self { - TypedTransaction::Legacy(tx) => &tx.to, - TypedTransaction::EIP2930(tx) => &tx.to, - TypedTransaction::EIP1559(tx) => &tx.to, + TypedTransaction::Legacy(tx) => &tx.tx().to, + TypedTransaction::EIP2930(tx) => &tx.tx().to, + TypedTransaction::EIP1559(tx) => &tx.tx().to, TypedTransaction::EIP4844(tx) => &tx.tx().tx().to, TypedTransaction::Deposit(tx) => &tx.kind, } } /// Returns the callee if this transaction is a call - pub fn to(&self) -> Option
{ + pub fn to(&self) -> Option<&Address> { self.kind().to() } @@ -887,65 +886,49 @@ impl TypedTransaction { impl Encodable for TypedTransaction { fn encode(&self, out: &mut dyn bytes::BufMut) { match self { - TypedTransaction::Legacy(tx) => tx.encode(out), - TypedTransaction::EIP2930(tx) => tx.encode(out), - TypedTransaction::EIP1559(tx) => tx.encode(out), - TypedTransaction::EIP4844(tx) => tx.encode(out), - TypedTransaction::Deposit(tx) => tx.encode(out), + TypedTransaction::Legacy(tx) => TxEnvelope::from(tx.clone()).encode(out), + TypedTransaction::EIP2930(tx) => TxEnvelope::from(tx.clone()).encode(out), + TypedTransaction::EIP1559(tx) => TxEnvelope::from(tx.clone()).encode(out), + TypedTransaction::EIP4844(tx) => TxEnvelope::from(tx.clone()).encode(out), + TypedTransaction::Deposit(tx) => { + let tx_payload_len = tx.fields_len(); + let tx_header_len = Header { list: false, payload_length: tx_payload_len }.length(); + Header { list: false, payload_length: 1 + tx_payload_len + tx_header_len }.encode(out); + out.put_u8(0x7E); + tx.encode(out); + }, } } } impl Decodable for TypedTransaction { fn decode(buf: &mut &[u8]) -> alloy_rlp::Result { - use bytes::Buf; - use std::cmp::Ordering; + let mut h_decode_copy = *buf; + let header = alloy_rlp::Header::decode(&mut h_decode_copy)?; - let first = *buf.first().ok_or(alloy_rlp::Error::Custom("empty slice"))?; + // Legacy TX + if header.list { + return Ok(TxEnvelope::decode(buf)?.into()) + } - // a signed transaction is either encoded as a string (non legacy) or a list (legacy). - // We should not consume the buffer if we are decoding a legacy transaction, so let's - // check if the first byte is between 0x80 and 0xbf. - match first.cmp(&alloy_rlp::EMPTY_LIST_CODE) { - Ordering::Less => { - // strip out the string header - // NOTE: typed transaction encodings either contain a "rlp header" which contains - // the type of the payload and its length, or they do not contain a header and - // start with the tx type byte. - // - // This line works for both types of encodings because byte slices starting with - // 0x01 and 0x02 return a Header { list: false, payload_length: 1 } when input to - // Header::decode. - // If the encoding includes a header, the header will be properly decoded and - // consumed. - // Otherwise, header decoding will succeed but nothing is consumed. - let _header = alloy_rlp::Header::decode(buf)?; - let tx_type = *buf.first().ok_or(alloy_rlp::Error::Custom( - "typed tx cannot be decoded from an empty slice", - ))?; - if tx_type == 0x01 { - buf.advance(1); - as Decodable>::decode(buf).map(TypedTransaction::EIP2930) - } else if tx_type == 0x02 { - buf.advance(1); - as Decodable>::decode(buf).map(TypedTransaction::EIP1559) - } else if tx_type == 0x03 { - buf.advance(1); - as Decodable>::decode(buf) - .map(TypedTransaction::EIP4844) - } else if tx_type == 0x7E { - buf.advance(1); - ::decode(buf).map(TypedTransaction::Deposit) - } else { - Err(alloy_rlp::Error::Custom("invalid tx type")) - } - } - Ordering::Equal => { - Err(alloy_rlp::Error::Custom("an empty list is not a valid transaction encoding")) - } - Ordering::Greater => { - as Decodable>::decode(buf).map(TypedTransaction::Legacy) - } + // Check byte after header + let ty = *h_decode_copy.first().ok_or(alloy_rlp::Error::Custom("empty slice"))?; + + if ty != 0x7E { + Ok(TxEnvelope::decode(buf)?.into()) + } else { + Ok(Self::Deposit(DepositTransaction::decode(&mut h_decode_copy)?)) + } + } +} + +impl From for TypedTransaction { + fn from(value: TxEnvelope) -> Self { + match value { + TxEnvelope::Legacy(tx) => TypedTransaction::Legacy(tx), + TxEnvelope::Eip2930(tx) => TypedTransaction::EIP2930(tx), + TxEnvelope::Eip1559(tx) => TypedTransaction::EIP1559(tx), + TxEnvelope::Eip4844(tx) => TypedTransaction::EIP4844(tx), } } } @@ -954,7 +937,7 @@ impl Decodable for TypedTransaction { pub struct TransactionEssentials { pub kind: TxKind, pub input: Bytes, - pub nonce: U256, + pub nonce: u64, pub gas_limit: U256, pub gas_price: Option, pub max_fee_per_gas: Option, diff --git a/crates/anvil/core/src/eth/transaction/optimism.rs b/crates/anvil/core/src/eth/transaction/optimism.rs index bcbcec22014a..da4447b57c00 100644 --- a/crates/anvil/core/src/eth/transaction/optimism.rs +++ b/crates/anvil/core/src/eth/transaction/optimism.rs @@ -142,102 +142,6 @@ impl DepositTransactionRequest { } } -impl Transaction for DepositTransactionRequest { - type Signature = Signature; - - fn chain_id(&self) -> Option { - None - } - - fn gas_limit(&self) -> u64 { - self.gas_limit.to::() - } - - fn nonce(&self) -> u64 { - u64::MAX - } - - fn decode_signed(buf: &mut &[u8]) -> alloy_rlp::Result> - where - Self: Sized, - { - let header = alloy_rlp::Header::decode(buf)?; - if !header.list { - return Err(alloy_rlp::Error::UnexpectedString); - } - - let tx = Self::decode_inner(buf)?; - let signature = Signature::decode_rlp_vrs(buf)?; - - Ok(tx.into_signed(signature)) - } - - fn encode_signed(&self, signature: &Signature, out: &mut dyn bytes::BufMut) { - self.encode_with_signature(signature, out) - } - - fn gas_price(&self) -> Option { - None - } - - fn input(&self) -> &[u8] { - &self.input - } - - fn input_mut(&mut self) -> &mut Bytes { - &mut self.input - } - - fn into_signed(self, signature: Signature) -> alloy_consensus::Signed - where - Self: Sized, - { - alloy_consensus::Signed::new_unchecked(self.clone(), signature, self.signature_hash()) - } - - fn set_chain_id(&mut self, _chain_id: ChainId) {} - - fn set_gas_limit(&mut self, limit: u64) { - self.gas_limit = U256::from(limit); - } - - fn set_gas_price(&mut self, _price: U256) {} - - fn set_input(&mut self, data: Bytes) { - self.input = data; - } - - fn set_nonce(&mut self, _nonce: u64) {} - - fn set_to(&mut self, to: TxKind) { - self.kind = to; - } - - fn set_value(&mut self, value: U256) { - self.value = value; - } - - fn signature_hash(&self) -> B256 { - self.signature_hash() - } - - fn to(&self) -> TxKind { - self.kind - } - - fn value(&self) -> U256 { - self.value - } - - fn encode_for_signing(&self, out: &mut dyn alloy_rlp::BufMut) { - self.encode_for_signing(out) - } - - fn payload_len_for_signature(&self) -> usize { - self.payload_len_for_signature() - } -} - impl From for DepositTransactionRequest { fn from(tx: DepositTransaction) -> Self { Self { @@ -264,7 +168,7 @@ impl Encodable for DepositTransactionRequest { /// See #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct DepositTransaction { - pub nonce: U256, + pub nonce: u64, pub source_hash: B256, pub from: Address, pub kind: TxKind, @@ -276,7 +180,7 @@ pub struct DepositTransaction { } impl DepositTransaction { - pub fn nonce(&self) -> &U256 { + pub fn nonce(&self) -> &u64 { &self.nonce } @@ -335,7 +239,7 @@ impl DepositTransaction { /// - `input` pub fn decode_inner(buf: &mut &[u8]) -> Result { Ok(Self { - nonce: U256::ZERO, + nonce: 0, source_hash: Decodable::decode(buf)?, from: Decodable::decode(buf)?, kind: Decodable::decode(buf)?, diff --git a/crates/script/src/transaction.rs b/crates/script/src/transaction.rs index 80a2814207aa..cea8ed326772 100644 --- a/crates/script/src/transaction.rs +++ b/crates/script/src/transaction.rs @@ -1,6 +1,6 @@ use super::{artifacts::ArtifactInfo, ScriptResult}; use alloy_dyn_abi::JsonAbiExt; -use alloy_primitives::{Address, Bytes, B256}; +use alloy_primitives::{Address, Bytes, B256, U256}; use alloy_rpc_types::request::TransactionRequest; use ethers_core::types::{ transaction::eip2718::TypedTransaction, NameOrAddress, @@ -70,7 +70,7 @@ impl TransactionWithMetadata { to: transaction.to.map(ToEthers::to_ethers).map(Into::into), value: transaction.value.map(ToEthers::to_ethers), data: transaction.input.into_input().map(ToEthers::to_ethers), - nonce: transaction.nonce.map(|n| n.to::().into()), + nonce: transaction.nonce.map(U256::from), gas: transaction.gas.map(ToEthers::to_ethers), ..Default::default() }), From 3077ad873426b9612b6cdedb7b4fa98c2b61c95a Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Fri, 22 Mar 2024 08:23:45 +0400 Subject: [PATCH 17/63] make anvil compile --- Cargo.lock | 114 ++++++++---------- Cargo.toml | 10 +- crates/anvil/core/src/eth/transaction/mod.rs | 36 ++++-- .../core/src/eth/transaction/optimism.rs | 78 ++++++++++-- crates/anvil/src/cmd.rs | 2 +- crates/anvil/src/config.rs | 8 +- crates/anvil/src/eth/api.rs | 48 +++----- crates/anvil/src/eth/backend/db.rs | 7 +- crates/anvil/src/eth/backend/executor.rs | 2 +- crates/anvil/src/eth/backend/fork.rs | 12 +- crates/anvil/src/eth/backend/mem/mod.rs | 52 ++++---- crates/anvil/src/eth/backend/mem/state.rs | 12 +- crates/anvil/src/eth/backend/mem/storage.rs | 3 +- crates/anvil/src/eth/fees.rs | 8 +- crates/anvil/src/eth/sign.rs | 18 ++- crates/anvil/src/lib.rs | 2 +- crates/anvil/src/pubsub.rs | 3 +- crates/common/src/provider/alloy.rs | 3 +- 18 files changed, 227 insertions(+), 191 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b99b4961aabf..7785488b33d6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -112,7 +112,7 @@ dependencies = [ "alloy-network", "alloy-primitives", "alloy-provider", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", + "alloy-rpc-types", "alloy-sol-types", "alloy-transport", "futures", @@ -192,7 +192,7 @@ dependencies = [ "alloy-eips", "alloy-json-rpc", "alloy-primitives", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", + "alloy-rpc-types", "alloy-signer", "async-trait", "futures-utils-wasm", @@ -236,8 +236,8 @@ dependencies = [ "alloy-primitives", "alloy-pubsub", "alloy-rpc-client", - "alloy-rpc-trace-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", + "alloy-rpc-trace-types", + "alloy-rpc-types", "alloy-transport", "alloy-transport-http", "async-stream", @@ -320,23 +320,12 @@ version = "0.1.0" source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-primitives", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", + "alloy-rpc-types", "alloy-serde", "serde", "serde_json", ] -[[package]] -name = "alloy-rpc-trace-types" -version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=9ac2c90#9ac2c90d58a9994d4b61c879e33c6af2739a2b4f" -dependencies = [ - "alloy-primitives", - "alloy-rpc-types 0.1.0 (git+https://github.com/alloy-rs/alloy?rev=9ac2c90)", - "serde", - "serde_json", -] - [[package]] name = "alloy-rpc-types" version = "0.1.0" @@ -353,19 +342,6 @@ dependencies = [ "thiserror", ] -[[package]] -name = "alloy-rpc-types" -version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=9ac2c90#9ac2c90d58a9994d4b61c879e33c6af2739a2b4f" -dependencies = [ - "alloy-primitives", - "alloy-rlp", - "itertools 0.12.1", - "serde", - "serde_json", - "thiserror", -] - [[package]] name = "alloy-serde" version = "0.1.0" @@ -667,8 +643,8 @@ dependencies = [ "alloy-primitives", "alloy-provider", "alloy-rlp", - "alloy-rpc-trace-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", + "alloy-rpc-trace-types", + "alloy-rpc-types", "alloy-signer", "alloy-signer-wallet", "alloy-sol-types", @@ -730,8 +706,8 @@ dependencies = [ "alloy-network", "alloy-primitives", "alloy-rlp", - "alloy-rpc-trace-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", + "alloy-rpc-trace-types", + "alloy-rpc-types", "anvil-core", "bytes", "c-kzg", @@ -1537,9 +1513,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" -version = "2.4.2" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed570934406eb16438a4e976b1b4500774099c13b8cb96eec99f620f05090ddf" +checksum = "cf4b9d6a944f767f8e5e0db018570623c85f3d925ac718db4e06d0187adb21c1" dependencies = [ "arbitrary", "serde", @@ -1760,7 +1736,7 @@ dependencies = [ "alloy-primitives", "alloy-provider", "alloy-rlp", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", + "alloy-rpc-types", "alloy-signer", "alloy-signer-wallet", "alloy-transport", @@ -1839,7 +1815,7 @@ dependencies = [ "alloy-dyn-abi", "alloy-json-abi", "alloy-primitives", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", + "alloy-rpc-types", "clap", "criterion", "dirs 5.0.1", @@ -2326,7 +2302,7 @@ version = "0.27.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f476fe445d41c9e991fd07515a6f463074b782242ccf4a5b7b1d1012e70824df" dependencies = [ - "bitflags 2.4.2", + "bitflags 2.5.0", "crossterm_winapi", "libc", "mio", @@ -3393,7 +3369,7 @@ dependencies = [ "alloy-dyn-abi", "alloy-json-abi", "alloy-primitives", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", + "alloy-rpc-types", "anvil", "async-trait", "axum", @@ -3509,7 +3485,7 @@ dependencies = [ "alloy-dyn-abi", "alloy-json-abi", "alloy-primitives", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", + "alloy-rpc-types", "async-recursion", "clap", "const-hex", @@ -3608,7 +3584,7 @@ dependencies = [ "alloy-json-abi", "alloy-primitives", "alloy-provider", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", + "alloy-rpc-types", "alloy-signer", "alloy-signer-wallet", "alloy-sol-types", @@ -3693,7 +3669,7 @@ dependencies = [ "alloy-provider", "alloy-pubsub", "alloy-rpc-client", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", + "alloy-rpc-types", "alloy-signer-wallet", "alloy-sol-types", "alloy-transport", @@ -3861,7 +3837,7 @@ dependencies = [ "alloy-json-abi", "alloy-primitives", "alloy-provider", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", + "alloy-rpc-types", "alloy-sol-types", "alloy-transport", "arrayvec", @@ -4288,7 +4264,7 @@ version = "0.12.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e874f41437441c02991dcea76990b9058fadfc54b02ab4dd06ab2218af43897" dependencies = [ - "bitflags 2.4.2", + "bitflags 2.5.0", "bstr", "gix-path", "libc", @@ -4334,7 +4310,7 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c07c98204529ac3f24b34754540a852593d2a4c7349008df389240266627a72a" dependencies = [ - "bitflags 2.4.2", + "bitflags 2.5.0", "bstr", "gix-features", "gix-path", @@ -4419,7 +4395,7 @@ version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9615cbd6b456898aeb942cd75e5810c382fbfc48dbbff2fa23ebd2d33dcbe9c7" dependencies = [ - "bitflags 2.4.2", + "bitflags 2.5.0", "gix-path", "libc", "windows", @@ -5211,7 +5187,7 @@ version = "0.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85c833ca1e66078851dba29046874e38f08b2c883700aa29a03ddd3b23814ee8" dependencies = [ - "bitflags 2.4.2", + "bitflags 2.5.0", "libc", "redox_syscall", ] @@ -5500,7 +5476,7 @@ version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ab2156c4fce2f8df6c499cc1c763e4394b7482525bf2a9701c9d79d215f519e4" dependencies = [ - "bitflags 2.4.2", + "bitflags 2.5.0", "cfg-if", "cfg_aliases", "libc", @@ -5750,7 +5726,7 @@ version = "0.10.64" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95a0481286a310808298130d22dd1fef0fa571e05a8f44ec801801e84b216b1f" dependencies = [ - "bitflags 2.4.2", + "bitflags 2.5.0", "cfg-if", "foreign-types", "libc", @@ -6412,7 +6388,7 @@ checksum = "31b476131c3c86cb68032fdc5cb6d5a1045e3e42d96b69fa599fd77701e1f5bf" dependencies = [ "bit-set", "bit-vec", - "bitflags 2.4.2", + "bitflags 2.5.0", "lazy_static", "num-traits", "rand 0.8.5", @@ -6461,7 +6437,7 @@ version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dce76ce678ffc8e5675b22aa1405de0b7037e2fdf8913fea40d1926c6fe1e6e7" dependencies = [ - "bitflags 2.4.2", + "bitflags 2.5.0", "memchr", "pulldown-cmark-escape", "unicase", @@ -6590,7 +6566,7 @@ version = "0.24.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ebc917cfb527a566c37ecb94c7e3fd098353516fb4eb6bea17015ade0182425" dependencies = [ - "bitflags 2.4.2", + "bitflags 2.5.0", "cassowary", "crossterm", "indoc", @@ -6753,8 +6729,9 @@ dependencies = [ [[package]] name = "revm" -version = "7.1.0" -source = "git+https://github.com/bluealloy/revm?rev=5aff229a#5aff229a1046f410e13e5512df036707144668cc" +version = "7.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24fd3ed4b62dc61c647552d8b781811ae25ec74d23309055077e4dfb392444d2" dependencies = [ "auto_impl", "cfg-if", @@ -6768,11 +6745,10 @@ dependencies = [ [[package]] name = "revm-inspectors" version = "0.1.0" -source = "git+https://github.com/paradigmxyz/evm-inspectors?rev=ba0b6ab#ba0b6ab695802c752601f17f5c941b62a067ad64" dependencies = [ "alloy-primitives", - "alloy-rpc-trace-types 0.1.0 (git+https://github.com/alloy-rs/alloy?rev=9ac2c90)", - "alloy-rpc-types 0.1.0 (git+https://github.com/alloy-rs/alloy?rev=9ac2c90)", + "alloy-rpc-trace-types", + "alloy-rpc-types", "alloy-sol-types", "anstyle", "colorchoice", @@ -6784,8 +6760,9 @@ dependencies = [ [[package]] name = "revm-interpreter" -version = "3.3.0" -source = "git+https://github.com/bluealloy/revm?rev=5aff229a#5aff229a1046f410e13e5512df036707144668cc" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f0a1818f8c876b0d71a0714217c34da7df8a42c0462750768779d55680e4554" dependencies = [ "revm-primitives", "serde", @@ -6793,8 +6770,9 @@ dependencies = [ [[package]] name = "revm-precompile" -version = "5.0.0" -source = "git+https://github.com/bluealloy/revm?rev=5aff229a#5aff229a1046f410e13e5512df036707144668cc" +version = "5.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a9645a70f1df1e5bd7fa8718b9ba486fac9c3f0467aa6b58e7f590d5f6fd0f7" dependencies = [ "aurora-engine-modexp", "c-kzg", @@ -6809,12 +6787,13 @@ dependencies = [ [[package]] name = "revm-primitives" -version = "3.0.0" -source = "git+https://github.com/bluealloy/revm?rev=5aff229a#5aff229a1046f410e13e5512df036707144668cc" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "323ad597cf75ac9cb1d161be29fcc3562426f0278a1d04741697fca556e1ceea" dependencies = [ "alloy-primitives", "auto_impl", - "bitflags 2.4.2", + "bitflags 2.5.0", "bitvec", "c-kzg", "cfg-if", @@ -7000,7 +6979,7 @@ version = "0.38.31" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ea3e1a662af26cd7a3ba09c0297a31af215563ecf42817c98df621387f4e949" dependencies = [ - "bitflags 2.4.2", + "bitflags 2.5.0", "errno", "libc", "linux-raw-sys", @@ -7074,7 +7053,7 @@ version = "12.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "994eca4bca05c87e86e15d90fc7a91d1be64b4482b38cb2d27474568fe7c9db9" dependencies = [ - "bitflags 2.4.2", + "bitflags 2.5.0", "cfg-if", "clipboard-win", "fd-lock 3.0.13", @@ -7220,6 +7199,7 @@ version = "0.28.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d24b59d129cdadea20aea4fb2352fa053712e5d713eee47d700cd4b2bc002f10" dependencies = [ + "rand 0.8.5", "secp256k1-sys", ] @@ -8220,7 +8200,7 @@ version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "61c5bb1d698276a2443e5ecfabc1008bf15a36c12e6a7176e7bf089ea9131140" dependencies = [ - "bitflags 2.4.2", + "bitflags 2.5.0", "bytes", "futures-core", "futures-util", diff --git a/Cargo.toml b/Cargo.toml index 635eba438a42..2238eced1ada 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -139,11 +139,9 @@ foundry-compilers = { version = "0.3.9", default-features = false } ## revm # no default features to avoid c-kzg -revm = { version = "7.1", default-features = false } +revm = { version = "7.2", default-features = false } revm-primitives = { version = "3", default-features = false } -revm-inspectors = { git = "https://github.com/paradigmxyz/evm-inspectors", rev = "ba0b6ab", features = [ - "serde", -] } +revm-inspectors = { path = "../evm-inspectors", features = ["serde"] } ## ethers ethers = { version = "2.0.14", default-features = false } @@ -220,10 +218,6 @@ tower = "0.4" tower-http = "0.4" [patch.crates-io] -revm = { git = "https://github.com/bluealloy/revm", rev = "5aff229a" } -revm-interpreter = { git = "https://github.com/bluealloy/revm", rev = "5aff229a" } -revm-primitives = { git = "https://github.com/bluealloy/revm", rev = "5aff229a" } -revm-precompile = { git = "https://github.com/bluealloy/revm", rev = "5aff229a" } alloy-primitives = { git = "https://github.com/klkvr/core", rev = "0473659" } alloy-json-abi = { git = "https://github.com/klkvr/core", rev = "0473659" } alloy-sol-types = { git = "https://github.com/klkvr/core", rev = "0473659" } diff --git a/crates/anvil/core/src/eth/transaction/mod.rs b/crates/anvil/core/src/eth/transaction/mod.rs index a0eab8198639..6b9f910f9995 100644 --- a/crates/anvil/core/src/eth/transaction/mod.rs +++ b/crates/anvil/core/src/eth/transaction/mod.rs @@ -5,10 +5,11 @@ use crate::eth::{ utils::eip_to_revm_access_list, }; use alloy_consensus::{ - BlobTransactionSidecar, ReceiptWithBloom, Signed, TxEip1559, TxEip2930, TxEip4844, TxEip4844Variant, TxEip4844WithSidecar, TxEnvelope, TxLegacy + BlobTransactionSidecar, ReceiptWithBloom, Signed, TxEip1559, TxEip2930, TxEip4844, + TxEip4844Variant, TxEip4844WithSidecar, TxEnvelope, TxLegacy, }; -use alloy_eips::eip2718::Encodable2718; -use alloy_primitives::{Address, Bloom, Bytes, Log, Signature, TxHash, TxKind, B256, U128, U256, U64, U8}; +use alloy_eips::eip2718::Decodable2718; +use alloy_primitives::{Address, Bloom, Bytes, Log, Signature, TxHash, TxKind, B256, U256, U8}; use alloy_rlp::{Decodable, Encodable, Header}; use alloy_rpc_types::{ request::TransactionRequest, AccessList, Signature as RpcSignature, @@ -893,10 +894,11 @@ impl Encodable for TypedTransaction { TypedTransaction::Deposit(tx) => { let tx_payload_len = tx.fields_len(); let tx_header_len = Header { list: false, payload_length: tx_payload_len }.length(); - Header { list: false, payload_length: 1 + tx_payload_len + tx_header_len }.encode(out); + Header { list: false, payload_length: 1 + tx_payload_len + tx_header_len } + .encode(out); out.put_u8(0x7E); tx.encode(out); - }, + } } } } @@ -922,6 +924,27 @@ impl Decodable for TypedTransaction { } } +impl Decodable2718 for TypedTransaction { + fn typed_decode(ty: u8, buf: &mut &[u8]) -> alloy_rlp::Result { + if ty == 0x7E { + return Ok(Self::Deposit(DepositTransaction::decode(buf)?)) + } + match TxEnvelope::typed_decode(ty, buf)? { + TxEnvelope::Eip2930(tx) => Ok(Self::EIP2930(tx)), + TxEnvelope::Eip1559(tx) => Ok(Self::EIP1559(tx)), + TxEnvelope::Eip4844(tx) => Ok(Self::EIP4844(tx)), + TxEnvelope::Legacy(_) => unreachable!(), + } + } + + fn fallback_decode(buf: &mut &[u8]) -> alloy_rlp::Result { + match TxEnvelope::fallback_decode(buf)? { + TxEnvelope::Legacy(tx) => Ok(Self::Legacy(tx)), + _ => unreachable!(), + } + } +} + impl From for TypedTransaction { fn from(value: TxEnvelope) -> Self { match value { @@ -1010,8 +1033,6 @@ impl From for ReceiptWithBloom { impl Encodable for TypedReceipt { fn encode(&self, out: &mut dyn bytes::BufMut) { - use alloy_rlp::Header; - match self { TypedReceipt::Legacy(r) => r.encode(out), receipt => { @@ -1053,7 +1074,6 @@ impl Encodable for TypedReceipt { impl Decodable for TypedReceipt { fn decode(buf: &mut &[u8]) -> alloy_rlp::Result { - use alloy_rlp::Header; use bytes::Buf; use std::cmp::Ordering; diff --git a/crates/anvil/core/src/eth/transaction/optimism.rs b/crates/anvil/core/src/eth/transaction/optimism.rs index da4447b57c00..6cec804d3aa0 100644 --- a/crates/anvil/core/src/eth/transaction/optimism.rs +++ b/crates/anvil/core/src/eth/transaction/optimism.rs @@ -1,5 +1,5 @@ -use alloy_consensus::{Transaction, TxType}; -use alloy_primitives::{Address, Bytes, ChainId, Signature, TxKind, B256, U256}; +use alloy_consensus::{SignableTransaction, Signed, Transaction, TxType}; +use alloy_primitives::{keccak256, Address, Bytes, ChainId, Signature, TxKind, B256, U256}; use alloy_rlp::{ length_of_length, Decodable, Encodable, Error as DecodeError, Header as RlpHeader, }; @@ -133,12 +133,74 @@ impl DepositTransactionRequest { 1 + length_of_length(payload_length) + payload_length } - /// Outputs the signature hash of the transaction by first encoding without a signature, then - /// hashing. - pub(crate) fn signature_hash(&self) -> B256 { - let mut buf = Vec::with_capacity(self.payload_len_for_signature()); - self.encode_for_signing(&mut buf); - alloy_primitives::utils::keccak256(&buf) + fn encoded_len_with_signature(&self, signature: &Signature) -> usize { + // this counts the tx fields and signature fields + let payload_length = self.fields_len() + signature.rlp_vrs_len(); + + // this counts: + // * tx type byte + // * inner header length + // * inner payload length + 1 + alloy_rlp::Header { list: true, payload_length }.length() + payload_length + } +} + +impl Transaction for DepositTransactionRequest { + fn input(&self) -> &[u8] { + &self.input + } + + /// Get `to`. + fn to(&self) -> TxKind { + self.kind + } + + /// Get `value`. + fn value(&self) -> U256 { + self.value + } + + /// Get `chain_id`. + fn chain_id(&self) -> Option { + None + } + + /// Get `nonce`. + fn nonce(&self) -> u64 { + u64::MAX + } + + /// Get `gas_limit`. + fn gas_limit(&self) -> u64 { + self.gas_limit.to() + } + + /// Get `gas_price`. + fn gas_price(&self) -> Option { + None + } +} + +impl SignableTransaction for DepositTransactionRequest { + fn set_chain_id(&mut self, _chain_id: ChainId) {} + + fn payload_len_for_signature(&self) -> usize { + self.payload_len_for_signature() + } + + fn into_signed(self, signature: Signature) -> Signed { + let mut buf = Vec::with_capacity(self.encoded_len_with_signature(&signature)); + self.encode_with_signature(&signature, &mut buf); + let hash = keccak256(&buf); + + // Drop any v chain id value to ensure the signature format is correct at the time of + // combination for an EIP-4844 transaction. V should indicate the y-parity of the + // signature. + Signed::new_unchecked(self, signature.with_parity_bool(), hash) + } + + fn encode_for_signing(&self, out: &mut dyn alloy_rlp::BufMut) { + self.encode_for_signing(out); } } diff --git a/crates/anvil/src/cmd.rs b/crates/anvil/src/cmd.rs index 508c3dc8e1f1..72c91aed6ff1 100644 --- a/crates/anvil/src/cmd.rs +++ b/crates/anvil/src/cmd.rs @@ -5,7 +5,7 @@ use crate::{ }; use alloy_genesis::Genesis; use alloy_primitives::{utils::Unit, U256}; -use alloy_signer::coins_bip39::{English, Mnemonic}; +use alloy_signer_wallet::coins_bip39::{English, Mnemonic}; use anvil_server::ServerConfig; use clap::Parser; use core::fmt; diff --git a/crates/anvil/src/config.rs b/crates/anvil/src/config.rs index f7ac3e65e2e0..9ab02003de9a 100644 --- a/crates/anvil/src/config.rs +++ b/crates/anvil/src/config.rs @@ -16,14 +16,16 @@ use crate::{ FeeManager, Hardfork, }; use alloy_genesis::Genesis; +use alloy_network::Ethereum; use alloy_primitives::{hex, utils::Unit, U256}; use alloy_provider::Provider; use alloy_rpc_types::BlockNumberOrTag; -use alloy_signer::{ +use alloy_signer::Signer; +use alloy_signer_wallet::{ coins_bip39::{English, Mnemonic}, - LocalWallet, MnemonicBuilder, Signer as AlloySigner, + LocalWallet, MnemonicBuilder, }; -use alloy_transport::TransportError; +use alloy_transport::{Transport, TransportError}; use anvil_server::ServerConfig; use foundry_common::{ provider::alloy::ProviderBuilder, ALCHEMY_FREE_TIER_CUPS, NON_ARCHIVE_NODE_WARNING, diff --git a/crates/anvil/src/eth/api.rs b/crates/anvil/src/eth/api.rs index 83754480bb83..648478bfc750 100644 --- a/crates/anvil/src/eth/api.rs +++ b/crates/anvil/src/eth/api.rs @@ -31,11 +31,9 @@ use crate::{ revm::primitives::Output, ClientFork, LoggingManager, Miner, MiningMode, StorageInfo, }; -use alloy_consensus::TxLegacy; use alloy_dyn_abi::TypedData; -use alloy_network::{Signed, TxKind}; -use alloy_primitives::{Address, Bytes, TxHash, B256, B64, U256, U64}; -use alloy_rlp::Decodable; +use alloy_network::eip2718::Decodable2718; +use alloy_primitives::{Address, Bytes, TxHash, TxKind, B256, B64, U256, U64}; use alloy_rpc_trace_types::{ geth::{DefaultFrame, GethDebugTracingOptions, GethDefaultTracingOptions, GethTrace}, parity::LocalizedTransactionTrace, @@ -900,7 +898,7 @@ impl EthApi { // pre-validate self.backend.validate_pool_transaction(&pending_transaction).await?; - let requires = required_marker(nonce, on_chain_nonce, from); + let requires = required_marker(nonce.to(), on_chain_nonce.to(), from); let provides = vec![to_marker(nonce.to::(), from)]; debug_assert!(requires != provides); @@ -916,26 +914,8 @@ impl EthApi { if data.is_empty() { return Err(BlockchainError::EmptyRawTransactionData); } - let transaction = if data[0] > 0x7f { - // legacy transaction - match Signed::::decode(&mut data) { - Ok(transaction) => TypedTransaction::Legacy(transaction), - Err(_) => return Err(BlockchainError::FailedToDecodeSignedTransaction), - } - } else { - // the [TypedTransaction] requires a valid rlp input, - // but EIP-1559 prepends a version byte, so we need to encode the data first to get a - // valid rlp and then rlp decode impl of `TypedTransaction` will remove and check the - // version byte - let extend = alloy_rlp::encode(data); - let tx = match TypedTransaction::decode(&mut &extend[..]) { - Ok(transaction) => transaction, - Err(_) => return Err(BlockchainError::FailedToDecodeSignedTransaction), - }; - - self.ensure_typed_transaction_supported(&tx)?; - tx - }; + let transaction = TypedTransaction::decode_2718(&mut data) + .map_err(|_| BlockchainError::FailedToDecodeSignedTransaction)?; let pending_transaction = PendingTransaction::new(transaction)?; // pre-validate @@ -949,7 +929,7 @@ impl EthApi { let priority = self.transaction_priority(&pending_transaction.transaction); let pool_transaction = PoolTransaction { requires, - provides: vec![to_marker(nonce.to::(), *pending_transaction.sender())], + provides: vec![to_marker(nonce, *pending_transaction.sender())], pending_transaction, priority, }; @@ -1991,7 +1971,7 @@ impl EthApi { // pre-validate self.backend.validate_pool_transaction(&pending_transaction).await?; - let requires = required_marker(nonce, on_chain_nonce, from); + let requires = required_marker(nonce.to(), on_chain_nonce.to(), from); let provides = vec![to_marker(nonce.to::(), from)]; self.add_pending_transaction(pending_transaction, requires, provides) @@ -2023,7 +2003,7 @@ impl EthApi { let gas_price = tx.gas_price(); let value = tx.value(); let gas = tx.gas_limit(); - TxpoolInspectSummary { to, value, gas, gas_price } + TxpoolInspectSummary { to: to.copied(), value, gas, gas_price } } // Note: naming differs geth vs anvil: @@ -2471,7 +2451,7 @@ impl EthApi { request: TransactionRequest, nonce: U256, ) -> Result { - let chain_id = request.chain_id.map(|c| c.to::()).unwrap_or_else(|| self.chain_id()); + let chain_id = request.chain_id.unwrap_or_else(|| self.chain_id()); let max_fee_per_gas = request.max_fee_per_gas; let gas_price = request.gas_price; @@ -2530,7 +2510,7 @@ impl EthApi { if let BlockRequest::Number(number) = block_request { if let Some(fork) = self.get_fork() { if fork.predates_fork_inclusive(number) { - return Ok(fork.get_nonce(address, number).await?); + return Ok(fork.get_nonce(address, number).await?.to()); } } } @@ -2554,7 +2534,7 @@ impl EthApi { ) -> Result<(U256, U256)> { let highest_nonce = self.get_transaction_count(from, Some(BlockId::Number(BlockNumber::Pending))).await?; - let nonce = request.nonce.map(|n| n.to::()).unwrap_or(highest_nonce); + let nonce = request.nonce.map(U256::from).unwrap_or(highest_nonce); Ok((nonce, highest_nonce)) } @@ -2592,13 +2572,13 @@ impl EthApi { } } -fn required_marker(provided_nonce: U256, on_chain_nonce: U256, from: Address) -> Vec { +fn required_marker(provided_nonce: u64, on_chain_nonce: u64, from: Address) -> Vec { if provided_nonce == on_chain_nonce { return Vec::new(); } - let prev_nonce = provided_nonce.saturating_sub(U256::from(1)); + let prev_nonce = provided_nonce.saturating_sub(1); if on_chain_nonce <= prev_nonce { - vec![to_marker(prev_nonce.to::(), from)] + vec![to_marker(prev_nonce, from)] } else { Vec::new() } diff --git a/crates/anvil/src/eth/backend/db.rs b/crates/anvil/src/eth/backend/db.rs index 2630d19a7663..2fbad509b925 100644 --- a/crates/anvil/src/eth/backend/db.rs +++ b/crates/anvil/src/eth/backend/db.rs @@ -8,7 +8,6 @@ use foundry_common::errors::FsPathError; use foundry_evm::{ backend::{DatabaseError, DatabaseResult, MemDb, RevertSnapshotAction, StateSnapshot}, fork::BlockchainDb, - hashbrown::HashMap, revm::{ db::{CacheDB, DatabaseRef, DbAccount}, primitives::{BlockEnv, Bytecode, KECCAK_EMPTY}, @@ -17,7 +16,11 @@ use foundry_evm::{ }; use hash_db::HashDB; use serde::{Deserialize, Serialize}; -use std::{collections::BTreeMap, fmt, path::Path}; +use std::{ + collections::{BTreeMap, HashMap}, + fmt, + path::Path, +}; /// Type alias for the `HashDB` representation of the Database pub type AsHashDB = Box>>; diff --git a/crates/anvil/src/eth/backend/executor.rs b/crates/anvil/src/eth/backend/executor.rs index 320d4688462c..778f79f781d1 100644 --- a/crates/anvil/src/eth/backend/executor.rs +++ b/crates/anvil/src/eth/backend/executor.rs @@ -186,7 +186,7 @@ impl<'a, DB: Db + ?Sized, Validator: TransactionValidator> TransactionExecutor<' transaction_hash: transaction.hash(), transaction_index, from: *transaction.pending_transaction.sender(), - to: transaction.pending_transaction.transaction.to(), + to: transaction.pending_transaction.transaction.to().copied(), contract_address, logs, logs_bloom: *receipt.logs_bloom(), diff --git a/crates/anvil/src/eth/backend/fork.rs b/crates/anvil/src/eth/backend/fork.rs index cb4f66871442..244a2f5a9b3d 100644 --- a/crates/anvil/src/eth/backend/fork.rs +++ b/crates/anvil/src/eth/backend/fork.rs @@ -171,7 +171,7 @@ impl ClientFork { block: Option, ) -> Result { let block = block.unwrap_or(BlockNumber::Latest); - let res = self.provider().call((*request).clone(), Some(block.into())).await?; + let res = self.provider().call(request, Some(block.into())).await?; Ok(res) } @@ -183,7 +183,7 @@ impl ClientFork { block: Option, ) -> Result { let block = block.unwrap_or(BlockNumber::Latest); - let res = self.provider().estimate_gas(request.clone(), Some(block.into())).await?; + let res = self.provider().estimate_gas(&request, Some(block.into())).await?; Ok(res) } @@ -194,7 +194,7 @@ impl ClientFork { request: &TransactionRequest, block: Option, ) -> Result { - self.provider().create_access_list(request.clone(), block.map(|b| b.into())).await + self.provider().create_access_list(&request, block.map(|b| b.into())).await } pub async fn storage_at( @@ -211,7 +211,7 @@ impl ClientFork { return Ok(logs); } - let logs = self.provider().get_logs(filter.clone()).await?; + let logs = self.provider().get_logs(&filter).await?; let mut storage = self.storage_write(); storage.logs.insert(filter.clone(), logs.clone()); @@ -230,7 +230,7 @@ impl ClientFork { let block_id = BlockId::Number(blocknumber.into()); - let code = self.provider().get_code_at(address, Some(block_id)).await?; + let code = self.provider().get_code_at(address, block_id).await?; let mut storage = self.storage_write(); storage.code_at.insert((address, blocknumber), code.clone().0.into()); @@ -251,7 +251,7 @@ impl ClientFork { &self, address: Address, blocknumber: u64, - ) -> Result { + ) -> Result { trace!(target: "backend::fork", "get_nonce={:?}", address); self.provider().get_transaction_count(address, Some(blocknumber.into())).await } diff --git a/crates/anvil/src/eth/backend/mem/mod.rs b/crates/anvil/src/eth/backend/mem/mod.rs index 013c303e3285..2f46391a6323 100644 --- a/crates/anvil/src/eth/backend/mem/mod.rs +++ b/crates/anvil/src/eth/backend/mem/mod.rs @@ -30,7 +30,6 @@ use crate::{ NodeConfig, }; use alloy_consensus::{Header, Receipt, ReceiptWithBloom}; -use alloy_network::Sealable; use alloy_primitives::{keccak256, Address, Bytes, TxHash, B256, B64, U128, U256, U64, U8}; use alloy_rlp::Decodable; use alloy_rpc_trace_types::{ @@ -38,10 +37,10 @@ use alloy_rpc_trace_types::{ parity::LocalizedTransactionTrace, }; use alloy_rpc_types::{ - request::TransactionRequest, state::StateOverride, AccessList, Block as AlloyBlock, BlockId, - BlockNumberOrTag as BlockNumber, EIP1186AccountProofResponse as AccountProof, - EIP1186StorageProof as StorageProof, Filter, FilteredParams, Header as AlloyHeader, Log, - Transaction, TransactionReceipt, + request::TransactionRequest, serde_helpers::JsonStorageKey, state::StateOverride, AccessList, + Block as AlloyBlock, BlockId, BlockNumberOrTag as BlockNumber, + EIP1186AccountProofResponse as AccountProof, EIP1186StorageProof as StorageProof, Filter, + FilteredParams, Header as AlloyHeader, Log, Transaction, TransactionReceipt, }; use anvil_core::{ eth::{ @@ -524,8 +523,8 @@ impl Backend { } /// Returns balance of the given account. - pub async fn current_nonce(&self, address: Address) -> DatabaseResult { - Ok(U256::from(self.get_account(address).await?.nonce)) + pub async fn current_nonce(&self, address: Address) -> DatabaseResult { + Ok(self.get_account(address).await?.nonce) } /// Sets the coinbase address @@ -930,7 +929,7 @@ impl Backend { let executed_tx = executor.execute(); // we also need to update the new blockhash in the db itself - let block_hash = executed_tx.block.block.header.hash(); + let block_hash = executed_tx.block.block.header.hash_slow(); db.insert_block_hash(U256::from(executed_tx.block.block.header.number), block_hash); (executed_tx, block_hash) @@ -1095,7 +1094,7 @@ impl Backend { value: value.unwrap_or_default(), data: input.into_input().unwrap_or_default(), chain_id: None, - nonce: nonce.map(|n| n.to::()), + nonce, access_list: alloy_to_revm_access_list(access_list.unwrap_or_default().0), ..Default::default() }; @@ -1245,7 +1244,7 @@ impl Backend { fn mined_logs_for_block(&self, filter: Filter, block: Block) -> Vec { let params = FilteredParams::new(Some(filter.clone())); let mut all_logs = Vec::new(); - let block_hash = block.header.hash(); + let block_hash = block.header.hash_slow(); let mut block_log_index = 0u32; let transactions: Vec<_> = { @@ -1518,7 +1517,7 @@ impl Backend { let Block { header, transactions, .. } = block; - let hash = header.hash(); + let hash = header.hash_slow(); let Header { parent_hash, ommers_hash, @@ -1664,7 +1663,7 @@ impl Backend { if let Some((state, block)) = self .get_block(block_number.to::()) - .and_then(|block| Some((states.get(&block.header.hash())?, block))) + .and_then(|block| Some((states.get(&block.header.hash_slow())?, block))) { let block = BlockEnv { number: block.header.number.to_alloy(), @@ -1793,7 +1792,7 @@ impl Backend { ) -> Result { if let BlockRequest::Pending(pool_transactions) = &block_request { if let Some(value) = get_pool_transactions_nonce(pool_transactions, address) { - return Ok(value); + return Ok(U256::from(value)); } } let final_block_request = match block_request { @@ -1976,13 +1975,13 @@ impl Backend { let transaction_type = transaction.transaction.r#type(); let effective_gas_price = match transaction.transaction { - TypedTransaction::Legacy(t) => t.gas_price, - TypedTransaction::EIP2930(t) => t.gas_price, + TypedTransaction::Legacy(t) => t.tx().gas_price, + TypedTransaction::EIP2930(t) => t.tx().gas_price, TypedTransaction::EIP1559(t) => block .header .base_fee_per_gas .map_or(self.base_fee().to::(), |b| b as u128) - .checked_add(t.max_priority_fee_per_gas) + .checked_add(t.tx().max_priority_fee_per_gas) .unwrap_or(u128::MAX), TypedTransaction::EIP4844(t) => block .header @@ -1996,7 +1995,7 @@ impl Backend { let deposit_nonce = transaction_type.and_then(|x| (x == 0x7E).then_some(info.nonce)); let mut inner = TransactionReceipt { - transaction_hash: Some(info.transaction_hash), + transaction_hash: info.transaction_hash, transaction_index: U64::from(info.transaction_index), block_hash: Some(block_hash), block_number: Some(U256::from(block.header.number)), @@ -2227,7 +2226,7 @@ impl Backend { let key = B256::from(keccak256(storage_key)); prove_storage(&account, &account_db.0, key).map( |(storage_proof, storage_value)| StorageProof { - key: alloy_rpc_types::JsonStorageKey(storage_key), + key: JsonStorageKey(storage_key), value: U256::from_be_bytes(storage_value.0), proof: storage_proof .into_iter() @@ -2275,14 +2274,14 @@ impl Backend { fn get_pool_transactions_nonce( pool_transactions: &[Arc], address: Address, -) -> Option { +) -> Option { if let Some(highest_nonce) = pool_transactions .iter() .filter(|tx| *tx.pending_transaction.sender() == address) .map(|tx| tx.pending_transaction.nonce()) .max() { - let tx_count = highest_nonce.saturating_add(U256::from(1)); + let tx_count = highest_nonce.saturating_add(1); return Some(tx_count) } None @@ -2387,7 +2386,7 @@ impl TransactionValidator for Backend { env: &EnvWithHandlerCfg, ) -> Result<(), InvalidTransactionError> { self.validate_pool_transaction_for(tx, account, env)?; - if tx.nonce().to::() > account.nonce { + if tx.nonce() > account.nonce { return Err(InvalidTransactionError::NonceTooHigh); } Ok(()) @@ -2404,8 +2403,8 @@ pub fn transaction_build( base_fee: Option, ) -> Transaction { let mut transaction: Transaction = eth_transaction.clone().into(); - if info.is_some() && transaction.transaction_type.unwrap_or(U64::ZERO).to::() == 0x7E { - transaction.nonce = U64::from(info.as_ref().unwrap().nonce); + if info.is_some() && transaction.transaction_type.unwrap_or_default().to::() == 0x7E { + transaction.nonce = info.as_ref().unwrap().nonce; } if eth_transaction.is_dynamic_fee() { @@ -2418,9 +2417,8 @@ pub fn transaction_build( let base_fee = base_fee.unwrap_or(U256::ZERO); let max_priority_fee_per_gas = transaction.max_priority_fee_per_gas.map(|g| g.to::()).unwrap_or(U256::ZERO); - transaction.gas_price = Some( - base_fee.checked_add(max_priority_fee_per_gas).unwrap_or(U256::MAX).to::(), - ); + transaction.gas_price = + Some(base_fee.checked_add(max_priority_fee_per_gas).unwrap_or(U256::MAX)); } } else { transaction.max_fee_per_gas = None; @@ -2454,7 +2452,7 @@ pub fn transaction_build( transaction.hash = tx_hash; } - transaction.to = info.as_ref().map_or(eth_transaction.to(), |status| status.to); + transaction.to = info.as_ref().map_or(eth_transaction.to().copied(), |status| status.to); transaction } diff --git a/crates/anvil/src/eth/backend/mem/state.rs b/crates/anvil/src/eth/backend/mem/state.rs index af936578d04a..828c6358ea36 100644 --- a/crates/anvil/src/eth/backend/mem/state.rs +++ b/crates/anvil/src/eth/backend/mem/state.rs @@ -7,17 +7,17 @@ use alloy_rpc_types::state::StateOverride; use anvil_core::eth::trie::RefSecTrieDBMut; use foundry_evm::{ backend::DatabaseError, - hashbrown::HashMap as Map, revm::{ db::{CacheDB, DatabaseRef, DbAccount}, primitives::{AccountInfo, Bytecode}, }, }; use memory_db::HashKey; +use std::collections::HashMap; use trie_db::TrieMut; /// Returns storage trie of an account as `HashDB` -pub fn storage_trie_db(storage: &Map) -> (AsHashDB, B256) { +pub fn storage_trie_db(storage: &HashMap) -> (AsHashDB, B256) { // Populate DB with full trie from entries. let (db, root) = { let mut db = , _>>::default(); @@ -38,7 +38,7 @@ pub fn storage_trie_db(storage: &Map) -> (AsHashDB, B256) { } /// Returns the account data as `HashDB` -pub fn trie_hash_db(accounts: &Map) -> (AsHashDB, B256) { +pub fn trie_hash_db(accounts: &HashMap) -> (AsHashDB, B256) { let accounts = trie_accounts(accounts); // Populate DB with full trie from entries. @@ -58,7 +58,7 @@ pub fn trie_hash_db(accounts: &Map) -> (AsHashDB, B256) { } /// Returns all RLP-encoded Accounts -pub fn trie_accounts(accounts: &Map) -> Vec<(Address, Bytes)> { +pub fn trie_accounts(accounts: &HashMap) -> Vec<(Address, Bytes)> { accounts .iter() .map(|(address, account)| { @@ -68,12 +68,12 @@ pub fn trie_accounts(accounts: &Map) -> Vec<(Address, Bytes) .collect() } -pub fn state_merkle_trie_root(accounts: &Map) -> B256 { +pub fn state_merkle_trie_root(accounts: &HashMap) -> B256 { trie_hash_db(accounts).1 } /// Returns the RLP for this account. -pub fn trie_account_rlp(info: &AccountInfo, storage: &Map) -> Bytes { +pub fn trie_account_rlp(info: &AccountInfo, storage: &HashMap) -> Bytes { let mut out: Vec = Vec::new(); let list: [&dyn Encodable; 4] = [&info.nonce, &info.balance, &storage_trie_db(storage).1, &info.code_hash]; diff --git a/crates/anvil/src/eth/backend/mem/storage.rs b/crates/anvil/src/eth/backend/mem/storage.rs index 0e2ac2b636ad..d3b13df6155a 100644 --- a/crates/anvil/src/eth/backend/mem/storage.rs +++ b/crates/anvil/src/eth/backend/mem/storage.rs @@ -6,7 +6,6 @@ use crate::eth::{ }, pool::transactions::PoolTransaction, }; -use alloy_network::Sealable; use alloy_primitives::{Bytes, TxHash, B256, U256, U64}; use alloy_rpc_trace_types::{ geth::{DefaultFrame, GethDefaultTracingOptions}, @@ -239,7 +238,7 @@ impl BlockchainStorage { ..Default::default() }; let block = Block::new::(partial_header, vec![], vec![]); - let genesis_hash = block.header.hash(); + let genesis_hash = block.header.hash_slow(); let best_hash = genesis_hash; let best_number: U64 = U64::from(0u64); diff --git a/crates/anvil/src/eth/fees.rs b/crates/anvil/src/eth/fees.rs index ef2d38eca87f..38a90f6c2da8 100644 --- a/crates/anvil/src/eth/fees.rs +++ b/crates/anvil/src/eth/fees.rs @@ -249,14 +249,14 @@ impl FeeHistoryService { let effective_reward = match block.transactions.get(i).map(|tx| &tx.transaction) { Some(TypedTransaction::Legacy(t)) => { - U256::from(t.gas_price).saturating_sub(base_fee).to::() + U256::from(t.tx().gas_price).saturating_sub(base_fee).to::() } Some(TypedTransaction::EIP2930(t)) => { - U256::from(t.gas_price).saturating_sub(base_fee).to::() + U256::from(t.tx().gas_price).saturating_sub(base_fee).to::() } Some(TypedTransaction::EIP1559(t)) => { - U256::from(t.max_priority_fee_per_gas) - .min(U256::from(t.max_fee_per_gas).saturating_sub(base_fee)) + U256::from(t.tx().max_priority_fee_per_gas) + .min(U256::from(t.tx().max_fee_per_gas).saturating_sub(base_fee)) .to::() } // TODO: This probably needs to be extended to extract 4844 info. diff --git a/crates/anvil/src/eth/sign.rs b/crates/anvil/src/eth/sign.rs index 4886d96f0468..949a517fa769 100644 --- a/crates/anvil/src/eth/sign.rs +++ b/crates/anvil/src/eth/sign.rs @@ -1,8 +1,10 @@ use crate::eth::error::BlockchainError; +use alloy_consensus::{SignableTransaction, Signed}; use alloy_dyn_abi::TypedData; -use alloy_network::{Signed, Transaction}; -use alloy_primitives::{Address, Signature, B256, U256}; -use alloy_signer::{LocalWallet, Signer as AlloySigner, SignerSync as AlloySignerSync}; +use alloy_network::TxSignerSync; +use alloy_primitives::{Address, Signature, B256}; +use alloy_signer::Signer as AlloySigner; +use alloy_signer_wallet::LocalWallet; use anvil_core::eth::transaction::{ optimism::{DepositTransaction, DepositTransactionRequest}, TypedTransaction, TypedTransactionRequest, @@ -84,17 +86,13 @@ impl Signer for DevSigner { // typed data. signer.set_chain_id(None); - Ok(signer - .sign_hash( - payload.eip712_signing_hash().map_err(|_| BlockchainError::NoSignerAvailable)?, - ) - .await?) + Ok(signer.sign_dynamic_typed_data(payload).await?) } async fn sign_hash(&self, address: Address, hash: B256) -> Result { let signer = self.accounts.get(&address).ok_or(BlockchainError::NoSignerAvailable)?; - Ok(signer.sign_hash(hash).await?) + Ok(signer.sign_hash(&hash).await?) } fn sign_transaction( @@ -160,7 +158,7 @@ pub fn build_typed_transaction( source_hash, mint, is_system_tx, - nonce: U256::ZERO, + nonce: 0, }) } }; diff --git a/crates/anvil/src/lib.rs b/crates/anvil/src/lib.rs index 23a328d7a8b9..ff524d14b847 100644 --- a/crates/anvil/src/lib.rs +++ b/crates/anvil/src/lib.rs @@ -17,7 +17,7 @@ use crate::{ tasks::TaskManager, }; use alloy_primitives::{Address, U256}; -use alloy_signer::{LocalWallet, Signer as AlloySigner}; +use alloy_signer_wallet::LocalWallet; use eth::backend::fork::ClientFork; use foundry_common::provider::alloy::{ProviderBuilder, RetryProvider}; use foundry_evm::revm; diff --git a/crates/anvil/src/pubsub.rs b/crates/anvil/src/pubsub.rs index b0b8b33bbecd..2c0c614fc254 100644 --- a/crates/anvil/src/pubsub.rs +++ b/crates/anvil/src/pubsub.rs @@ -3,7 +3,6 @@ use crate::{ StorageInfo, }; use alloy_consensus::ReceiptWithBloom; -use alloy_network::Sealable; use alloy_primitives::{Log, TxHash, B256, U256}; use alloy_rpc_types::{pubsub::SubscriptionResult, FilteredParams, Log as AlloyLog}; use anvil_core::eth::{block::Block, subscription::SubscriptionId, transaction::TypedReceipt}; @@ -165,7 +164,7 @@ pub fn filter_logs( true } - let block_hash = block.header.hash(); + let block_hash = block.header.hash_slow(); let mut logs = vec![]; let mut log_index: u32 = 0; for (receipt_index, receipt) in receipts.into_iter().enumerate() { diff --git a/crates/common/src/provider/alloy.rs b/crates/common/src/provider/alloy.rs index b025db896e6f..fb8084f8bea5 100644 --- a/crates/common/src/provider/alloy.rs +++ b/crates/common/src/provider/alloy.rs @@ -4,7 +4,8 @@ use crate::{ provider::runtime_transport::RuntimeTransportBuilder, ALCHEMY_FREE_TIER_CUPS, REQUEST_TIMEOUT, }; use alloy_provider::{ - network::Ethereum, utils::Eip1559Estimation, Provider, ProviderBuilder as AlloyProviderBuilder, RootProvider + network::Ethereum, utils::Eip1559Estimation, Provider, ProviderBuilder as AlloyProviderBuilder, + RootProvider, }; use alloy_rpc_client::ClientBuilder; use ethers_middleware::gas_oracle::{GasCategory, GasOracle, Polygon}; From 2867eace82591bc2b090a0bcd8c33660f106dfe1 Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Fri, 22 Mar 2024 11:46:06 +0400 Subject: [PATCH 18/63] wip: make script compile --- Cargo.lock | 154 ++++++++++------ Cargo.toml | 42 ++--- crates/cli/Cargo.toml | 2 - crates/cli/src/utils/mod.rs | 39 +---- crates/common/src/provider/alloy.rs | 3 +- crates/script/Cargo.toml | 16 +- crates/script/src/broadcast.rs | 139 +++++++-------- crates/script/src/build.rs | 11 +- crates/script/src/execute.rs | 10 +- crates/script/src/lib.rs | 10 +- crates/script/src/providers.rs | 28 +-- crates/script/src/receipts.rs | 67 +++++-- crates/script/src/sequence.rs | 23 +-- crates/script/src/simulate.rs | 23 +-- crates/script/src/transaction.rs | 260 ++-------------------------- 15 files changed, 297 insertions(+), 530 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7785488b33d6..c5e37e09e1c5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -90,12 +90,11 @@ dependencies = [ [[package]] name = "alloy-consensus" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ - "alloy-eips", + "alloy-eips 0.1.0", "alloy-primitives", "alloy-rlp", - "alloy-serde", + "alloy-serde 0.1.0", "c-kzg", "serde", "sha2", @@ -103,16 +102,25 @@ dependencies = [ ] [[package]] -name = "alloy-contract" +name = "alloy-consensus" version = "0.1.0" source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" +dependencies = [ + "alloy-eips 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", + "alloy-primitives", + "alloy-rlp", +] + +[[package]] +name = "alloy-contract" +version = "0.1.0" dependencies = [ "alloy-dyn-abi", "alloy-json-abi", "alloy-network", "alloy-primitives", "alloy-provider", - "alloy-rpc-types", + "alloy-rpc-types 0.1.0", "alloy-sol-types", "alloy-transport", "futures", @@ -141,6 +149,15 @@ dependencies = [ "winnow 0.6.5", ] +[[package]] +name = "alloy-eips" +version = "0.1.0" +dependencies = [ + "alloy-primitives", + "alloy-rlp", + "serde", +] + [[package]] name = "alloy-eips" version = "0.1.0" @@ -154,10 +171,9 @@ dependencies = [ [[package]] name = "alloy-genesis" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-primitives", - "alloy-serde", + "alloy-serde 0.1.0", "serde", ] @@ -175,7 +191,6 @@ dependencies = [ [[package]] name = "alloy-json-rpc" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-primitives", "serde", @@ -186,13 +201,12 @@ dependencies = [ [[package]] name = "alloy-network" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ - "alloy-consensus", - "alloy-eips", + "alloy-consensus 0.1.0", + "alloy-eips 0.1.0", "alloy-json-rpc", "alloy-primitives", - "alloy-rpc-types", + "alloy-rpc-types 0.1.0", "alloy-signer", "async-trait", "futures-utils-wasm", @@ -229,15 +243,14 @@ dependencies = [ [[package]] name = "alloy-provider" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-json-rpc", "alloy-network", "alloy-primitives", "alloy-pubsub", "alloy-rpc-client", - "alloy-rpc-trace-types", - "alloy-rpc-types", + "alloy-rpc-trace-types 0.1.0", + "alloy-rpc-types 0.1.0", "alloy-transport", "alloy-transport-http", "async-stream", @@ -255,7 +268,6 @@ dependencies = [ [[package]] name = "alloy-pubsub" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-json-rpc", "alloy-primitives", @@ -295,7 +307,6 @@ dependencies = [ [[package]] name = "alloy-rpc-client" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-json-rpc", "alloy-primitives", @@ -314,16 +325,42 @@ dependencies = [ "url", ] +[[package]] +name = "alloy-rpc-trace-types" +version = "0.1.0" +dependencies = [ + "alloy-primitives", + "alloy-rpc-types 0.1.0", + "alloy-serde 0.1.0", + "serde", + "serde_json", +] + [[package]] name = "alloy-rpc-trace-types" version = "0.1.0" source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-primitives", - "alloy-rpc-types", - "alloy-serde", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", + "alloy-serde 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", + "serde", + "serde_json", +] + +[[package]] +name = "alloy-rpc-types" +version = "0.1.0" +dependencies = [ + "alloy-consensus 0.1.0", + "alloy-eips 0.1.0", + "alloy-primitives", + "alloy-rlp", + "alloy-serde 0.1.0", + "itertools 0.12.1", "serde", "serde_json", + "thiserror", ] [[package]] @@ -331,17 +368,26 @@ name = "alloy-rpc-types" version = "0.1.0" source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ - "alloy-consensus", - "alloy-eips", + "alloy-consensus 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", + "alloy-eips 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", "alloy-primitives", "alloy-rlp", - "alloy-serde", + "alloy-serde 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", "itertools 0.12.1", "serde", "serde_json", "thiserror", ] +[[package]] +name = "alloy-serde" +version = "0.1.0" +dependencies = [ + "alloy-primitives", + "serde", + "serde_json", +] + [[package]] name = "alloy-serde" version = "0.1.0" @@ -355,7 +401,6 @@ dependencies = [ [[package]] name = "alloy-signer" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-dyn-abi", "alloy-primitives", @@ -370,9 +415,8 @@ dependencies = [ [[package]] name = "alloy-signer-aws" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ - "alloy-consensus", + "alloy-consensus 0.1.0", "alloy-network", "alloy-primitives", "alloy-signer", @@ -387,9 +431,8 @@ dependencies = [ [[package]] name = "alloy-signer-ledger" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ - "alloy-consensus", + "alloy-consensus 0.1.0", "alloy-network", "alloy-primitives", "alloy-signer", @@ -404,9 +447,8 @@ dependencies = [ [[package]] name = "alloy-signer-trezor" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ - "alloy-consensus", + "alloy-consensus 0.1.0", "alloy-network", "alloy-primitives", "alloy-signer", @@ -420,9 +462,8 @@ dependencies = [ [[package]] name = "alloy-signer-wallet" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ - "alloy-consensus", + "alloy-consensus 0.1.0", "alloy-network", "alloy-primitives", "alloy-signer", @@ -487,7 +528,6 @@ dependencies = [ [[package]] name = "alloy-transport" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-json-rpc", "base64 0.22.0", @@ -505,7 +545,6 @@ dependencies = [ [[package]] name = "alloy-transport-http" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-json-rpc", "alloy-transport", @@ -518,7 +557,6 @@ dependencies = [ [[package]] name = "alloy-transport-ipc" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-json-rpc", "alloy-pubsub", @@ -536,7 +574,6 @@ dependencies = [ [[package]] name = "alloy-transport-ws" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-pubsub", "alloy-transport", @@ -636,15 +673,15 @@ name = "anvil" version = "0.2.0" dependencies = [ "alloy-chains", - "alloy-consensus", + "alloy-consensus 0.1.0", "alloy-dyn-abi", "alloy-genesis", "alloy-network", "alloy-primitives", "alloy-provider", "alloy-rlp", - "alloy-rpc-trace-types", - "alloy-rpc-types", + "alloy-rpc-trace-types 0.1.0", + "alloy-rpc-types 0.1.0", "alloy-signer", "alloy-signer-wallet", "alloy-sol-types", @@ -700,14 +737,14 @@ dependencies = [ name = "anvil-core" version = "0.2.0" dependencies = [ - "alloy-consensus", + "alloy-consensus 0.1.0", "alloy-dyn-abi", - "alloy-eips", + "alloy-eips 0.1.0", "alloy-network", "alloy-primitives", "alloy-rlp", - "alloy-rpc-trace-types", - "alloy-rpc-types", + "alloy-rpc-trace-types 0.1.0", + "alloy-rpc-types 0.1.0", "anvil-core", "bytes", "c-kzg", @@ -1727,7 +1764,7 @@ checksum = "df8670b8c7b9dae1793364eafadf7239c40d669904660c5960d74cfd80b46a53" name = "cast" version = "0.2.0" dependencies = [ - "alloy-consensus", + "alloy-consensus 0.1.0", "alloy-contract", "alloy-dyn-abi", "alloy-json-abi", @@ -1736,7 +1773,7 @@ dependencies = [ "alloy-primitives", "alloy-provider", "alloy-rlp", - "alloy-rpc-types", + "alloy-rpc-types 0.1.0", "alloy-signer", "alloy-signer-wallet", "alloy-transport", @@ -1815,7 +1852,7 @@ dependencies = [ "alloy-dyn-abi", "alloy-json-abi", "alloy-primitives", - "alloy-rpc-types", + "alloy-rpc-types 0.1.0", "clap", "criterion", "dirs 5.0.1", @@ -3369,7 +3406,7 @@ dependencies = [ "alloy-dyn-abi", "alloy-json-abi", "alloy-primitives", - "alloy-rpc-types", + "alloy-rpc-types 0.1.0", "anvil", "async-trait", "axum", @@ -3482,18 +3519,22 @@ dependencies = [ name = "forge-script" version = "0.2.0" dependencies = [ + "alloy-chains", + "alloy-consensus 0.1.0", "alloy-dyn-abi", + "alloy-eips 0.1.0", "alloy-json-abi", + "alloy-network", "alloy-primitives", - "alloy-rpc-types", + "alloy-provider", + "alloy-rpc-types 0.1.0", + "alloy-signer", + "alloy-transport", "async-recursion", "clap", "const-hex", "dialoguer", "dunce", - "ethers-core", - "ethers-providers", - "ethers-signers", "eyre", "forge-verify", "foundry-cheatcodes", @@ -3584,7 +3625,7 @@ dependencies = [ "alloy-json-abi", "alloy-primitives", "alloy-provider", - "alloy-rpc-types", + "alloy-rpc-types 0.1.0", "alloy-signer", "alloy-signer-wallet", "alloy-sol-types", @@ -3634,7 +3675,6 @@ dependencies = [ "clap", "color-eyre", "dotenvy", - "ethers-core", "eyre", "forge-fmt", "foundry-common", @@ -3669,7 +3709,7 @@ dependencies = [ "alloy-provider", "alloy-pubsub", "alloy-rpc-client", - "alloy-rpc-types", + "alloy-rpc-types 0.1.0", "alloy-signer-wallet", "alloy-sol-types", "alloy-transport", @@ -3837,7 +3877,7 @@ dependencies = [ "alloy-json-abi", "alloy-primitives", "alloy-provider", - "alloy-rpc-types", + "alloy-rpc-types 0.1.0", "alloy-sol-types", "alloy-transport", "arrayvec", @@ -3979,7 +4019,7 @@ dependencies = [ name = "foundry-wallets" version = "0.2.0" dependencies = [ - "alloy-consensus", + "alloy-consensus 0.1.0", "alloy-dyn-abi", "alloy-network", "alloy-primitives", @@ -6747,8 +6787,8 @@ name = "revm-inspectors" version = "0.1.0" dependencies = [ "alloy-primitives", - "alloy-rpc-trace-types", - "alloy-rpc-types", + "alloy-rpc-trace-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", + "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", "alloy-sol-types", "anstyle", "colorchoice", diff --git a/Cargo.toml b/Cargo.toml index 2238eced1ada..38d5ba258a61 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -154,27 +154,27 @@ ethers-middleware = { version = "2.0.14", default-features = false } ethers-solc = { version = "2.0.14", default-features = false } ## alloy -alloy-consensus = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-contract = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-eips = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-genesis = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-json-rpc = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-network = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-node-bindings = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-provider = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-pubsub = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-rpc-client = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-rpc-trace-types = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-rpc-types = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-signer = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-signer-wallet = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-signer-aws = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-signer-ledger = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-signer-trezor = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-transport = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-transport-http = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-transport-ipc = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-transport-ws = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-consensus = { path = "../alloy/crates/consensus", default-features = false } +alloy-contract = { path = "../alloy/crates/contract", default-features = false } +alloy-eips = { path = "../alloy/crates/eips", default-features = false } +alloy-genesis = { path = "../alloy/crates/genesis", default-features = false } +alloy-json-rpc = { path = "../alloy/crates/json-rpc", default-features = false } +alloy-network = { path = "../alloy/crates/network", default-features = false } +alloy-node-bindings = { path = "../alloy/crates/node-bindings", default-features = false } +alloy-provider = { path = "../alloy/crates/provider", default-features = false } +alloy-pubsub = { path = "../alloy/crates/pubsub", default-features = false } +alloy-rpc-client = { path = "../alloy/crates/rpc-client", default-features = false } +alloy-rpc-trace-types = { path = "../alloy/crates/rpc-trace-types", default-features = false } +alloy-rpc-types = { path = "../alloy/crates/rpc-types", default-features = false } +alloy-signer = { path = "../alloy/crates/signer", default-features = false } +alloy-signer-wallet = { path = "../alloy/crates/signer-wallet", default-features = false } +alloy-signer-aws = { path = "../alloy/crates/signer-aws", default-features = false } +alloy-signer-ledger = { path = "../alloy/crates/signer-ledger", default-features = false } +alloy-signer-trezor = { path = "../alloy/crates/signer-trezor", default-features = false } +alloy-transport = { path = "../alloy/crates/transport", default-features = false } +alloy-transport-http = { path = "../alloy/crates/transport-http", default-features = false } +alloy-transport-ipc = { path = "../alloy/crates/transport-ipc", default-features = false } +alloy-transport-ws = { path = "../alloy/crates/transport-ws", default-features = false } alloy-primitives = { version = "0.6.4", features = ["getrandom"] } alloy-dyn-abi = "0.6.4" alloy-json-abi = "0.6.4" diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index 217240a5a873..ab5489e61239 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -25,8 +25,6 @@ alloy-primitives.workspace = true alloy-provider.workspace = true alloy-transport.workspace = true -ethers-core.workspace = true - clap = { version = "4", features = ["derive", "env", "unicode", "wrap_help"] } color-eyre.workspace = true dotenvy = "0.15" diff --git a/crates/cli/src/utils/mod.rs b/crates/cli/src/utils/mod.rs index f5ed9f1f04a1..2e0ed3dad8b0 100644 --- a/crates/cli/src/utils/mod.rs +++ b/crates/cli/src/utils/mod.rs @@ -1,15 +1,12 @@ use alloy_json_abi::JsonAbi; -use alloy_primitives::{utils::format_units, U256}; +use alloy_primitives::U256; use alloy_provider::{network::Ethereum, Provider}; use alloy_transport::Transport; -use ethers_core::types::TransactionReceipt; use eyre::{ContextCompat, Result}; -use foundry_common::types::ToAlloy; use foundry_config::{Chain, Config}; use std::{ ffi::OsStr, future::Future, - ops::Mul, path::{Path, PathBuf}, process::{Command, Output, Stdio}, time::{Duration, SystemTime, UNIX_EPOCH}, @@ -252,40 +249,6 @@ pub fn enable_paint() { } } -/// Prints parts of the receipt to stdout -pub fn print_receipt(chain: Chain, receipt: &TransactionReceipt) { - let gas_used = receipt.gas_used.unwrap_or_default(); - let gas_price = receipt.effective_gas_price.unwrap_or_default(); - foundry_common::shell::println(format!( - "\n##### {chain}\n{status}Hash: {tx_hash:?}{caddr}\nBlock: {bn}\n{gas}\n", - status = if receipt.status.map_or(true, |s| s.is_zero()) { - "❌ [Failed]" - } else { - "✅ [Success]" - }, - tx_hash = receipt.transaction_hash, - caddr = if let Some(addr) = &receipt.contract_address { - format!("\nContract Address: {}", addr.to_alloy().to_checksum(None)) - } else { - String::new() - }, - bn = receipt.block_number.unwrap_or_default(), - gas = if gas_price.is_zero() { - format!("Gas Used: {gas_used}") - } else { - let paid = format_units(gas_used.mul(gas_price).to_alloy(), 18) - .unwrap_or_else(|_| "N/A".into()); - let gas_price = format_units(gas_price.to_alloy(), 9).unwrap_or_else(|_| "N/A".into()); - format!( - "Paid: {} ETH ({gas_used} gas * {} gwei)", - paid.trim_end_matches('0'), - gas_price.trim_end_matches('0').trim_end_matches('.') - ) - }, - )) - .expect("could not print receipt"); -} - /// Useful extensions to [`std::process::Command`]. pub trait CommandUtils { /// Returns the command's output if execution is successful, otherwise, throws an error. diff --git a/crates/common/src/provider/alloy.rs b/crates/common/src/provider/alloy.rs index fb8084f8bea5..2c1099d1c772 100644 --- a/crates/common/src/provider/alloy.rs +++ b/crates/common/src/provider/alloy.rs @@ -8,6 +8,7 @@ use alloy_provider::{ RootProvider, }; use alloy_rpc_client::ClientBuilder; +use alloy_transport::Transport; use ethers_middleware::gas_oracle::{GasCategory, GasOracle, Polygon}; use eyre::{Result, WrapErr}; use foundry_common::types::ToAlloy; @@ -254,7 +255,7 @@ impl ProviderBuilder { /// - polygon /// /// Fallback is the default [`Provider::estimate_eip1559_fees`] implementation -pub async fn estimate_eip1559_fees>( +pub async fn estimate_eip1559_fees, T: Transport + Clone>( provider: &P, chain: Option, ) -> Result { diff --git a/crates/script/Cargo.toml b/crates/script/Cargo.toml index 5ae57482200e..27680eb2fe76 100644 --- a/crates/script/Cargo.toml +++ b/crates/script/Cargo.toml @@ -32,19 +32,25 @@ clap = { version = "4", features = ["derive", "env", "unicode", "wrap_help"] } semver = "1" futures = "0.3" async-recursion = "1.0.5" -alloy-primitives.workspace = true -alloy-dyn-abi.workspace = true + itertools.workspace = true parking_lot = "0.12" yansi = "0.5" -ethers-core.workspace = true -ethers-providers.workspace = true -ethers-signers.workspace = true revm-inspectors.workspace = true alloy-rpc-types.workspace = true alloy-json-abi.workspace = true dialoguer = { version = "0.11", default-features = false } indicatif = "0.17" +alloy-signer.workspace = true +alloy-network.workspace = true +alloy-provider.workspace = true +alloy-chains.workspace = true +alloy-dyn-abi.workspace = true +alloy-primitives.workspace = true +alloy-eips.workspace = true +alloy-transport.workspace = true +alloy-consensus.workspace = true + [dev-dependencies] tempfile = "3" \ No newline at end of file diff --git a/crates/script/src/broadcast.rs b/crates/script/src/broadcast.rs index 224bcc44cf45..85255c0a15d0 100644 --- a/crates/script/src/broadcast.rs +++ b/crates/script/src/broadcast.rs @@ -4,10 +4,14 @@ use crate::{ }; use super::receipts; +use alloy_eips::eip2718::Encodable2718; +use alloy_network::{Ethereum, EthereumSigner, TransactionBuilder}; use alloy_primitives::{utils::format_units, Address, TxHash, U256}; -use ethers_core::types::{transaction::eip2718::TypedTransaction, BlockId}; -use ethers_providers::{JsonRpcClient, Middleware, Provider}; -use ethers_signers::Signer; +use alloy_provider::Provider; +use alloy_network::TxSigner; +use std::sync::Arc; +use alloy_rpc_types::TransactionRequest; +use alloy_transport::Transport; use eyre::{bail, Context, Result}; use forge_verify::provider::VerificationProviderType; use foundry_cheatcodes::ScriptWallets; @@ -16,11 +20,10 @@ use foundry_cli::{ utils::{has_batch_support, has_different_gas_calc}, }; use foundry_common::{ - provider::ethers::{ + provider::alloy::{ estimate_eip1559_fees, get_http_provider, try_get_http_provider, RetryProvider, }, shell, - types::{ToAlloy, ToEthers}, }; use foundry_config::Config; use foundry_wallets::WalletSigner; @@ -28,59 +31,55 @@ use futures::{future::join_all, StreamExt}; use itertools::Itertools; use std::{ collections::{HashMap, HashSet}, - sync::Arc, }; -pub async fn estimate_gas( - tx: &mut TypedTransaction, - provider: &Provider, +pub async fn estimate_gas( + tx: &mut TransactionRequest, + provider: &P, estimate_multiplier: u64, ) -> Result<()> where - T: JsonRpcClient, + P: Provider, + T: Transport + Clone, { // if already set, some RPC endpoints might simply return the gas value that is already // set in the request and omit the estimate altogether, so we remove it here - let _ = tx.gas_mut().take(); + tx.gas = None; - tx.set_gas( + tx.set_gas_limit( provider .estimate_gas(tx, None) .await - .wrap_err_with(|| format!("Failed to estimate gas for tx: {:?}", tx.sighash()))? * - estimate_multiplier / - 100, + .wrap_err("Failed to estimate gas for tx")? * + U256::from(estimate_multiplier) / + U256::from(100), ); Ok(()) } -pub async fn next_nonce( - caller: Address, - provider_url: &str, - block: Option, -) -> eyre::Result { - let provider = Provider::try_from(provider_url) +pub async fn next_nonce(caller: Address, provider_url: &str) -> eyre::Result { + let provider = try_get_http_provider(provider_url) .wrap_err_with(|| format!("bad fork_url provider: {provider_url}"))?; - let res = provider.get_transaction_count(caller.to_ethers(), block).await?.to_alloy(); + let res = provider.get_transaction_count(caller, None).await?; res.try_into().map_err(Into::into) } pub async fn send_transaction( provider: Arc, - mut tx: TypedTransaction, - kind: SendTransactionKind<'_>, + mut tx: TransactionRequest, + kind: SendTransactionKind, sequential_broadcast: bool, is_fixed_gas_limit: bool, estimate_via_rpc: bool, estimate_multiplier: u64, ) -> Result { - let from = tx.from().expect("no sender"); + let from = tx.from.expect("no sender"); if sequential_broadcast { - let nonce = provider.get_transaction_count(*from, None).await?; + let nonce = provider.get_transaction_count(from, None).await?; - let tx_nonce = tx.nonce().expect("no nonce"); - if nonce != *tx_nonce { + let tx_nonce = tx.nonce.expect("no nonce"); + if nonce.to::() != tx_nonce { bail!("EOA nonce changed unexpectedly while sending transactions. Expected {tx_nonce} got {nonce} from provider.") } } @@ -96,29 +95,27 @@ pub async fn send_transaction( debug!("sending transaction from unlocked account {:?}: {:?}", addr, tx); // Submit the transaction - provider.send_transaction(tx, None).await? + provider.send_transaction(tx).await? } SendTransactionKind::Raw(signer) => { debug!("sending transaction: {:?}", tx); - // Signing manually so we skip `fill_transaction` and its `eth_createAccessList` - // request. - let signature = - signer.sign_transaction(&tx).await.wrap_err("Failed to sign transaction")?; + let signer = EthereumSigner::new(signer); + let signed = tx.build(&signer).await?; // Submit the raw transaction - provider.send_raw_transaction(tx.rlp_signed(&signature)).await? + provider.send_raw_transaction(signed.encoded_2718().as_ref()).await? } }; - Ok(pending.tx_hash().to_alloy()) + Ok(*pending.tx_hash()) } /// How to send a single transaction #[derive(Clone)] -pub enum SendTransactionKind<'a> { +pub enum SendTransactionKind { Unlocked(Address), - Raw(&'a WalletSigner), + Raw(Arc), } /// Represents how to send _all_ transactions @@ -126,14 +123,14 @@ pub enum SendTransactionsKind { /// Send via `eth_sendTransaction` and rely on the `from` address being unlocked. Unlocked(HashSet
), /// Send a signed transaction via `eth_sendRawTransaction` - Raw(HashMap), + Raw(HashMap>), } impl SendTransactionsKind { /// Returns the [`SendTransactionKind`] for the given address /// /// Returns an error if no matching signer is found or the address is not unlocked - pub fn for_sender(&self, addr: &Address) -> Result> { + pub fn for_sender(&self, addr: &Address) -> Result { match self { SendTransactionsKind::Unlocked(unlocked) => { if !unlocked.contains(addr) { @@ -143,7 +140,7 @@ impl SendTransactionsKind { } SendTransactionsKind::Raw(wallets) => { if let Some(wallet) = wallets.get(addr) { - Ok(SendTransactionKind::Raw(wallet)) + Ok(SendTransactionKind::Raw(wallet.clone())) } else { bail!("No matching signer for {:?} found", addr) } @@ -202,8 +199,8 @@ impl BundledState { .iter() .flat_map(|sequence| { sequence - .typed_transactions() - .map(|tx| (*tx.from().expect("No sender for onchain transaction!")).to_alloy()) + .transactions() + .map(|tx| (tx.from().expect("No sender for onchain transaction!"))) }) .collect::>(); @@ -233,6 +230,8 @@ impl BundledState { ); } + let signers = signers.into_iter().map(|(addr, signer)| (addr, Arc::new(signer))).collect(); + SendTransactionsKind::Raw(signers) }; @@ -244,22 +243,20 @@ impl BundledState { if already_broadcasted < sequence.transactions.len() { // Make a one-time gas price estimation - let (gas_price, eip1559_fees) = match self.args.with_gas_price { - None => match sequence.transactions.front().unwrap().typed_tx() { - TypedTransaction::Eip1559(_) => { - let mut fees = estimate_eip1559_fees(&provider, Some(sequence.chain)) + let (gas_price, eip1559_fees) = match (self.args.legacy, self.args.with_gas_price) { + (_, Some(gas_price)) => (Some(gas_price), None), + (true, None) => (Some(provider.get_gas_price().await?), None), + (false, None) => { + let mut fees = estimate_eip1559_fees(&provider, Some(sequence.chain)) .await - .wrap_err("Failed to estimate EIP1559 fees. This chain might not support EIP1559, try adding --legacy to your command.")?; - - if let Some(priority_gas_price) = self.args.priority_gas_price { - fees.1 = priority_gas_price.to_ethers(); - } + .wrap_err("Failed to estimate EIP1559 fees. This chain might not support EIP1559, try adding --legacy to your command.")?; - (None, Some(fees)) + if let Some(priority_gas_price) = self.args.priority_gas_price { + fees.max_priority_fee_per_gas = priority_gas_price; } - _ => (provider.get_gas_price().await.ok(), None), - }, - Some(gas_price) => (Some(gas_price.to_ethers()), None), + + (None, Some(fees)) + } }; // Iterate through transactions, matching the `from` field with the associated @@ -269,35 +266,21 @@ impl BundledState { .iter() .skip(already_broadcasted) .map(|tx_with_metadata| { - let tx = tx_with_metadata.typed_tx(); - let from = - (*tx.from().expect("No sender for onchain transaction!")).to_alloy(); + let tx = tx_with_metadata.tx(); + let from = tx.from().expect("No sender for onchain transaction!"); let kind = send_kind.for_sender(&from)?; let is_fixed_gas_limit = tx_with_metadata.is_fixed_gas_limit; let mut tx = tx.clone(); - tx.set_chain_id(sequence.chain); if let Some(gas_price) = gas_price { tx.set_gas_price(gas_price); } else { let eip1559_fees = eip1559_fees.expect("was set above"); - // fill gas price - match tx { - TypedTransaction::Eip1559(ref mut inner) => { - inner.max_priority_fee_per_gas = Some(eip1559_fees.1); - inner.max_fee_per_gas = Some(eip1559_fees.0); - } - _ => { - // If we're here, it means that first transaction of the - // sequence was EIP1559 transaction (see match statement above), - // however, we can only have transactions of the same type in - // the sequence. - unreachable!() - } - } + tx.set_max_priority_fee_per_gas(eip1559_fees.max_priority_fee_per_gas); + tx.set_max_fee_per_gas(eip1559_fees.max_fee_per_gas); } Ok((tx, kind, is_fixed_gas_limit)) @@ -381,9 +364,13 @@ impl BundledState { let (total_gas, total_gas_price, total_paid) = sequence.receipts.iter().fold( (U256::ZERO, U256::ZERO, U256::ZERO), |acc, receipt| { - let gas_used = receipt.gas_used.unwrap_or_default().to_alloy(); - let gas_price = receipt.effective_gas_price.unwrap_or_default().to_alloy(); - (acc.0 + gas_used, acc.1 + gas_price, acc.2 + gas_used * gas_price) + let gas_used = receipt.gas_used.unwrap_or_default(); + let gas_price = receipt.effective_gas_price; + ( + acc.0 + gas_used, + acc.1 + U256::from(gas_price), + acc.2 + gas_used * U256::from(gas_price), + ) }, ); let paid = format_units(total_paid, 18).unwrap_or_else(|_| "N/A".to_string()); diff --git a/crates/script/src/build.rs b/crates/script/src/build.rs index 41e898d96a72..b0d0b758c4e8 100644 --- a/crates/script/src/build.rs +++ b/crates/script/src/build.rs @@ -7,14 +7,13 @@ use crate::{ }; use alloy_primitives::{Address, Bytes}; -use ethers_providers::Middleware; +use alloy_provider::Provider; use eyre::{Context, OptionExt, Result}; use foundry_cheatcodes::ScriptWallets; use foundry_cli::utils::get_cached_entry_by_name; use foundry_common::{ compile::{self, ContractSources, ProjectCompiler}, - provider::ethers::try_get_http_provider, - types::ToAlloy, + provider::alloy::try_get_http_provider, ContractsByArtifact, }; use foundry_compilers::{ @@ -262,7 +261,7 @@ impl CompiledState { } else { let fork_url = self.script_config.evm_opts.fork_url.clone().ok_or_eyre("Missing --fork-url field, if you were trying to broadcast a multi-chain sequence, please use --multi flag")?; let provider = Arc::new(try_get_http_provider(fork_url)?); - Some(provider.get_chainid().await?.as_u64()) + Some(provider.get_chain_id().await?.to::()) }; let sequence = match self.try_load_sequence(chain, false) { @@ -290,7 +289,7 @@ impl CompiledState { s.transactions .iter() .skip(s.receipts.len()) - .map(|t| t.transaction.from().expect("from is missing in script artifact")) + .map(|t| t.transaction.from.expect("from is missing in script artifact")) }); let available_signers = self @@ -298,7 +297,7 @@ impl CompiledState { .signers() .map_err(|e| eyre::eyre!("Failed to get available signers: {}", e))?; - if !froms.all(|from| available_signers.contains(&from.to_alloy())) { + if !froms.all(|from| available_signers.contains(&from)) { // IF we are missing required signers, execute script as we might need to collect // private keys from the execution. let executed = self.link()?.prepare_execution().await?.execute().await?; diff --git a/crates/script/src/execute.rs b/crates/script/src/execute.rs index cdf4353d3860..cc0b98ddfc1c 100644 --- a/crates/script/src/execute.rs +++ b/crates/script/src/execute.rs @@ -7,16 +7,16 @@ use crate::{ use super::{runner::ScriptRunner, JsonResult, NestedValue, ScriptResult}; use alloy_dyn_abi::FunctionExt; use alloy_json_abi::{Function, InternalType, JsonAbi}; -use alloy_primitives::{Address, Bytes, U64}; +use alloy_primitives::{Address, Bytes}; +use alloy_provider::Provider; use alloy_rpc_types::request::TransactionRequest; use async_recursion::async_recursion; -use ethers_providers::Middleware; use eyre::Result; use foundry_cheatcodes::ScriptWallets; use foundry_cli::utils::{ensure_clean_constructor, needs_setup}; use foundry_common::{ fmt::{format_token, format_token_raw}, - provider::ethers::{get_http_provider, RpcUrl}, + provider::alloy::{get_http_provider, RpcUrl}, shell, ContractsByArtifact, }; use foundry_compilers::artifacts::ContractBytecodeSome; @@ -130,7 +130,7 @@ impl PreExecutionState { transaction: TransactionRequest { from: Some(self.script_config.evm_opts.sender), input: Some(bytes.clone()).into(), - nonce: Some(U64::from(self.script_config.sender_nonce + i as u64)), + nonce: Some(self.script_config.sender_nonce + i as u64), ..Default::default() }, }) @@ -248,7 +248,7 @@ impl RpcData { async fn check_shanghai_support(&self) -> Result<()> { let chain_ids = self.total_rpcs.iter().map(|rpc| async move { let provider = get_http_provider(rpc); - let id = provider.get_chainid().await.ok()?; + let id = provider.get_chain_id().await.ok()?; let id_u64: u64 = id.try_into().ok()?; NamedChain::try_from(id_u64).ok() }); diff --git a/crates/script/src/lib.rs b/crates/script/src/lib.rs index 6af8faf61cb7..2fd6bdba8f06 100644 --- a/crates/script/src/lib.rs +++ b/crates/script/src/lib.rs @@ -7,11 +7,11 @@ use self::transaction::AdditionalContract; use crate::runner::ScriptRunner; use alloy_json_abi::{Function, JsonAbi}; use alloy_primitives::{Address, Bytes, Log, U256}; +use alloy_signer::Signer; use broadcast::next_nonce; use build::PreprocessedState; use clap::{Parser, ValueHint}; use dialoguer::Confirm; -use ethers_signers::Signer; use eyre::{ContextCompat, Result, WrapErr}; use forge_verify::RetryArgs; use foundry_cli::{opts::CoreBuildArgs, utils::LoadConfig}; @@ -21,9 +21,7 @@ use foundry_common::{ errors::UnlinkedByteCode, evm::{Breakpoints, EvmArgs}, provider::ethers::RpcUrl, - shell, - types::ToAlloy, - CONTRACT_MAX_SIZE, SELECTOR_LEN, + shell, CONTRACT_MAX_SIZE, SELECTOR_LEN, }; use foundry_compilers::{artifacts::ContractBytecodeSome, ArtifactId}; use foundry_config::{ @@ -517,7 +515,7 @@ pub struct ScriptConfig { impl ScriptConfig { pub async fn new(config: Config, evm_opts: EvmOpts) -> Result { let sender_nonce = if let Some(fork_url) = evm_opts.fork_url.as_ref() { - next_nonce(evm_opts.sender, fork_url, None).await? + next_nonce(evm_opts.sender, fork_url).await? } else { // dapptools compatibility 1 @@ -527,7 +525,7 @@ impl ScriptConfig { pub async fn update_sender(&mut self, sender: Address) -> Result<()> { self.sender_nonce = if let Some(fork_url) = self.evm_opts.fork_url.as_ref() { - next_nonce(sender, fork_url, None).await? + next_nonce(sender, fork_url).await? } else { // dapptools compatibility 1 diff --git a/crates/script/src/providers.rs b/crates/script/src/providers.rs index f29a72629320..8163707cf465 100644 --- a/crates/script/src/providers.rs +++ b/crates/script/src/providers.rs @@ -1,11 +1,7 @@ use alloy_primitives::U256; -use ethers_providers::{Middleware, Provider}; +use alloy_provider::{utils::Eip1559Estimation, Provider}; use eyre::{Result, WrapErr}; -use foundry_common::{ - provider::ethers::{get_http_provider, RpcUrl}, - runtime_client::RuntimeClient, - types::ToAlloy, -}; +use foundry_common::provider::alloy::{get_http_provider, RetryProvider, RpcUrl}; use foundry_config::Chain; use std::{ collections::{hash_map::Entry, HashMap}, @@ -47,7 +43,7 @@ impl Deref for ProvidersManager { /// Holds related metadata to each provider RPC. #[derive(Debug)] pub struct ProviderInfo { - pub provider: Arc>, + pub provider: Arc, pub chain: u64, pub gas_price: GasPrice, pub is_legacy: bool, @@ -57,13 +53,13 @@ pub struct ProviderInfo { #[derive(Debug)] pub enum GasPrice { Legacy(Result), - EIP1559(Result<(U256, U256)>), + EIP1559(Result), } impl ProviderInfo { pub async fn new(rpc: &str, mut is_legacy: bool) -> Result { let provider = Arc::new(get_http_provider(rpc)); - let chain = provider.get_chainid().await?.as_u64(); + let chain = provider.get_chain_id().await?.to::(); if let Some(chain) = Chain::from(chain).named() { is_legacy |= chain.is_legacy(); @@ -71,19 +67,11 @@ impl ProviderInfo { let gas_price = if is_legacy { GasPrice::Legacy( - provider - .get_gas_price() - .await - .wrap_err("Failed to get legacy gas price") - .map(|p| p.to_alloy()), + provider.get_gas_price().await.wrap_err("Failed to get legacy gas price"), ) } else { GasPrice::EIP1559( - provider - .estimate_eip1559_fees(None) - .await - .wrap_err("Failed to get EIP-1559 fees") - .map(|p| (p.0.to_alloy(), p.1.to_alloy())), + provider.estimate_eip1559_fees(None).await.wrap_err("Failed to get EIP-1559 fees"), ) }; @@ -94,7 +82,7 @@ impl ProviderInfo { pub fn gas_price(&self) -> Result { let res = match &self.gas_price { GasPrice::Legacy(res) => res.as_ref(), - GasPrice::EIP1559(res) => res.as_ref().map(|res| &res.0), + GasPrice::EIP1559(res) => res.as_ref().map(|res| &res.max_fee_per_gas), }; match res { Ok(val) => Ok(*val), diff --git a/crates/script/src/receipts.rs b/crates/script/src/receipts.rs index 29848aad3564..a3bf398aca42 100644 --- a/crates/script/src/receipts.rs +++ b/crates/script/src/receipts.rs @@ -1,13 +1,11 @@ use super::sequence::ScriptSequence; -use alloy_primitives::TxHash; -use ethers_core::types::TransactionReceipt; -use ethers_providers::{Middleware, PendingTransaction}; +use alloy_chains::Chain; +use alloy_primitives::{utils::format_units, TxHash, U256}; +use alloy_provider::{PendingTransactionBuilder, Provider}; +use alloy_rpc_types::TransactionReceipt; use eyre::Result; -use foundry_cli::{init_progress, update_progress, utils::print_receipt}; -use foundry_common::{ - provider::ethers::RetryProvider, - types::{ToAlloy, ToEthers}, -}; +use foundry_cli::{init_progress, update_progress}; +use foundry_common::provider::alloy::RetryProvider; use futures::StreamExt; use std::sync::Arc; @@ -20,7 +18,7 @@ enum TxStatus { impl From for TxStatus { fn from(receipt: TransactionReceipt) -> Self { - let status = receipt.status.expect("receipt is from an ancient, pre-EIP658 block"); + let status = receipt.status_code.expect("receipt is from an ancient, pre-EIP658 block"); if status.is_zero() { TxStatus::Revert(receipt) } else { @@ -87,7 +85,7 @@ pub async fn clear_pendings( } Ok(TxStatus::Success(receipt)) => { trace!(tx_hash=?tx_hash, "received tx receipt"); - deployment_sequence.remove_pending(receipt.transaction_hash.to_alloy()); + deployment_sequence.remove_pending(receipt.transaction_hash); receipts.push(receipt); } Ok(TxStatus::Revert(receipt)) => { @@ -95,7 +93,7 @@ pub async fn clear_pendings( // if this is not removed from pending, then the script becomes // un-resumable. Is this desirable on reverts? warn!(tx_hash=?tx_hash, "Transaction Failure"); - deployment_sequence.remove_pending(receipt.transaction_hash.to_alloy()); + deployment_sequence.remove_pending(receipt.transaction_hash); errors.push(format!("Transaction Failure: {:?}", receipt.transaction_hash)); } } @@ -105,7 +103,7 @@ pub async fn clear_pendings( } // sort receipts by blocks asc and index - receipts.sort_unstable(); + receipts.sort_by_key(|r| (r.block_number, r.transaction_index)); // print all receipts for receipt in receipts { @@ -136,20 +134,53 @@ async fn check_tx_status( // still neatly return the tuple let result = async move { // First check if there's a receipt - let receipt_opt = provider.get_transaction_receipt(hash.to_ethers()).await?; + let receipt_opt = provider.get_transaction_receipt(hash).await?; if let Some(receipt) = receipt_opt { return Ok(receipt.into()); } // If the tx is present in the mempool, run the pending tx future, and // assume the next drop is really really real - let pending_res = PendingTransaction::new(hash.to_ethers(), provider).await?; - match pending_res { - Some(receipt) => Ok(receipt.into()), - None => Ok(TxStatus::Dropped), - } + Ok(PendingTransactionBuilder::new(provider, hash) + .get_receipt() + .await + .map_or(TxStatus::Dropped, |r| r.into())) } .await; (hash, result) } + +/// Prints parts of the receipt to stdout +pub fn print_receipt(chain: Chain, receipt: &TransactionReceipt) { + let gas_used = receipt.gas_used.unwrap_or_default(); + let gas_price = receipt.effective_gas_price; + foundry_common::shell::println(format!( + "\n##### {chain}\n{status}Hash: {tx_hash:?}{caddr}\nBlock: {bn}\n{gas}\n", + status = if receipt.status_code.map_or(true, |s| s.is_zero()) { + "❌ [Failed]" + } else { + "✅ [Success]" + }, + tx_hash = receipt.transaction_hash, + caddr = if let Some(addr) = &receipt.contract_address { + format!("\nContract Address: {}", addr.to_checksum(None)) + } else { + String::new() + }, + bn = receipt.block_number.unwrap_or_default(), + gas = if gas_price.is_zero() { + format!("Gas Used: {gas_used}") + } else { + let paid = format_units(gas_used.saturating_mul(gas_price.to()), 18) + .unwrap_or_else(|_| "N/A".into()); + let gas_price = format_units(U256::from(gas_price), 9).unwrap_or_else(|_| "N/A".into()); + format!( + "Paid: {} ETH ({gas_used} gas * {} gwei)", + paid.trim_end_matches('0'), + gas_price.trim_end_matches('0').trim_end_matches('.') + ) + }, + )) + .expect("could not print receipt"); +} diff --git a/crates/script/src/sequence.rs b/crates/script/src/sequence.rs index 9fdee7b021bf..fb0eae1e1222 100644 --- a/crates/script/src/sequence.rs +++ b/crates/script/src/sequence.rs @@ -1,18 +1,14 @@ use super::{multi_sequence::MultiChainSequence, NestedValue}; use crate::{ - transaction::{wrapper, AdditionalContract, TransactionWithMetadata}, + transaction::{AdditionalContract, TransactionWithMetadata}, verify::VerifyBundle, }; use alloy_primitives::{Address, TxHash}; -use ethers_core::types::{transaction::eip2718::TypedTransaction, TransactionReceipt}; +use alloy_rpc_types::{TransactionReceipt, TransactionRequest}; use eyre::{ContextCompat, Result, WrapErr}; use forge_verify::provider::VerificationProviderType; use foundry_cli::utils::{now, Git}; -use foundry_common::{ - fs, shell, - types::{ToAlloy, ToEthers}, - SELECTOR_LEN, -}; +use foundry_common::{fs, shell, SELECTOR_LEN}; use foundry_compilers::ArtifactId; use foundry_config::Config; use serde::{Deserialize, Serialize}; @@ -91,7 +87,6 @@ pub const DRY_RUN_DIR: &str = "dry-run"; #[derive(Clone, Default, Serialize, Deserialize)] pub struct ScriptSequence { pub transactions: VecDeque, - #[serde(serialize_with = "wrapper::serialize_receipts")] pub receipts: Vec, pub libraries: Vec, pub pending: Vec, @@ -207,7 +202,7 @@ impl ScriptSequence { /// Sorts all receipts with ascending transaction index pub fn sort_receipts(&mut self) { - self.receipts.sort_unstable() + self.receipts.sort_by_key(|r| (r.block_number, r.transaction_index)); } pub fn add_pending(&mut self, index: usize, tx_hash: TxHash) { @@ -284,13 +279,13 @@ impl ScriptSequence { let mut offset = 0; if tx.is_create2() { - receipt.contract_address = tx.contract_address.map(|a| a.to_ethers()); + receipt.contract_address = tx.contract_address; offset = 32; } // Verify contract created directly from the transaction if let (Some(address), Some(data)) = - (receipt.contract_address.map(|h| h.to_alloy()), tx.typed_tx().data()) + (receipt.contract_address, tx.tx().input.input()) { match verify.get_verify_args(address, offset, &data.0, &self.libraries) { Some(verify) => future_verifications.push(verify.run()), @@ -300,7 +295,7 @@ impl ScriptSequence { // Verify potential contracts created during the transaction execution for AdditionalContract { address, init_code, .. } in &tx.additional_contracts { - match verify.get_verify_args(*address, 0, init_code, &self.libraries) { + match verify.get_verify_args(*address, 0, init_code.as_ref(), &self.libraries) { Some(verify) => future_verifications.push(verify.run()), None => unverifiable_contracts.push(*address), }; @@ -357,8 +352,8 @@ impl ScriptSequence { } /// Returns the list of the transactions without the metadata. - pub fn typed_transactions(&self) -> impl Iterator { - self.transactions.iter().map(|tx| tx.typed_tx()) + pub fn transactions(&self) -> impl Iterator { + self.transactions.iter().map(|tx| tx.tx()) } pub fn fill_sensitive(&mut self, sensitive: &SensitiveScriptSequence) { diff --git a/crates/script/src/simulate.rs b/crates/script/src/simulate.rs index 07e962ddff32..38df550bb4cf 100644 --- a/crates/script/src/simulate.rs +++ b/crates/script/src/simulate.rs @@ -13,13 +13,12 @@ use crate::{ sequence::get_commit_hash, ScriptArgs, ScriptConfig, ScriptResult, }; +use alloy_network::TransactionBuilder; use alloy_primitives::{utils::format_units, Address, U256}; use eyre::{Context, Result}; use foundry_cheatcodes::{BroadcastableTransactions, ScriptWallets}; use foundry_cli::utils::{has_different_gas_calc, now}; -use foundry_common::{ - get_contract_name, provider::ethers::RpcUrl, shell, types::ToAlloy, ContractsByArtifact, -}; +use foundry_common::{get_contract_name, provider::ethers::RpcUrl, shell, ContractsByArtifact}; use foundry_evm::traces::render_trace_arena; use futures::future::join_all; use parking_lot::RwLock; @@ -293,15 +292,14 @@ impl FilledTransactionsState { let provider_info = manager.get_or_init_provider(&tx.rpc, self.args.legacy).await?; // Handles chain specific requirements. - tx.change_type(provider_info.is_legacy); tx.transaction.set_chain_id(provider_info.chain); if !self.args.skip_simulation { - let typed_tx = tx.typed_tx_mut(); + let tx = tx.tx_mut(); if has_different_gas_calc(provider_info.chain) { trace!("estimating with different gas calculation"); - let gas = *typed_tx.gas().expect("gas is set by simulation."); + let gas = tx.gas.expect("gas is set by simulation."); // We are trying to show the user an estimation of the total gas usage. // @@ -314,22 +312,19 @@ impl FilledTransactionsState { // for chains where `has_different_gas_calc` returns true, // we await each transaction before broadcasting the next // one. - if let Err(err) = estimate_gas( - typed_tx, - &provider_info.provider, - self.args.gas_estimate_multiplier, - ) - .await + if let Err(err) = + estimate_gas(tx, &provider_info.provider, self.args.gas_estimate_multiplier) + .await { trace!("gas estimation failed: {err}"); // Restore gas value, since `estimate_gas` will remove it. - typed_tx.set_gas(gas); + tx.set_gas_limit(gas); } } let total_gas = total_gas_per_rpc.entry(tx_rpc.clone()).or_insert(U256::ZERO); - *total_gas += (*typed_tx.gas().expect("gas is set")).to_alloy(); + *total_gas += tx.gas.expect("gas is set"); } new_sequence.push_back(tx); diff --git a/crates/script/src/transaction.rs b/crates/script/src/transaction.rs index cea8ed326772..061eba64b6b9 100644 --- a/crates/script/src/transaction.rs +++ b/crates/script/src/transaction.rs @@ -1,18 +1,9 @@ use super::{artifacts::ArtifactInfo, ScriptResult}; use alloy_dyn_abi::JsonAbiExt; -use alloy_primitives::{Address, Bytes, B256, U256}; +use alloy_primitives::{Address, Bytes, B256}; use alloy_rpc_types::request::TransactionRequest; -use ethers_core::types::{ - transaction::eip2718::TypedTransaction, NameOrAddress, - TransactionRequest as EthersTransactionRequest, -}; use eyre::{ContextCompat, Result, WrapErr}; -use foundry_common::{ - fmt::format_token_raw, - provider::ethers::RpcUrl, - types::{ToAlloy, ToEthers}, - SELECTOR_LEN, -}; +use foundry_common::{fmt::format_token_raw, provider::ethers::RpcUrl, SELECTOR_LEN}; use foundry_evm::{constants::DEFAULT_CREATE2_DEPLOYER, traces::CallTraceDecoder}; use itertools::Itertools; use revm_inspectors::tracing::types::CallKind; @@ -24,7 +15,6 @@ use std::collections::BTreeMap; pub struct AdditionalContract { #[serde(rename = "transactionType")] pub opcode: CallKind, - #[serde(serialize_with = "wrapper::serialize_addr")] pub address: Address, pub init_code: Bytes, } @@ -37,7 +27,7 @@ pub struct TransactionWithMetadata { pub opcode: CallKind, #[serde(default = "default_string")] pub contract_name: Option, - #[serde(default = "default_address", serialize_with = "wrapper::serialize_opt_addr")] + #[serde(default = "default_address")] pub contract_address: Option
, #[serde(default = "default_string")] pub function: Option, @@ -45,7 +35,7 @@ pub struct TransactionWithMetadata { pub arguments: Option>, #[serde(skip)] pub rpc: RpcUrl, - pub transaction: TypedTransaction, + pub transaction: TransactionRequest, pub additional_contracts: Vec, pub is_fixed_gas_limit: bool, } @@ -64,18 +54,7 @@ fn default_vec_of_strings() -> Option> { impl TransactionWithMetadata { pub fn from_tx_request(transaction: TransactionRequest) -> Self { - Self { - transaction: TypedTransaction::Legacy(EthersTransactionRequest { - from: transaction.from.map(ToEthers::to_ethers), - to: transaction.to.map(ToEthers::to_ethers).map(Into::into), - value: transaction.value.map(ToEthers::to_ethers), - data: transaction.input.into_input().map(ToEthers::to_ethers), - nonce: transaction.nonce.map(U256::from), - gas: transaction.gas.map(ToEthers::to_ethers), - ..Default::default() - }), - ..Default::default() - } + Self { transaction, ..Default::default() } } pub fn new( @@ -92,8 +71,8 @@ impl TransactionWithMetadata { metadata.is_fixed_gas_limit = is_fixed_gas_limit; // Specify if any contract was directly created with this transaction - if let Some(NameOrAddress::Address(to)) = metadata.transaction.to().cloned() { - if to.to_alloy() == DEFAULT_CREATE2_DEPLOYER { + if let Some(to) = metadata.transaction.to { + if to == DEFAULT_CREATE2_DEPLOYER { metadata.set_create( true, Address::from_slice(&result.returned), @@ -101,10 +80,10 @@ impl TransactionWithMetadata { )?; } else { metadata - .set_call(to.to_alloy(), local_contracts, decoder) + .set_call(to, local_contracts, decoder) .wrap_err("Could not decode transaction type.")?; } - } else if metadata.transaction.to().is_none() { + } else { metadata.set_create( false, result.address.wrap_err("There should be a contract address from CREATE.")?, @@ -150,7 +129,7 @@ impl TransactionWithMetadata { self.contract_name = info.map(|info| info.contract_name.clone()); self.contract_address = Some(address); - let Some(data) = self.transaction.data() else { return Ok(()) }; + let Some(data) = self.transaction.input.input() else { return Ok(()) }; let Some(info) = info else { return Ok(()) }; // `create2` transactions are prefixed by a 32 byte salt. @@ -197,7 +176,7 @@ impl TransactionWithMetadata { self.opcode = CallKind::Call; self.contract_address = Some(target); - let Some(data) = self.transaction.data() else { return Ok(()) }; + let Some(data) = self.transaction.input.input() else { return Ok(()) }; if data.len() < SELECTOR_LEN { return Ok(()); } @@ -229,19 +208,11 @@ impl TransactionWithMetadata { Ok(()) } - pub fn change_type(&mut self, is_legacy: bool) { - self.transaction = if is_legacy { - TypedTransaction::Legacy(self.transaction.clone().into()) - } else { - TypedTransaction::Eip1559(self.transaction.clone().into()) - }; - } - - pub fn typed_tx(&self) -> &TypedTransaction { + pub fn tx(&self) -> &TransactionRequest { &self.transaction } - pub fn typed_tx_mut(&mut self) -> &mut TypedTransaction { + pub fn tx_mut(&mut self) -> &mut TransactionRequest { &mut self.transaction } @@ -249,208 +220,3 @@ impl TransactionWithMetadata { self.opcode == CallKind::Create2 } } - -// wrapper for modifying ethers-rs type serialization -pub mod wrapper { - pub use super::*; - use ethers_core::{ - types::{Bloom, Bytes, Log, TransactionReceipt, H256, U256, U64}, - utils::to_checksum, - }; - - pub fn serialize_addr(addr: &Address, serializer: S) -> Result - where - S: serde::Serializer, - { - serializer.serialize_str(&to_checksum(&addr.to_ethers(), None)) - } - - pub fn serialize_opt_addr(opt: &Option
, serializer: S) -> Result - where - S: serde::Serializer, - { - match opt { - Some(addr) => serialize_addr(addr, serializer), - None => serializer.serialize_none(), - } - } - - pub fn serialize_vec_with_wrapped( - vec: &[T], - serializer: S, - ) -> Result - where - S: serde::Serializer, - T: Clone, - WrappedType: serde::Serialize + From, - { - serializer.collect_seq(vec.iter().cloned().map(WrappedType::from)) - } - - // copied from https://github.com/gakonst/ethers-rs - #[derive(Serialize, Deserialize)] - struct WrappedLog { - /// The contract address that emitted the log. - #[serde(serialize_with = "serialize_addr")] - pub address: Address, - - /// 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.) - pub topics: Vec, - - /// Data - pub data: Bytes, - - /// Block Hash - #[serde(rename = "blockHash")] - #[serde(skip_serializing_if = "Option::is_none")] - pub block_hash: Option, - - /// Block Number - #[serde(rename = "blockNumber")] - #[serde(skip_serializing_if = "Option::is_none")] - pub block_number: Option, - - /// Transaction Hash - #[serde(rename = "transactionHash")] - #[serde(skip_serializing_if = "Option::is_none")] - pub transaction_hash: Option, - - /// Transaction Index - #[serde(rename = "transactionIndex")] - #[serde(skip_serializing_if = "Option::is_none")] - pub transaction_index: Option, - - /// Integer of the log index position in the block. None if it's a pending log. - #[serde(rename = "logIndex")] - #[serde(skip_serializing_if = "Option::is_none")] - pub log_index: Option, - - /// Integer of the transactions index position log was created from. - /// None when it's a pending log. - #[serde(rename = "transactionLogIndex")] - #[serde(skip_serializing_if = "Option::is_none")] - pub transaction_log_index: Option, - - /// Log Type - #[serde(rename = "logType")] - #[serde(skip_serializing_if = "Option::is_none")] - pub log_type: Option, - - /// True when the log was removed, due to a chain reorganization. - /// false if it's a valid log. - #[serde(skip_serializing_if = "Option::is_none")] - pub removed: Option, - } - impl From for WrappedLog { - fn from(log: Log) -> Self { - Self { - address: log.address.to_alloy(), - topics: log.topics, - data: log.data, - block_hash: log.block_hash, - block_number: log.block_number, - transaction_hash: log.transaction_hash, - transaction_index: log.transaction_index, - log_index: log.log_index, - transaction_log_index: log.transaction_log_index, - log_type: log.log_type, - removed: log.removed, - } - } - } - - fn serialize_logs( - logs: &[Log], - serializer: S, - ) -> Result { - serialize_vec_with_wrapped::(logs, serializer) - } - - // "Receipt" of an executed transaction: details of its execution. - // copied from https://github.com/gakonst/ethers-rs - #[derive(Clone, Default, Serialize, Deserialize)] - pub struct WrappedTransactionReceipt { - /// Transaction hash. - #[serde(rename = "transactionHash")] - pub transaction_hash: H256, - /// Index within the block. - #[serde(rename = "transactionIndex")] - pub transaction_index: U64, - /// Hash of the block this transaction was included within. - #[serde(rename = "blockHash")] - pub block_hash: Option, - /// Number of the block this transaction was included within. - #[serde(rename = "blockNumber")] - pub block_number: Option, - /// The address of the sender. - #[serde(serialize_with = "serialize_addr")] - pub from: Address, - // The address of the receiver. `None` when its a contract creation transaction. - #[serde(serialize_with = "serialize_opt_addr")] - pub to: Option
, - /// Cumulative gas used within the block after this was executed. - #[serde(rename = "cumulativeGasUsed")] - pub cumulative_gas_used: U256, - /// Gas used by this transaction alone. - /// - /// Gas used is `None` if the client is running in light client mode. - #[serde(rename = "gasUsed")] - pub gas_used: Option, - /// Contract address created, or `None` if not a deployment. - #[serde(rename = "contractAddress", serialize_with = "serialize_opt_addr")] - pub contract_address: Option
, - /// Logs generated within this transaction. - #[serde(serialize_with = "serialize_logs")] - pub logs: Vec, - /// Status: either 1 (success) or 0 (failure). Only present after activation of [EIP-658](https://eips.ethereum.org/EIPS/eip-658) - pub status: Option, - /// State root. Only present before activation of [EIP-658](https://eips.ethereum.org/EIPS/eip-658) - #[serde(default, skip_serializing_if = "Option::is_none")] - pub root: Option, - /// Logs bloom - #[serde(rename = "logsBloom")] - pub logs_bloom: Bloom, - /// Transaction type, Some(1) for AccessList transaction, None for Legacy - #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] - pub transaction_type: Option, - /// The price paid post-execution by the transaction (i.e. base fee + priority fee). - /// Both fields in 1559-style transactions are *maximums* (max fee + max priority fee), the - /// amount that's actually paid by users can only be determined post-execution - #[serde(rename = "effectiveGasPrice", default, skip_serializing_if = "Option::is_none")] - pub effective_gas_price: Option, - } - impl From for WrappedTransactionReceipt { - fn from(receipt: TransactionReceipt) -> Self { - Self { - transaction_hash: receipt.transaction_hash, - transaction_index: receipt.transaction_index, - block_hash: receipt.block_hash, - block_number: receipt.block_number, - from: receipt.from.to_alloy(), - to: receipt.to.map(|addr| addr.to_alloy()), - cumulative_gas_used: receipt.cumulative_gas_used, - gas_used: receipt.gas_used, - contract_address: receipt.contract_address.map(|addr| addr.to_alloy()), - logs: receipt.logs, - status: receipt.status, - root: receipt.root, - logs_bloom: receipt.logs_bloom, - transaction_type: receipt.transaction_type, - effective_gas_price: receipt.effective_gas_price, - } - } - } - - pub fn serialize_receipts( - receipts: &[TransactionReceipt], - serializer: S, - ) -> Result { - serialize_vec_with_wrapped::( - receipts, serializer, - ) - } -} From dc1df120d2fbf53311661f9a1bfb107710e5bb45 Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Fri, 22 Mar 2024 12:51:47 +0400 Subject: [PATCH 19/63] fix script --- Cargo.lock | 146 ++++++++++++--------------------- Cargo.toml | 42 +++++----- crates/script/Cargo.toml | 1 - crates/script/src/broadcast.rs | 32 ++++---- 4 files changed, 89 insertions(+), 132 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c5e37e09e1c5..224529ea5a46 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -90,37 +90,29 @@ dependencies = [ [[package]] name = "alloy-consensus" version = "0.1.0" +source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ - "alloy-eips 0.1.0", + "alloy-eips", "alloy-primitives", "alloy-rlp", - "alloy-serde 0.1.0", + "alloy-serde", "c-kzg", "serde", "sha2", "thiserror", ] -[[package]] -name = "alloy-consensus" -version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" -dependencies = [ - "alloy-eips 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", - "alloy-primitives", - "alloy-rlp", -] - [[package]] name = "alloy-contract" version = "0.1.0" +source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-dyn-abi", "alloy-json-abi", "alloy-network", "alloy-primitives", "alloy-provider", - "alloy-rpc-types 0.1.0", + "alloy-rpc-types", "alloy-sol-types", "alloy-transport", "futures", @@ -149,15 +141,6 @@ dependencies = [ "winnow 0.6.5", ] -[[package]] -name = "alloy-eips" -version = "0.1.0" -dependencies = [ - "alloy-primitives", - "alloy-rlp", - "serde", -] - [[package]] name = "alloy-eips" version = "0.1.0" @@ -171,9 +154,10 @@ dependencies = [ [[package]] name = "alloy-genesis" version = "0.1.0" +source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-primitives", - "alloy-serde 0.1.0", + "alloy-serde", "serde", ] @@ -191,6 +175,7 @@ dependencies = [ [[package]] name = "alloy-json-rpc" version = "0.1.0" +source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-primitives", "serde", @@ -201,12 +186,13 @@ dependencies = [ [[package]] name = "alloy-network" version = "0.1.0" +source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ - "alloy-consensus 0.1.0", - "alloy-eips 0.1.0", + "alloy-consensus", + "alloy-eips", "alloy-json-rpc", "alloy-primitives", - "alloy-rpc-types 0.1.0", + "alloy-rpc-types", "alloy-signer", "async-trait", "futures-utils-wasm", @@ -243,14 +229,15 @@ dependencies = [ [[package]] name = "alloy-provider" version = "0.1.0" +source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-json-rpc", "alloy-network", "alloy-primitives", "alloy-pubsub", "alloy-rpc-client", - "alloy-rpc-trace-types 0.1.0", - "alloy-rpc-types 0.1.0", + "alloy-rpc-trace-types", + "alloy-rpc-types", "alloy-transport", "alloy-transport-http", "async-stream", @@ -268,6 +255,7 @@ dependencies = [ [[package]] name = "alloy-pubsub" version = "0.1.0" +source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-json-rpc", "alloy-primitives", @@ -307,6 +295,7 @@ dependencies = [ [[package]] name = "alloy-rpc-client" version = "0.1.0" +source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-json-rpc", "alloy-primitives", @@ -325,42 +314,16 @@ dependencies = [ "url", ] -[[package]] -name = "alloy-rpc-trace-types" -version = "0.1.0" -dependencies = [ - "alloy-primitives", - "alloy-rpc-types 0.1.0", - "alloy-serde 0.1.0", - "serde", - "serde_json", -] - [[package]] name = "alloy-rpc-trace-types" version = "0.1.0" source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-primitives", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", - "alloy-serde 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", - "serde", - "serde_json", -] - -[[package]] -name = "alloy-rpc-types" -version = "0.1.0" -dependencies = [ - "alloy-consensus 0.1.0", - "alloy-eips 0.1.0", - "alloy-primitives", - "alloy-rlp", - "alloy-serde 0.1.0", - "itertools 0.12.1", + "alloy-rpc-types", + "alloy-serde", "serde", "serde_json", - "thiserror", ] [[package]] @@ -368,26 +331,17 @@ name = "alloy-rpc-types" version = "0.1.0" source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ - "alloy-consensus 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", - "alloy-eips 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", + "alloy-consensus", + "alloy-eips", "alloy-primitives", "alloy-rlp", - "alloy-serde 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", + "alloy-serde", "itertools 0.12.1", "serde", "serde_json", "thiserror", ] -[[package]] -name = "alloy-serde" -version = "0.1.0" -dependencies = [ - "alloy-primitives", - "serde", - "serde_json", -] - [[package]] name = "alloy-serde" version = "0.1.0" @@ -401,6 +355,7 @@ dependencies = [ [[package]] name = "alloy-signer" version = "0.1.0" +source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-dyn-abi", "alloy-primitives", @@ -415,8 +370,9 @@ dependencies = [ [[package]] name = "alloy-signer-aws" version = "0.1.0" +source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ - "alloy-consensus 0.1.0", + "alloy-consensus", "alloy-network", "alloy-primitives", "alloy-signer", @@ -431,8 +387,9 @@ dependencies = [ [[package]] name = "alloy-signer-ledger" version = "0.1.0" +source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ - "alloy-consensus 0.1.0", + "alloy-consensus", "alloy-network", "alloy-primitives", "alloy-signer", @@ -447,8 +404,9 @@ dependencies = [ [[package]] name = "alloy-signer-trezor" version = "0.1.0" +source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ - "alloy-consensus 0.1.0", + "alloy-consensus", "alloy-network", "alloy-primitives", "alloy-signer", @@ -462,8 +420,9 @@ dependencies = [ [[package]] name = "alloy-signer-wallet" version = "0.1.0" +source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ - "alloy-consensus 0.1.0", + "alloy-consensus", "alloy-network", "alloy-primitives", "alloy-signer", @@ -528,6 +487,7 @@ dependencies = [ [[package]] name = "alloy-transport" version = "0.1.0" +source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-json-rpc", "base64 0.22.0", @@ -545,6 +505,7 @@ dependencies = [ [[package]] name = "alloy-transport-http" version = "0.1.0" +source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-json-rpc", "alloy-transport", @@ -557,6 +518,7 @@ dependencies = [ [[package]] name = "alloy-transport-ipc" version = "0.1.0" +source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-json-rpc", "alloy-pubsub", @@ -574,6 +536,7 @@ dependencies = [ [[package]] name = "alloy-transport-ws" version = "0.1.0" +source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" dependencies = [ "alloy-pubsub", "alloy-transport", @@ -673,15 +636,15 @@ name = "anvil" version = "0.2.0" dependencies = [ "alloy-chains", - "alloy-consensus 0.1.0", + "alloy-consensus", "alloy-dyn-abi", "alloy-genesis", "alloy-network", "alloy-primitives", "alloy-provider", "alloy-rlp", - "alloy-rpc-trace-types 0.1.0", - "alloy-rpc-types 0.1.0", + "alloy-rpc-trace-types", + "alloy-rpc-types", "alloy-signer", "alloy-signer-wallet", "alloy-sol-types", @@ -737,14 +700,14 @@ dependencies = [ name = "anvil-core" version = "0.2.0" dependencies = [ - "alloy-consensus 0.1.0", + "alloy-consensus", "alloy-dyn-abi", - "alloy-eips 0.1.0", + "alloy-eips", "alloy-network", "alloy-primitives", "alloy-rlp", - "alloy-rpc-trace-types 0.1.0", - "alloy-rpc-types 0.1.0", + "alloy-rpc-trace-types", + "alloy-rpc-types", "anvil-core", "bytes", "c-kzg", @@ -1764,7 +1727,7 @@ checksum = "df8670b8c7b9dae1793364eafadf7239c40d669904660c5960d74cfd80b46a53" name = "cast" version = "0.2.0" dependencies = [ - "alloy-consensus 0.1.0", + "alloy-consensus", "alloy-contract", "alloy-dyn-abi", "alloy-json-abi", @@ -1773,7 +1736,7 @@ dependencies = [ "alloy-primitives", "alloy-provider", "alloy-rlp", - "alloy-rpc-types 0.1.0", + "alloy-rpc-types", "alloy-signer", "alloy-signer-wallet", "alloy-transport", @@ -1852,7 +1815,7 @@ dependencies = [ "alloy-dyn-abi", "alloy-json-abi", "alloy-primitives", - "alloy-rpc-types 0.1.0", + "alloy-rpc-types", "clap", "criterion", "dirs 5.0.1", @@ -3406,7 +3369,7 @@ dependencies = [ "alloy-dyn-abi", "alloy-json-abi", "alloy-primitives", - "alloy-rpc-types 0.1.0", + "alloy-rpc-types", "anvil", "async-trait", "axum", @@ -3520,14 +3483,13 @@ name = "forge-script" version = "0.2.0" dependencies = [ "alloy-chains", - "alloy-consensus 0.1.0", "alloy-dyn-abi", - "alloy-eips 0.1.0", + "alloy-eips", "alloy-json-abi", "alloy-network", "alloy-primitives", "alloy-provider", - "alloy-rpc-types 0.1.0", + "alloy-rpc-types", "alloy-signer", "alloy-transport", "async-recursion", @@ -3625,7 +3587,7 @@ dependencies = [ "alloy-json-abi", "alloy-primitives", "alloy-provider", - "alloy-rpc-types 0.1.0", + "alloy-rpc-types", "alloy-signer", "alloy-signer-wallet", "alloy-sol-types", @@ -3709,7 +3671,7 @@ dependencies = [ "alloy-provider", "alloy-pubsub", "alloy-rpc-client", - "alloy-rpc-types 0.1.0", + "alloy-rpc-types", "alloy-signer-wallet", "alloy-sol-types", "alloy-transport", @@ -3877,7 +3839,7 @@ dependencies = [ "alloy-json-abi", "alloy-primitives", "alloy-provider", - "alloy-rpc-types 0.1.0", + "alloy-rpc-types", "alloy-sol-types", "alloy-transport", "arrayvec", @@ -4019,7 +3981,7 @@ dependencies = [ name = "foundry-wallets" version = "0.2.0" dependencies = [ - "alloy-consensus 0.1.0", + "alloy-consensus", "alloy-dyn-abi", "alloy-network", "alloy-primitives", @@ -6787,8 +6749,8 @@ name = "revm-inspectors" version = "0.1.0" dependencies = [ "alloy-primitives", - "alloy-rpc-trace-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", - "alloy-rpc-types 0.1.0 (git+https://github.com/klkvr/alloy?rev=6ac0827)", + "alloy-rpc-trace-types", + "alloy-rpc-types", "alloy-sol-types", "anstyle", "colorchoice", diff --git a/Cargo.toml b/Cargo.toml index 38d5ba258a61..2238eced1ada 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -154,27 +154,27 @@ ethers-middleware = { version = "2.0.14", default-features = false } ethers-solc = { version = "2.0.14", default-features = false } ## alloy -alloy-consensus = { path = "../alloy/crates/consensus", default-features = false } -alloy-contract = { path = "../alloy/crates/contract", default-features = false } -alloy-eips = { path = "../alloy/crates/eips", default-features = false } -alloy-genesis = { path = "../alloy/crates/genesis", default-features = false } -alloy-json-rpc = { path = "../alloy/crates/json-rpc", default-features = false } -alloy-network = { path = "../alloy/crates/network", default-features = false } -alloy-node-bindings = { path = "../alloy/crates/node-bindings", default-features = false } -alloy-provider = { path = "../alloy/crates/provider", default-features = false } -alloy-pubsub = { path = "../alloy/crates/pubsub", default-features = false } -alloy-rpc-client = { path = "../alloy/crates/rpc-client", default-features = false } -alloy-rpc-trace-types = { path = "../alloy/crates/rpc-trace-types", default-features = false } -alloy-rpc-types = { path = "../alloy/crates/rpc-types", default-features = false } -alloy-signer = { path = "../alloy/crates/signer", default-features = false } -alloy-signer-wallet = { path = "../alloy/crates/signer-wallet", default-features = false } -alloy-signer-aws = { path = "../alloy/crates/signer-aws", default-features = false } -alloy-signer-ledger = { path = "../alloy/crates/signer-ledger", default-features = false } -alloy-signer-trezor = { path = "../alloy/crates/signer-trezor", default-features = false } -alloy-transport = { path = "../alloy/crates/transport", default-features = false } -alloy-transport-http = { path = "../alloy/crates/transport-http", default-features = false } -alloy-transport-ipc = { path = "../alloy/crates/transport-ipc", default-features = false } -alloy-transport-ws = { path = "../alloy/crates/transport-ws", default-features = false } +alloy-consensus = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-contract = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-eips = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-genesis = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-json-rpc = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-network = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-node-bindings = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-provider = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-pubsub = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-rpc-client = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-rpc-trace-types = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-rpc-types = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-signer = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-signer-wallet = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-signer-aws = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-signer-ledger = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-signer-trezor = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-transport = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-transport-http = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-transport-ipc = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-transport-ws = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } alloy-primitives = { version = "0.6.4", features = ["getrandom"] } alloy-dyn-abi = "0.6.4" alloy-json-abi = "0.6.4" diff --git a/crates/script/Cargo.toml b/crates/script/Cargo.toml index 27680eb2fe76..e62e054bfadb 100644 --- a/crates/script/Cargo.toml +++ b/crates/script/Cargo.toml @@ -50,7 +50,6 @@ alloy-dyn-abi.workspace = true alloy-primitives.workspace = true alloy-eips.workspace = true alloy-transport.workspace = true -alloy-consensus.workspace = true [dev-dependencies] tempfile = "3" \ No newline at end of file diff --git a/crates/script/src/broadcast.rs b/crates/script/src/broadcast.rs index 85255c0a15d0..f7ba7fb4389d 100644 --- a/crates/script/src/broadcast.rs +++ b/crates/script/src/broadcast.rs @@ -1,15 +1,12 @@ +use super::receipts; use crate::{ build::LinkedBuildData, sequence::ScriptSequenceKind, verify::BroadcastedState, ScriptArgs, ScriptConfig, }; - -use super::receipts; use alloy_eips::eip2718::Encodable2718; use alloy_network::{Ethereum, EthereumSigner, TransactionBuilder}; use alloy_primitives::{utils::format_units, Address, TxHash, U256}; use alloy_provider::Provider; -use alloy_network::TxSigner; -use std::sync::Arc; use alloy_rpc_types::TransactionRequest; use alloy_transport::Transport; use eyre::{bail, Context, Result}; @@ -26,11 +23,11 @@ use foundry_common::{ shell, }; use foundry_config::Config; -use foundry_wallets::WalletSigner; use futures::{future::join_all, StreamExt}; use itertools::Itertools; use std::{ collections::{HashMap, HashSet}, + sync::Arc, }; pub async fn estimate_gas( @@ -47,10 +44,7 @@ where tx.gas = None; tx.set_gas_limit( - provider - .estimate_gas(tx, None) - .await - .wrap_err("Failed to estimate gas for tx")? * + provider.estimate_gas(tx, None).await.wrap_err("Failed to estimate gas for tx")? * U256::from(estimate_multiplier) / U256::from(100), ); @@ -67,7 +61,7 @@ pub async fn next_nonce(caller: Address, provider_url: &str) -> eyre::Result, mut tx: TransactionRequest, - kind: SendTransactionKind, + kind: SendTransactionKind<'_>, sequential_broadcast: bool, is_fixed_gas_limit: bool, estimate_via_rpc: bool, @@ -100,8 +94,7 @@ pub async fn send_transaction( SendTransactionKind::Raw(signer) => { debug!("sending transaction: {:?}", tx); - let signer = EthereumSigner::new(signer); - let signed = tx.build(&signer).await?; + let signed = tx.build(signer).await?; // Submit the raw transaction provider.send_raw_transaction(signed.encoded_2718().as_ref()).await? @@ -113,9 +106,9 @@ pub async fn send_transaction( /// How to send a single transaction #[derive(Clone)] -pub enum SendTransactionKind { +pub enum SendTransactionKind<'a> { Unlocked(Address), - Raw(Arc), + Raw(&'a EthereumSigner), } /// Represents how to send _all_ transactions @@ -123,14 +116,14 @@ pub enum SendTransactionsKind { /// Send via `eth_sendTransaction` and rely on the `from` address being unlocked. Unlocked(HashSet
), /// Send a signed transaction via `eth_sendRawTransaction` - Raw(HashMap>), + Raw(HashMap), } impl SendTransactionsKind { /// Returns the [`SendTransactionKind`] for the given address /// /// Returns an error if no matching signer is found or the address is not unlocked - pub fn for_sender(&self, addr: &Address) -> Result { + pub fn for_sender(&self, addr: &Address) -> Result> { match self { SendTransactionsKind::Unlocked(unlocked) => { if !unlocked.contains(addr) { @@ -140,7 +133,7 @@ impl SendTransactionsKind { } SendTransactionsKind::Raw(wallets) => { if let Some(wallet) = wallets.get(addr) { - Ok(SendTransactionKind::Raw(wallet.clone())) + Ok(SendTransactionKind::Raw(wallet)) } else { bail!("No matching signer for {:?} found", addr) } @@ -230,7 +223,10 @@ impl BundledState { ); } - let signers = signers.into_iter().map(|(addr, signer)| (addr, Arc::new(signer))).collect(); + let signers = signers + .into_iter() + .map(|(addr, signer)| (addr, EthereumSigner::new(signer))) + .collect(); SendTransactionsKind::Raw(signers) }; From 9fac722510479abc74dbcbd5d19a52c46b7995e8 Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Fri, 22 Mar 2024 14:26:32 +0400 Subject: [PATCH 20/63] make forge compile --- Cargo.lock | 10 +- crates/common/src/provider/ethers.rs | 40 ----- crates/forge/Cargo.toml | 10 +- crates/forge/bin/cmd/create.rs | 241 ++++++++++++--------------- 4 files changed, 123 insertions(+), 178 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 224529ea5a46..25acfcb89d62 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3366,10 +3366,16 @@ checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" name = "forge" version = "0.2.0" dependencies = [ + "alloy-chains", + "alloy-consensus", "alloy-dyn-abi", "alloy-json-abi", + "alloy-network", "alloy-primitives", + "alloy-provider", "alloy-rpc-types", + "alloy-signer", + "alloy-transport", "anvil", "async-trait", "axum", @@ -3382,10 +3388,6 @@ dependencies = [ "dialoguer", "dunce", "ethers-contract", - "ethers-core", - "ethers-middleware", - "ethers-providers", - "ethers-signers", "evm-disassembler", "eyre", "forge-doc", diff --git a/crates/common/src/provider/ethers.rs b/crates/common/src/provider/ethers.rs index 0d4acd2ce377..7d99763de321 100644 --- a/crates/common/src/provider/ethers.rs +++ b/crates/common/src/provider/ethers.rs @@ -4,8 +4,6 @@ use crate::{ runtime_client::{RuntimeClient, RuntimeClientBuilder}, ALCHEMY_FREE_TIER_CUPS, REQUEST_TIMEOUT, }; -use ethers_core::types::U256; -use ethers_middleware::gas_oracle::{GasCategory, GasOracle, Polygon}; use ethers_providers::{is_local_endpoint, Middleware, Provider, DEFAULT_LOCAL_POLL_INTERVAL}; use eyre::{Result, WrapErr}; use foundry_config::NamedChain; @@ -251,44 +249,6 @@ impl ProviderBuilder { } } -/// Estimates EIP1559 fees depending on the chain -/// -/// Uses custom gas oracles for -/// - polygon -/// -/// Fallback is the default [`Provider::estimate_eip1559_fees`] implementation -pub async fn estimate_eip1559_fees( - provider: &M, - chain: Option, -) -> Result<(U256, U256)> -where - M::Error: 'static, -{ - let chain = if let Some(chain) = chain { - chain - } else { - provider.get_chainid().await.wrap_err("Failed to get chain id")?.as_u64() - }; - - if let Ok(chain) = NamedChain::try_from(chain) { - // handle chains that deviate from `eth_feeHistory` and have their own oracle - match chain { - NamedChain::Polygon | NamedChain::PolygonMumbai => { - // TODO: phase this out somehow - let chain = match chain { - NamedChain::Polygon => ethers_core::types::Chain::Polygon, - NamedChain::PolygonMumbai => ethers_core::types::Chain::PolygonMumbai, - _ => unreachable!(), - }; - let estimator = Polygon::new(chain)?.category(GasCategory::Standard); - return Ok(estimator.estimate_eip1559_fees().await?); - } - _ => {} - } - } - provider.estimate_eip1559_fees(None).await.wrap_err("Failed fetch EIP1559 fees") -} - #[cfg(not(windows))] fn resolve_path(path: &Path) -> Result { if path.is_absolute() { diff --git a/crates/forge/Cargo.toml b/crates/forge/Cargo.toml index 8e8c7c2b1268..7826d118064c 100644 --- a/crates/forge/Cargo.toml +++ b/crates/forge/Cargo.toml @@ -28,10 +28,6 @@ foundry-wallets.workspace = true foundry-linking.workspace = true ethers-contract.workspace = true -ethers-core.workspace = true -ethers-middleware.workspace = true -ethers-providers.workspace = true -ethers-signers.workspace = true revm-inspectors.workspace = true @@ -55,6 +51,12 @@ alloy-dyn-abi.workspace = true alloy-json-abi.workspace = true alloy-primitives = { workspace = true, features = ["serde"] } alloy-rpc-types.workspace = true +alloy-provider.workspace = true +alloy-network.workspace = true +alloy-transport.workspace = true +alloy-signer.workspace = true +alloy-consensus.workspace = true +alloy-chains.workspace = true async-trait = "0.1" clap = { version = "4", features = ["derive", "env", "unicode", "wrap_help"] } diff --git a/crates/forge/bin/cmd/create.rs b/crates/forge/bin/cmd/create.rs index 9dee30675d5f..9c13f5790c11 100644 --- a/crates/forge/bin/cmd/create.rs +++ b/crates/forge/bin/cmd/create.rs @@ -1,17 +1,13 @@ +use alloy_chains::Chain; use alloy_dyn_abi::{DynSolValue, JsonAbiExt, ResolveSolType}; use alloy_json_abi::{Constructor, JsonAbi}; +use alloy_network::{Ethereum, EthereumSigner, TransactionBuilder}; use alloy_primitives::{Address, Bytes}; +use alloy_provider::{Provider, ProviderBuilder}; +use alloy_rpc_types::{TransactionReceipt, TransactionRequest}; +use alloy_signer::Signer; +use alloy_transport::{Transport, TransportError}; use clap::{Parser, ValueHint}; -use ethers_contract::ContractError; -use ethers_core::{ - abi::InvalidOutputType, - types::{ - transaction::eip2718::TypedTransaction, BlockNumber, Chain, Eip1559TransactionRequest, - TransactionReceipt, TransactionRequest, - }, -}; -use ethers_middleware::SignerMiddleware; -use ethers_providers::Middleware; use eyre::{Context, Result}; use forge_verify::RetryArgs; use foundry_cli::{ @@ -19,10 +15,7 @@ use foundry_cli::{ utils::{self, read_constructor_args_file, remove_contract, LoadConfig}, }; use foundry_common::{ - compile::ProjectCompiler, - fmt::parse_tokens, - provider::ethers::estimate_eip1559_fees, - types::{ToAlloy, ToEthers}, + compile::ProjectCompiler, fmt::parse_tokens, provider::alloy::estimate_eip1559_fees, }; use foundry_compilers::{artifacts::BytecodeObject, info::ContractInfo, utils::canonicalized}; use serde_json::json; @@ -118,7 +111,7 @@ impl CreateArgs { // Add arguments to constructor let config = self.eth.try_load_config_emit_warnings()?; - let provider = utils::get_provider(&config)?; + let provider = utils::get_alloy_provider(&config)?; let params = match abi.constructor { Some(ref v) => { let constructor_args = @@ -136,18 +129,20 @@ impl CreateArgs { let chain_id = if let Some(chain_id) = self.chain_id() { chain_id } else { - provider.get_chainid().await?.as_u64() + provider.get_chain_id().await?.to() }; if self.unlocked { // Deploy with unlocked account let sender = self.eth.wallet.from.expect("required"); - let provider = provider.with_sender(sender.to_ethers()); - self.deploy(abi, bin, params, provider, chain_id).await + self.deploy(abi, bin, params, provider, chain_id, sender).await } else { // Deploy with signer let signer = self.eth.wallet.signer().await?; - let provider = SignerMiddleware::new_with_provider_chain(provider, signer).await?; - self.deploy(abi, bin, params, provider, chain_id).await + let deployer = signer.address(); + let provider = ProviderBuilder::<_, Ethereum>::default() + .signer(EthereumSigner::new(signer)) + .provider(provider); + self.deploy(abi, bin, params, provider, chain_id, deployer).await } } @@ -206,16 +201,15 @@ impl CreateArgs { } /// Deploys the contract - async fn deploy( + async fn deploy, T: Transport + Clone>( self, abi: JsonAbi, bin: BytecodeObject, args: Vec, - provider: M, + provider: P, chain: u64, + deployer_address: Address, ) -> Result<()> { - let deployer_address = - provider.default_sender().expect("no sender address set for provider"); let bin = bin.into_bytes().unwrap_or_else(|| { panic!("no bytecode found in bin object for {}", self.contract.name) }); @@ -223,7 +217,7 @@ impl CreateArgs { let factory = ContractFactory::new(abi.clone(), bin.clone(), provider.clone()); let is_args_empty = args.is_empty(); - let deployer = + let mut deployer = factory.deploy_tokens(args.clone()).context("failed to deploy contract").map_err(|e| { if is_args_empty { e.wrap_err("no arguments provided for contract constructor; consider --constructor-args or --constructor-args-path") @@ -231,57 +225,50 @@ impl CreateArgs { e } })?; - let is_legacy = self.tx.legacy || - Chain::try_from(chain).map(|x| Chain::is_legacy(&x)).unwrap_or_default(); - let mut deployer = if is_legacy { deployer.legacy() } else { deployer }; + let is_legacy = + self.tx.legacy || Chain::try_from(chain).map(|x| x.is_legacy()).unwrap_or_default(); // set tx value if specified if let Some(value) = self.tx.value { - deployer.tx.set_value(value.to_ethers()); + deployer.tx.set_value(value); } - // fill tx first because if you target a lower gas than current base, eth_estimateGas - // will fail and create will fail - provider.fill_transaction(&mut deployer.tx, None).await?; - - // the max - let mut priority_fee = self.tx.priority_gas_price; + deployer.tx.set_from(deployer_address); - // set gas price if specified - if let Some(gas_price) = self.tx.gas_price { - deployer.tx.set_gas_price(gas_price.to_ethers()); - } else if !is_legacy { - // estimate EIP1559 fees - let (max_fee, max_priority_fee) = estimate_eip1559_fees(&provider, Some(chain)) + if is_legacy { + let gas_price = if let Some(gas_price) = self.tx.gas_price { + gas_price + } else { + provider.get_gas_price().await? + }; + deployer.tx.set_gas_price(gas_price); + } else { + let estimate = estimate_eip1559_fees(&provider, Some(chain)) .await .wrap_err("Failed to estimate EIP1559 fees. This chain might not support EIP1559, try adding --legacy to your command.")?; - deployer.tx.set_gas_price(max_fee); - if priority_fee.is_none() { - priority_fee = Some(max_priority_fee.to_alloy()); - } + let priority_fee = if let Some(priority_fee) = self.tx.priority_gas_price { + priority_fee + } else { + estimate.max_priority_fee_per_gas + }; + let max_fee = if let Some(max_fee) = self.tx.gas_price { + max_fee + } else { + estimate.max_fee_per_gas + }; + + deployer.tx.set_max_fee_per_gas(max_fee); + deployer.tx.set_max_priority_fee_per_gas(priority_fee); } // set gas limit if specified if let Some(gas_limit) = self.tx.gas_limit { - deployer.tx.set_gas(gas_limit.to_ethers()); + deployer.tx.set_gas_limit(gas_limit); } // set nonce if specified if let Some(nonce) = self.tx.nonce { - deployer.tx.set_nonce(nonce.to_ethers()); - } - - // set priority fee if specified - if let Some(priority_fee) = priority_fee { - if is_legacy { - eyre::bail!("there is no priority fee for legacy txs"); - } - deployer.tx = match deployer.tx { - TypedTransaction::Eip1559(eip1559_tx_request) => TypedTransaction::Eip1559( - eip1559_tx_request.max_priority_fee_per_gas(priority_fee.to_ethers()), - ), - _ => deployer.tx, - }; + deployer.tx.set_nonce(nonce.to()); } // Before we actually deploy the contract we try check if the verify settings are valid @@ -304,13 +291,13 @@ impl CreateArgs { let address = deployed_contract; if self.json { let output = json!({ - "deployer": deployer_address.to_alloy().to_string(), + "deployer": deployer_address.to_string(), "deployedTo": address.to_string(), "transactionHash": receipt.transaction_hash }); println!("{output}"); } else { - println!("Deployer: {}", deployer_address.to_alloy()); + println!("Deployer: {deployer_address}"); println!("Deployed to: {address}"); println!("Transaction hash: {:?}", receipt.transaction_hash); }; @@ -376,7 +363,7 @@ impl CreateArgs { /// compatibility with less-abstract Contracts. /// /// For full usage docs, see [`DeploymentTxFactory`]. -pub type ContractFactory = DeploymentTxFactory, M>; +pub type ContractFactory = DeploymentTxFactory, P, T>; /// Helper which manages the deployment transaction of a smart contract. It /// wraps a deployment transaction, and retrieves the contract address output @@ -385,16 +372,16 @@ pub type ContractFactory = DeploymentTxFactory, M>; /// Currently, we recommend using the [`ContractDeployer`] type alias. #[derive(Debug)] #[must_use = "ContractDeploymentTx does nothing unless you `send` it"] -pub struct ContractDeploymentTx { +pub struct ContractDeploymentTx { /// the actual deployer, exposed for overriding the defaults - pub deployer: Deployer, + pub deployer: Deployer, /// marker for the `Contract` type to create afterwards /// /// this type will be used to construct it via `From::from(Contract)` _contract: PhantomData, } -impl Clone for ContractDeploymentTx +impl Clone for ContractDeploymentTx where B: Clone, { @@ -403,8 +390,8 @@ where } } -impl From> for ContractDeploymentTx { - fn from(deployer: Deployer) -> Self { +impl From> for ContractDeploymentTx { + fn from(deployer: Deployer) -> Self { Self { deployer, _contract: PhantomData } } } @@ -412,17 +399,17 @@ impl From> for ContractDeploymentTx { /// Helper which manages the deployment transaction of a smart contract #[derive(Debug)] #[must_use = "Deployer does nothing unless you `send` it"] -pub struct Deployer { +pub struct Deployer { /// The deployer's transaction, exposed for overriding the defaults - pub tx: TypedTransaction, + pub tx: TransactionRequest, abi: JsonAbi, client: B, confs: usize, - block: BlockNumber, - _m: PhantomData, + _p: PhantomData

, + _t: PhantomData, } -impl Clone for Deployer +impl Clone for Deployer where B: Clone, { @@ -432,53 +419,38 @@ where abi: self.abi.clone(), client: self.client.clone(), confs: self.confs, - block: self.block, - _m: PhantomData, + _p: PhantomData, + _t: PhantomData, } } } -impl Deployer +impl Deployer where - B: Borrow + Clone, - M: Middleware, + B: Borrow

+ Clone, + P: Provider, + T: Transport + Clone, { - /// Uses a Legacy transaction instead of an EIP-1559 one to do the deployment - pub fn legacy(mut self) -> Self { - self.tx = match self.tx { - TypedTransaction::Eip1559(inner) => { - let tx: TransactionRequest = inner.into(); - TypedTransaction::Legacy(tx) - } - other => other, - }; - self - } - /// Broadcasts the contract deployment transaction and after waiting for it to /// be sufficiently confirmed (default: 1), it returns a tuple with /// the [`Contract`](crate::Contract) struct at the deployed contract's address /// and the corresponding [`TransactionReceipt`]. pub async fn send_with_receipt( self, - ) -> Result<(Address, TransactionReceipt), ContractError> { - let pending_tx = self + ) -> Result<(Address, TransactionReceipt), ContractDeploymentError> { + let receipt = self .client .borrow() - .send_transaction(self.tx, Some(self.block.into())) - .await - .map_err(ContractError::from_middleware_error)?; - - // TODO: Should this be calculated "optimistically" by address/nonce? - let receipt = pending_tx - .confirmations(self.confs) - .await - .ok() - .flatten() - .ok_or(ContractError::ContractNotDeployed)?; - let address = receipt.contract_address.ok_or(ContractError::ContractNotDeployed)?; - - Ok((address.to_alloy(), receipt)) + .send_transaction(self.tx) + .await? + .with_confirmations(self.confs as u64) + .get_receipt() + .await?; + + let address = + receipt.contract_address.ok_or(ContractDeploymentError::ContractNotDeployed)?; + + Ok((address, receipt)) } } @@ -519,14 +491,15 @@ where /// # Ok(()) /// # } #[derive(Debug)] -pub struct DeploymentTxFactory { +pub struct DeploymentTxFactory { client: B, abi: JsonAbi, bytecode: Bytes, - _m: PhantomData, + _p: PhantomData

, + _t: PhantomData, } -impl Clone for DeploymentTxFactory +impl Clone for DeploymentTxFactory where B: Clone, { @@ -535,39 +508,42 @@ where client: self.client.clone(), abi: self.abi.clone(), bytecode: self.bytecode.clone(), - _m: PhantomData, + _p: PhantomData, + _t: PhantomData, } } } -impl DeploymentTxFactory +impl DeploymentTxFactory where - B: Borrow + Clone, - M: Middleware, + B: Borrow

+ Clone, + P: Provider, + T: Transport + Clone, { /// Creates a factory for deployment of the Contract with bytecode, and the /// constructor defined in the abi. The client will be used to send any deployment /// transaction. pub fn new(abi: JsonAbi, bytecode: Bytes, client: B) -> Self { - Self { client, abi, bytecode, _m: PhantomData } + Self { client, abi, bytecode, _p: PhantomData, _t: PhantomData } } /// Create a deployment tx using the provided tokens as constructor /// arguments - pub fn deploy_tokens(self, params: Vec) -> Result, ContractError> + pub fn deploy_tokens( + self, + params: Vec, + ) -> Result, ContractDeploymentError> where B: Clone, { // Encode the constructor args & concatenate with the bytecode if necessary let data: Bytes = match (self.abi.constructor(), params.is_empty()) { - (None, false) => return Err(ContractError::ConstructorError), + (None, false) => return Err(ContractDeploymentError::ConstructorError), (None, true) => self.bytecode.clone(), (Some(constructor), _) => { let input: Bytes = constructor .abi_encode_input(¶ms) - .map_err(|f| { - ContractError::DetokenizationError(InvalidOutputType(f.to_string())) - })? + .map_err(|f| ContractDeploymentError::DetokenizationError(f))? .into(); // Concatenate the bytecode and abi-encoded constructor call. self.bytecode.iter().copied().chain(input).collect() @@ -575,27 +551,32 @@ where }; // create the tx object. Since we're deploying a contract, `to` is `None` - // We default to EIP1559 transactions, but the sender can convert it back - // to a legacy one. - let tx = Eip1559TransactionRequest { - to: None, - data: Some(data.to_ethers()), - ..Default::default() - }; - - let tx = tx.into(); + let tx = TransactionRequest::default().input(data.into()).to(None); Ok(Deployer { client: self.client.clone(), abi: self.abi, tx, confs: 1, - block: BlockNumber::Latest, - _m: PhantomData, + _p: PhantomData, + _t: PhantomData, }) } } +#[derive(thiserror::Error, Debug)] +/// An Error which is thrown when interacting with a smart contract +pub enum ContractDeploymentError { + #[error("constructor is not defined in the ABI")] + ConstructorError, + #[error(transparent)] + DetokenizationError(#[from] alloy_dyn_abi::Error), + #[error("contract was not deployed")] + ContractNotDeployed, + #[error(transparent)] + RpcError(#[from] TransportError), +} + #[cfg(test)] mod tests { use super::*; From 78279884fff81be75e21a3cd2d794e8449830d40 Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Fri, 22 Mar 2024 22:11:09 +0400 Subject: [PATCH 21/63] fix: anvil tests --- Cargo.lock | 57 ++++++++------- Cargo.toml | 49 ++++++------- crates/anvil/core/src/eth/block.rs | 3 +- crates/anvil/core/src/eth/transaction/mod.rs | 58 ++++++++-------- crates/anvil/src/eth/api.rs | 10 +-- crates/anvil/src/eth/backend/executor.rs | 2 +- crates/anvil/src/eth/backend/mem/mod.rs | 2 +- crates/anvil/tests/it/api.rs | 1 - crates/anvil/tests/it/fork.rs | 38 ++++++---- crates/anvil/tests/it/otterscan.rs | 3 +- crates/anvil/tests/it/transaction.rs | 25 ++++--- crates/cast/bin/cmd/logs.rs | 73 ++++++++++++-------- crates/cast/bin/opts.rs | 22 +++--- crates/cast/src/lib.rs | 2 +- crates/cast/src/tx.rs | 8 +-- crates/cheatcodes/src/evm.rs | 4 +- crates/evm/core/src/abi/hardhat_console.rs | 3 +- crates/evm/core/src/backend/cow.rs | 4 +- crates/evm/core/src/backend/mod.rs | 6 +- crates/forge/Cargo.toml | 3 + crates/forge/bin/cmd/create.rs | 2 +- crates/forge/tests/cli/utils.rs | 5 +- 22 files changed, 205 insertions(+), 175 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 25acfcb89d62..8123e95f855f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -90,7 +90,7 @@ dependencies = [ [[package]] name = "alloy-consensus" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" +source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" dependencies = [ "alloy-eips", "alloy-primitives", @@ -105,7 +105,7 @@ dependencies = [ [[package]] name = "alloy-contract" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" +source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" dependencies = [ "alloy-dyn-abi", "alloy-json-abi", @@ -144,17 +144,18 @@ dependencies = [ [[package]] name = "alloy-eips" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" +source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" dependencies = [ "alloy-primitives", "alloy-rlp", + "alloy-serde", "serde", ] [[package]] name = "alloy-genesis" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" +source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" dependencies = [ "alloy-primitives", "alloy-serde", @@ -164,10 +165,9 @@ dependencies = [ [[package]] name = "alloy-json-abi" version = "0.6.4" -source = "git+https://github.com/klkvr/core?rev=0473659#04736599a54c240ae1708746f45749d95907a192" dependencies = [ "alloy-primitives", - "alloy-sol-type-parser 0.6.4 (git+https://github.com/klkvr/core?rev=0473659)", + "alloy-sol-type-parser 0.6.4", "serde", "serde_json", ] @@ -175,7 +175,7 @@ dependencies = [ [[package]] name = "alloy-json-rpc" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" +source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" dependencies = [ "alloy-primitives", "serde", @@ -186,7 +186,7 @@ dependencies = [ [[package]] name = "alloy-network" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" +source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" dependencies = [ "alloy-consensus", "alloy-eips", @@ -203,7 +203,6 @@ dependencies = [ [[package]] name = "alloy-primitives" version = "0.6.4" -source = "git+https://github.com/klkvr/core?rev=0473659#04736599a54c240ae1708746f45749d95907a192" dependencies = [ "alloy-rlp", "arbitrary", @@ -229,7 +228,7 @@ dependencies = [ [[package]] name = "alloy-provider" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" +source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" dependencies = [ "alloy-json-rpc", "alloy-network", @@ -255,7 +254,7 @@ dependencies = [ [[package]] name = "alloy-pubsub" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" +source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" dependencies = [ "alloy-json-rpc", "alloy-primitives", @@ -295,7 +294,7 @@ dependencies = [ [[package]] name = "alloy-rpc-client" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" +source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" dependencies = [ "alloy-json-rpc", "alloy-primitives", @@ -317,7 +316,7 @@ dependencies = [ [[package]] name = "alloy-rpc-trace-types" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" +source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" dependencies = [ "alloy-primitives", "alloy-rpc-types", @@ -329,7 +328,7 @@ dependencies = [ [[package]] name = "alloy-rpc-types" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" +source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" dependencies = [ "alloy-consensus", "alloy-eips", @@ -345,7 +344,7 @@ dependencies = [ [[package]] name = "alloy-serde" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" +source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" dependencies = [ "alloy-primitives", "serde", @@ -355,7 +354,7 @@ dependencies = [ [[package]] name = "alloy-signer" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" +source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" dependencies = [ "alloy-dyn-abi", "alloy-primitives", @@ -370,7 +369,7 @@ dependencies = [ [[package]] name = "alloy-signer-aws" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" +source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" dependencies = [ "alloy-consensus", "alloy-network", @@ -387,7 +386,7 @@ dependencies = [ [[package]] name = "alloy-signer-ledger" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" +source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" dependencies = [ "alloy-consensus", "alloy-network", @@ -404,7 +403,7 @@ dependencies = [ [[package]] name = "alloy-signer-trezor" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" +source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" dependencies = [ "alloy-consensus", "alloy-network", @@ -420,7 +419,7 @@ dependencies = [ [[package]] name = "alloy-signer-wallet" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" +source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" dependencies = [ "alloy-consensus", "alloy-network", @@ -439,7 +438,6 @@ dependencies = [ [[package]] name = "alloy-sol-macro" version = "0.6.4" -source = "git+https://github.com/klkvr/core?rev=0473659#04736599a54c240ae1708746f45749d95907a192" dependencies = [ "alloy-json-abi", "const-hex", @@ -458,8 +456,6 @@ dependencies = [ [[package]] name = "alloy-sol-type-parser" version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0045cc89524e1451ccf33e8581355b6027ac7c6e494bb02959d4213ad0d8e91d" dependencies = [ "winnow 0.6.5", ] @@ -467,7 +463,8 @@ dependencies = [ [[package]] name = "alloy-sol-type-parser" version = "0.6.4" -source = "git+https://github.com/klkvr/core?rev=0473659#04736599a54c240ae1708746f45749d95907a192" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0045cc89524e1451ccf33e8581355b6027ac7c6e494bb02959d4213ad0d8e91d" dependencies = [ "winnow 0.6.5", ] @@ -475,7 +472,6 @@ dependencies = [ [[package]] name = "alloy-sol-types" version = "0.6.4" -source = "git+https://github.com/klkvr/core?rev=0473659#04736599a54c240ae1708746f45749d95907a192" dependencies = [ "alloy-json-abi", "alloy-primitives", @@ -487,7 +483,7 @@ dependencies = [ [[package]] name = "alloy-transport" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" +source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" dependencies = [ "alloy-json-rpc", "base64 0.22.0", @@ -505,7 +501,7 @@ dependencies = [ [[package]] name = "alloy-transport-http" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" +source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" dependencies = [ "alloy-json-rpc", "alloy-transport", @@ -518,7 +514,7 @@ dependencies = [ [[package]] name = "alloy-transport-ipc" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" +source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" dependencies = [ "alloy-json-rpc", "alloy-pubsub", @@ -536,7 +532,7 @@ dependencies = [ [[package]] name = "alloy-transport-ws" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=6ac0827#6ac082746a253fc4516a97ad8638439c0823a66f" +source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" dependencies = [ "alloy-pubsub", "alloy-transport", @@ -3375,6 +3371,7 @@ dependencies = [ "alloy-provider", "alloy-rpc-types", "alloy-signer", + "alloy-signer-wallet", "alloy-transport", "anvil", "async-trait", @@ -3388,6 +3385,7 @@ dependencies = [ "dialoguer", "dunce", "ethers-contract", + "ethers-core", "evm-disassembler", "eyre", "forge-doc", @@ -7785,7 +7783,6 @@ dependencies = [ [[package]] name = "syn-solidity" version = "0.6.4" -source = "git+https://github.com/klkvr/core?rev=0473659#04736599a54c240ae1708746f45749d95907a192" dependencies = [ "paste", "proc-macro2", diff --git a/Cargo.toml b/Cargo.toml index 2238eced1ada..69948b19daa4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -154,32 +154,33 @@ ethers-middleware = { version = "2.0.14", default-features = false } ethers-solc = { version = "2.0.14", default-features = false } ## alloy -alloy-consensus = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-contract = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-eips = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-genesis = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-json-rpc = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-network = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-node-bindings = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-provider = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-pubsub = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-rpc-client = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-rpc-trace-types = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-rpc-types = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-signer = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-signer-wallet = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-signer-aws = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-signer-ledger = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-signer-trezor = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-transport = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-transport-http = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-transport-ipc = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } -alloy-transport-ws = { git = "https://github.com/klkvr/alloy", rev = "6ac0827", default-features = false } +alloy-consensus = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } +alloy-contract = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } +alloy-eips = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } +alloy-genesis = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } +alloy-json-rpc = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } +alloy-network = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } +alloy-node-bindings = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } +alloy-provider = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } +alloy-pubsub = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } +alloy-rpc-client = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } +alloy-rpc-trace-types = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } +alloy-rpc-types = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } +alloy-signer = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } +alloy-signer-wallet = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } +alloy-signer-aws = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } +alloy-signer-ledger = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } +alloy-signer-trezor = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } +alloy-transport = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } +alloy-transport-http = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } +alloy-transport-ipc = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } +alloy-transport-ws = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } alloy-primitives = { version = "0.6.4", features = ["getrandom"] } alloy-dyn-abi = "0.6.4" alloy-json-abi = "0.6.4" alloy-sol-types = "0.6.4" syn-solidity = "0.6.4" +alloy-sol-macro-input = "0.6.4" alloy-chains = "0.1" @@ -218,6 +219,6 @@ tower = "0.4" tower-http = "0.4" [patch.crates-io] -alloy-primitives = { git = "https://github.com/klkvr/core", rev = "0473659" } -alloy-json-abi = { git = "https://github.com/klkvr/core", rev = "0473659" } -alloy-sol-types = { git = "https://github.com/klkvr/core", rev = "0473659" } +alloy-primitives = { path = "../core/crates/primitives" } +alloy-json-abi = { path = "../core/crates/json-abi" } +alloy-sol-types = { path = "../core/crates/sol-types" } \ No newline at end of file diff --git a/crates/anvil/core/src/eth/block.rs b/crates/anvil/core/src/eth/block.rs index c304eefa4a10..4f6c5a94188a 100644 --- a/crates/anvil/core/src/eth/block.rs +++ b/crates/anvil/core/src/eth/block.rs @@ -120,7 +120,6 @@ impl From

for PartialHeader { #[cfg(test)] mod tests { - use alloy_network::Sealable; use alloy_primitives::{ b256, hex::{self, FromHex}, @@ -257,7 +256,7 @@ mod tests { excess_blob_gas: None, parent_beacon_block_root: None, }; - assert_eq!(header.hash(), expected_hash); + assert_eq!(header.hash_slow(), expected_hash); } #[test] diff --git a/crates/anvil/core/src/eth/transaction/mod.rs b/crates/anvil/core/src/eth/transaction/mod.rs index 6b9f910f9995..409cebe22985 100644 --- a/crates/anvil/core/src/eth/transaction/mod.rs +++ b/crates/anvil/core/src/eth/transaction/mod.rs @@ -79,10 +79,11 @@ pub fn transaction_request_to_typed(tx: TransactionRequest) -> Option { + (Some(0), _, None, None, None, None, None, None, _) | + (None, Some(_), None, None, None, None, None, None, _) => { Some(TypedTransactionRequest::Legacy(TxLegacy { nonce: nonce.unwrap_or_default(), gas_price: gas_price.unwrap_or_default().to::(), @@ -97,8 +98,8 @@ pub fn transaction_request_to_typed(tx: TransactionRequest) -> Option { + (Some(1), _, None, None, _, None, None, None, _) | + (None, _, None, None, Some(_), None, None, None, _) => { Some(TypedTransactionRequest::EIP2930(TxEip2930 { nonce: nonce.unwrap_or_default(), gas_price: gas_price.unwrap_or_default().to(), @@ -114,10 +115,10 @@ pub fn transaction_request_to_typed(tx: TransactionRequest) -> Option { + (Some(2), None, _, _, _, _, None, None, _) | + (None, None, Some(_), _, _, _, None, None, _) | + (None, None, _, Some(_), _, _, None, None, _) | + (None, None, None, None, None, _, None, None, _) => { // Empty fields fall back to the canonical transaction schema. Some(TypedTransactionRequest::EIP1559(TxEip1559 { nonce: nonce.unwrap_or_default(), @@ -135,7 +136,7 @@ pub fn transaction_request_to_typed(tx: TransactionRequest) -> Option { + (Some(3), None, _, _, _, Some(_), Some(_), Some(sidecar), Some(to)) => { let tx = TxEip4844 { nonce: nonce.unwrap_or_default(), max_fee_per_gas: max_fee_per_gas.unwrap_or_default().to::(), @@ -144,10 +145,7 @@ pub fn transaction_request_to_typed(tx: TransactionRequest) -> Option(), value: value.unwrap_or(U256::ZERO), input: input.into_input().unwrap_or_default(), - to: match to { - Some(to) => TxKind::Call(to), - None => TxKind::Create, - }, + to, chain_id: 0, access_list: to_eip_access_list(access_list.unwrap_or_default()), blob_versioned_hashes: blob_versioned_hashes.unwrap_or_default(), @@ -558,7 +556,7 @@ impl PendingTransaction { } = tx.tx().tx(); TxEnv { caller, - transact_to: transact_to(to), + transact_to: TransactTo::call(*to), data: alloy_primitives::Bytes(input.0.clone()), chain_id: Some(*chain_id), nonce: Some(*nonce), @@ -732,7 +730,7 @@ impl TypedTransaction { access_list: to_alloy_access_list(t.tx().access_list.clone()), }, TypedTransaction::EIP4844(t) => TransactionEssentials { - kind: t.tx().tx().to, + kind: TxKind::Call(t.tx().tx().to), input: t.tx().tx().input.clone(), nonce: t.tx().tx().nonce, gas_limit: U256::from(t.tx().tx().gas_limit), @@ -852,19 +850,19 @@ impl TypedTransaction { } /// Returns what kind of transaction this is - pub fn kind(&self) -> &TxKind { + pub fn kind(&self) -> TxKind { match self { - TypedTransaction::Legacy(tx) => &tx.tx().to, - TypedTransaction::EIP2930(tx) => &tx.tx().to, - TypedTransaction::EIP1559(tx) => &tx.tx().to, - TypedTransaction::EIP4844(tx) => &tx.tx().tx().to, - TypedTransaction::Deposit(tx) => &tx.kind, + TypedTransaction::Legacy(tx) => tx.tx().to, + TypedTransaction::EIP2930(tx) => tx.tx().to, + TypedTransaction::EIP1559(tx) => tx.tx().to, + TypedTransaction::EIP4844(tx) => TxKind::Call(tx.tx().tx().to), + TypedTransaction::Deposit(tx) => tx.kind, } } /// Returns the callee if this transaction is a call - pub fn to(&self) -> Option<&Address> { - self.kind().to() + pub fn to(&self) -> Option
{ + self.kind().to().copied() } /// Returns the Signature of the transaction @@ -1233,7 +1231,7 @@ mod tests { assert_eq!( tx.tx().tx().to, - TxKind::Call(address!("11E9CA82A3a762b4B5bd264d4173a242e7a77064")) + address!("11E9CA82A3a762b4B5bd264d4173a242e7a77064") ); assert_eq!( @@ -1259,11 +1257,11 @@ mod tests { panic!("decoding TypedTransaction failed"); }; - assert_eq!(tx.input, Bytes::from(b"")); - assert_eq!(tx.gas_price, 1); - assert_eq!(tx.gas_limit, 21000); - assert_eq!(tx.nonce, 0); - if let TxKind::Call(to) = tx.to { + assert_eq!(tx.tx().input, Bytes::from(b"")); + assert_eq!(tx.tx().gas_price, 1); + assert_eq!(tx.tx().gas_limit, 21000); + assert_eq!(tx.tx().nonce, 0); + if let TxKind::Call(to) = tx.tx().to { assert_eq!( to, "0x095e7baea6a6c7c4c2dfeb977efac326af552d87".parse::
().unwrap() @@ -1271,7 +1269,7 @@ mod tests { } else { panic!("expected a call transaction"); } - assert_eq!(tx.value, U256::from(0x0au64)); + assert_eq!(tx.tx().value, U256::from(0x0au64)); assert_eq!( tx.recover_signer().unwrap(), "0f65fe9276bc9a24ae7083ae28e2660ef72df99e".parse::
().unwrap() diff --git a/crates/anvil/src/eth/api.rs b/crates/anvil/src/eth/api.rs index 648478bfc750..9c8d37b69541 100644 --- a/crates/anvil/src/eth/api.rs +++ b/crates/anvil/src/eth/api.rs @@ -916,6 +916,9 @@ impl EthApi { } let transaction = TypedTransaction::decode_2718(&mut data) .map_err(|_| BlockchainError::FailedToDecodeSignedTransaction)?; + + self.ensure_typed_transaction_supported(&transaction)?; + let pending_transaction = PendingTransaction::new(transaction)?; // pre-validate @@ -2003,7 +2006,7 @@ impl EthApi { let gas_price = tx.gas_price(); let value = tx.value(); let gas = tx.gas_limit(); - TxpoolInspectSummary { to: to.copied(), value, gas, gas_price } + TxpoolInspectSummary { to, value, gas, gas_price } } // Note: naming differs geth vs anvil: @@ -2655,10 +2658,7 @@ fn determine_base_gas_by_kind(request: &TransactionRequest) -> U256 { TxKind::Call(_) => MIN_TRANSACTION_GAS, TxKind::Create => MIN_CREATE_GAS, }, - TypedTransactionRequest::EIP4844(req) => match req.tx().to { - TxKind::Call(_) => MIN_TRANSACTION_GAS, - TxKind::Create => MIN_CREATE_GAS, - }, + TypedTransactionRequest::EIP4844(_) => MIN_TRANSACTION_GAS, TypedTransactionRequest::Deposit(req) => match req.kind { TxKind::Call(_) => MIN_TRANSACTION_GAS, TxKind::Create => MIN_CREATE_GAS, diff --git a/crates/anvil/src/eth/backend/executor.rs b/crates/anvil/src/eth/backend/executor.rs index 778f79f781d1..320d4688462c 100644 --- a/crates/anvil/src/eth/backend/executor.rs +++ b/crates/anvil/src/eth/backend/executor.rs @@ -186,7 +186,7 @@ impl<'a, DB: Db + ?Sized, Validator: TransactionValidator> TransactionExecutor<' transaction_hash: transaction.hash(), transaction_index, from: *transaction.pending_transaction.sender(), - to: transaction.pending_transaction.transaction.to().copied(), + to: transaction.pending_transaction.transaction.to(), contract_address, logs, logs_bloom: *receipt.logs_bloom(), diff --git a/crates/anvil/src/eth/backend/mem/mod.rs b/crates/anvil/src/eth/backend/mem/mod.rs index 2f46391a6323..af4aefaf8cb9 100644 --- a/crates/anvil/src/eth/backend/mem/mod.rs +++ b/crates/anvil/src/eth/backend/mem/mod.rs @@ -2452,7 +2452,7 @@ pub fn transaction_build( transaction.hash = tx_hash; } - transaction.to = info.as_ref().map_or(eth_transaction.to().copied(), |status| status.to); + transaction.to = info.as_ref().map_or(eth_transaction.to(), |status| status.to); transaction } diff --git a/crates/anvil/tests/it/api.rs b/crates/anvil/tests/it/api.rs index 28eaf83d46d5..7ae68e190744 100644 --- a/crates/anvil/tests/it/api.rs +++ b/crates/anvil/tests/it/api.rs @@ -10,7 +10,6 @@ use alloy_rpc_types::{ request::{TransactionInput as CallInput, TransactionRequest as CallRequest}, state::{AccountOverride, StateOverride}, }; -use alloy_signer::Signer as AlloySigner; use anvil::{ eth::{api::CLIENT_VERSION, EthApi}, spawn, NodeConfig, CHAIN_ID, diff --git a/crates/anvil/tests/it/fork.rs b/crates/anvil/tests/it/fork.rs index e8a63c944d3a..55ed260db509 100644 --- a/crates/anvil/tests/it/fork.rs +++ b/crates/anvil/tests/it/fork.rs @@ -4,13 +4,12 @@ use crate::{ abi::*, utils::{self, ethers_http_provider}, }; -use alloy_primitives::{address, U256 as rU256}; -use alloy_provider::Provider; +use alloy_primitives::{address, U256 as rU256, U64 as rU64}; +use alloy_provider::Provider as AlloyProvider; use alloy_rpc_types::{ request::{TransactionInput, TransactionRequest as CallRequest}, BlockNumberOrTag, }; -use alloy_signer::Signer as AlloySigner; use anvil::{eth::EthApi, spawn, NodeConfig, NodeHandle}; use anvil_core::types::Forking; use ethers::{ @@ -290,7 +289,7 @@ async fn test_fork_snapshotting() { let provider = handle.http_provider(); let nonce = provider.get_transaction_count(from, None).await.unwrap(); - assert_eq!(nonce, initial_nonce + rU256::from(1)); + assert_eq!(nonce, initial_nonce + rU64::from(1)); let to_balance = provider.get_balance(to, None).await.unwrap(); assert_eq!(balance_before.saturating_add(amount), to_balance); @@ -329,7 +328,7 @@ async fn test_fork_snapshotting_repeated() { let _ = tx_provider.send_transaction(tx, None).await.unwrap().await.unwrap().unwrap(); let nonce = provider.get_transaction_count(from, None).await.unwrap(); - assert_eq!(nonce, initial_nonce + rU256::from(1)); + assert_eq!(nonce, initial_nonce + rU64::from(1)); let to_balance = provider.get_balance(to, None).await.unwrap(); assert_eq!(balance_before.saturating_add(amount), to_balance); @@ -383,7 +382,7 @@ async fn test_fork_snapshotting_blocks() { assert_eq!(block_number_after, block_number + 1); let nonce = provider.get_transaction_count(from, None).await.unwrap(); - assert_eq!(nonce, initial_nonce + rU256::from(1)); + assert_eq!(nonce, initial_nonce + rU64::from(1)); let to_balance = provider.get_balance(to, None).await.unwrap(); assert_eq!(balance_before.saturating_add(amount), to_balance); @@ -397,12 +396,12 @@ async fn test_fork_snapshotting_blocks() { // repeat transaction let _ = tx_provider.send_transaction(tx.clone(), None).await.unwrap().await.unwrap().unwrap(); let nonce = provider.get_transaction_count(from, None).await.unwrap(); - assert_eq!(nonce, initial_nonce + rU256::from(1)); + assert_eq!(nonce, initial_nonce + rU64::from(1)); // revert again: nothing to revert since snapshot gone assert!(!api.evm_revert(snapshot).await.unwrap()); let nonce = provider.get_transaction_count(from, None).await.unwrap(); - assert_eq!(nonce, initial_nonce + rU256::from(1)); + assert_eq!(nonce, initial_nonce + rU64::from(1)); let block_number_after = provider.get_block_number().await.unwrap(); assert_eq!(block_number_after, block_number + 1); } @@ -468,17 +467,23 @@ async fn can_reset_properly() { let (origin_api, origin_handle) = spawn(NodeConfig::test()).await; let account = origin_handle.dev_accounts().next().unwrap(); let origin_provider = origin_handle.http_provider(); - let origin_nonce = rU256::from(1u64); - origin_api.anvil_set_nonce(account, origin_nonce).await.unwrap(); + let origin_nonce = 1u64; + origin_api.anvil_set_nonce(account, rU256::from(origin_nonce)).await.unwrap(); - assert_eq!(origin_nonce, origin_provider.get_transaction_count(account, None).await.unwrap()); + assert_eq!( + origin_nonce, + origin_provider.get_transaction_count(account, None).await.unwrap().to::() + ); let (fork_api, fork_handle) = spawn(NodeConfig::test().with_eth_rpc_url(Some(origin_handle.http_endpoint()))).await; let fork_provider = fork_handle.http_provider(); let fork_tx_provider = ethers_http_provider(&fork_handle.http_endpoint()); - assert_eq!(origin_nonce, fork_provider.get_transaction_count(account, None).await.unwrap()); + assert_eq!( + origin_nonce, + fork_provider.get_transaction_count(account, None).await.unwrap().to::() + ); let to = Address::random(); let to_balance = fork_provider.get_balance(to.to_alloy(), None).await.unwrap(); @@ -487,15 +492,18 @@ async fn can_reset_properly() { // nonce incremented by 1 assert_eq!( - origin_nonce + rU256::from(1), - fork_provider.get_transaction_count(account, None).await.unwrap() + origin_nonce + rU256::from(1).to::(), + fork_provider.get_transaction_count(account, None).await.unwrap().to::() ); // resetting to origin state fork_api.anvil_reset(Some(Forking::default())).await.unwrap(); // nonce reset to origin - assert_eq!(origin_nonce, fork_provider.get_transaction_count(account, None).await.unwrap()); + assert_eq!( + origin_nonce, + fork_provider.get_transaction_count(account, None).await.unwrap().to::() + ); // balance is reset assert_eq!(to_balance, fork_provider.get_balance(to.to_alloy(), None).await.unwrap()); diff --git a/crates/anvil/tests/it/otterscan.rs b/crates/anvil/tests/it/otterscan.rs index 8dca5f7a2e25..fddb09d05b97 100644 --- a/crates/anvil/tests/it/otterscan.rs +++ b/crates/anvil/tests/it/otterscan.rs @@ -5,7 +5,6 @@ use crate::{ }; use alloy_primitives::U256 as rU256; use alloy_rpc_types::{BlockNumberOrTag, BlockTransactions}; -use alloy_signer::Signer as AlloySigner; use anvil::{ eth::otterscan::types::{ OtsInternalOperation, OtsInternalOperationType, OtsTrace, OtsTraceType, @@ -485,7 +484,7 @@ async fn can_call_ots_get_block_transactions() { result.receipts.iter().enumerate().for_each(|(i, receipt)| { let expected = hashes.pop_front(); - assert_eq!(expected, receipt.transaction_hash.map(|h| h.to_ethers())); + assert_eq!(expected, Some(receipt.transaction_hash.to_ethers())); assert_eq!( expected.map(|h| h.to_alloy()), result.fullblock.block.transactions.hashes().nth(i).copied(), diff --git a/crates/anvil/tests/it/transaction.rs b/crates/anvil/tests/it/transaction.rs index 18a74e1a9d8a..ec245433f36f 100644 --- a/crates/anvil/tests/it/transaction.rs +++ b/crates/anvil/tests/it/transaction.rs @@ -2,13 +2,12 @@ use crate::{ abi::*, utils::{ethers_http_provider, ethers_ws_provider}, }; -use alloy_primitives::U256 as rU256; +use alloy_primitives::{Bytes, U256 as rU256}; use alloy_rpc_types::{ request::TransactionRequest as AlloyTransactionRequest, state::{AccountOverride, StateOverride}, BlockNumberOrTag, }; -use alloy_signer::Signer as AlloySigner; use anvil::{spawn, Hardfork, NodeConfig}; use ethers::{ abi::ethereum_types::BigEndianHash, @@ -21,7 +20,7 @@ use ethers::{ Address, BlockNumber, Transaction, TransactionReceipt, H256, U256, }, }; -use foundry_common::types::{to_call_request_from_tx_request, ToAlloy, ToEthers}; +use foundry_common::types::{ToAlloy, ToEthers}; use futures::{future::join_all, FutureExt, StreamExt}; use std::{collections::HashSet, sync::Arc, time::Duration}; use tokio::time::timeout; @@ -962,9 +961,12 @@ async fn estimates_gas_on_pending_by_default() { let tx = TransactionRequest::new().from(sender).to(recipient).value(1e18 as u64); client.send_transaction(tx, None).await.unwrap(); - let tx = - TransactionRequest::new().from(recipient).to(sender).value(1e10 as u64).data(vec![0x42]); - api.estimate_gas(to_call_request_from_tx_request(tx), None, None).await.unwrap(); + let tx = AlloyTransactionRequest::default() + .from(recipient.to_alloy()) + .to(Some(sender.to_alloy())) + .value(rU256::from(1e10)) + .input(Bytes::from(vec![0x42]).into()); + api.estimate_gas(tx, None, None).await.unwrap(); } #[tokio::test(flavor = "multi_thread")] @@ -975,11 +977,14 @@ async fn test_estimate_gas() { let sender = wallet.address(); let recipient = Address::random(); - let tx = - TransactionRequest::new().from(recipient).to(sender).value(1e10 as u64).data(vec![0x42]); + let tx = AlloyTransactionRequest::default() + .from(recipient.to_alloy()) + .to(Some(sender.to_alloy())) + .value(rU256::from(1e10)) + .input(Bytes::from(vec![0x42]).into()); // Expect the gas estimation to fail due to insufficient funds. let error_result = - api.estimate_gas(to_call_request_from_tx_request(tx.clone()), None, None).await; + api.estimate_gas(tx.clone(), None, None).await; assert!(error_result.is_err(), "Expected an error due to insufficient funds"); let error_message = error_result.unwrap_err().to_string(); @@ -998,7 +1003,7 @@ async fn test_estimate_gas() { // Estimate gas with state override implying sufficient funds. let gas_estimate = api - .estimate_gas(to_call_request_from_tx_request(tx), None, Some(state_override)) + .estimate_gas(tx, None, Some(state_override)) .await .expect("Failed to estimate gas with state override"); diff --git a/crates/cast/bin/cmd/logs.rs b/crates/cast/bin/cmd/logs.rs index 20c545819217..0f831a613b91 100644 --- a/crates/cast/bin/cmd/logs.rs +++ b/crates/cast/bin/cmd/logs.rs @@ -279,7 +279,8 @@ pub fn sanitize_token(token: Token) -> Token { #[cfg(test)] mod tests { use super::*; - use ethers_core::types::H160; + use alloy_primitives::{B256, U160, U256 as rU256}; + use alloy_rpc_types::ValueOrArray; const ADDRESS: &str = "0x4D1A2e2bB4F88F0250f26Ffff098B0b30B26BF38"; const TRANSFER_SIG: &str = "Transfer(address indexed,address indexed,uint256)"; @@ -288,13 +289,13 @@ mod tests { #[test] fn test_build_filter_basic() { - let from_block = Some(BlockNumber::from(1337)); - let to_block = Some(BlockNumber::Latest); + let from_block = Some(BlockNumberOrTag::from(1337)); + let to_block = Some(BlockNumberOrTag::Latest); let address = Address::from_str(ADDRESS).ok(); let expected = Filter { block_option: FilterBlockOption::Range { from_block, to_block }, - address: Some(ValueOrArray::Value(address.unwrap())), - topics: [None, None, None, None], + address: ValueOrArray::Value(address.unwrap()).into(), + topics: [vec![].into(), vec![].into(), vec![].into(), vec![].into()], }; let filter = build_filter(from_block, to_block, address, None, vec![]).unwrap(); assert_eq!(filter, expected) @@ -304,8 +305,13 @@ mod tests { fn test_build_filter_sig() { let expected = Filter { block_option: FilterBlockOption::Range { from_block: None, to_block: None }, - address: None, - topics: [Some(H256::from_str(TRANSFER_TOPIC).unwrap().into()), None, None, None], + address: vec![].into(), + topics: [ + B256::from_str(TRANSFER_TOPIC).unwrap().into(), + vec![].into(), + vec![].into(), + vec![].into(), + ], }; let filter = build_filter(None, None, None, Some(TRANSFER_SIG.to_string()), vec![]).unwrap(); @@ -316,8 +322,13 @@ mod tests { fn test_build_filter_mismatch() { let expected = Filter { block_option: FilterBlockOption::Range { from_block: None, to_block: None }, - address: None, - topics: [Some(H256::from_str(TRANSFER_TOPIC).unwrap().into()), None, None, None], + address: vec![].into(), + topics: [ + B256::from_str(TRANSFER_TOPIC).unwrap().into(), + vec![].into(), + vec![].into(), + vec![].into(), + ], }; let filter = build_filter( None, @@ -332,14 +343,16 @@ mod tests { #[test] fn test_build_filter_sig_with_arguments() { + let addr = Address::from_str(ADDRESS).unwrap(); + let addr = rU256::from(U160::from_be_bytes(addr.0 .0)); let expected = Filter { block_option: FilterBlockOption::Range { from_block: None, to_block: None }, - address: None, + address: vec![].into(), topics: [ - Some(H256::from_str(TRANSFER_TOPIC).unwrap().into()), - Some(H160::from_str(ADDRESS).unwrap().into()), - None, - None, + B256::from_str(TRANSFER_TOPIC).unwrap().into(), + addr.into(), + vec![].into(), + vec![].into(), ], }; let filter = build_filter( @@ -355,14 +368,16 @@ mod tests { #[test] fn test_build_filter_sig_with_skipped_arguments() { + let addr = Address::from_str(ADDRESS).unwrap(); + let addr = rU256::from(U160::from_be_bytes(addr.0 .0)); let expected = Filter { block_option: FilterBlockOption::Range { from_block: None, to_block: None }, - address: None, + address: vec![].into(), topics: [ - Some(H256::from_str(TRANSFER_TOPIC).unwrap().into()), - None, - Some(H160::from_str(ADDRESS).unwrap().into()), - None, + vec![B256::from_str(TRANSFER_TOPIC).unwrap()].into(), + vec![].into(), + addr.into(), + vec![].into(), ], }; let filter = build_filter( @@ -380,12 +395,12 @@ mod tests { fn test_build_filter_with_topics() { let expected = Filter { block_option: FilterBlockOption::Range { from_block: None, to_block: None }, - address: None, + address: vec![].into(), topics: [ - Some(H256::from_str(TRANSFER_TOPIC).unwrap().into()), - Some(H256::from_str(TRANSFER_TOPIC).unwrap().into()), - None, - None, + vec![B256::from_str(TRANSFER_TOPIC).unwrap()].into(), + vec![B256::from_str(TRANSFER_TOPIC).unwrap()].into(), + vec![].into(), + vec![].into(), ], }; let filter = build_filter( @@ -404,12 +419,12 @@ mod tests { fn test_build_filter_with_skipped_topic() { let expected = Filter { block_option: FilterBlockOption::Range { from_block: None, to_block: None }, - address: None, + address: vec![].into(), topics: [ - Some(H256::from_str(TRANSFER_TOPIC).unwrap().into()), - None, - Some(H256::from_str(TRANSFER_TOPIC).unwrap().into()), - None, + vec![B256::from_str(TRANSFER_TOPIC).unwrap()].into(), + vec![].into(), + vec![B256::from_str(TRANSFER_TOPIC).unwrap()].into(), + vec![].into(), ], }; let filter = build_filter( diff --git a/crates/cast/bin/opts.rs b/crates/cast/bin/opts.rs index 9c23713d47e5..628c3430e625 100644 --- a/crates/cast/bin/opts.rs +++ b/crates/cast/bin/opts.rs @@ -907,9 +907,9 @@ pub fn parse_slot(s: &str) -> Result { #[cfg(test)] mod tests { use super::*; + use alloy_rpc_types::{BlockNumberOrTag, RpcBlockHash}; use cast::SimpleCast; use clap::CommandFactory; - use ethers_core::types::BlockNumber; #[test] fn verify_cli() { @@ -998,30 +998,34 @@ mod tests { let test_cases = [ TestCase { input: "0".to_string(), - expect: BlockId::Number(BlockNumber::Number(0u64.into())), + expect: BlockId::Number(BlockNumberOrTag::Number(0u64)), }, TestCase { input: "0x56462c47c03df160f66819f0a79ea07def1569f8aac0fe91bb3a081159b61b4a" .to_string(), - expect: BlockId::Hash( + expect: BlockId::Hash(RpcBlockHash::from_hash( "0x56462c47c03df160f66819f0a79ea07def1569f8aac0fe91bb3a081159b61b4a" .parse() .unwrap(), - ), + None, + )), + }, + TestCase { + input: "latest".to_string(), + expect: BlockId::Number(BlockNumberOrTag::Latest), }, - TestCase { input: "latest".to_string(), expect: BlockId::Number(BlockNumber::Latest) }, TestCase { input: "earliest".to_string(), - expect: BlockId::Number(BlockNumber::Earliest), + expect: BlockId::Number(BlockNumberOrTag::Earliest), }, TestCase { input: "pending".to_string(), - expect: BlockId::Number(BlockNumber::Pending), + expect: BlockId::Number(BlockNumberOrTag::Pending), }, - TestCase { input: "safe".to_string(), expect: BlockId::Number(BlockNumber::Safe) }, + TestCase { input: "safe".to_string(), expect: BlockId::Number(BlockNumberOrTag::Safe) }, TestCase { input: "finalized".to_string(), - expect: BlockId::Number(BlockNumber::Finalized), + expect: BlockId::Number(BlockNumberOrTag::Finalized), }, ]; diff --git a/crates/cast/src/lib.rs b/crates/cast/src/lib.rs index f5bbf97630d9..1f9bfbbff2c6 100644 --- a/crates/cast/src/lib.rs +++ b/crates/cast/src/lib.rs @@ -687,7 +687,7 @@ where eyre::bail!("tx not found: {:?}", tx_hash) } else { PendingTransactionBuilder::new(self.provider.root(), tx_hash.into()) - .with_confirmations(confs) + .with_required_confirmations(confs) .get_receipt() .await? } diff --git a/crates/cast/src/tx.rs b/crates/cast/src/tx.rs index 03c1da8900a1..d3e02ef1a570 100644 --- a/crates/cast/src/tx.rs +++ b/crates/cast/src/tx.rs @@ -301,7 +301,7 @@ mod tests { TxBuilder::new(&provider, ADDR_1, Some(ADDR_2), NamedChain::Mainnet, true).await?; // don't check anything other than the tx type - the rest is covered in the non-legacy case let (tx, _) = builder.build(); - match tx { + match tx.build_unsigned().unwrap() { TypedTransaction::Legacy(_) => {} _ => { panic!("Wrong tx type"); @@ -326,9 +326,9 @@ mod tests { builder.etherscan_api_key(Some(String::from("what a lovely day"))); // not testing for this :-/ let (tx, _) = builder.build(); - assert_eq!(tx.gas, Some(12)); - assert_eq!(tx.gas_price, Some(34)); - assert_eq!(tx.value, Some(56)); + assert_eq!(tx.gas, Some(U256::from(12))); + assert_eq!(tx.gas_price, Some(U256::from(34))); + assert_eq!(tx.value, Some(U256::from(56))); assert_eq!(tx.nonce, Some(78)); assert_eq!(tx.chain_id, Some(1)); Ok(()) diff --git a/crates/cheatcodes/src/evm.rs b/crates/cheatcodes/src/evm.rs index b3aa0fdaf461..52cc11e67e67 100644 --- a/crates/cheatcodes/src/evm.rs +++ b/crates/cheatcodes/src/evm.rs @@ -13,7 +13,7 @@ use revm::{ primitives::{Account, Bytecode, SpecId, KECCAK_EMPTY}, InnerEvmContext, }; -use std::{collections::HashMap, path::Path}; +use std::{collections::{BTreeMap, HashMap}, path::Path}; mod fork; pub(crate) mod mapping; @@ -73,7 +73,7 @@ impl Cheatcode for loadAllocsCall { ensure!(path.exists(), "allocs file does not exist: {pathToAllocsJson}"); // Let's first assume we're reading a file with only the allocs. - let allocs: HashMap = match read_json_file(path) { + let allocs: BTreeMap = match read_json_file(path) { Ok(allocs) => allocs, Err(_) => { // Let's try and read from a genesis file, and extract allocs. diff --git a/crates/evm/core/src/abi/hardhat_console.rs b/crates/evm/core/src/abi/hardhat_console.rs index 4b9aa3ba2a89..05328704733d 100644 --- a/crates/evm/core/src/abi/hardhat_console.rs +++ b/crates/evm/core/src/abi/hardhat_console.rs @@ -4,8 +4,9 @@ use foundry_macros::ConsoleFmt; use once_cell::sync::Lazy; use revm::primitives::HashMap; + sol!( - #[sol(abi)] + #[sol(abi, all_derives)] #[derive(ConsoleFmt)] HardhatConsole, "src/abi/HardhatConsole.json" diff --git a/crates/evm/core/src/backend/cow.rs b/crates/evm/core/src/backend/cow.rs index c0ff88ea40a1..f41a1cd43048 100644 --- a/crates/evm/core/src/backend/cow.rs +++ b/crates/evm/core/src/backend/cow.rs @@ -18,7 +18,7 @@ use revm::{ }, Database, DatabaseCommit, Inspector, JournaledState, }; -use std::{borrow::Cow, collections::HashMap}; +use std::{borrow::Cow, collections::BTreeMap}; /// A wrapper around `Backend` that ensures only `revm::DatabaseRef` functions are called. /// @@ -213,7 +213,7 @@ impl<'a> DatabaseExt for CowBackend<'a> { fn load_allocs( &mut self, - allocs: &HashMap, + allocs: &BTreeMap, journaled_state: &mut JournaledState, ) -> Result<(), DatabaseError> { self.backend_mut(&Env::default()).load_allocs(allocs, journaled_state) diff --git a/crates/evm/core/src/backend/mod.rs b/crates/evm/core/src/backend/mod.rs index f55259f4d1e0..944501326e01 100644 --- a/crates/evm/core/src/backend/mod.rs +++ b/crates/evm/core/src/backend/mod.rs @@ -22,7 +22,7 @@ use revm::{ Database, DatabaseCommit, Inspector, JournaledState, }; use std::{ - collections::{HashMap, HashSet}, + collections::{BTreeMap, HashMap, HashSet}, time::Instant, }; @@ -262,7 +262,7 @@ pub trait DatabaseExt: Database { /// Returns [Ok] if all accounts were successfully inserted into the journal, [Err] otherwise. fn load_allocs( &mut self, - allocs: &HashMap, + allocs: &BTreeMap, journaled_state: &mut JournaledState, ) -> Result<(), DatabaseError>; @@ -1332,7 +1332,7 @@ impl DatabaseExt for Backend { /// Returns [Ok] if all accounts were successfully inserted into the journal, [Err] otherwise. fn load_allocs( &mut self, - allocs: &HashMap, + allocs: &BTreeMap, journaled_state: &mut JournaledState, ) -> Result<(), DatabaseError> { // Loop through all of the allocs defined in the map and commit them to the journal. diff --git a/crates/forge/Cargo.toml b/crates/forge/Cargo.toml index 7826d118064c..903541f45d19 100644 --- a/crates/forge/Cargo.toml +++ b/crates/forge/Cargo.toml @@ -102,6 +102,9 @@ svm = { package = "svm-rs", version = "0.3", default-features = false, features tempfile = "3" tracing-subscriber = { workspace = true, features = ["env-filter", "fmt"] } +ethers-core.workspace = true +alloy-signer-wallet.workspace = true + [features] default = ["rustls"] rustls = [ diff --git a/crates/forge/bin/cmd/create.rs b/crates/forge/bin/cmd/create.rs index 9c13f5790c11..44e91fa5301d 100644 --- a/crates/forge/bin/cmd/create.rs +++ b/crates/forge/bin/cmd/create.rs @@ -443,7 +443,7 @@ where .borrow() .send_transaction(self.tx) .await? - .with_confirmations(self.confs as u64) + .with_required_confirmations(self.confs as u64) .get_receipt() .await?; diff --git a/crates/forge/tests/cli/utils.rs b/crates/forge/tests/cli/utils.rs index 12b0fe13470f..e8e79fa68872 100644 --- a/crates/forge/tests/cli/utils.rs +++ b/crates/forge/tests/cli/utils.rs @@ -1,7 +1,8 @@ //! Various helper functions +use alloy_signer_wallet::LocalWallet; use ethers_core::types::{Address, Chain}; -use ethers_signers::{LocalWallet, Signer}; +use foundry_common::types::ToEthers; /// Returns the current millis since unix epoch. /// @@ -46,7 +47,7 @@ pub struct EnvExternalities { impl EnvExternalities { pub fn address(&self) -> Option
{ let pk: LocalWallet = self.pk.parse().ok()?; - Some(pk.address()) + Some(pk.address().to_ethers()) } pub fn goerli() -> Option { From 67107c38ed47dc8d5a45a2bbed41aa814d46ffc7 Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Sat, 23 Mar 2024 21:49:22 +0400 Subject: [PATCH 22/63] bump alloy --- Cargo.lock | 31 +++++++++++++------- Cargo.toml | 9 +++--- crates/anvil/core/src/eth/transaction/mod.rs | 5 +--- crates/anvil/src/eth/api.rs | 2 +- crates/anvil/tests/it/transaction.rs | 3 +- crates/cheatcodes/src/evm.rs | 5 +++- crates/evm/core/src/abi/hardhat_console.rs | 1 - crates/forge/bin/cmd/create.rs | 2 +- 8 files changed, 34 insertions(+), 24 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8123e95f855f..1b6fd6f3b8a5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -123,12 +123,11 @@ dependencies = [ [[package]] name = "alloy-dyn-abi" version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2919acdad13336bc5dc26b636cdd6892c2f27fb0d4a58320a00c2713cf6a4e9a" +source = "git+https://github.com/alloy-rs/core?rev=ff339696fa9b490698cb3edec3d4647fae0bd332#ff339696fa9b490698cb3edec3d4647fae0bd332" dependencies = [ "alloy-json-abi", "alloy-primitives", - "alloy-sol-type-parser 0.6.4 (registry+https://github.com/rust-lang/crates.io-index)", + "alloy-sol-type-parser", "alloy-sol-types", "arbitrary", "const-hex", @@ -165,9 +164,10 @@ dependencies = [ [[package]] name = "alloy-json-abi" version = "0.6.4" +source = "git+https://github.com/alloy-rs/core?rev=ff339696fa9b490698cb3edec3d4647fae0bd332#ff339696fa9b490698cb3edec3d4647fae0bd332" dependencies = [ "alloy-primitives", - "alloy-sol-type-parser 0.6.4", + "alloy-sol-type-parser", "serde", "serde_json", ] @@ -203,6 +203,7 @@ dependencies = [ [[package]] name = "alloy-primitives" version = "0.6.4" +source = "git+https://github.com/alloy-rs/core?rev=ff339696fa9b490698cb3edec3d4647fae0bd332#ff339696fa9b490698cb3edec3d4647fae0bd332" dependencies = [ "alloy-rlp", "arbitrary", @@ -438,33 +439,41 @@ dependencies = [ [[package]] name = "alloy-sol-macro" version = "0.6.4" +source = "git+https://github.com/alloy-rs/core?rev=ff339696fa9b490698cb3edec3d4647fae0bd332#ff339696fa9b490698cb3edec3d4647fae0bd332" dependencies = [ "alloy-json-abi", + "alloy-sol-macro-input", "const-hex", - "dunce", "heck 0.4.1", "indexmap", "proc-macro-error", "proc-macro2", "quote", - "serde_json", "syn 2.0.53", "syn-solidity", "tiny-keccak", ] [[package]] -name = "alloy-sol-type-parser" +name = "alloy-sol-macro-input" version = "0.6.4" +source = "git+https://github.com/alloy-rs/core?rev=ff339696fa9b490698cb3edec3d4647fae0bd332#ff339696fa9b490698cb3edec3d4647fae0bd332" dependencies = [ - "winnow 0.6.5", + "alloy-json-abi", + "const-hex", + "dunce", + "heck 0.5.0", + "proc-macro2", + "quote", + "serde_json", + "syn 2.0.53", + "syn-solidity", ] [[package]] name = "alloy-sol-type-parser" version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0045cc89524e1451ccf33e8581355b6027ac7c6e494bb02959d4213ad0d8e91d" +source = "git+https://github.com/alloy-rs/core?rev=ff339696fa9b490698cb3edec3d4647fae0bd332#ff339696fa9b490698cb3edec3d4647fae0bd332" dependencies = [ "winnow 0.6.5", ] @@ -472,6 +481,7 @@ dependencies = [ [[package]] name = "alloy-sol-types" version = "0.6.4" +source = "git+https://github.com/alloy-rs/core?rev=ff339696fa9b490698cb3edec3d4647fae0bd332#ff339696fa9b490698cb3edec3d4647fae0bd332" dependencies = [ "alloy-json-abi", "alloy-primitives", @@ -7783,6 +7793,7 @@ dependencies = [ [[package]] name = "syn-solidity" version = "0.6.4" +source = "git+https://github.com/alloy-rs/core?rev=ff339696fa9b490698cb3edec3d4647fae0bd332#ff339696fa9b490698cb3edec3d4647fae0bd332" dependencies = [ "paste", "proc-macro2", diff --git a/Cargo.toml b/Cargo.toml index 69948b19daa4..292a8298237c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -180,7 +180,6 @@ alloy-dyn-abi = "0.6.4" alloy-json-abi = "0.6.4" alloy-sol-types = "0.6.4" syn-solidity = "0.6.4" -alloy-sol-macro-input = "0.6.4" alloy-chains = "0.1" @@ -219,6 +218,8 @@ tower = "0.4" tower-http = "0.4" [patch.crates-io] -alloy-primitives = { path = "../core/crates/primitives" } -alloy-json-abi = { path = "../core/crates/json-abi" } -alloy-sol-types = { path = "../core/crates/sol-types" } \ No newline at end of file +alloy-primitives = { git = "https://github.com/alloy-rs/core", rev = "ff339696fa9b490698cb3edec3d4647fae0bd332" } +alloy-sol-types = { git = "https://github.com/alloy-rs/core", rev = "ff339696fa9b490698cb3edec3d4647fae0bd332" } +alloy-json-abi = { git = "https://github.com/alloy-rs/core", rev = "ff339696fa9b490698cb3edec3d4647fae0bd332" } +alloy-dyn-abi = { git = "https://github.com/alloy-rs/core", rev = "ff339696fa9b490698cb3edec3d4647fae0bd332" } +syn-solidity = { git = "https://github.com/alloy-rs/core", rev = "ff339696fa9b490698cb3edec3d4647fae0bd332" } \ No newline at end of file diff --git a/crates/anvil/core/src/eth/transaction/mod.rs b/crates/anvil/core/src/eth/transaction/mod.rs index 409cebe22985..feaabd00a338 100644 --- a/crates/anvil/core/src/eth/transaction/mod.rs +++ b/crates/anvil/core/src/eth/transaction/mod.rs @@ -1229,10 +1229,7 @@ mod tests { _ => unreachable!(), }; - assert_eq!( - tx.tx().tx().to, - address!("11E9CA82A3a762b4B5bd264d4173a242e7a77064") - ); + assert_eq!(tx.tx().tx().to, address!("11E9CA82A3a762b4B5bd264d4173a242e7a77064")); assert_eq!( tx.tx().tx().blob_versioned_hashes, diff --git a/crates/anvil/src/eth/api.rs b/crates/anvil/src/eth/api.rs index 9c8d37b69541..a9d13a53d5fa 100644 --- a/crates/anvil/src/eth/api.rs +++ b/crates/anvil/src/eth/api.rs @@ -916,7 +916,7 @@ impl EthApi { } let transaction = TypedTransaction::decode_2718(&mut data) .map_err(|_| BlockchainError::FailedToDecodeSignedTransaction)?; - + self.ensure_typed_transaction_supported(&transaction)?; let pending_transaction = PendingTransaction::new(transaction)?; diff --git a/crates/anvil/tests/it/transaction.rs b/crates/anvil/tests/it/transaction.rs index ec245433f36f..538f6401193c 100644 --- a/crates/anvil/tests/it/transaction.rs +++ b/crates/anvil/tests/it/transaction.rs @@ -983,8 +983,7 @@ async fn test_estimate_gas() { .value(rU256::from(1e10)) .input(Bytes::from(vec![0x42]).into()); // Expect the gas estimation to fail due to insufficient funds. - let error_result = - api.estimate_gas(tx.clone(), None, None).await; + let error_result = api.estimate_gas(tx.clone(), None, None).await; assert!(error_result.is_err(), "Expected an error due to insufficient funds"); let error_message = error_result.unwrap_err().to_string(); diff --git a/crates/cheatcodes/src/evm.rs b/crates/cheatcodes/src/evm.rs index 52cc11e67e67..bd9f80fdf2d2 100644 --- a/crates/cheatcodes/src/evm.rs +++ b/crates/cheatcodes/src/evm.rs @@ -13,7 +13,10 @@ use revm::{ primitives::{Account, Bytecode, SpecId, KECCAK_EMPTY}, InnerEvmContext, }; -use std::{collections::{BTreeMap, HashMap}, path::Path}; +use std::{ + collections::{BTreeMap, HashMap}, + path::Path, +}; mod fork; pub(crate) mod mapping; diff --git a/crates/evm/core/src/abi/hardhat_console.rs b/crates/evm/core/src/abi/hardhat_console.rs index 05328704733d..a6e7429c2329 100644 --- a/crates/evm/core/src/abi/hardhat_console.rs +++ b/crates/evm/core/src/abi/hardhat_console.rs @@ -4,7 +4,6 @@ use foundry_macros::ConsoleFmt; use once_cell::sync::Lazy; use revm::primitives::HashMap; - sol!( #[sol(abi, all_derives)] #[derive(ConsoleFmt)] diff --git a/crates/forge/bin/cmd/create.rs b/crates/forge/bin/cmd/create.rs index 44e91fa5301d..28228eb688e0 100644 --- a/crates/forge/bin/cmd/create.rs +++ b/crates/forge/bin/cmd/create.rs @@ -1,5 +1,5 @@ use alloy_chains::Chain; -use alloy_dyn_abi::{DynSolValue, JsonAbiExt, ResolveSolType}; +use alloy_dyn_abi::{DynSolValue, JsonAbiExt, Specifier}; use alloy_json_abi::{Constructor, JsonAbi}; use alloy_network::{Ethereum, EthereumSigner, TransactionBuilder}; use alloy_primitives::{Address, Bytes}; From 09ee81f81899985418a7784c23788e4165f74b71 Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Sun, 24 Mar 2024 03:38:47 +0400 Subject: [PATCH 23/63] fix tests --- Cargo.lock | 229 +++++++++++++++++++++------- Cargo.toml | 42 ++--- crates/cast/src/tx.rs | 8 +- crates/common/Cargo.toml | 6 +- crates/common/src/provider/retry.rs | 2 + crates/common/src/runtime_client.rs | 10 +- crates/forge/bin/cmd/create.rs | 29 ++-- 7 files changed, 228 insertions(+), 98 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1b6fd6f3b8a5..92f60d9078e6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -90,7 +90,7 @@ dependencies = [ [[package]] name = "alloy-consensus" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" +source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" dependencies = [ "alloy-eips", "alloy-primitives", @@ -105,7 +105,7 @@ dependencies = [ [[package]] name = "alloy-contract" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" +source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" dependencies = [ "alloy-dyn-abi", "alloy-json-abi", @@ -143,18 +143,21 @@ dependencies = [ [[package]] name = "alloy-eips" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" +source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" dependencies = [ "alloy-primitives", "alloy-rlp", "alloy-serde", + "c-kzg", + "derive_more", + "once_cell", "serde", ] [[package]] name = "alloy-genesis" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" +source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" dependencies = [ "alloy-primitives", "alloy-serde", @@ -175,7 +178,7 @@ dependencies = [ [[package]] name = "alloy-json-rpc" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" +source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" dependencies = [ "alloy-primitives", "serde", @@ -186,7 +189,7 @@ dependencies = [ [[package]] name = "alloy-network" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" +source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" dependencies = [ "alloy-consensus", "alloy-eips", @@ -229,7 +232,7 @@ dependencies = [ [[package]] name = "alloy-provider" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" +source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" dependencies = [ "alloy-json-rpc", "alloy-network", @@ -246,7 +249,7 @@ dependencies = [ "dashmap", "futures", "lru", - "reqwest", + "reqwest 0.12.1", "serde_json", "tokio", "tracing", @@ -255,7 +258,7 @@ dependencies = [ [[package]] name = "alloy-pubsub" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" +source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" dependencies = [ "alloy-json-rpc", "alloy-primitives", @@ -295,7 +298,7 @@ dependencies = [ [[package]] name = "alloy-rpc-client" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" +source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" dependencies = [ "alloy-json-rpc", "alloy-primitives", @@ -304,7 +307,7 @@ dependencies = [ "alloy-transport-http", "futures", "pin-project", - "reqwest", + "reqwest 0.12.1", "serde", "serde_json", "tokio", @@ -317,7 +320,7 @@ dependencies = [ [[package]] name = "alloy-rpc-trace-types" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" +source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" dependencies = [ "alloy-primitives", "alloy-rpc-types", @@ -329,7 +332,7 @@ dependencies = [ [[package]] name = "alloy-rpc-types" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" +source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" dependencies = [ "alloy-consensus", "alloy-eips", @@ -345,7 +348,7 @@ dependencies = [ [[package]] name = "alloy-serde" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" +source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" dependencies = [ "alloy-primitives", "serde", @@ -355,7 +358,7 @@ dependencies = [ [[package]] name = "alloy-signer" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" +source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" dependencies = [ "alloy-dyn-abi", "alloy-primitives", @@ -370,7 +373,7 @@ dependencies = [ [[package]] name = "alloy-signer-aws" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" +source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" dependencies = [ "alloy-consensus", "alloy-network", @@ -387,7 +390,7 @@ dependencies = [ [[package]] name = "alloy-signer-ledger" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" +source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" dependencies = [ "alloy-consensus", "alloy-network", @@ -404,7 +407,7 @@ dependencies = [ [[package]] name = "alloy-signer-trezor" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" +source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" dependencies = [ "alloy-consensus", "alloy-network", @@ -420,7 +423,7 @@ dependencies = [ [[package]] name = "alloy-signer-wallet" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" +source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" dependencies = [ "alloy-consensus", "alloy-network", @@ -493,7 +496,7 @@ dependencies = [ [[package]] name = "alloy-transport" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" +source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" dependencies = [ "alloy-json-rpc", "base64 0.22.0", @@ -511,11 +514,11 @@ dependencies = [ [[package]] name = "alloy-transport-http" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" +source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" dependencies = [ "alloy-json-rpc", "alloy-transport", - "reqwest", + "reqwest 0.12.1", "serde_json", "tower", "url", @@ -524,7 +527,7 @@ dependencies = [ [[package]] name = "alloy-transport-ipc" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" +source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" dependencies = [ "alloy-json-rpc", "alloy-pubsub", @@ -542,7 +545,7 @@ dependencies = [ [[package]] name = "alloy-transport-ws" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=cf5d733#cf5d73388e077e16600b9cde2a4c6121e37db0e4" +source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" dependencies = [ "alloy-pubsub", "alloy-transport", @@ -681,7 +684,7 @@ dependencies = [ "foundry-evm", "futures", "hash-db", - "hyper", + "hyper 0.14.28", "itertools 0.12.1", "k256", "memory-db", @@ -749,7 +752,7 @@ dependencies = [ "bytes", "clap", "futures", - "hyper", + "hyper 0.14.28", "parity-tokio-ipc", "parking_lot", "pin-project", @@ -1086,7 +1089,7 @@ dependencies = [ "fastrand", "hex", "http 0.2.12", - "hyper", + "hyper 0.14.28", "ring 0.17.8", "time", "tokio", @@ -1122,7 +1125,7 @@ dependencies = [ "bytes", "fastrand", "http 0.2.12", - "http-body", + "http-body 0.4.6", "percent-encoding", "pin-project-lite", "tracing", @@ -1264,7 +1267,7 @@ dependencies = [ "bytes-utils", "futures-core", "http 0.2.12", - "http-body", + "http-body 0.4.6", "once_cell", "percent-encoding", "pin-project-lite", @@ -1305,8 +1308,8 @@ dependencies = [ "fastrand", "h2", "http 0.2.12", - "http-body", - "hyper", + "http-body 0.4.6", + "hyper 0.14.28", "hyper-rustls", "once_cell", "pin-project-lite", @@ -1343,7 +1346,7 @@ dependencies = [ "bytes", "bytes-utils", "http 0.2.12", - "http-body", + "http-body 0.4.6", "itoa", "num-integer", "pin-project-lite", @@ -1390,8 +1393,8 @@ dependencies = [ "bytes", "futures-util", "http 0.2.12", - "http-body", - "hyper", + "http-body 0.4.6", + "hyper 0.14.28", "itoa", "matchit", "memchr", @@ -1422,7 +1425,7 @@ dependencies = [ "bytes", "futures-util", "http 0.2.12", - "http-body", + "http-body 0.4.6", "mime", "rustversion", "tower-layer", @@ -1835,7 +1838,7 @@ dependencies = [ "foundry-evm", "once_cell", "regex", - "reqwest", + "reqwest 0.11.26", "revm", "rustyline", "semver 1.0.22", @@ -2949,7 +2952,7 @@ dependencies = [ "proc-macro2", "quote", "regex", - "reqwest", + "reqwest 0.11.26", "serde", "serde_json", "syn 2.0.53", @@ -3011,7 +3014,7 @@ checksum = "e79e5973c26d4baf0ce55520bd732314328cabe53193286671b47144145b9649" dependencies = [ "chrono", "ethers-core", - "reqwest", + "reqwest 0.11.26", "semver 1.0.22", "serde", "serde_json", @@ -3035,7 +3038,7 @@ dependencies = [ "futures-locks", "futures-util", "instant", - "reqwest", + "reqwest 0.11.26", "serde", "serde_json", "thiserror", @@ -3068,7 +3071,7 @@ dependencies = [ "jsonwebtoken", "once_cell", "pin-project", - "reqwest", + "reqwest 0.11.26", "serde", "serde_json", "thiserror", @@ -3414,7 +3417,7 @@ dependencies = [ "foundry-wallets", "futures", "globset", - "hyper", + "hyper 0.14.28", "indicatif", "itertools 0.12.1", "once_cell", @@ -3426,7 +3429,7 @@ dependencies = [ "proptest", "rayon", "regex", - "reqwest", + "reqwest 0.11.26", "revm-inspectors", "rustc-hash", "semver 1.0.22", @@ -3552,7 +3555,7 @@ dependencies = [ "futures", "once_cell", "regex", - "reqwest", + "reqwest 0.11.26", "semver 1.0.22", "serde", "serde_json", @@ -3580,7 +3583,7 @@ dependencies = [ "alloy-json-abi", "alloy-primitives", "foundry-compilers", - "reqwest", + "reqwest 0.11.26", "semver 1.0.22", "serde", "serde_json", @@ -3707,7 +3710,8 @@ dependencies = [ "once_cell", "pretty_assertions", "rand 0.8.5", - "reqwest", + "reqwest 0.11.26", + "reqwest 0.12.1", "rustc-hash", "semver 1.0.22", "serde", @@ -3778,7 +3782,7 @@ dependencies = [ "path-slash", "pretty_assertions", "regex", - "reqwest", + "reqwest 0.11.26", "revm-primitives", "semver 1.0.22", "serde", @@ -4691,6 +4695,29 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "http-body" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1cac85db508abc24a2e48553ba12a996e87244a0395ce011e62b37158745d643" +dependencies = [ + "bytes", + "http 1.1.0", +] + +[[package]] +name = "http-body-util" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0475f8b2ac86659c21b64320d5d653f9efe42acd2a4e560073ec61a155a34f1d" +dependencies = [ + "bytes", + "futures-core", + "http 1.1.0", + "http-body 1.0.0", + "pin-project-lite", +] + [[package]] name = "http-range-header" version = "0.3.1" @@ -4727,7 +4754,7 @@ dependencies = [ "futures-util", "h2", "http 0.2.12", - "http-body", + "http-body 0.4.6", "httparse", "httpdate", "itoa", @@ -4739,6 +4766,25 @@ dependencies = [ "want", ] +[[package]] +name = "hyper" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "186548d73ac615b32a73aafe38fb4f56c0d340e110e5a200bcadbaf2e199263a" +dependencies = [ + "bytes", + "futures-channel", + "futures-util", + "http 1.1.0", + "http-body 1.0.0", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + [[package]] name = "hyper-rustls" version = "0.24.2" @@ -4747,7 +4793,7 @@ checksum = "ec3efd23720e2049821a693cbc7e65ea87c72f1c58ff2f9522ff332b1491e590" dependencies = [ "futures-util", "http 0.2.12", - "hyper", + "hyper 0.14.28", "log", "rustls", "rustls-native-certs", @@ -4762,10 +4808,46 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6183ddfa99b85da61a140bea0efc93fdf56ceaa041b37d553518030827f9905" dependencies = [ "bytes", - "hyper", + "hyper 0.14.28", + "native-tls", + "tokio", + "tokio-native-tls", +] + +[[package]] +name = "hyper-tls" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" +dependencies = [ + "bytes", + "http-body-util", + "hyper 1.2.0", + "hyper-util", "native-tls", "tokio", "tokio-native-tls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca38ef113da30126bbff9cd1705f9273e15d45498615d138b0c20279ac7a76aa" +dependencies = [ + "bytes", + "futures-channel", + "futures-util", + "http 1.1.0", + "http-body 1.0.0", + "hyper 1.2.0", + "pin-project-lite", + "socket2", + "tokio", + "tower", + "tower-service", + "tracing", ] [[package]] @@ -6707,10 +6789,10 @@ dependencies = [ "futures-util", "h2", "http 0.2.12", - "http-body", - "hyper", + "http-body 0.4.6", + "hyper 0.14.28", "hyper-rustls", - "hyper-tls", + "hyper-tls 0.5.0", "ipnet", "js-sys", "log", @@ -6739,6 +6821,45 @@ dependencies = [ "winreg", ] +[[package]] +name = "reqwest" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e333b1eb9fe677f6893a9efcb0d277a2d3edd83f358a236b657c32301dc6e5f6" +dependencies = [ + "base64 0.21.7", + "bytes", + "futures-core", + "futures-util", + "http 1.1.0", + "http-body 1.0.0", + "http-body-util", + "hyper 1.2.0", + "hyper-tls 0.6.0", + "hyper-util", + "ipnet", + "js-sys", + "log", + "mime", + "native-tls", + "once_cell", + "percent-encoding", + "pin-project-lite", + "rustls-pemfile", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-native-tls", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "winreg", +] + [[package]] name = "revm" version = "7.2.0" @@ -7732,7 +7853,7 @@ dependencies = [ "fs2", "hex", "once_cell", - "reqwest", + "reqwest 0.11.26", "semver 1.0.22", "serde", "serde_json", @@ -8217,7 +8338,7 @@ dependencies = [ "futures-core", "futures-util", "http 0.2.12", - "http-body", + "http-body 0.4.6", "http-range-header", "httpdate", "mime", diff --git a/Cargo.toml b/Cargo.toml index 292a8298237c..2ee556b4ee1a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -154,27 +154,27 @@ ethers-middleware = { version = "2.0.14", default-features = false } ethers-solc = { version = "2.0.14", default-features = false } ## alloy -alloy-consensus = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } -alloy-contract = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } -alloy-eips = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } -alloy-genesis = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } -alloy-json-rpc = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } -alloy-network = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } -alloy-node-bindings = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } -alloy-provider = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } -alloy-pubsub = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } -alloy-rpc-client = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } -alloy-rpc-trace-types = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } -alloy-rpc-types = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } -alloy-signer = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } -alloy-signer-wallet = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } -alloy-signer-aws = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } -alloy-signer-ledger = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } -alloy-signer-trezor = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } -alloy-transport = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } -alloy-transport-http = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } -alloy-transport-ipc = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } -alloy-transport-ws = { git = "https://github.com/klkvr/alloy", rev = "cf5d733", default-features = false } +alloy-consensus = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } +alloy-contract = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } +alloy-eips = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } +alloy-genesis = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } +alloy-json-rpc = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } +alloy-network = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } +alloy-node-bindings = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } +alloy-provider = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } +alloy-pubsub = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } +alloy-rpc-client = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } +alloy-rpc-trace-types = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } +alloy-rpc-types = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } +alloy-signer = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } +alloy-signer-wallet = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } +alloy-signer-aws = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } +alloy-signer-ledger = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } +alloy-signer-trezor = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } +alloy-transport = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } +alloy-transport-http = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } +alloy-transport-ipc = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } +alloy-transport-ws = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } alloy-primitives = { version = "0.6.4", features = ["getrandom"] } alloy-dyn-abi = "0.6.4" alloy-json-abi = "0.6.4" diff --git a/crates/cast/src/tx.rs b/crates/cast/src/tx.rs index d3e02ef1a570..fb0742cafc14 100644 --- a/crates/cast/src/tx.rs +++ b/crates/cast/src/tx.rs @@ -47,6 +47,7 @@ pub struct TxBuilder<'a, P, T> { func: Option, etherscan_api_key: Option, provider: &'a P, + legacy: bool, transport: PhantomData, } @@ -67,9 +68,9 @@ impl<'a, T: Transport + Clone, P: Provider> TxBuilder<'a, P, T> { let chain = chain.into(); let tx = TransactionRequest::default() - .from(from) - .transaction_type(if chain.is_legacy() || legacy { 0 } else { 2 }) - .to(to); + .with_from(from) + .with_chain_id(chain.id()) + .with_to(to.into()); Ok(Self { to, @@ -79,6 +80,7 @@ impl<'a, T: Transport + Clone, P: Provider> TxBuilder<'a, P, T> { etherscan_api_key: None, provider, transport: PhantomData, + legacy: legacy || chain.is_legacy(), }) } diff --git a/crates/common/Cargo.toml b/crates/common/Cargo.toml index 6390b53606f5..9b2de72bd265 100644 --- a/crates/common/Cargo.toml +++ b/crates/common/Cargo.toml @@ -18,6 +18,8 @@ ethers-core.workspace = true ethers-middleware.workspace = true ethers-providers = { workspace = true, features = ["ws", "ipc"] } ethers-signers.workspace = true +# should be removed along with ethers +reqwest_ethers = { package = "reqwest", version = "0.11" } alloy-dyn-abi = { workspace = true, features = ["arbitrary", "eip712"] } alloy-json-abi.workspace = true @@ -32,7 +34,7 @@ alloy-rpc-client.workspace = true alloy-provider.workspace = true alloy-transport.workspace = true alloy-signer-wallet.workspace = true -alloy-transport-http.workspace = true +alloy-transport-http = { workspace = true, features = ["reqwest-default-tls"] } alloy-transport-ws.workspace = true alloy-transport-ipc.workspace = true alloy-json-rpc.workspace = true @@ -52,7 +54,7 @@ globset = "0.4" hex.workspace = true once_cell = "1" rand.workspace = true -reqwest = { version = "0.11", default-features = false } +reqwest = { version = "0.12", default-features = false } semver = "1" serde_json.workspace = true serde.workspace = true diff --git a/crates/common/src/provider/retry.rs b/crates/common/src/provider/retry.rs index e7277bd4b198..92ea0601ed99 100644 --- a/crates/common/src/provider/retry.rs +++ b/crates/common/src/provider/retry.rs @@ -49,6 +49,8 @@ impl RetryPolicy for RateLimitRetryPolicy { false } TransportError::ErrorResp(err) => should_retry_json_rpc_error(err), + TransportError::NullResp => true, + TransportError::UnsupportedFeature(_) => false, } } diff --git a/crates/common/src/runtime_client.rs b/crates/common/src/runtime_client.rs index ea0fe593830c..aab2bd4af27e 100644 --- a/crates/common/src/runtime_client.rs +++ b/crates/common/src/runtime_client.rs @@ -5,9 +5,9 @@ use ethers_core::types::U256; use ethers_providers::{ Authorization, ConnectionDetails, Http, HttpRateLimitRetryPolicy, Ipc, JsonRpcClient, JsonRpcError, JwtAuth, JwtKey, ProviderError, PubsubClient, RetryClient, RetryClientBuilder, - RpcError, Ws, + RpcError, Ws }; -use reqwest::{ +use reqwest_ethers::{ header::{HeaderName, HeaderValue}, Url, }; @@ -128,10 +128,10 @@ impl RuntimeClient { async fn connect(&self) -> Result { match self.url.scheme() { "http" | "https" => { - let mut client_builder = reqwest::Client::builder() + let mut client_builder = reqwest_ethers::Client::builder() .timeout(self.timeout) .tls_built_in_root_certs(self.url.scheme() == "https"); - let mut headers = reqwest::header::HeaderMap::new(); + let mut headers = reqwest_ethers::header::HeaderMap::new(); if let Some(jwt) = self.jwt.as_ref() { let auth = build_auth(jwt.clone()).map_err(|err| { @@ -144,7 +144,7 @@ impl RuntimeClient { .expect("Header should be valid string"); auth_value.set_sensitive(true); - headers.insert(reqwest::header::AUTHORIZATION, auth_value); + headers.insert(reqwest_ethers::header::AUTHORIZATION, auth_value); }; for header in self.headers.iter() { diff --git a/crates/forge/bin/cmd/create.rs b/crates/forge/bin/cmd/create.rs index 28228eb688e0..bcd92942318c 100644 --- a/crates/forge/bin/cmd/create.rs +++ b/crates/forge/bin/cmd/create.rs @@ -227,14 +227,27 @@ impl CreateArgs { })?; let is_legacy = self.tx.legacy || Chain::try_from(chain).map(|x| x.is_legacy()).unwrap_or_default(); + + deployer.tx.set_from(deployer_address); + deployer.tx.set_chain_id(chain); + + deployer.tx.set_nonce(if let Some(nonce) = self.tx.nonce { + Ok(nonce) + } else { + provider.get_transaction_count(deployer_address, None).await + }?.to()); + + deployer.tx.set_gas_limit(if let Some(gas_limit) = self.tx.gas_limit { + Ok(gas_limit) + } else { + provider.estimate_gas(&deployer.tx, None).await + }?); // set tx value if specified if let Some(value) = self.tx.value { deployer.tx.set_value(value); } - deployer.tx.set_from(deployer_address); - if is_legacy { let gas_price = if let Some(gas_price) = self.tx.gas_price { gas_price @@ -260,17 +273,7 @@ impl CreateArgs { deployer.tx.set_max_fee_per_gas(max_fee); deployer.tx.set_max_priority_fee_per_gas(priority_fee); } - - // set gas limit if specified - if let Some(gas_limit) = self.tx.gas_limit { - deployer.tx.set_gas_limit(gas_limit); - } - - // set nonce if specified - if let Some(nonce) = self.tx.nonce { - deployer.tx.set_nonce(nonce.to()); - } - + // Before we actually deploy the contract we try check if the verify settings are valid let mut constructor_args = None; if self.verify { From 1539d37df734ee5e5a081101634281d9748d37fb Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Mon, 25 Mar 2024 03:48:24 +0400 Subject: [PATCH 24/63] fix tx builder --- Cargo.lock | 47 +-- Cargo.toml | 42 +-- crates/anvil/core/src/eth/transaction/mod.rs | 10 +- crates/cast/Cargo.toml | 2 + crates/cast/bin/cmd/access_list.rs | 68 ++-- crates/cast/bin/cmd/call.rs | 137 ++++--- crates/cast/bin/cmd/estimate.rs | 38 +- crates/cast/bin/cmd/mktx.rs | 2 +- crates/cast/bin/cmd/send.rs | 9 +- crates/cast/bin/main.rs | 19 +- crates/cast/bin/tx.rs | 79 ++++- crates/cast/src/lib.rs | 80 ++--- crates/cast/src/tx.rs | 355 ------------------- crates/cli/Cargo.toml | 3 + crates/cli/src/utils/abi.rs | 61 ++++ crates/cli/src/utils/mod.rs | 3 + crates/common/src/fmt/ui.rs | 6 +- crates/common/src/runtime_client.rs | 2 +- crates/common/src/transactions.rs | 17 +- crates/forge/bin/cmd/create.rs | 19 +- crates/wallets/src/wallet.rs | 2 +- 21 files changed, 367 insertions(+), 634 deletions(-) delete mode 100644 crates/cast/src/tx.rs create mode 100644 crates/cli/src/utils/abi.rs diff --git a/Cargo.lock b/Cargo.lock index 92f60d9078e6..05e6847b27b0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -90,7 +90,7 @@ dependencies = [ [[package]] name = "alloy-consensus" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" +source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" dependencies = [ "alloy-eips", "alloy-primitives", @@ -105,7 +105,7 @@ dependencies = [ [[package]] name = "alloy-contract" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" +source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" dependencies = [ "alloy-dyn-abi", "alloy-json-abi", @@ -143,7 +143,7 @@ dependencies = [ [[package]] name = "alloy-eips" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" +source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -157,7 +157,7 @@ dependencies = [ [[package]] name = "alloy-genesis" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" +source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" dependencies = [ "alloy-primitives", "alloy-serde", @@ -178,7 +178,7 @@ dependencies = [ [[package]] name = "alloy-json-rpc" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" +source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" dependencies = [ "alloy-primitives", "serde", @@ -189,7 +189,7 @@ dependencies = [ [[package]] name = "alloy-network" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" +source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" dependencies = [ "alloy-consensus", "alloy-eips", @@ -232,7 +232,7 @@ dependencies = [ [[package]] name = "alloy-provider" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" +source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" dependencies = [ "alloy-json-rpc", "alloy-network", @@ -258,7 +258,7 @@ dependencies = [ [[package]] name = "alloy-pubsub" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" +source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" dependencies = [ "alloy-json-rpc", "alloy-primitives", @@ -298,7 +298,7 @@ dependencies = [ [[package]] name = "alloy-rpc-client" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" +source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" dependencies = [ "alloy-json-rpc", "alloy-primitives", @@ -320,7 +320,7 @@ dependencies = [ [[package]] name = "alloy-rpc-trace-types" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" +source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" dependencies = [ "alloy-primitives", "alloy-rpc-types", @@ -332,7 +332,7 @@ dependencies = [ [[package]] name = "alloy-rpc-types" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" +source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" dependencies = [ "alloy-consensus", "alloy-eips", @@ -348,7 +348,7 @@ dependencies = [ [[package]] name = "alloy-serde" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" +source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" dependencies = [ "alloy-primitives", "serde", @@ -358,7 +358,7 @@ dependencies = [ [[package]] name = "alloy-signer" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" +source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" dependencies = [ "alloy-dyn-abi", "alloy-primitives", @@ -373,7 +373,7 @@ dependencies = [ [[package]] name = "alloy-signer-aws" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" +source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" dependencies = [ "alloy-consensus", "alloy-network", @@ -390,7 +390,7 @@ dependencies = [ [[package]] name = "alloy-signer-ledger" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" +source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" dependencies = [ "alloy-consensus", "alloy-network", @@ -407,7 +407,7 @@ dependencies = [ [[package]] name = "alloy-signer-trezor" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" +source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" dependencies = [ "alloy-consensus", "alloy-network", @@ -423,7 +423,7 @@ dependencies = [ [[package]] name = "alloy-signer-wallet" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" +source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" dependencies = [ "alloy-consensus", "alloy-network", @@ -496,7 +496,7 @@ dependencies = [ [[package]] name = "alloy-transport" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" +source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" dependencies = [ "alloy-json-rpc", "base64 0.22.0", @@ -514,7 +514,7 @@ dependencies = [ [[package]] name = "alloy-transport-http" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" +source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" dependencies = [ "alloy-json-rpc", "alloy-transport", @@ -527,7 +527,7 @@ dependencies = [ [[package]] name = "alloy-transport-ipc" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" +source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" dependencies = [ "alloy-json-rpc", "alloy-pubsub", @@ -545,7 +545,7 @@ dependencies = [ [[package]] name = "alloy-transport-ws" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=067bf1b#067bf1b8c416342e9a9fdb959ae174a28b371aae" +source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" dependencies = [ "alloy-pubsub", "alloy-transport", @@ -1736,6 +1736,7 @@ checksum = "df8670b8c7b9dae1793364eafadf7239c40d669904660c5960d74cfd80b46a53" name = "cast" version = "0.2.0" dependencies = [ + "alloy-chains", "alloy-consensus", "alloy-contract", "alloy-dyn-abi", @@ -1748,6 +1749,7 @@ dependencies = [ "alloy-rpc-types", "alloy-signer", "alloy-signer-wallet", + "alloy-sol-types", "alloy-transport", "async-trait", "aws-sdk-kms", @@ -3642,6 +3644,7 @@ dependencies = [ name = "foundry-cli" version = "0.2.0" dependencies = [ + "alloy-chains", "alloy-dyn-abi", "alloy-json-abi", "alloy-primitives", @@ -3649,6 +3652,7 @@ dependencies = [ "alloy-transport", "clap", "color-eyre", + "const-hex", "dotenvy", "eyre", "forge-fmt", @@ -3658,6 +3662,7 @@ dependencies = [ "foundry-debugger", "foundry-evm", "foundry-wallets", + "futures", "indicatif", "once_cell", "regex", diff --git a/Cargo.toml b/Cargo.toml index 2ee556b4ee1a..4182b74cd58d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -154,27 +154,27 @@ ethers-middleware = { version = "2.0.14", default-features = false } ethers-solc = { version = "2.0.14", default-features = false } ## alloy -alloy-consensus = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } -alloy-contract = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } -alloy-eips = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } -alloy-genesis = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } -alloy-json-rpc = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } -alloy-network = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } -alloy-node-bindings = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } -alloy-provider = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } -alloy-pubsub = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } -alloy-rpc-client = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } -alloy-rpc-trace-types = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } -alloy-rpc-types = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } -alloy-signer = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } -alloy-signer-wallet = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } -alloy-signer-aws = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } -alloy-signer-ledger = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } -alloy-signer-trezor = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } -alloy-transport = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } -alloy-transport-http = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } -alloy-transport-ipc = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } -alloy-transport-ws = { git = "https://github.com/klkvr/alloy", rev = "067bf1b", default-features = false } +alloy-consensus = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } +alloy-contract = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } +alloy-eips = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } +alloy-genesis = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } +alloy-json-rpc = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } +alloy-network = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } +alloy-node-bindings = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } +alloy-provider = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } +alloy-pubsub = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } +alloy-rpc-client = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } +alloy-rpc-trace-types = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } +alloy-rpc-types = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } +alloy-signer = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } +alloy-signer-wallet = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } +alloy-signer-aws = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } +alloy-signer-ledger = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } +alloy-signer-trezor = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } +alloy-transport = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } +alloy-transport-http = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } +alloy-transport-ipc = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } +alloy-transport-ws = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } alloy-primitives = { version = "0.6.4", features = ["getrandom"] } alloy-dyn-abi = "0.6.4" alloy-json-abi = "0.6.4" diff --git a/crates/anvil/core/src/eth/transaction/mod.rs b/crates/anvil/core/src/eth/transaction/mod.rs index feaabd00a338..9f99cd68a961 100644 --- a/crates/anvil/core/src/eth/transaction/mod.rs +++ b/crates/anvil/core/src/eth/transaction/mod.rs @@ -308,7 +308,7 @@ pub fn to_alloy_transaction_with_hash_and_sender( access_list: None, transaction_type: None, max_fee_per_blob_gas: None, - blob_versioned_hashes: vec![], + blob_versioned_hashes: None, other: Default::default(), }, TypedTransaction::EIP2930(t) => RpcTransaction { @@ -335,7 +335,7 @@ pub fn to_alloy_transaction_with_hash_and_sender( access_list: Some(from_eip_to_alloy_access_list(t.tx().access_list.clone())), transaction_type: Some(U8::from(1)), max_fee_per_blob_gas: None, - blob_versioned_hashes: vec![], + blob_versioned_hashes: None, other: Default::default(), }, TypedTransaction::EIP1559(t) => RpcTransaction { @@ -362,7 +362,7 @@ pub fn to_alloy_transaction_with_hash_and_sender( access_list: Some(from_eip_to_alloy_access_list(t.tx().access_list.clone())), transaction_type: Some(U8::from(2)), max_fee_per_blob_gas: None, - blob_versioned_hashes: vec![], + blob_versioned_hashes: None, other: Default::default(), }, TypedTransaction::EIP4844(t) => RpcTransaction { @@ -389,7 +389,7 @@ pub fn to_alloy_transaction_with_hash_and_sender( access_list: Some(from_eip_to_alloy_access_list(t.tx().tx().access_list.clone())), transaction_type: Some(U8::from(3)), max_fee_per_blob_gas: Some(U256::from(t.tx().tx().max_fee_per_blob_gas)), - blob_versioned_hashes: t.tx().tx().blob_versioned_hashes.clone(), + blob_versioned_hashes: Some(t.tx().tx().blob_versioned_hashes.clone()), other: Default::default(), }, TypedTransaction::Deposit(t) => RpcTransaction { @@ -411,7 +411,7 @@ pub fn to_alloy_transaction_with_hash_and_sender( access_list: None, transaction_type: None, max_fee_per_blob_gas: None, - blob_versioned_hashes: vec![], + blob_versioned_hashes: None, other: Default::default(), }, } diff --git a/crates/cast/Cargo.toml b/crates/cast/Cargo.toml index 65c8565dce0d..750a11172c7e 100644 --- a/crates/cast/Cargo.toml +++ b/crates/cast/Cargo.toml @@ -43,6 +43,8 @@ alloy-signer-wallet = { workspace = true, features = ["mnemonic", "keystore"] } alloy-contract.workspace = true alloy-consensus = { workspace = true, features = ["serde"] } alloy-network.workspace = true +alloy-sol-types.workspace = true +alloy-chains.workspace = true ethers-core.workspace = true diff --git a/crates/cast/bin/cmd/access_list.rs b/crates/cast/bin/cmd/access_list.rs index 25195f457698..bf6aedd5e513 100644 --- a/crates/cast/bin/cmd/access_list.rs +++ b/crates/cast/bin/cmd/access_list.rs @@ -1,14 +1,14 @@ -use alloy_network::Ethereum; +use alloy_network::{Ethereum, TransactionBuilder}; use alloy_primitives::Address; use alloy_provider::Provider; -use alloy_rpc_types::BlockId; +use alloy_rpc_types::{BlockId, TransactionRequest}; use alloy_transport::Transport; -use cast::{Cast, TxBuilder}; +use cast::Cast; use clap::Parser; -use eyre::{Result, WrapErr}; +use eyre::Result; use foundry_cli::{ opts::{EthereumOpts, TransactionOpts}, - utils, + utils::{self, parse_function_args}, }; use foundry_common::ens::NameOrAddress; use foundry_config::{Chain, Config}; @@ -65,16 +65,27 @@ impl AccessListArgs { let provider = utils::get_alloy_provider(&config)?; let chain = utils::get_chain(config.chain, &provider).await?; let sender = eth.wallet.sender().await; + let etherscan_api_key = config.get_etherscan_api_key(Some(chain)); let to = match to { - Some(NameOrAddress::Name(name)) => { - Some(NameOrAddress::Name(name).resolve(&provider).await?) - } - Some(NameOrAddress::Address(addr)) => Some(addr), + Some(to) => Some(to.resolve(&provider).await?), None => None, }; - access_list(&provider, sender, to, sig, args, data, tx, chain, block, to_json).await?; + access_list( + &provider, + etherscan_api_key.as_deref(), + sender, + to, + sig, + args, + data, + tx, + chain, + block, + to_json, + ) + .await?; Ok(()) } } @@ -82,6 +93,7 @@ impl AccessListArgs { #[allow(clippy::too_many_arguments)] async fn access_list, T: Transport + Clone>( provider: P, + etherscan_api_key: Option<&str>, from: Address, to: Option
, sig: Option, @@ -92,28 +104,34 @@ async fn access_list, T: Transport + Clone>( block: Option, to_json: bool, ) -> Result<()> { - let mut builder = TxBuilder::new(&provider, from, to, chain, tx.legacy).await?; - builder - .gas(tx.gas_limit) - .gas_price(tx.gas_price) - .priority_gas_price(tx.priority_gas_price) - .nonce(tx.nonce.map(|n| n.to())); - - builder.value(tx.value); + let mut req = TransactionRequest::default() + .with_to(to.into()) + .with_from(from) + .with_value(tx.value.unwrap_or_default()) + .with_chain_id(chain.id()); + + if let Some(gas_limit) = tx.gas_limit { + req.set_gas_limit(gas_limit); + } - if let Some(sig) = sig { - builder.set_args(sig.as_str(), args).await?; + if let Some(nonce) = tx.nonce { + req.set_nonce(nonce.to()); } - if let Some(data) = data { + + let data = if let Some(sig) = sig { + parse_function_args(&sig, args, to, chain, &provider, etherscan_api_key).await?.0 + } else if let Some(data) = data { // Note: `sig+args` and `data` are mutually exclusive - builder.set_data(hex::decode(data).wrap_err("Expected hex encoded function data")?.into()); - } + hex::decode(data)? + } else { + Vec::new() + }; - let builder_output = builder.peek(); + req.set_input(data.into()); let cast = Cast::new(&provider); - let access_list: String = cast.access_list(builder_output, block, to_json).await?; + let access_list: String = cast.access_list(&req, block, to_json).await?; println!("{}", access_list); diff --git a/crates/cast/bin/cmd/call.rs b/crates/cast/bin/cmd/call.rs index 22113e625ee1..228cab71c31b 100644 --- a/crates/cast/bin/cmd/call.rs +++ b/crates/cast/bin/cmd/call.rs @@ -1,15 +1,12 @@ -use alloy_consensus::Transaction; use alloy_network::TransactionBuilder; use alloy_primitives::U256; -use alloy_provider::{network::Ethereum, Provider}; -use alloy_rpc_types::BlockId; -use alloy_transport::Transport; -use cast::{Cast, TxBuilder}; +use alloy_rpc_types::{BlockId, TransactionRequest}; +use cast::Cast; use clap::Parser; -use eyre::{Result, WrapErr}; +use eyre::Result; use foundry_cli::{ opts::{EthereumOpts, TransactionOpts}, - utils::{self, handle_traces, parse_ether_value, TraceResult}, + utils::{self, handle_traces, parse_ether_value, parse_function_args, TraceResult}, }; use foundry_common::ens::NameOrAddress; use foundry_compilers::EvmVersion; @@ -117,26 +114,43 @@ impl CallArgs { let provider = utils::get_alloy_provider(&config)?; let chain = utils::get_chain(config.chain, &provider).await?; let sender = eth.wallet.sender().await; + let etherscan_api_key = config.get_etherscan_api_key(Some(chain)); let to = match to { - Some(NameOrAddress::Name(name)) => { - Some(NameOrAddress::Name(name).resolve(&provider).await?) - } - Some(NameOrAddress::Address(addr)) => Some(addr), + Some(to) => Some(to.resolve(&provider).await?), None => None, }; - let mut builder = TxBuilder::new(&provider, sender, to, chain, tx.legacy).await?; + let mut req = TransactionRequest::default() + .with_to(to.into()) + .with_from(sender) + .with_value(tx.value.unwrap_or_default()); - builder - .gas(tx.gas_limit) - .etherscan_api_key(config.get_etherscan_api_key(Some(chain))) - .gas_price(tx.gas_price) - .priority_gas_price(tx.priority_gas_price) - .nonce(tx.nonce.map(|n| n.to())); + if let Some(nonce) = tx.nonce { + req.set_nonce(nonce.to()); + } - match command { + let (data, func) = match command { Some(CallSubcommands::Create { code, sig, args, value }) => { + if let Some(value) = value { + req.set_value(value); + } + + let mut data = hex::decode(code)?; + + if let Some(s) = sig { + let (mut constructor_args, _) = parse_function_args( + &s, + args, + None, + chain, + &provider, + etherscan_api_key.as_deref(), + ) + .await?; + data.append(&mut constructor_args); + } + if trace { let figment = Config::figment_with_root(find_project_root_path(None).unwrap()) .merge(eth.rpc); @@ -150,8 +164,8 @@ impl CallArgs { let trace = match executor.deploy( sender, - code.into_bytes().into(), - value.unwrap_or(U256::ZERO), + data.into(), + req.value.unwrap_or_default(), None, ) { Ok(deploy_result) => TraceResult::from(deploy_result), @@ -163,12 +177,26 @@ impl CallArgs { return Ok(()); } - // fill the builder after the conditional so we dont move values - fill_create(&mut builder, value, code, sig, args).await?; + (data, None) } _ => { // fill first here because we need to use the builder in the conditional - fill_tx(&mut builder, tx.value, sig, args, data).await?; + let (data, func) = if let Some(sig) = sig { + parse_function_args( + &sig, + args, + to, + chain, + &provider, + etherscan_api_key.as_deref(), + ) + .await? + } else if let Some(data) = data { + // Note: `sig+args` and `data` are mutually exclusive + (hex::decode(data)?, None) + } else { + (Vec::new(), None) + }; if trace { let figment = Config::figment_with_root(find_project_root_path(None).unwrap()) @@ -181,73 +209,28 @@ impl CallArgs { let mut executor = TracingExecutor::new(env, fork, evm_version, debug); - let (tx, _) = builder.build(); - - let tx = tx.build_unsigned()?; - let trace = TraceResult::from(executor.call_raw_committing( sender, - *tx.to().to().expect("an address to be here"), - tx.input().to_vec().into(), - tx.value(), + req.to.expect("an address to be here"), + data.into(), + req.value.unwrap_or_default(), )?); handle_traces(trace, &config, chain, labels, debug).await?; return Ok(()); } + + (data, func) } }; - let builder_output = builder.build(); - println!("{}", Cast::new(provider).call(builder_output, block).await?); - - Ok(()) - } -} - -/// fills the builder from create arg -async fn fill_create, T: Transport + Clone>( - builder: &mut TxBuilder<'_, P, T>, - value: Option, - code: String, - sig: Option, - args: Vec, -) -> Result<()> { - builder.value(value); - - let mut data = hex::decode(code)?; - - if let Some(s) = sig { - let (mut sigdata, _func) = builder.create_args(&s, args).await?; - data.append(&mut sigdata); - } - - builder.set_data(data.into()); + req.set_input(data.into()); - Ok(()) -} + println!("{}", Cast::new(provider).call(&req, func.as_ref(), block).await?); -/// fills the builder from args -async fn fill_tx, T: Transport + Clone>( - builder: &mut TxBuilder<'_, P, T>, - value: Option, - sig: Option, - args: Vec, - data: Option, -) -> Result<()> { - builder.value(value); - - if let Some(sig) = sig { - builder.set_args(sig.as_str(), args).await?; - } - - if let Some(data) = data { - // Note: `sig+args` and `data` are mutually exclusive - builder.set_data(hex::decode(data).wrap_err("Expected hex encoded function data")?.into()); + Ok(()) } - - Ok(()) } #[cfg(test)] diff --git a/crates/cast/bin/cmd/estimate.rs b/crates/cast/bin/cmd/estimate.rs index 2876d07189b5..c024768a49fc 100644 --- a/crates/cast/bin/cmd/estimate.rs +++ b/crates/cast/bin/cmd/estimate.rs @@ -1,10 +1,12 @@ +use alloy_network::TransactionBuilder; use alloy_primitives::U256; -use cast::{Cast, TxBuilder}; +use alloy_provider::Provider; +use alloy_rpc_types::TransactionRequest; use clap::Parser; use eyre::Result; use foundry_cli::{ opts::{EtherscanOpts, RpcOpts}, - utils::{self, parse_ether_value}, + utils::{self, parse_ether_value, parse_function_args}, }; use foundry_common::ens::NameOrAddress; use foundry_config::{figment::Figment, Config}; @@ -87,37 +89,41 @@ impl EstimateArgs { let from = from.resolve(&provider).await?; let to = match to { - Some(NameOrAddress::Name(name)) => { - Some(NameOrAddress::Name(name).resolve(&provider).await?) - } - Some(NameOrAddress::Address(addr)) => Some(addr), + Some(to) => Some(to.resolve(&provider).await?), None => None, }; - let mut builder = TxBuilder::new(&provider, from, to, chain, false).await?; - builder.etherscan_api_key(api_key); + let mut req = TransactionRequest::default() + .with_to(to.into()) + .with_from(from) + .with_value(value.unwrap_or_default()); - match command { + let data = match command { Some(EstimateSubcommands::Create { code, sig, args, value }) => { - builder.value(value); + if let Some(value) = value { + req.set_value(value); + } let mut data = hex::decode(code)?; if let Some(s) = sig { - let (mut sigdata, _func) = builder.create_args(&s, args).await?; - data.append(&mut sigdata); + let (mut constructor_args, _) = + parse_function_args(&s, args, to, chain, &provider, api_key.as_deref()) + .await?; + data.append(&mut constructor_args); } - builder.set_data(data.into()); + data } _ => { let sig = sig.ok_or_else(|| eyre::eyre!("Function signature must be provided."))?; - builder.value(value).set_args(sig.as_str(), args).await?; + parse_function_args(&sig, args, to, chain, &provider, api_key.as_deref()).await?.0 } }; - let builder_output = builder.peek(); - let gas = Cast::new(&provider).estimate(builder_output).await?; + req.set_input(data.into()); + + let gas = provider.estimate_gas(&req, None).await?; println!("{gas}"); Ok(()) } diff --git a/crates/cast/bin/cmd/mktx.rs b/crates/cast/bin/cmd/mktx.rs index 969355c1bc15..f34dbcfa5509 100644 --- a/crates/cast/bin/cmd/mktx.rs +++ b/crates/cast/bin/cmd/mktx.rs @@ -96,7 +96,7 @@ impl MakeTxArgs { let (tx, _) = tx::build_tx(&provider, from, to, code, sig, args, tx, chain, api_key).await?; - let tx = tx.build::(&signer.into()).await?; + let tx = tx.build(&EthereumSigner::new(signer)).await?; let signed_tx = hex::encode(tx.encoded_2718()); println!("0x{signed_tx}"); diff --git a/crates/cast/bin/cmd/send.rs b/crates/cast/bin/cmd/send.rs index 4bc48c3afd5e..86aebbe3e001 100644 --- a/crates/cast/bin/cmd/send.rs +++ b/crates/cast/bin/cmd/send.rs @@ -113,10 +113,7 @@ impl SendTxArgs { let api_key = config.get_etherscan_api_key(Some(chain)); let to = match to { - Some(NameOrAddress::Name(name)) => { - Some(NameOrAddress::Name(name).resolve(&provider).await?) - } - Some(NameOrAddress::Address(addr)) => Some(addr), + Some(to) => Some(to.resolve(&provider).await?), None => None, }; @@ -215,12 +212,12 @@ async fn cast_send, T: Transport + Clone>( confs: u64, to_json: bool, ) -> Result<()> { - let builder_output = + let (tx, _) = tx::build_tx(&provider, from, to, code, sig, args, tx, chain, etherscan_api_key).await?; let cast = Cast::new(provider); - let pending_tx = cast.send(builder_output).await?; + let pending_tx = cast.send(tx).await?; let tx_hash = pending_tx.inner().tx_hash(); if cast_async { diff --git a/crates/cast/bin/main.rs b/crates/cast/bin/main.rs index 13286872f810..5f3ca57c94cf 100644 --- a/crates/cast/bin/main.rs +++ b/crates/cast/bin/main.rs @@ -4,7 +4,7 @@ extern crate tracing; use alloy_primitives::{keccak256, Address, B256}; use alloy_provider::Provider; use alloy_rpc_types::{BlockId, BlockNumberOrTag::Latest}; -use cast::{Cast, SimpleCast, TxBuilder}; +use cast::{Cast, SimpleCast}; use clap::{CommandFactory, Parser}; use clap_complete::generate; use eyre::Result; @@ -12,7 +12,7 @@ use foundry_cli::{handler, prompt, stdin, utils}; use foundry_common::{ abi::get_event, ens::{lookup_address, resolve_name}, - fmt::format_tokens, + fmt::{format_tokens, format_uint_exp}, fs, selectors::{ decode_calldata, decode_event_topic, decode_function_selector, decode_selectors, @@ -213,18 +213,9 @@ async fn main() -> Result<()> { match erc20 { Some(token) => { - let chain = utils::get_chain(config.chain, &provider).await?; - let mut builder = - TxBuilder::new(&provider, Address::ZERO, Some(token), chain, true).await?; - - builder - .set_args( - "balanceOf(address) returns (uint256)", - vec![format!("{account_addr:#x}")], - ) - .await?; - let builder_output = builder.build(); - println!("{}", Cast::new(&provider).call(builder_output, block).await?); + let balance = + Cast::new(&provider).erc20_balance(token, account_addr, block).await?; + println!("{}", format_uint_exp(balance)); } None => { let value = Cast::new(&provider).balance(account_addr, block).await?; diff --git a/crates/cast/bin/tx.rs b/crates/cast/bin/tx.rs index f08c1dde72b5..7504cdffd58b 100644 --- a/crates/cast/bin/tx.rs +++ b/crates/cast/bin/tx.rs @@ -1,9 +1,11 @@ +use alloy_json_abi::Function; +use alloy_network::TransactionBuilder; use alloy_primitives::Address; use alloy_provider::{network::Ethereum, Provider}; +use alloy_rpc_types::TransactionRequest; use alloy_transport::Transport; -use cast::{TxBuilder, TxBuilderOutput}; use eyre::Result; -use foundry_cli::opts::TransactionOpts; +use foundry_cli::{opts::TransactionOpts, utils::parse_function_args}; use foundry_common::ens::NameOrAddress; use foundry_config::Chain; @@ -50,33 +52,74 @@ pub async fn build_tx< tx: TransactionOpts, chain: impl Into, etherscan_api_key: Option, -) -> Result { +) -> Result<(TransactionRequest, Option)> { + let chain = chain.into(); + let from = from.into().resolve(provider).await?; let to = if let Some(to) = to { Some(to.into().resolve(provider).await?) } else { None }; - let mut builder = TxBuilder::new(provider, from, to, chain, tx.legacy).await?; - builder - .etherscan_api_key(etherscan_api_key) - .gas(tx.gas_limit) - .gas_price(tx.gas_price) - .priority_gas_price(tx.priority_gas_price) - .value(tx.value) - .nonce(tx.nonce.map(|n| n.to())); + let mut req = TransactionRequest::default() + .with_to(to.into()) + .with_from(from) + .with_value(tx.value.unwrap_or_default()) + .with_chain_id(chain.id()); + + req.set_nonce( + if let Some(nonce) = tx.nonce { + nonce + } else { + provider.get_transaction_count(from, None).await? + } + .to(), + ); + + if tx.legacy || chain.is_legacy() { + req.set_gas_price(if let Some(gas_price) = tx.gas_price { + gas_price + } else { + provider.get_gas_price().await? + }); + } else { + let (max_fee, priority_fee) = match (tx.gas_price, tx.priority_gas_price) { + (Some(gas_price), Some(priority_gas_price)) => (gas_price, priority_gas_price), + (_, _) => { + let estimate = provider.estimate_eip1559_fees(None).await?; + ( + tx.gas_price.unwrap_or(estimate.max_fee_per_gas), + tx.priority_gas_price.unwrap_or(estimate.max_priority_fee_per_gas), + ) + } + }; + + req.set_max_fee_per_gas(max_fee); + req.set_max_priority_fee_per_gas(priority_fee); + } let params = sig.as_deref().map(|sig| (sig, args)); - if let Some(code) = code { + let (data, func) = if let Some(code) = code { let mut data = hex::decode(code)?; if let Some((sig, args)) = params { - let (mut sigdata, _) = builder.create_args(sig, args).await?; + let (mut sigdata, _) = + parse_function_args(sig, args, None, chain, provider, etherscan_api_key.as_deref()) + .await?; data.append(&mut sigdata); } - builder.set_data(data.into()); + (data, None) + } else if let Some((sig, args)) = params { + parse_function_args(sig, args, None, chain, provider, etherscan_api_key.as_deref()).await? } else { - builder.args(params).await?; - } + (Vec::new(), None) + }; + + req.set_input(data.into()); + + req.set_gas_limit(if let Some(gas_limit) = tx.gas_limit { + gas_limit + } else { + provider.estimate_gas(&req, None).await? + }); - let builder_output = builder.build(); - Ok(builder_output) + Ok((req, func)) } diff --git a/crates/cast/src/lib.rs b/crates/cast/src/lib.rs index 1f9bfbbff2c6..2ee659f4573c 100644 --- a/crates/cast/src/lib.rs +++ b/crates/cast/src/lib.rs @@ -1,6 +1,6 @@ use alloy_consensus::TxEnvelope; use alloy_dyn_abi::{DynSolType, DynSolValue, FunctionExt}; -use alloy_json_abi::ContractObject; +use alloy_json_abi::{ContractObject, Function}; use alloy_primitives::{ utils::{keccak256, ParseUnits, Unit}, Address, Keccak256, TxHash, B256, I256, U256, U64, @@ -13,7 +13,8 @@ use alloy_provider::{ PendingTransactionBuilder, Provider, }; use alloy_rlp::Decodable; -use alloy_rpc_types::{BlockId, BlockNumberOrTag, Filter}; +use alloy_rpc_types::{BlockId, BlockNumberOrTag, Filter, TransactionRequest}; +use alloy_sol_types::sol; use alloy_transport::Transport; use base::{Base, NumberWithBase, ToBase}; use chrono::DateTime; @@ -37,7 +38,6 @@ use std::{ sync::atomic::{AtomicBool, Ordering}, }; use tokio::signal::ctrl_c; -pub use tx::{TxBuilder, TxBuilderOutput, TxBuilderPeekOutput}; use foundry_common::abi::encode_function_args_packed; pub use foundry_evm::*; @@ -45,12 +45,19 @@ pub use foundry_evm::*; pub mod base; pub mod errors; mod rlp_converter; -mod tx; use rlp_converter::Item; // TODO: CastContract with common contract initializers? Same for CastProviders? +sol! { + #[sol(rpc)] + interface IERC20 { + #[derive(Debug)] + function balanceOf(address owner) external view returns (uint256); + } +} + pub struct Cast { provider: P, transport: PhantomData, @@ -110,11 +117,11 @@ where /// ``` pub async fn call<'a>( &self, - builder_output: TxBuilderOutput, + req: &TransactionRequest, + func: Option<&Function>, block: Option, ) -> Result { - let (tx, func) = builder_output; - let res = self.provider.call(&tx, block).await?; + let res = self.provider.call(req, block).await?; let mut decoded = vec![]; @@ -126,7 +133,7 @@ where // ensure the address is a contract if res.is_empty() { // check that the recipient is a contract that can be called - if let Some(addr) = tx.to { + if let Some(addr) = req.to { if let Ok(code) = self.provider.get_code_at(addr, block.unwrap_or_default()).await { @@ -179,12 +186,11 @@ where /// ``` pub async fn access_list( &self, - builder_output: TxBuilderPeekOutput<'_>, + req: &TransactionRequest, block: Option, to_json: bool, ) -> Result { - let (tx, _) = builder_output; - let access_list = self.provider.create_access_list(&tx, block).await?; + let access_list = self.provider.create_access_list(req, block).await?; let res = if to_json { serde_json::to_string(&access_list)? } else { @@ -239,9 +245,8 @@ where /// ``` pub async fn send( &self, - builder_output: TxBuilderOutput, + tx: TransactionRequest, ) -> Result> { - let (tx, _) = builder_output; let res = self.provider.send_transaction(tx).await?; Ok(res) @@ -277,41 +282,6 @@ where Ok(res) } - /// Estimates the gas cost of a transaction - /// - /// # Example - /// - /// ```ignore - /// use alloy_primitives::U256; - /// use cast::{Cast, TxBuilder}; - /// use ethers_core::types::Address; - /// use ethers_providers::{Http, Provider}; - /// use std::str::FromStr; - /// - /// # async fn foo() -> eyre::Result<()> { - /// let provider = Provider::::try_from("http://localhost:8545")?; - /// let from = Address::from_str("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045")?; - /// let to = Address::from_str("0xB3C95ff08316fb2F2e3E52Ee82F8e7b605Aa1304")?; - /// let sig = "greet(string)()"; - /// let args = vec!["5".to_owned()]; - /// let value = U256::from_str("1").unwrap(); - /// let mut builder = TxBuilder::new(&provider, from, Some(to), Chain::Mainnet, false).await?; - /// builder.set_value(value).set_args(sig, args).await?; - /// let builder_output = builder.peek(); - /// let cast = Cast::new(&provider); - /// let data = cast.estimate(builder_output).await?; - /// println!("{}", data); - /// # Ok(()) - /// # } - /// ``` - pub async fn estimate(&self, builder_output: TxBuilderPeekOutput<'_>) -> Result { - let (tx, _) = builder_output; - - let res = self.provider.estimate_gas(&tx, None).await?; - - Ok::<_, eyre::Error>(res) - } - /// # Example /// /// ```ignore @@ -929,6 +899,20 @@ where Ok(()) } + + pub async fn erc20_balance( + &self, + token: Address, + owner: Address, + block: Option, + ) -> Result { + Ok(IERC20::new(token, &self.provider) + .balanceOf(owner) + .block(block.unwrap_or_default()) + .call() + .await? + ._0) + } } pub struct InterfaceSource { diff --git a/crates/cast/src/tx.rs b/crates/cast/src/tx.rs deleted file mode 100644 index fb0742cafc14..000000000000 --- a/crates/cast/src/tx.rs +++ /dev/null @@ -1,355 +0,0 @@ -use std::marker::PhantomData; - -use crate::errors::FunctionSignatureError; -use alloy_json_abi::Function; -use alloy_primitives::{Address, Bytes, U256}; -use alloy_provider::{ - network::{Ethereum, TransactionBuilder}, - Provider, -}; -use alloy_rpc_types::request::TransactionRequest; -use alloy_transport::Transport; -use eyre::Result; -use foundry_common::{ - abi::{encode_function_args, get_func, get_func_etherscan}, - ens::NameOrAddress, -}; -use foundry_config::Chain; -use futures::future::join_all; - -pub type TxBuilderOutput = (TransactionRequest, Option); -pub type TxBuilderPeekOutput<'a> = (&'a TransactionRequest, &'a Option); - -/// Transaction builder -/// -/// # Examples -/// -/// ``` -/// # async fn foo() -> eyre::Result<()> { -/// # use alloy_primitives::{Address, U256}; -/// # use cast::TxBuilder; -/// # use foundry_config::NamedChain; -/// # use std::str::FromStr; -/// let provider = foundry_common::provider::alloy::get_http_provider("http://localhost:8545"); -/// let from = Address::from_str("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045").unwrap(); -/// let to = Address::from_str("0xb8c2c29ee19d8307cb7255e1cd9cbde883a267d5").unwrap(); -/// let mut builder = TxBuilder::new(&provider, from, Some(to), NamedChain::Mainnet, false).await?; -/// builder.gas(Some(U256::from(1))); -/// let (tx, _) = builder.build(); -/// # Ok(()) -/// # } -/// ``` -#[derive(Debug)] -pub struct TxBuilder<'a, P, T> { - to: Option
, - chain: Chain, - tx: TransactionRequest, - func: Option, - etherscan_api_key: Option, - provider: &'a P, - legacy: bool, - transport: PhantomData, -} - -impl<'a, T: Transport + Clone, P: Provider> TxBuilder<'a, P, T> { - /// Create a new TxBuilder - /// `provider` - provider to use - /// `from` - 'from' field. Could be an ENS name - /// `to` - `to`. Could be a ENS - /// `chain` - chain to construct the tx for - /// `legacy` - use type 1 transaction - pub async fn new( - provider: &'a P, - from: Address, - to: Option
, - chain: impl Into, - legacy: bool, - ) -> Result { - let chain = chain.into(); - - let tx = TransactionRequest::default() - .with_from(from) - .with_chain_id(chain.id()) - .with_to(to.into()); - - Ok(Self { - to, - chain, - tx, - func: None, - etherscan_api_key: None, - provider, - transport: PhantomData, - legacy: legacy || chain.is_legacy(), - }) - } - - /// Set gas for tx - pub fn set_gas(&mut self, v: U256) -> &mut Self { - self.tx.set_gas_limit(v); - self - } - - /// Set gas for tx, if `v` is not None - pub fn gas(&mut self, v: Option) -> &mut Self { - if let Some(value) = v { - self.set_gas(value); - } - self - } - - /// Set gas price - pub fn set_gas_price(&mut self, v: U256) -> &mut Self { - self.tx.set_gas_price(v); - self - } - - /// Set gas price, if `v` is not None - pub fn gas_price(&mut self, v: Option) -> &mut Self { - if let Some(value) = v { - self.set_gas_price(value); - } - self - } - - /// Set priority gas price - pub fn set_priority_gas_price(&mut self, v: U256) -> &mut Self { - if let Some(2) = self.tx.transaction_type.map(|v| v.to::()) { - self.tx.set_max_priority_fee_per_gas(v); - } - - self - } - - /// Set priority gas price, if `v` is not None - pub fn priority_gas_price(&mut self, v: Option) -> &mut Self { - if let Some(value) = v { - self.set_priority_gas_price(value); - } - self - } - - /// Set value - pub fn set_value(&mut self, v: U256) -> &mut Self { - self.tx.set_value(v); - self - } - - /// Set value, if `v` is not None - pub fn value(&mut self, v: Option) -> &mut Self { - if let Some(value) = v { - self.set_value(value); - } - self - } - - /// Set nonce - pub fn set_nonce(&mut self, v: u64) -> &mut Self { - self.tx.set_nonce(v); - self - } - - /// Set nonce, if `v` is not None - pub fn nonce(&mut self, v: Option) -> &mut Self { - if let Some(value) = v { - self.set_nonce(value); - } - self - } - - /// Set etherscan API key. Used to look up function signature buy name - pub fn set_etherscan_api_key(&mut self, v: String) -> &mut Self { - self.etherscan_api_key = Some(v); - self - } - - /// Set etherscan API key, if `v` is not None - pub fn etherscan_api_key(&mut self, v: Option) -> &mut Self { - if let Some(value) = v { - self.set_etherscan_api_key(value); - } - self - } - - pub fn set_data(&mut self, v: Bytes) -> &mut Self { - self.tx.set_input(v); - self - } - - pub async fn create_args( - &mut self, - sig: &str, - args: Vec, - ) -> Result<(Vec, Function)> { - if sig.trim().is_empty() { - return Err(FunctionSignatureError::MissingSignature.into()) - } - - let args = resolve_name_args(&args, self.provider).await; - - let func = if sig.contains('(') { - // a regular function signature with parentheses - get_func(sig)? - } else if sig.starts_with("0x") { - // if only calldata is provided, returning a dummy function - get_func("x()")? - } else { - get_func_etherscan( - sig, - self.to.ok_or(FunctionSignatureError::MissingToAddress)?, - &args, - self.chain, - self.etherscan_api_key.as_ref().ok_or_else(|| { - FunctionSignatureError::MissingEtherscan { sig: sig.to_string() } - })?, - ) - .await? - }; - - if sig.starts_with("0x") { - Ok((hex::decode(sig)?, func)) - } else { - Ok((encode_function_args(&func, &args)?, func)) - } - } - - /// Set function arguments - /// `sig` can be: - /// * a fragment (`do(uint32,string)`) - /// * selector + abi-encoded calldata - /// (`0xcdba2fd40000000000000000000000000000000000000000000000000000000000007a69`) - /// * only function name (`do`) - in this case, etherscan lookup is performed on `tx.to`'s - /// contract - pub async fn set_args(&mut self, sig: &str, args: Vec) -> Result<&mut Self> { - let (data, func) = self.create_args(sig, args).await?; - self.tx.set_input(data.into()); - self.func = Some(func); - Ok(self) - } - - /// Set function arguments, if `value` is not None - pub async fn args(&mut self, value: Option<(&str, Vec)>) -> Result<&mut Self> { - if let Some((sig, args)) = value { - return self.set_args(sig, args).await - } - Ok(self) - } - - /// Consuming build: returns typed transaction and optional function call - pub fn build(self) -> TxBuilderOutput { - (self.tx, self.func) - } - - pub fn peek(&self) -> TxBuilderPeekOutput { - (&self.tx, &self.func) - } -} - -async fn resolve_name_args>( - args: &[String], - provider: &P, -) -> Vec { - join_all(args.iter().map(|arg| async { - if arg.contains('.') { - let addr = NameOrAddress::Name(arg.to_string()).resolve(provider).await; - match addr { - Ok(addr) => addr.to_string(), - Err(_) => arg.to_string(), - } - } else { - arg.to_string() - } - })) - .await -} - -#[cfg(test)] -mod tests { - use crate::TxBuilder; - use alloy_consensus::TypedTransaction; - use alloy_network::TransactionBuilder; - use alloy_primitives::{Address, U256}; - use foundry_config::NamedChain; - - const ADDR_1: Address = Address::with_last_byte(1); - const ADDR_2: Address = Address::with_last_byte(2); - - #[tokio::test(flavor = "multi_thread")] - async fn builder_new_non_legacy() -> eyre::Result<()> { - // Instanciate a local provider although it'll do nothing. - let provider = foundry_common::provider::alloy::get_http_provider("http://localhost:8545"); - let builder = - TxBuilder::new(&provider, ADDR_1, Some(ADDR_2), NamedChain::Mainnet, false).await?; - let (tx, args) = builder.build(); - assert_eq!(tx.from.unwrap(), ADDR_1); - assert_eq!(tx.to.unwrap(), ADDR_2); - assert_eq!(args, None); - - let tx = tx.build_unsigned().unwrap(); - - match tx { - TypedTransaction::Eip1559(_) => {} - _ => { - panic!("Wrong tx type"); - } - } - Ok(()) - } - - #[tokio::test(flavor = "multi_thread")] - async fn builder_new_legacy() -> eyre::Result<()> { - let provider = foundry_common::provider::alloy::get_http_provider("http://localhost:8545"); - let builder = - TxBuilder::new(&provider, ADDR_1, Some(ADDR_2), NamedChain::Mainnet, true).await?; - // don't check anything other than the tx type - the rest is covered in the non-legacy case - let (tx, _) = builder.build(); - match tx.build_unsigned().unwrap() { - TypedTransaction::Legacy(_) => {} - _ => { - panic!("Wrong tx type"); - } - } - Ok(()) - } - - #[tokio::test(flavor = "multi_thread")] - async fn builder_fields() -> eyre::Result<()> { - let provider = foundry_common::provider::alloy::get_http_provider("http://localhost:8545"); - let mut builder = - TxBuilder::new(&provider, ADDR_1, Some(ADDR_2), NamedChain::Mainnet, false) - .await - .unwrap(); - builder - .gas(Some(U256::from(12u32))) - .gas_price(Some(U256::from(34u32))) - .value(Some(U256::from(56u32))) - .nonce(Some(78)); - - builder.etherscan_api_key(Some(String::from("what a lovely day"))); // not testing for this :-/ - let (tx, _) = builder.build(); - - assert_eq!(tx.gas, Some(U256::from(12))); - assert_eq!(tx.gas_price, Some(U256::from(34))); - assert_eq!(tx.value, Some(U256::from(56))); - assert_eq!(tx.nonce, Some(78)); - assert_eq!(tx.chain_id, Some(1)); - Ok(()) - } - - #[tokio::test(flavor = "multi_thread")] - async fn builder_args() -> eyre::Result<()> { - let provider = foundry_common::provider::alloy::get_http_provider("http://localhost:8545"); - let mut builder = - TxBuilder::new(&provider, ADDR_1, Some(ADDR_2), NamedChain::Mainnet, false) - .await - .unwrap(); - builder.args(Some(("what_a_day(int)", vec![String::from("31337")]))).await?; - let (_, function_maybe) = builder.build(); - - assert_ne!(function_maybe, None); - let function = function_maybe.unwrap(); - assert_eq!(function.name, String::from("what_a_day")); - // could test function.inputs() but that should be covered by utils's unit test - Ok(()) - } -} diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index ab5489e61239..fcc95d55e822 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -24,6 +24,7 @@ alloy-json-abi.workspace = true alloy-primitives.workspace = true alloy-provider.workspace = true alloy-transport.workspace = true +alloy-chains.workspace = true clap = { version = "4", features = ["derive", "env", "unicode", "wrap_help"] } color-eyre.workspace = true @@ -40,6 +41,8 @@ tracing-error = "0.2" tracing-subscriber = { workspace = true, features = ["registry", "env-filter", "fmt"] } tracing.workspace = true yansi = "0.5" +hex.workspace = true +futures = "0.3" [dev-dependencies] tempfile = "3.7" diff --git a/crates/cli/src/utils/abi.rs b/crates/cli/src/utils/abi.rs new file mode 100644 index 000000000000..afe05336aeff --- /dev/null +++ b/crates/cli/src/utils/abi.rs @@ -0,0 +1,61 @@ +use alloy_chains::Chain; +use alloy_json_abi::Function; +use alloy_primitives::Address; +use alloy_provider::{network::Ethereum, Provider}; +use alloy_transport::Transport; +use eyre::{OptionExt, Result}; +use foundry_common::{ + abi::{encode_function_args, get_func, get_func_etherscan}, + ens::NameOrAddress, +}; +use futures::future::join_all; + +async fn resolve_name_args>( + args: &[String], + provider: &P, +) -> Vec { + join_all(args.iter().map(|arg| async { + if arg.contains('.') { + let addr = NameOrAddress::Name(arg.to_string()).resolve(provider).await; + match addr { + Ok(addr) => addr.to_string(), + Err(_) => arg.to_string(), + } + } else { + arg.to_string() + } + })) + .await +} + +pub async fn parse_function_args>( + sig: &str, + args: Vec, + to: Option
, + chain: Chain, + provider: &P, + etherscan_api_key: Option<&str>, +) -> Result<(Vec, Option)> { + if sig.trim().is_empty() { + eyre::bail!("Function signature or calldata must be provided.") + } + + let args = resolve_name_args(&args, provider).await; + + if sig.starts_with("0x") { + return Ok((hex::decode(sig)?, None)); + } + + let func = if sig.contains('(') { + // a regular function signature with parentheses + get_func(sig)? + } else { + let etherscan_api_key = etherscan_api_key.ok_or_eyre( + "If you wish to fetch function data from EtherScan, please provide an API key.", + )?; + let to = to.ok_or_eyre("A 'to' address must be provided to fetch function data.")?; + get_func_etherscan(sig, to, &args, chain, etherscan_api_key).await? + }; + + Ok((encode_function_args(&func, &args)?, Some(func))) +} diff --git a/crates/cli/src/utils/mod.rs b/crates/cli/src/utils/mod.rs index 2e0ed3dad8b0..a3c0ecd8ec94 100644 --- a/crates/cli/src/utils/mod.rs +++ b/crates/cli/src/utils/mod.rs @@ -21,6 +21,9 @@ pub use cmd::*; mod suggestions; pub use suggestions::*; +mod abi; +pub use abi::*; + // reexport all `foundry_config::utils` #[doc(hidden)] pub use foundry_config::utils::*; diff --git a/crates/common/src/fmt/ui.rs b/crates/common/src/fmt/ui.rs index ff41f69dca43..fe984f8b3812 100644 --- a/crates/common/src/fmt/ui.rs +++ b/crates/common/src/fmt/ui.rs @@ -219,7 +219,7 @@ impl UIfmt for Block { format!( " {} -transactions {}", +transactions: {}", pretty_block_basics(self), self.transactions.pretty() ) @@ -372,8 +372,8 @@ pub fn get_pretty_tx_attr(transaction: &Transaction, attr: &str) -> Option Some(transaction.hash.pretty()), "input" => Some(transaction.input.pretty()), "nonce" => Some(transaction.nonce.to_string()), - "s" => transaction.signature.map(|s| s.s.pretty()), - "r" => transaction.signature.map(|s| s.r.pretty()), + "s" => transaction.signature.map(|s| B256::from(s.s).pretty()), + "r" => transaction.signature.map(|s| B256::from(s.r).pretty()), "to" => Some(transaction.to.pretty()), "transactionIndex" | "transaction_index" => Some(transaction.transaction_index.pretty()), "v" => transaction.signature.map(|s| s.v.pretty()), diff --git a/crates/common/src/runtime_client.rs b/crates/common/src/runtime_client.rs index aab2bd4af27e..3bb1631d5fb7 100644 --- a/crates/common/src/runtime_client.rs +++ b/crates/common/src/runtime_client.rs @@ -5,7 +5,7 @@ use ethers_core::types::U256; use ethers_providers::{ Authorization, ConnectionDetails, Http, HttpRateLimitRetryPolicy, Ipc, JsonRpcClient, JsonRpcError, JwtAuth, JwtKey, ProviderError, PubsubClient, RetryClient, RetryClientBuilder, - RpcError, Ws + RpcError, Ws, }; use reqwest_ethers::{ header::{HeaderName, HeaderValue}, diff --git a/crates/common/src/transactions.rs b/crates/common/src/transactions.rs index 1a62c49261c3..03db9508154c 100644 --- a/crates/common/src/transactions.rs +++ b/crates/common/src/transactions.rs @@ -69,22 +69,11 @@ impl From for TransactionReceipt { } fn extract_revert_reason>(error_string: S) -> Option { - let message_substr = "message: execution reverted: "; - - let mut temp = ""; - + let message_substr = "execution reverted: "; error_string .as_ref() - .find(message_substr) - .and_then(|index| { - let (_, rest) = error_string.as_ref().split_at(index + message_substr.len()); - temp = rest; - rest.rfind(", ") - }) - .map(|index| { - let (reason, _) = temp.split_at(index); - reason.to_string() - }) + .find(&message_substr) + .map(|index| error_string.as_ref().split_at(index + message_substr.len()).1.to_string()) } #[cfg(test)] diff --git a/crates/forge/bin/cmd/create.rs b/crates/forge/bin/cmd/create.rs index bcd92942318c..e326119c17c8 100644 --- a/crates/forge/bin/cmd/create.rs +++ b/crates/forge/bin/cmd/create.rs @@ -227,15 +227,18 @@ impl CreateArgs { })?; let is_legacy = self.tx.legacy || Chain::try_from(chain).map(|x| x.is_legacy()).unwrap_or_default(); - + deployer.tx.set_from(deployer_address); deployer.tx.set_chain_id(chain); - - deployer.tx.set_nonce(if let Some(nonce) = self.tx.nonce { - Ok(nonce) - } else { - provider.get_transaction_count(deployer_address, None).await - }?.to()); + + deployer.tx.set_nonce( + if let Some(nonce) = self.tx.nonce { + Ok(nonce) + } else { + provider.get_transaction_count(deployer_address, None).await + }? + .to(), + ); deployer.tx.set_gas_limit(if let Some(gas_limit) = self.tx.gas_limit { Ok(gas_limit) @@ -273,7 +276,7 @@ impl CreateArgs { deployer.tx.set_max_fee_per_gas(max_fee); deployer.tx.set_max_priority_fee_per_gas(priority_fee); } - + // Before we actually deploy the contract we try check if the verify settings are valid let mut constructor_args = None; if self.verify { diff --git a/crates/wallets/src/wallet.rs b/crates/wallets/src/wallet.rs index a4333b40d58f..5773e57d80b6 100644 --- a/crates/wallets/src/wallet.rs +++ b/crates/wallets/src/wallet.rs @@ -206,7 +206,7 @@ mod tests { } Err(x) => { assert!( - x.to_string().contains("Failed to create wallet"), + x.to_string().contains("Failed to decode private key"), "Error message is not user-friendly" ); } From 7889a57fd84eacc219b664bca7b94fcdc83a0ec2 Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Mon, 25 Mar 2024 03:50:18 +0400 Subject: [PATCH 25/63] fix cargo.toml --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 4182b74cd58d..66b6b9d81204 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,7 +28,7 @@ resolver = "2" [workspace.package] version = "0.2.0" edition = "2021" -rust-version = "1.76" # Remember to update clippy.toml as well +rust-version = "1.76" # Remember to update clippy.toml as well authors = ["Foundry Contributors"] license = "MIT OR Apache-2.0" homepage = "https://github.com/foundry-rs/foundry" From b479fa87418e550a3c7f5cee14486d04dde37618 Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Mon, 25 Mar 2024 03:50:54 +0400 Subject: [PATCH 26/63] fix cargo.toml --- Cargo.toml | 2 -- 1 file changed, 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 66b6b9d81204..6445cff8de9a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -180,9 +180,7 @@ alloy-dyn-abi = "0.6.4" alloy-json-abi = "0.6.4" alloy-sol-types = "0.6.4" syn-solidity = "0.6.4" - alloy-chains = "0.1" - alloy-rlp = "0.3.3" solang-parser = "=0.3.3" From 2d67791d01384eb6959498e475dd81163a826d67 Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Mon, 25 Mar 2024 04:01:59 +0400 Subject: [PATCH 27/63] fix script gas price logic --- crates/script/src/broadcast.rs | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/crates/script/src/broadcast.rs b/crates/script/src/broadcast.rs index f7ba7fb4389d..cfb0cf7a7c8c 100644 --- a/crates/script/src/broadcast.rs +++ b/crates/script/src/broadcast.rs @@ -3,10 +3,11 @@ use crate::{ build::LinkedBuildData, sequence::ScriptSequenceKind, verify::BroadcastedState, ScriptArgs, ScriptConfig, }; +use alloy_chains::Chain; use alloy_eips::eip2718::Encodable2718; use alloy_network::{Ethereum, EthereumSigner, TransactionBuilder}; use alloy_primitives::{utils::format_units, Address, TxHash, U256}; -use alloy_provider::Provider; +use alloy_provider::{utils::Eip1559Estimation, Provider}; use alloy_rpc_types::TransactionRequest; use alloy_transport::Transport; use eyre::{bail, Context, Result}; @@ -238,15 +239,28 @@ impl BundledState { let already_broadcasted = sequence.receipts.len(); if already_broadcasted < sequence.transactions.len() { + let is_legacy = Chain::from(sequence.chain).is_legacy() || self.args.legacy; // Make a one-time gas price estimation - let (gas_price, eip1559_fees) = match (self.args.legacy, self.args.with_gas_price) { - (_, Some(gas_price)) => (Some(gas_price), None), - (true, None) => (Some(provider.get_gas_price().await?), None), - (false, None) => { + let (gas_price, eip1559_fees) = match ( + is_legacy, + self.args.with_gas_price, + self.args.priority_gas_price, + ) { + (true, Some(gas_price), _) => (Some(gas_price), None), + (true, None, _) => (Some(provider.get_gas_price().await?), None), + (false, Some(max_fee_per_gas), Some(max_priority_fee_per_gas)) => ( + None, + Some(Eip1559Estimation { max_fee_per_gas, max_priority_fee_per_gas }), + ), + (false, _, _) => { let mut fees = estimate_eip1559_fees(&provider, Some(sequence.chain)) .await .wrap_err("Failed to estimate EIP1559 fees. This chain might not support EIP1559, try adding --legacy to your command.")?; + if let Some(gas_price) = self.args.with_gas_price { + fees.max_fee_per_gas = gas_price; + } + if let Some(priority_gas_price) = self.args.priority_gas_price { fees.max_priority_fee_per_gas = priority_gas_price; } From 43d19b15af448b8afabb944c92c4fff35c56d755 Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Tue, 26 Mar 2024 01:26:32 +0400 Subject: [PATCH 28/63] remove ethers from anvil --- Cargo.lock | 88 ++--------------------------------- crates/anvil/Cargo.toml | 3 +- crates/anvil/src/tasks/mod.rs | 54 +++++++++++---------- crates/anvil/tests/it/fork.rs | 12 +++-- crates/cast/Cargo.toml | 3 +- 5 files changed, 44 insertions(+), 116 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 44484456df7e..17fb5062b3f8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2903,11 +2903,9 @@ dependencies = [ "ethers-addressbook", "ethers-contract", "ethers-core", - "ethers-etherscan", "ethers-middleware", "ethers-providers", "ethers-signers", - "ethers-solc", ] [[package]] @@ -2951,13 +2949,11 @@ dependencies = [ "const-hex", "dunce", "ethers-core", - "ethers-etherscan", "eyre", "prettyplease", "proc-macro2", "quote", "regex", - "reqwest 0.11.27", "serde", "serde_json", "syn 2.0.53", @@ -3011,22 +3007,6 @@ dependencies = [ "unicode-xid", ] -[[package]] -name = "ethers-etherscan" -version = "2.0.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e79e5973c26d4baf0ce55520bd732314328cabe53193286671b47144145b9649" -dependencies = [ - "chrono", - "ethers-core", - "reqwest 0.11.27", - "semver 1.0.22", - "serde", - "serde_json", - "thiserror", - "tracing", -] - [[package]] name = "ethers-middleware" version = "2.0.14" @@ -3111,38 +3091,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "ethers-solc" -version = "2.0.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "66244a771d9163282646dbeffe0e6eca4dda4146b6498644e678ac6089b11edd" -dependencies = [ - "cfg-if", - "const-hex", - "dirs 5.0.1", - "dunce", - "ethers-core", - "glob", - "home", - "md-5", - "num_cpus", - "once_cell", - "path-slash", - "rayon", - "regex", - "semver 1.0.22", - "serde", - "serde_json", - "solang-parser", - "svm-rs 0.3.5", - "thiserror", - "tiny-keccak", - "tokio", - "tracing", - "walkdir", - "yansi 0.5.1", -] - [[package]] name = "event-listener" version = "2.5.3" @@ -3437,7 +3385,7 @@ dependencies = [ "similar", "solang-parser", "strum 0.26.2", - "svm-rs 0.4.1", + "svm-rs", "tempfile", "thiserror", "tokio", @@ -3756,7 +3704,7 @@ dependencies = [ "serde_json", "sha2", "solang-parser", - "svm-rs 0.4.1", + "svm-rs", "svm-rs-builds", "tempfile", "thiserror", @@ -4024,16 +3972,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "fs2" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213" -dependencies = [ - "libc", - "winapi", -] - [[package]] name = "fs4" version = "0.7.0" @@ -7855,26 +7793,6 @@ version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6bdef32e8150c2a081110b42772ffe7d7c9032b606bc226c8260fd97e0976601" -[[package]] -name = "svm-rs" -version = "0.3.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11297baafe5fa0c99d5722458eac6a5e25c01eb1b8e5cd137f54079093daa7a4" -dependencies = [ - "dirs 5.0.1", - "fs2", - "hex", - "once_cell", - "reqwest 0.11.27", - "semver 1.0.22", - "serde", - "serde_json", - "sha2", - "thiserror", - "url", - "zip", -] - [[package]] name = "svm-rs" version = "0.4.1" @@ -7905,7 +7823,7 @@ dependencies = [ "const-hex", "semver 1.0.22", "serde_json", - "svm-rs 0.4.1", + "svm-rs", ] [[package]] diff --git a/crates/anvil/Cargo.toml b/crates/anvil/Cargo.toml index e2888672cf0b..60e2b1c26087 100644 --- a/crates/anvil/Cargo.toml +++ b/crates/anvil/Cargo.toml @@ -35,7 +35,6 @@ foundry-evm.workspace = true # evm support bytes = "1.4.0" k256.workspace = true -ethers = { workspace = true, features = ["rustls", "ws", "ipc", "optimism"] } trie-db = "0.23" hash-db = "0.15" memory-db = "0.29" @@ -97,7 +96,7 @@ ethereum-forkid = "0.12" [dev-dependencies] alloy-json-abi.workspace = true -ethers = { workspace = true, features = ["abigen"] } +ethers = { workspace = true, features = ["abigen", "optimism"] } ethers-core = { workspace = true, features = ["optimism"] } foundry-compilers = { workspace = true, features = ["project-util", "full"] } diff --git a/crates/anvil/src/tasks/mod.rs b/crates/anvil/src/tasks/mod.rs index 429f8d5d3291..8a3000b00b44 100644 --- a/crates/anvil/src/tasks/mod.rs +++ b/crates/anvil/src/tasks/mod.rs @@ -1,12 +1,13 @@ //! Task management support use crate::{shutdown::Shutdown, tasks::block_listener::BlockListener, EthApi}; +use alloy_network::Ethereum; +use alloy_primitives::B256; +use alloy_provider::Provider; +use alloy_rpc_types::Block; +use alloy_transport::Transport; use anvil_core::types::Forking; -use ethers::{ - prelude::Middleware, - providers::{JsonRpcClient, PubsubClient}, - types::{Block, H256}, -}; +use futures::StreamExt; use std::{fmt, future::Future}; use tokio::{runtime::Handle, task::JoinHandle}; @@ -63,20 +64,20 @@ impl TaskManager { /// handle.task_manager().spawn_reset_on_new_polled_blocks(provider, api); /// # } /// ``` - pub fn spawn_reset_on_new_polled_blocks

(&self, provider: P, api: EthApi) + pub fn spawn_reset_on_new_polled_blocks(&self, provider: P, api: EthApi) where - P: Middleware + Clone + Unpin + 'static + Send + Sync, -

::Provider: JsonRpcClient, + P: Provider + Clone + Unpin + 'static, + T: Transport + Clone, { self.spawn_block_poll_listener(provider.clone(), move |hash| { let provider = provider.clone(); let api = api.clone(); async move { - if let Ok(Some(block)) = provider.get_block(hash).await { + if let Ok(Some(block)) = provider.get_block(hash.into(), false).await { let _ = api .anvil_reset(Some(Forking { json_rpc_url: None, - block_number: block.number.map(|b| b.as_u64()), + block_number: block.header.number.map(|b| b.to()), })) .await; } @@ -87,16 +88,21 @@ impl TaskManager { /// Spawns a new [`BlockListener`] task that listens for new blocks (poll-based) See also /// [`Provider::watch_blocks`] and executes the future the `task_factory` returns for the new /// block hash - pub fn spawn_block_poll_listener(&self, provider: P, task_factory: F) + pub fn spawn_block_poll_listener(&self, provider: P, task_factory: F) where - P: Middleware + Unpin + 'static, -

::Provider: JsonRpcClient, - F: Fn(H256) -> Fut + Unpin + Send + Sync + 'static, + P: Provider + 'static, + T: Transport + Clone, + F: Fn(B256) -> Fut + Unpin + Send + Sync + 'static, Fut: Future + Send, { let shutdown = self.on_shutdown.clone(); self.spawn(async move { - let blocks = provider.watch_blocks().await.unwrap(); + let blocks = provider + .watch_blocks() + .await + .unwrap() + .into_stream() + .flat_map(futures::stream::iter); BlockListener::new(shutdown, blocks, task_factory).await; }); } @@ -116,10 +122,10 @@ impl TaskManager { /// /// # } /// ``` - pub fn spawn_reset_on_subscribed_blocks

(&self, provider: P, api: EthApi) + pub fn spawn_reset_on_subscribed_blocks(&self, provider: P, api: EthApi) where - P: Middleware + Unpin + 'static + Send + Sync, -

::Provider: PubsubClient, + P: Provider + 'static, + T: Transport + Clone, { self.spawn_block_subscription(provider, move |block| { let api = api.clone(); @@ -127,7 +133,7 @@ impl TaskManager { let _ = api .anvil_reset(Some(Forking { json_rpc_url: None, - block_number: block.number.map(|b| b.as_u64()), + block_number: block.header.number.map(|b| b.to()), })) .await; } @@ -137,16 +143,16 @@ impl TaskManager { /// Spawns a new [`BlockListener`] task that listens for new blocks (via subscription) See also /// [`Provider::subscribe_blocks()`] and executes the future the `task_factory` returns for the /// new block hash - pub fn spawn_block_subscription(&self, provider: P, task_factory: F) + pub fn spawn_block_subscription(&self, provider: P, task_factory: F) where - P: Middleware + Unpin + 'static, -

::Provider: PubsubClient, - F: Fn(Block) -> Fut + Unpin + Send + Sync + 'static, + P: Provider + 'static, + T: Transport + Clone, + F: Fn(Block) -> Fut + Unpin + Send + Sync + 'static, Fut: Future + Send, { let shutdown = self.on_shutdown.clone(); self.spawn(async move { - let blocks = provider.subscribe_blocks().await.unwrap(); + let blocks = provider.subscribe_blocks().await.unwrap().into_stream(); BlockListener::new(shutdown, blocks, task_factory).await; }); } diff --git a/crates/anvil/tests/it/fork.rs b/crates/anvil/tests/it/fork.rs index 55ed260db509..5e61c231c5c0 100644 --- a/crates/anvil/tests/it/fork.rs +++ b/crates/anvil/tests/it/fork.rs @@ -22,7 +22,7 @@ use ethers::{ }, }; use foundry_common::{ - provider::ethers::get_http_provider, + provider::alloy::get_http_provider, rpc, rpc::next_http_rpc_endpoint, types::{ToAlloy, ToEthers}, @@ -762,13 +762,19 @@ async fn test_reset_fork_on_new_blocks() { let anvil_provider = ethers_http_provider(&handle.http_endpoint()); let endpoint = next_http_rpc_endpoint(); - let provider = Arc::new(get_http_provider(&endpoint).interval(Duration::from_secs(2))); + let provider = Arc::new(get_http_provider(&endpoint)); let current_block = anvil_provider.get_block_number().await.unwrap(); handle.task_manager().spawn_reset_on_new_polled_blocks(provider.clone(), api); - let mut stream = provider.watch_blocks().await.unwrap(); + let mut stream = provider + .watch_blocks() + .await + .unwrap() + .with_poll_interval(Duration::from_secs(2)) + .into_stream() + .flat_map(futures::stream::iter); // the http watcher may fetch multiple blocks at once, so we set a timeout here to offset edge // cases where the stream immediately returns a block tokio::time::sleep(Chain::Mainnet.average_blocktime_hint().unwrap()).await; diff --git a/crates/cast/Cargo.toml b/crates/cast/Cargo.toml index 750a11172c7e..aed5138d8056 100644 --- a/crates/cast/Cargo.toml +++ b/crates/cast/Cargo.toml @@ -47,6 +47,7 @@ alloy-sol-types.workspace = true alloy-chains.workspace = true ethers-core.workspace = true +ethers-contract.workspace = true chrono.workspace = true evm-disassembler.workspace = true @@ -64,8 +65,6 @@ aws-sdk-kms = { version = "1", default-features = false } # bin foundry-cli.workspace = true -ethers-contract.workspace = true - clap = { version = "4", features = ["derive", "env", "unicode", "wrap_help"] } clap_complete = "4" clap_complete_fig = "4" From f0a6243765fd317de7c274bef56b0dc244fe2bd0 Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Tue, 26 Mar 2024 01:35:50 +0400 Subject: [PATCH 29/63] clippy --- crates/anvil/src/eth/backend/fork.rs | 6 +++--- crates/anvil/src/eth/backend/mem/mod.rs | 3 +-- crates/cast/src/lib.rs | 4 ++-- crates/cheatcodes/src/env.rs | 3 +-- crates/cheatcodes/src/evm.rs | 2 +- crates/cheatcodes/src/inspector.rs | 3 +-- crates/common/src/transactions.rs | 2 +- crates/evm/core/src/backend/mod.rs | 12 ++++++------ crates/evm/evm/src/inspectors/stack.rs | 4 +--- crates/forge/bin/cmd/create.rs | 4 ++-- 10 files changed, 19 insertions(+), 24 deletions(-) diff --git a/crates/anvil/src/eth/backend/fork.rs b/crates/anvil/src/eth/backend/fork.rs index 244a2f5a9b3d..499cb08a936c 100644 --- a/crates/anvil/src/eth/backend/fork.rs +++ b/crates/anvil/src/eth/backend/fork.rs @@ -183,7 +183,7 @@ impl ClientFork { block: Option, ) -> Result { let block = block.unwrap_or(BlockNumber::Latest); - let res = self.provider().estimate_gas(&request, Some(block.into())).await?; + let res = self.provider().estimate_gas(request, Some(block.into())).await?; Ok(res) } @@ -194,7 +194,7 @@ impl ClientFork { request: &TransactionRequest, block: Option, ) -> Result { - self.provider().create_access_list(&request, block.map(|b| b.into())).await + self.provider().create_access_list(request, block.map(|b| b.into())).await } pub async fn storage_at( @@ -211,7 +211,7 @@ impl ClientFork { return Ok(logs); } - let logs = self.provider().get_logs(&filter).await?; + let logs = self.provider().get_logs(filter).await?; let mut storage = self.storage_write(); storage.logs.insert(filter.clone(), logs.clone()); diff --git a/crates/anvil/src/eth/backend/mem/mod.rs b/crates/anvil/src/eth/backend/mem/mod.rs index af4aefaf8cb9..e75bb5387a77 100644 --- a/crates/anvil/src/eth/backend/mem/mod.rs +++ b/crates/anvil/src/eth/backend/mem/mod.rs @@ -2341,8 +2341,7 @@ impl TransactionValidator for Backend { // check nonce let is_deposit_tx = matches!(&pending.transaction.transaction, TypedTransaction::Deposit(_)); - let nonce: u64 = - tx.nonce().try_into().map_err(|_| InvalidTransactionError::NonceMaxValue)?; + let nonce = tx.nonce(); if nonce < account.nonce && !is_deposit_tx { warn!(target: "backend", "[{:?}] nonce too low", tx.hash()); return Err(InvalidTransactionError::NonceTooLow); diff --git a/crates/cast/src/lib.rs b/crates/cast/src/lib.rs index 2ee659f4573c..a7627d1a3126 100644 --- a/crates/cast/src/lib.rs +++ b/crates/cast/src/lib.rs @@ -648,7 +648,7 @@ where let tx_hash = TxHash::from_str(&tx_hash).wrap_err("invalid tx hash")?; let mut receipt: TransactionReceiptWithRevertReason = - match self.provider.get_transaction_receipt(tx_hash.into()).await? { + match self.provider.get_transaction_receipt(tx_hash).await? { Some(r) => r, None => { // if the async flag is provided, immediately exit if no tx is found, otherwise @@ -656,7 +656,7 @@ where if cast_async { eyre::bail!("tx not found: {:?}", tx_hash) } else { - PendingTransactionBuilder::new(self.provider.root(), tx_hash.into()) + PendingTransactionBuilder::new(self.provider.root(), tx_hash) .with_required_confirmations(confs) .get_receipt() .await? diff --git a/crates/cheatcodes/src/env.rs b/crates/cheatcodes/src/env.rs index f8261d7a18f2..5d82d769390f 100644 --- a/crates/cheatcodes/src/env.rs +++ b/crates/cheatcodes/src/env.rs @@ -2,7 +2,6 @@ use crate::{string, Cheatcode, Cheatcodes, Error, Result, Vm::*}; use alloy_dyn_abi::DynSolType; -use alloy_primitives::Bytes; use alloy_sol_types::SolValue; use std::env; @@ -230,7 +229,7 @@ impl Cheatcode for envOr_12Call { impl Cheatcode for envOr_13Call { fn apply(&self, _state: &mut Cheatcodes) -> Result { let Self { name, delim, defaultValue } = self; - let default = defaultValue.iter().map(|vec| vec.clone()).collect::>(); + let default = defaultValue.to_vec(); env_array_default(name, delim, &default, &DynSolType::Bytes) } } diff --git a/crates/cheatcodes/src/evm.rs b/crates/cheatcodes/src/evm.rs index bd9f80fdf2d2..1c0baaf9d89e 100644 --- a/crates/cheatcodes/src/evm.rs +++ b/crates/cheatcodes/src/evm.rs @@ -114,7 +114,7 @@ impl Cheatcode for dumpStateCall { .ecx .journaled_state .state() - .into_iter() + .iter_mut() .filter(|(key, val)| !skip(key, val)) .map(|(key, val)| { ( diff --git a/crates/cheatcodes/src/inspector.rs b/crates/cheatcodes/src/inspector.rs index 57bcbed2006a..0f29ffef0e7f 100644 --- a/crates/cheatcodes/src/inspector.rs +++ b/crates/cheatcodes/src/inspector.rs @@ -1453,8 +1453,7 @@ impl Inspector for Cheatcodes { .code .clone() .unwrap_or_default() - .original_bytes() - .into(); + .original_bytes(); } } } diff --git a/crates/common/src/transactions.rs b/crates/common/src/transactions.rs index 03db9508154c..50c900187d54 100644 --- a/crates/common/src/transactions.rs +++ b/crates/common/src/transactions.rs @@ -72,7 +72,7 @@ fn extract_revert_reason>(error_string: S) -> Option { let message_substr = "execution reverted: "; error_string .as_ref() - .find(&message_substr) + .find(message_substr) .map(|index| error_string.as_ref().split_at(index + message_substr.len()).1.to_string()) } diff --git a/crates/evm/core/src/backend/mod.rs b/crates/evm/core/src/backend/mod.rs index 944501326e01..91f6cdb44466 100644 --- a/crates/evm/core/src/backend/mod.rs +++ b/crates/evm/core/src/backend/mod.rs @@ -976,7 +976,7 @@ impl DatabaseExt for Backend { // another caller, so we need to ensure the caller account is present in the // journaled state and database let caller = current.tx.caller; - if !journaled_state.state.contains_key(&caller) { + journaled_state.state.entry(caller).or_insert_with(|| { let caller_account = current_state .state .get(&caller) @@ -987,8 +987,8 @@ impl DatabaseExt for Backend { // update the caller account which is required by the evm fork.db.insert_account_info(caller, caller_account.clone()); } - journaled_state.state.insert(caller, caller_account.into()); - } + caller_account.into() + }); self.inner.revert_snapshot(id, fork_id, idx, *fork); self.active_fork_ids = Some((id, idx)) } @@ -1115,7 +1115,7 @@ impl DatabaseExt for Backend { // necessarily the same caller as for the test, however we must always // ensure that fork's state contains the current sender let caller = env.tx.caller; - if !fork.journaled_state.state.contains_key(&caller) { + fork.journaled_state.state.entry(caller).or_insert_with(|| { let caller_account = active_journaled_state .state .get(&env.tx.caller) @@ -1126,8 +1126,8 @@ impl DatabaseExt for Backend { // update the caller account which is required by the evm fork.db.insert_account_info(caller, caller_account.clone()); } - fork.journaled_state.state.insert(caller, caller_account.into()); - } + caller_account.into() + }); self.update_fork_db(active_journaled_state, &mut fork); diff --git a/crates/evm/evm/src/inspectors/stack.rs b/crates/evm/evm/src/inspectors/stack.rs index ea0af6bbc873..fb2b42d1bf7e 100644 --- a/crates/evm/evm/src/inspectors/stack.rs +++ b/crates/evm/evm/src/inspectors/stack.rs @@ -508,9 +508,7 @@ impl InspectorStack { if let Some(acc_mut) = ecx.journaled_state.state.get_mut(&addr) { acc_mut.status |= acc.status; for (key, val) in acc.storage { - if !acc_mut.storage.contains_key(&key) { - acc_mut.storage.insert(key, val); - } + acc_mut.storage.entry(key).or_insert(val); } } else { ecx.journaled_state.state.insert(addr, acc); diff --git a/crates/forge/bin/cmd/create.rs b/crates/forge/bin/cmd/create.rs index e326119c17c8..e3870ac675c2 100644 --- a/crates/forge/bin/cmd/create.rs +++ b/crates/forge/bin/cmd/create.rs @@ -226,7 +226,7 @@ impl CreateArgs { } })?; let is_legacy = - self.tx.legacy || Chain::try_from(chain).map(|x| x.is_legacy()).unwrap_or_default(); + self.tx.legacy || Chain::from(chain).is_legacy(); deployer.tx.set_from(deployer_address); deployer.tx.set_chain_id(chain); @@ -549,7 +549,7 @@ where (Some(constructor), _) => { let input: Bytes = constructor .abi_encode_input(¶ms) - .map_err(|f| ContractDeploymentError::DetokenizationError(f))? + .map_err(ContractDeploymentError::DetokenizationError)? .into(); // Concatenate the bytecode and abi-encoded constructor call. self.bytecode.iter().copied().chain(input).collect() From 203712ec5af928b13f20737c562e23094ddce84c Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Tue, 26 Mar 2024 01:37:43 +0400 Subject: [PATCH 30/63] rm all_derives --- crates/evm/core/src/abi/hardhat_console.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/evm/core/src/abi/hardhat_console.rs b/crates/evm/core/src/abi/hardhat_console.rs index a6e7429c2329..4b9aa3ba2a89 100644 --- a/crates/evm/core/src/abi/hardhat_console.rs +++ b/crates/evm/core/src/abi/hardhat_console.rs @@ -5,7 +5,7 @@ use once_cell::sync::Lazy; use revm::primitives::HashMap; sol!( - #[sol(abi, all_derives)] + #[sol(abi)] #[derive(ConsoleFmt)] HardhatConsole, "src/abi/HardhatConsole.json" From 25276b8ceada37fbb2208e3eab7917fb42d08198 Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Wed, 27 Mar 2024 04:44:19 +0400 Subject: [PATCH 31/63] deps --- Cargo.lock | 43 ++++++++++++++++++++++--------------------- Cargo.toml | 48 +++++++++++++++++++++++++----------------------- 2 files changed, 47 insertions(+), 44 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 17fb5062b3f8..b8c38f700d0d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -90,7 +90,7 @@ dependencies = [ [[package]] name = "alloy-consensus" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" +source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" dependencies = [ "alloy-eips", "alloy-primitives", @@ -105,7 +105,7 @@ dependencies = [ [[package]] name = "alloy-contract" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" +source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" dependencies = [ "alloy-dyn-abi", "alloy-json-abi", @@ -143,7 +143,7 @@ dependencies = [ [[package]] name = "alloy-eips" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" +source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -157,7 +157,7 @@ dependencies = [ [[package]] name = "alloy-genesis" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" +source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" dependencies = [ "alloy-primitives", "alloy-serde", @@ -178,7 +178,7 @@ dependencies = [ [[package]] name = "alloy-json-rpc" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" +source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" dependencies = [ "alloy-primitives", "serde", @@ -189,7 +189,7 @@ dependencies = [ [[package]] name = "alloy-network" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" +source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" dependencies = [ "alloy-consensus", "alloy-eips", @@ -232,7 +232,7 @@ dependencies = [ [[package]] name = "alloy-provider" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" +source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" dependencies = [ "alloy-json-rpc", "alloy-network", @@ -258,7 +258,7 @@ dependencies = [ [[package]] name = "alloy-pubsub" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" +source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" dependencies = [ "alloy-json-rpc", "alloy-primitives", @@ -298,7 +298,7 @@ dependencies = [ [[package]] name = "alloy-rpc-client" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" +source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" dependencies = [ "alloy-json-rpc", "alloy-primitives", @@ -320,7 +320,7 @@ dependencies = [ [[package]] name = "alloy-rpc-trace-types" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" +source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" dependencies = [ "alloy-primitives", "alloy-rpc-types", @@ -332,7 +332,7 @@ dependencies = [ [[package]] name = "alloy-rpc-types" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" +source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" dependencies = [ "alloy-consensus", "alloy-eips", @@ -348,7 +348,7 @@ dependencies = [ [[package]] name = "alloy-serde" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" +source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" dependencies = [ "alloy-primitives", "serde", @@ -358,7 +358,7 @@ dependencies = [ [[package]] name = "alloy-signer" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" +source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" dependencies = [ "alloy-dyn-abi", "alloy-primitives", @@ -373,7 +373,7 @@ dependencies = [ [[package]] name = "alloy-signer-aws" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" +source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" dependencies = [ "alloy-consensus", "alloy-network", @@ -390,7 +390,7 @@ dependencies = [ [[package]] name = "alloy-signer-ledger" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" +source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" dependencies = [ "alloy-consensus", "alloy-network", @@ -407,7 +407,7 @@ dependencies = [ [[package]] name = "alloy-signer-trezor" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" +source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" dependencies = [ "alloy-consensus", "alloy-network", @@ -423,7 +423,7 @@ dependencies = [ [[package]] name = "alloy-signer-wallet" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" +source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" dependencies = [ "alloy-consensus", "alloy-network", @@ -496,7 +496,7 @@ dependencies = [ [[package]] name = "alloy-transport" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" +source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" dependencies = [ "alloy-json-rpc", "base64 0.22.0", @@ -514,7 +514,7 @@ dependencies = [ [[package]] name = "alloy-transport-http" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" +source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" dependencies = [ "alloy-json-rpc", "alloy-transport", @@ -527,7 +527,7 @@ dependencies = [ [[package]] name = "alloy-transport-ipc" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" +source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" dependencies = [ "alloy-json-rpc", "alloy-pubsub", @@ -545,7 +545,7 @@ dependencies = [ [[package]] name = "alloy-transport-ws" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=05ca151#05ca1515220a0f461ca5d870c12741d827435fc2" +source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" dependencies = [ "alloy-pubsub", "alloy-transport", @@ -6828,6 +6828,7 @@ dependencies = [ [[package]] name = "revm-inspectors" version = "0.1.0" +source = "git+https://github.com/klkvr/evm-inspectors?rev=9ff0c29#9ff0c29d3a1b8feee1c6176a58a4a485723f7a4c" dependencies = [ "alloy-primitives", "alloy-rpc-trace-types", diff --git a/Cargo.toml b/Cargo.toml index ecf4a2fbe9ea..0b403ca9455a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,7 +28,7 @@ resolver = "2" [workspace.package] version = "0.2.0" edition = "2021" -rust-version = "1.76" # Remember to update clippy.toml as well +rust-version = "1.76" # Remember to update clippy.toml as well authors = ["Foundry Contributors"] license = "MIT OR Apache-2.0" homepage = "https://github.com/foundry-rs/foundry" @@ -142,7 +142,9 @@ foundry-compilers = { version = "0.3.13", default-features = false } # no default features to avoid c-kzg revm = { version = "7.2", default-features = false } revm-primitives = { version = "3", default-features = false } -revm-inspectors = { path = "../evm-inspectors", features = ["serde"] } +revm-inspectors = { git = "https://github.com/klkvr/evm-inspectors", rev = "9ff0c29", features = [ + "serde", +] } ## ethers ethers = { version = "2.0.14", default-features = false } @@ -154,27 +156,27 @@ ethers-signers = { version = "2.0.14", default-features = false } ethers-middleware = { version = "2.0.14", default-features = false } ## alloy -alloy-consensus = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } -alloy-contract = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } -alloy-eips = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } -alloy-genesis = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } -alloy-json-rpc = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } -alloy-network = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } -alloy-node-bindings = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } -alloy-provider = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } -alloy-pubsub = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } -alloy-rpc-client = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } -alloy-rpc-trace-types = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } -alloy-rpc-types = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } -alloy-signer = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } -alloy-signer-wallet = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } -alloy-signer-aws = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } -alloy-signer-ledger = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } -alloy-signer-trezor = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } -alloy-transport = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } -alloy-transport-http = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } -alloy-transport-ipc = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } -alloy-transport-ws = { git = "https://github.com/klkvr/alloy", rev = "05ca151", default-features = false } +alloy-consensus = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } +alloy-contract = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } +alloy-eips = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } +alloy-genesis = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } +alloy-json-rpc = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } +alloy-network = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } +alloy-node-bindings = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } +alloy-provider = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } +alloy-pubsub = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } +alloy-rpc-client = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } +alloy-rpc-trace-types = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } +alloy-rpc-types = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } +alloy-signer = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } +alloy-signer-wallet = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } +alloy-signer-aws = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } +alloy-signer-ledger = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } +alloy-signer-trezor = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } +alloy-transport = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } +alloy-transport-http = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } +alloy-transport-ipc = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } +alloy-transport-ws = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } alloy-primitives = { version = "0.6.4", features = ["getrandom"] } alloy-dyn-abi = "0.6.4" alloy-json-abi = "0.6.4" From a61f4a6db6d49f9c8b438713807bef2ea97dd3c3 Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Wed, 27 Mar 2024 04:45:33 +0400 Subject: [PATCH 32/63] fmt --- crates/cheatcodes/src/inspector.rs | 8 ++------ crates/forge/bin/cmd/create.rs | 3 +-- 2 files changed, 3 insertions(+), 8 deletions(-) diff --git a/crates/cheatcodes/src/inspector.rs b/crates/cheatcodes/src/inspector.rs index 0f29ffef0e7f..4ca59bcf276e 100644 --- a/crates/cheatcodes/src/inspector.rs +++ b/crates/cheatcodes/src/inspector.rs @@ -1448,12 +1448,8 @@ impl Inspector for Cheatcodes { ecx.journaled_state.load_account(address, &mut ecx.db) { create_access.newBalance = created_acc.info.balance; - create_access.deployedCode = created_acc - .info - .code - .clone() - .unwrap_or_default() - .original_bytes(); + create_access.deployedCode = + created_acc.info.code.clone().unwrap_or_default().original_bytes(); } } } diff --git a/crates/forge/bin/cmd/create.rs b/crates/forge/bin/cmd/create.rs index e3870ac675c2..4b73e47faebd 100644 --- a/crates/forge/bin/cmd/create.rs +++ b/crates/forge/bin/cmd/create.rs @@ -225,8 +225,7 @@ impl CreateArgs { e } })?; - let is_legacy = - self.tx.legacy || Chain::from(chain).is_legacy(); + let is_legacy = self.tx.legacy || Chain::from(chain).is_legacy(); deployer.tx.set_from(deployer_address); deployer.tx.set_chain_id(chain); From e6e3b57fdacd951892941bc7d27d1b0ee3eddd29 Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Wed, 27 Mar 2024 17:12:22 +0400 Subject: [PATCH 33/63] fix tests --- crates/common/src/transactions.rs | 12 +++--------- crates/forge/tests/it/invariant.rs | 4 ++-- 2 files changed, 5 insertions(+), 11 deletions(-) diff --git a/crates/common/src/transactions.rs b/crates/common/src/transactions.rs index 50c900187d54..74510f548c64 100644 --- a/crates/common/src/transactions.rs +++ b/crates/common/src/transactions.rs @@ -82,16 +82,10 @@ mod tests { #[test] fn test_extract_revert_reason() { - let error_string_1 = "(code: 3, message: execution reverted: Transaction too old, data: Some(String(\"0x08c379a0\")))"; - let error_string_2 = "(code: 3, message: execution reverted: missing data: amountIn, amountOut, data: Some(String(\"0x08c379a0\")))"; - let error_string_3 = - "(code: 4, message: invalid signature, data: Some(String(\"0x08c379a0\")))"; + let error_string_1 = "server returned an error response: error code 3: execution reverted: Transaction too old"; + let error_string_2 = "server returned an error response: error code 3: Invalid signature"; assert_eq!(extract_revert_reason(error_string_1), Some("Transaction too old".to_string())); - assert_eq!( - extract_revert_reason(error_string_2), - Some("missing data: amountIn, amountOut".to_string()) - ); - assert_eq!(extract_revert_reason(error_string_3), None); + assert_eq!(extract_revert_reason(error_string_2), None); } } diff --git a/crates/forge/tests/it/invariant.rs b/crates/forge/tests/it/invariant.rs index 82cf4909e790..906d88269d7a 100644 --- a/crates/forge/tests/it/invariant.rs +++ b/crates/forge/tests/it/invariant.rs @@ -243,14 +243,14 @@ async fn test_invariant_shrink() { let create_fren_sequence = sequence[0].clone(); assert_eq!( create_fren_sequence.contract_name.unwrap(), - "fuzz/invariant/common/InvariantInnerContract.t.sol:Jesus" + "default/fuzz/invariant/common/InvariantInnerContract.t.sol:Jesus" ); assert_eq!(create_fren_sequence.signature.unwrap(), "create_fren()"); let betray_sequence = sequence[1].clone(); assert_eq!( betray_sequence.contract_name.unwrap(), - "fuzz/invariant/common/InvariantInnerContract.t.sol:Judas" + "default/fuzz/invariant/common/InvariantInnerContract.t.sol:Judas" ); assert_eq!(betray_sequence.signature.unwrap(), "betray()"); } From 24f746a9082009956ea5c5eddd69c87ac3c5b4cd Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Wed, 27 Mar 2024 17:52:25 +0400 Subject: [PATCH 34/63] configure clippy --- clippy.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/clippy.toml b/clippy.toml index 472818efed9b..07ea6cab0848 100644 --- a/clippy.toml +++ b/clippy.toml @@ -1 +1,2 @@ msrv = "1.76" +ignore-interior-mutability = ["bytes::Bytes", "alloy_primitives::Bytes"] From 5d72ea9866ab698d71bad99c1ebfe37299d10c98 Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Wed, 27 Mar 2024 17:55:13 +0400 Subject: [PATCH 35/63] clippy --- crates/script/src/providers.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/script/src/providers.rs b/crates/script/src/providers.rs index 8163707cf465..022b0a3aeaea 100644 --- a/crates/script/src/providers.rs +++ b/crates/script/src/providers.rs @@ -46,7 +46,6 @@ pub struct ProviderInfo { pub provider: Arc, pub chain: u64, pub gas_price: GasPrice, - pub is_legacy: bool, } /// Represents the outcome of a gas price request @@ -75,7 +74,7 @@ impl ProviderInfo { ) }; - Ok(ProviderInfo { provider, chain, gas_price, is_legacy }) + Ok(ProviderInfo { provider, chain, gas_price }) } /// Returns the gas price to use From 1b762d84756e34ea475872cae59c38a0e696b4e9 Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Wed, 27 Mar 2024 18:15:49 +0400 Subject: [PATCH 36/63] add feature --- crates/anvil/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/anvil/Cargo.toml b/crates/anvil/Cargo.toml index 60e2b1c26087..ad43271e59b3 100644 --- a/crates/anvil/Cargo.toml +++ b/crates/anvil/Cargo.toml @@ -48,7 +48,7 @@ alloy-sol-types = { workspace = true, features = ["std"] } alloy-dyn-abi = { workspace = true, features = ["std", "eip712"] } alloy-rpc-types.workspace = true alloy-rpc-trace-types.workspace = true -alloy-provider.workspace = true +alloy-provider = { workspace = true, features = ["pubsub"] } alloy-transport.workspace = true alloy-chains.workspace = true alloy-genesis.workspace = true From 852fa11c1ebf4db5951effe72d4a5f454ce161f8 Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Wed, 27 Mar 2024 19:34:18 +0400 Subject: [PATCH 37/63] fix cargo deny --- Cargo.lock | 321 +++++++++++++++++++++++---------------- crates/common/Cargo.toml | 4 +- 2 files changed, 190 insertions(+), 135 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5d1a58534ea7..4f016b1950a9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -249,7 +249,7 @@ dependencies = [ "dashmap", "futures", "lru", - "reqwest 0.12.1", + "reqwest 0.12.2", "serde_json", "tokio", "tracing", @@ -292,7 +292,7 @@ checksum = "1a047897373be4bbb0224c1afdabca92648dc57a9c9ef6e7b0be3aff7a859c83" dependencies = [ "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -307,7 +307,7 @@ dependencies = [ "alloy-transport-http", "futures", "pin-project", - "reqwest 0.12.1", + "reqwest 0.12.2", "serde", "serde_json", "tokio", @@ -452,7 +452,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", "syn-solidity", "tiny-keccak", ] @@ -469,7 +469,7 @@ dependencies = [ "proc-macro2", "quote", "serde_json", - "syn 2.0.53", + "syn 2.0.55", "syn-solidity", ] @@ -518,7 +518,7 @@ source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfd dependencies = [ "alloy-json-rpc", "alloy-transport", - "reqwest 0.12.1", + "reqwest 0.12.2", "serde_json", "tower", "url", @@ -967,7 +967,7 @@ checksum = "30c5ef0ede93efbf733c1a727f3b6b5a1060bbedd5600183e66f6e4be4af0ec5" dependencies = [ "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -989,7 +989,7 @@ checksum = "16e62a023e7c117e27523144c5d2459f4397fcc3cab0085af8e2224f643a0193" dependencies = [ "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -1000,13 +1000,13 @@ checksum = "fbb36e985947064623dbd357f727af08ffd077f93d696782f3c56365fa2e2799" [[package]] name = "async-trait" -version = "0.1.78" +version = "0.1.79" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "461abc97219de0eaaf81fe3ef974a540158f3d079c2ab200f891f1a2ef201e85" +checksum = "a507401cad91ec6a857ed5513a2073c82a9b9048762b885bb98655b306964681" dependencies = [ "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -1059,20 +1059,20 @@ checksum = "3c87f3f15e7794432337fc718554eaa4dc8f04c9677a950ffe366f20a162ae42" dependencies = [ "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] name = "autocfg" -version = "1.1.0" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" +checksum = "f1fdabc7756949593fe60f30ec81974b613357de856987752631dea1e3394c80" [[package]] name = "aws-config" -version = "1.1.8" +version = "1.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f4084d18094aec9f79d509f4cb6ccf6b613c5037e32f32e74312e52b836e366" +checksum = "297b64446175a73987cedc3c438d79b2a654d0fff96f65ff530fbe039347644c" dependencies = [ "aws-credential-types", "aws-runtime", @@ -1095,6 +1095,7 @@ dependencies = [ "time", "tokio", "tracing", + "url", "zeroize", ] @@ -1130,14 +1131,14 @@ dependencies = [ "percent-encoding", "pin-project-lite", "tracing", - "uuid 1.7.0", + "uuid 1.8.0", ] [[package]] name = "aws-sdk-kms" -version = "1.17.0" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ffff97eef0a66fb565564d27cb108cc85409aa31cd6c8e22afed7abe5ccbd403" +checksum = "597a4e610d67363f6846c903ebca4ce65439033d5ec2a5d8effc96d5eaa53355" dependencies = [ "aws-credential-types", "aws-runtime", @@ -1157,9 +1158,9 @@ dependencies = [ [[package]] name = "aws-sdk-sso" -version = "1.17.0" +version = "1.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5cc34f5925899739a3f125bd3f7d37d081234a3df218feb9c9d337fd4c70e72" +checksum = "019a07902c43b03167ea5df0182f0cb63fae89f9a9682c44d18cf2e4a042cb34" dependencies = [ "aws-credential-types", "aws-runtime", @@ -1179,9 +1180,9 @@ dependencies = [ [[package]] name = "aws-sdk-ssooidc" -version = "1.17.0" +version = "1.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7327cddd32b1a6f2aaeaadb1336b671a7975e96a999d3b1bcf5aa47932dc6ddb" +checksum = "04c46ee08a48a7f4eaa4ad201dcc1dd537b49c50859d14d4510e00ad9d3f9af2" dependencies = [ "aws-credential-types", "aws-runtime", @@ -1201,9 +1202,9 @@ dependencies = [ [[package]] name = "aws-sdk-sts" -version = "1.17.0" +version = "1.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c11981cdb80e8e205e22beb6630a8bdec380a1256bd29efaab34aaebd07cfb9" +checksum = "f752ac730125ca6017f72f9db5ec1772c9ecc664f87aa7507a7d81b023c23713" dependencies = [ "aws-credential-types", "aws-runtime", @@ -1247,9 +1248,9 @@ dependencies = [ [[package]] name = "aws-smithy-async" -version = "1.1.8" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d26ea8fa03025b2face2b3038a63525a10891e3d8829901d502e5384a0d8cd46" +checksum = "f7a41ccd6b74401a49ca828617049e5c23d83163d330a4f90a8081aadee0ac45" dependencies = [ "futures-util", "pin-project-lite", @@ -1311,11 +1312,11 @@ dependencies = [ "http 0.2.12", "http-body 0.4.6", "hyper 0.14.28", - "hyper-rustls", + "hyper-rustls 0.24.2", "once_cell", "pin-project-lite", "pin-utils", - "rustls", + "rustls 0.21.10", "tokio", "tracing", ] @@ -1860,9 +1861,9 @@ dependencies = [ [[package]] name = "chrono" -version = "0.4.35" +version = "0.4.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8eaf5903dcbc0a39312feb77df2ff4c76387d591b9fc7b04a238dcf8bb62639a" +checksum = "8a0d04d43504c61aa6c7531f1871dd0d418d91130162063b789da00fd7057a5e" dependencies = [ "android-tzdata", "iana-time-zone", @@ -1909,9 +1910,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.3" +version = "4.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "949626d00e063efc93b6dca932419ceb5432f99769911c0b995f7e884c778813" +checksum = "90bc066a67923782aa8515dbaea16946c5bcc5addbd668bb80af688e53e548a0" dependencies = [ "clap_builder", "clap_derive", @@ -1953,14 +1954,14 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.5.3" +version = "4.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90239a040c80f5e14809ca132ddc4176ab33d5e17e49691793296e3fcb34d72f" +checksum = "528131438037fd55894f62d6e9f068b8f45ac57ffa77517819645d10aed04f64" dependencies = [ "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -2401,7 +2402,7 @@ dependencies = [ "proc-macro2", "quote", "strsim 0.10.0", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -2412,7 +2413,7 @@ checksum = "a668eda54683121533a393014d8692171709ff57a7d61f187b6e782719f8933f" dependencies = [ "darling_core", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -2473,7 +2474,7 @@ checksum = "67e77553c4162a157adbf834ebae5b415acbecbeafc7a74b0e886657506a7611" dependencies = [ "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -2494,7 +2495,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -2504,7 +2505,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "206868b8242f27cecce124c19fd88157fbd0dd334df2587f36417bafbc85097b" dependencies = [ "derive_builder_core", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -2748,7 +2749,7 @@ checksum = "6fd000fd6988e73bbe993ea3db9b1aa64906ab88766d654973924340c8cddb42" dependencies = [ "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -2956,7 +2957,7 @@ dependencies = [ "regex", "serde", "serde_json", - "syn 2.0.53", + "syn 2.0.55", "toml 0.8.12", "walkdir", ] @@ -2974,7 +2975,7 @@ dependencies = [ "proc-macro2", "quote", "serde_json", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -3000,7 +3001,7 @@ dependencies = [ "serde", "serde_json", "strum 0.26.2", - "syn 2.0.53", + "syn 2.0.55", "tempfile", "thiserror", "tiny-keccak", @@ -3170,9 +3171,9 @@ dependencies = [ [[package]] name = "fastrand" -version = "2.0.1" +version = "2.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5" +checksum = "658bd65b1cf4c852a3cc96f18a8ce7b5640f6b703f905c7d74532294c2a63984" [[package]] name = "fastrlp" @@ -3195,7 +3196,7 @@ dependencies = [ "bytes", "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -3662,7 +3663,7 @@ dependencies = [ "pretty_assertions", "rand 0.8.5", "reqwest 0.11.27", - "reqwest 0.12.1", + "reqwest 0.12.2", "rustc-hash", "semver 1.0.22", "serde", @@ -3915,7 +3916,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -4088,7 +4089,7 @@ checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" dependencies = [ "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -4421,7 +4422,7 @@ dependencies = [ "bstr", "log", "regex-automata 0.4.6", - "regex-syntax 0.8.2", + "regex-syntax 0.8.3", ] [[package]] @@ -4478,9 +4479,9 @@ dependencies = [ [[package]] name = "handlebars" -version = "5.1.0" +version = "5.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab283476b99e66691dee3f1640fea91487a8d81f50fb5ecc75538f8f8879a1e4" +checksum = "d08485b96a0e6393e9e4d1b8d48cf74ad6c063cd905eb33f42c1ce3f0377539b" dependencies = [ "log", "pest", @@ -4744,39 +4745,40 @@ dependencies = [ "http 0.2.12", "hyper 0.14.28", "log", - "rustls", + "rustls 0.21.10", "rustls-native-certs", "tokio", - "tokio-rustls", + "tokio-rustls 0.24.1", ] [[package]] -name = "hyper-tls" -version = "0.5.0" +name = "hyper-rustls" +version = "0.26.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6183ddfa99b85da61a140bea0efc93fdf56ceaa041b37d553518030827f9905" +checksum = "a0bea761b46ae2b24eb4aef630d8d1c398157b6fc29e6350ecf090a0b70c952c" dependencies = [ - "bytes", - "hyper 0.14.28", - "native-tls", + "futures-util", + "http 1.1.0", + "hyper 1.2.0", + "hyper-util", + "rustls 0.22.3", + "rustls-pki-types", "tokio", - "tokio-native-tls", + "tokio-rustls 0.25.0", + "tower-service", ] [[package]] name = "hyper-tls" -version = "0.6.0" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" +checksum = "d6183ddfa99b85da61a140bea0efc93fdf56ceaa041b37d553518030827f9905" dependencies = [ "bytes", - "http-body-util", - "hyper 1.2.0", - "hyper-util", + "hyper 0.14.28", "native-tls", "tokio", "tokio-native-tls", - "tower-service", ] [[package]] @@ -5062,9 +5064,9 @@ dependencies = [ [[package]] name = "itoa" -version = "1.0.10" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1a46d1a171d865aa5f83f92695765caa047a9b4cbae2cbf37dbd613a793fd4c" +checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" [[package]] name = "jobserver" @@ -5186,7 +5188,7 @@ dependencies = [ "lalrpop-util", "petgraph", "regex", - "regex-syntax 0.8.2", + "regex-syntax 0.8.3", "string_cache", "term", "tiny-keccak", @@ -5421,7 +5423,7 @@ checksum = "49e7bc1560b95a3c4a25d03de42fe76ca718ab92d1a22a55b9b4cf67b3ae635c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -5688,7 +5690,7 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -5786,7 +5788,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -6002,7 +6004,7 @@ dependencies = [ "proc-macro2", "proc-macro2-diagnostics", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -6060,7 +6062,7 @@ dependencies = [ "pest_meta", "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -6163,7 +6165,7 @@ dependencies = [ "phf_shared 0.11.2", "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -6201,7 +6203,7 @@ checksum = "2f38a4412a78282e09a2cf38d195ea5420d15ba0602cb375210efbc877243965" dependencies = [ "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -6307,12 +6309,12 @@ dependencies = [ [[package]] name = "prettyplease" -version = "0.2.16" +version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a41cf62165e97c7f814d2221421dbb9afcbcdb0a88068e5ea206e19951c2cbb5" +checksum = "8d3928fb5db768cb86f891ff014f0144589297e3c6a1aba6ed7cecfdace270c7" dependencies = [ "proc-macro2", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -6407,7 +6409,7 @@ checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", "version_check", "yansi 1.0.1", ] @@ -6437,7 +6439,7 @@ dependencies = [ "rand 0.8.5", "rand_chacha 0.3.1", "rand_xorshift", - "regex-syntax 0.8.2", + "regex-syntax 0.8.3", "rusty-fork", "tempfile", "unarray", @@ -6623,9 +6625,9 @@ dependencies = [ [[package]] name = "rayon" -version = "1.9.0" +version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4963ed1bc86e4f3ee217022bd855b297cef07fb9eac5dfa1f788b220b49b3bd" +checksum = "b418a60154510ca1a002a752ca9714984e21e4241e804d32555251faf8b78ffa" dependencies = [ "either", "rayon-core", @@ -6684,7 +6686,7 @@ dependencies = [ "aho-corasick", "memchr", "regex-automata 0.4.6", - "regex-syntax 0.8.2", + "regex-syntax 0.8.3", ] [[package]] @@ -6704,7 +6706,7 @@ checksum = "86b83b8b9847f9bf95ef68afb0b8e6cdb80f498442f5179a29fad448fcc1eaea" dependencies = [ "aho-corasick", "memchr", - "regex-syntax 0.8.2", + "regex-syntax 0.8.3", ] [[package]] @@ -6721,9 +6723,9 @@ checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1" [[package]] name = "regex-syntax" -version = "0.8.2" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f" +checksum = "adad44e29e4c806119491a7f06f03de4d1af22c3a680dd47f1e6e179439d1f56" [[package]] name = "reqwest" @@ -6740,8 +6742,8 @@ dependencies = [ "http 0.2.12", "http-body 0.4.6", "hyper 0.14.28", - "hyper-rustls", - "hyper-tls 0.5.0", + "hyper-rustls 0.24.2", + "hyper-tls", "ipnet", "js-sys", "log", @@ -6750,7 +6752,7 @@ dependencies = [ "once_cell", "percent-encoding", "pin-project-lite", - "rustls", + "rustls 0.21.10", "rustls-native-certs", "rustls-pemfile", "serde", @@ -6760,21 +6762,21 @@ dependencies = [ "system-configuration", "tokio", "tokio-native-tls", - "tokio-rustls", + "tokio-rustls 0.24.1", "tower-service", "url", "wasm-bindgen", "wasm-bindgen-futures", "web-sys", - "webpki-roots", + "webpki-roots 0.25.4", "winreg", ] [[package]] name = "reqwest" -version = "0.12.1" +version = "0.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e333b1eb9fe677f6893a9efcb0d277a2d3edd83f358a236b657c32301dc6e5f6" +checksum = "2d66674f2b6fb864665eea7a3c1ac4e3dfacd2fda83cf6f935a612e01b0e3338" dependencies = [ "base64 0.21.7", "bytes", @@ -6784,28 +6786,30 @@ dependencies = [ "http-body 1.0.0", "http-body-util", "hyper 1.2.0", - "hyper-tls 0.6.0", + "hyper-rustls 0.26.0", "hyper-util", "ipnet", "js-sys", "log", "mime", - "native-tls", "once_cell", "percent-encoding", "pin-project-lite", + "rustls 0.22.3", "rustls-pemfile", + "rustls-pki-types", "serde", "serde_json", "serde_urlencoded", "sync_wrapper", "tokio", - "tokio-native-tls", + "tokio-rustls 0.25.0", "tower-service", "url", "wasm-bindgen", "wasm-bindgen-futures", "web-sys", + "webpki-roots 0.26.1", "winreg", ] @@ -7077,10 +7081,24 @@ checksum = "f9d5a6813c0759e4609cd494e8e725babae6a2ca7b62a5536a13daaec6fcb7ba" dependencies = [ "log", "ring 0.17.8", - "rustls-webpki", + "rustls-webpki 0.101.7", "sct", ] +[[package]] +name = "rustls" +version = "0.22.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99008d7ad0bbbea527ec27bddbc0e432c5b87d8175178cee68d2eec9c4a1813c" +dependencies = [ + "log", + "ring 0.17.8", + "rustls-pki-types", + "rustls-webpki 0.102.2", + "subtle", + "zeroize", +] + [[package]] name = "rustls-native-certs" version = "0.6.3" @@ -7102,6 +7120,12 @@ dependencies = [ "base64 0.21.7", ] +[[package]] +name = "rustls-pki-types" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecd36cc4259e3e4514335c4a138c6b43171a8d61d8f5c9348f9fc7529416f247" + [[package]] name = "rustls-webpki" version = "0.101.7" @@ -7112,6 +7136,17 @@ dependencies = [ "untrusted 0.9.0", ] +[[package]] +name = "rustls-webpki" +version = "0.102.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faaa0a62740bedb9b2ef5afa303da42764c012f743917351dc9a237ea1663610" +dependencies = [ + "ring 0.17.8", + "rustls-pki-types", + "untrusted 0.9.0", +] + [[package]] name = "rustversion" version = "1.0.14" @@ -7179,9 +7214,9 @@ dependencies = [ [[package]] name = "scale-info" -version = "2.11.0" +version = "2.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ef2175c2907e7c8bc0a9c3f86aeb5ec1f3b275300ad58a44d0c3ae379a5e52e" +checksum = "788745a868b0e751750388f4e6546eb921ef714a4317fa6954f7cde114eb2eb7" dependencies = [ "cfg-if", "derive_more", @@ -7191,9 +7226,9 @@ dependencies = [ [[package]] name = "scale-info-derive" -version = "2.11.0" +version = "2.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "634d9b8eb8fd61c5cdd3390d9b2132300a7e7618955b98b8416f118c1b4e144f" +checksum = "7dc2f4e8bc344b9fc3d5f74f72c2e55bfc38d28dc2ebc69c194a3df424e4d9ac" dependencies = [ "proc-macro-crate 1.3.1", "proc-macro2", @@ -7374,7 +7409,7 @@ checksum = "7eb0b34b42edc17f6b7cac84a52a1c5f0e1bb2227e997ca9011ea3dd34e8610b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -7390,9 +7425,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.114" +version = "1.0.115" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5f09b1bd632ef549eaa9f60a1f8de742bdbc698e6cee2095fc84dde5f549ae0" +checksum = "12dc5c46daa8e9fdf4f5e71b6cf9a53f2487da0e86e55808e2d35539666497dd" dependencies = [ "indexmap", "itoa", @@ -7428,7 +7463,7 @@ checksum = "0b2e6b945e9d3df726b65d6ee24060aff8e3533d431f677a9695db04eff9dfdb" dependencies = [ "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -7474,7 +7509,7 @@ checksum = "b93fb4adc70021ac1b47f7d45e8cc4169baaa7ea58483bc5b721d19a26202212" dependencies = [ "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -7758,7 +7793,7 @@ dependencies = [ "proc-macro2", "quote", "rustversion", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -7771,7 +7806,7 @@ dependencies = [ "proc-macro2", "quote", "rustversion", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -7789,9 +7824,9 @@ dependencies = [ [[package]] name = "subtle" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6bdef32e8150c2a081110b42772ffe7d7c9032b606bc226c8260fd97e0976601" +checksum = "81cdd64d312baedb58e21336b31bc043b77e01cc99033ce76ef539f78e965ebc" [[package]] name = "svm-rs" @@ -7839,9 +7874,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.53" +version = "2.0.55" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7383cd0e49fff4b6b90ca5670bfd3e9d6a733b3f90c686605aa7eec8c4996032" +checksum = "002a1b3dbf967edfafc32655d0f377ab0bb7b994aa1d32c8cc7e9b8bf3ebb8f0" dependencies = [ "proc-macro2", "quote", @@ -7856,7 +7891,7 @@ dependencies = [ "paste", "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -7978,7 +8013,7 @@ checksum = "c61f3ba182994efc43764a46c018c347bc492c79f024e705f46567b418f6d4f7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -8100,7 +8135,7 @@ checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -8119,7 +8154,18 @@ version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c28327cf380ac148141087fbfb9de9d7bd4e84ab5d2c28fbc911d753de8a7081" dependencies = [ - "rustls", + "rustls 0.21.10", + "tokio", +] + +[[package]] +name = "tokio-rustls" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "775e0c0f0adb3a2f22a00c4745d728b479985fc15ee7ca6a2608388c5569860f" +dependencies = [ + "rustls 0.22.3", + "rustls-pki-types", "tokio", ] @@ -8143,11 +8189,11 @@ checksum = "212d5dcb2a1ce06d81107c3d0ffa3121fe974b73f068c8282cb1c32328113b6c" dependencies = [ "futures-util", "log", - "rustls", + "rustls 0.21.10", "tokio", - "tokio-rustls", + "tokio-rustls 0.24.1", "tungstenite", - "webpki-roots", + "webpki-roots 0.25.4", ] [[package]] @@ -8321,7 +8367,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -8448,7 +8494,7 @@ dependencies = [ "httparse", "log", "rand 0.8.5", - "rustls", + "rustls 0.21.10", "sha1", "thiserror", "url", @@ -8602,9 +8648,9 @@ dependencies = [ [[package]] name = "uuid" -version = "1.7.0" +version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f00cc9702ca12d3c81455259621e676d0f7251cec66a21e98fe2e9a37db93b2a" +checksum = "a183cf7feeba97b4dd1c0d46788634f6221d87fa961b305bed08c851829efcc0" [[package]] name = "valuable" @@ -8703,7 +8749,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", "wasm-bindgen-shared", ] @@ -8737,7 +8783,7 @@ checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -8812,6 +8858,15 @@ version = "0.25.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5f20c57d8d7db6d3b86154206ae5d8fba62dd39573114de97c2cb0578251f8e1" +[[package]] +name = "webpki-roots" +version = "0.26.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3de34ae270483955a94f4b21bdaaeb83d508bb84a01435f393818edb0012009" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "which" version = "4.4.2" @@ -9162,7 +9217,7 @@ checksum = "9ce1b18ccd8e73a9321186f97e46f9f04b778851177567b1975109d26a08d2a6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -9182,7 +9237,7 @@ checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" dependencies = [ "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -9226,9 +9281,9 @@ dependencies = [ [[package]] name = "zstd-sys" -version = "2.0.9+zstd.1.5.5" +version = "2.0.10+zstd.1.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e16efa8a874a0481a574084d34cc26fdb3b99627480f785888deb6386506656" +checksum = "c253a4914af5bafc8fa8c86ee400827e83cf6ec01195ec1f1ed8441bf00d65aa" dependencies = [ "cc", "pkg-config", diff --git a/crates/common/Cargo.toml b/crates/common/Cargo.toml index 9b2de72bd265..632b9ec8e81a 100644 --- a/crates/common/Cargo.toml +++ b/crates/common/Cargo.toml @@ -19,7 +19,7 @@ ethers-middleware.workspace = true ethers-providers = { workspace = true, features = ["ws", "ipc"] } ethers-signers.workspace = true # should be removed along with ethers -reqwest_ethers = { package = "reqwest", version = "0.11" } +reqwest_ethers = { package = "reqwest", version = "0.11", default-features = false } alloy-dyn-abi = { workspace = true, features = ["arbitrary", "eip712"] } alloy-json-abi.workspace = true @@ -34,7 +34,7 @@ alloy-rpc-client.workspace = true alloy-provider.workspace = true alloy-transport.workspace = true alloy-signer-wallet.workspace = true -alloy-transport-http = { workspace = true, features = ["reqwest-default-tls"] } +alloy-transport-http = { workspace = true, features = ["reqwest-rustls-tls"] } alloy-transport-ws.workspace = true alloy-transport-ipc.workspace = true alloy-json-rpc.workspace = true From c8781e5fc995833664c92645bf30fec44ed68b91 Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Wed, 27 Mar 2024 20:57:47 +0400 Subject: [PATCH 38/63] fix persist --- crates/evm/fuzz/src/strategies/state.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/evm/fuzz/src/strategies/state.rs b/crates/evm/fuzz/src/strategies/state.rs index a01c5566810b..dfc250465ceb 100644 --- a/crates/evm/fuzz/src/strategies/state.rs +++ b/crates/evm/fuzz/src/strategies/state.rs @@ -93,7 +93,11 @@ pub fn build_initial_state( ) -> EvmFuzzState { let mut state = FuzzDictionary::default(); - for (address, account) in db.accounts.iter() { + // Sort accounts to ensure deterministic dictionary generation from the same setUp state. + let mut accs = db.accounts.iter().collect::>(); + accs.sort_by_key(|(address, _)| *address); + + for (address, account) in accs { let address: Address = *address; // Insert basic account information state.values_mut().insert(address.into_word().into()); From 9760679b6c63ffbd00b236904fd7eac851abe1f9 Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Wed, 27 Mar 2024 21:49:57 +0400 Subject: [PATCH 39/63] fix doctests --- crates/anvil/src/tasks/mod.rs | 13 ++++++++----- crates/cast/src/lib.rs | 10 ++++------ 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/crates/anvil/src/tasks/mod.rs b/crates/anvil/src/tasks/mod.rs index 8a3000b00b44..d39a5d3c3782 100644 --- a/crates/anvil/src/tasks/mod.rs +++ b/crates/anvil/src/tasks/mod.rs @@ -53,13 +53,14 @@ impl TaskManager { /// /// ``` /// use anvil::{spawn, NodeConfig}; - /// use ethers::providers::Provider; - /// use std::sync::Arc; + /// use alloy_provider::RootProvider; + /// use alloy_network::Ethereum; + /// /// # async fn t() { /// let endpoint = "http://...."; /// let (api, handle) = spawn(NodeConfig::default().with_eth_rpc_url(Some(endpoint))).await; /// - /// let provider = Arc::new(Provider::try_from(endpoint).unwrap()); + /// let provider = RootProvider::::connect_builtin(endpoint).await.unwrap(); /// /// handle.task_manager().spawn_reset_on_new_polled_blocks(provider, api); /// # } @@ -112,11 +113,13 @@ impl TaskManager { /// /// ``` /// use anvil::{spawn, NodeConfig}; - /// use ethers::providers::Provider; + /// use alloy_provider::RootProvider; + /// use alloy_network::Ethereum; + /// /// # async fn t() { /// let (api, handle) = spawn(NodeConfig::default().with_eth_rpc_url(Some("http://...."))).await; /// - /// let provider = Provider::connect("ws://...").await.unwrap(); + /// let provider = RootProvider::::connect_builtin("ws://...").await.unwrap(); /// /// handle.task_manager().spawn_reset_on_subscribed_blocks(provider, api); /// diff --git a/crates/cast/src/lib.rs b/crates/cast/src/lib.rs index a7627d1a3126..dac565365340 100644 --- a/crates/cast/src/lib.rs +++ b/crates/cast/src/lib.rs @@ -74,13 +74,11 @@ where /// /// ``` /// use cast::Cast; - /// use ethers_providers::{Http, Provider}; /// use foundry_common::provider::alloy::get_http_provider; /// /// # async fn foo() -> eyre::Result<()> { - /// let provider = Provider::::try_from("http://localhost:8545")?; - /// let alloy_provider = get_http_provider("http://localhost:8545"); - /// let cast = Cast::new(provider, alloy_provider); + /// let provider = get_http_provider("http://localhost:8545"); + /// let cast = Cast::new(provider); /// # Ok(()) /// # } /// ``` @@ -1982,8 +1980,8 @@ impl SimpleCast { /// ``` /// use cast::SimpleCast as Cast; /// - /// let tx = "0x02f8f582a86a82058d8459682f008508351050808303fd84948e42f2f4101563bf679975178e880fd87d3efd4e80b884659ac74b00000000000000000000000080f0c1c49891dcfdd40b6e0f960f84e6042bcb6f000000000000000000000000b97ef9ef8734c71904d8002f8b6bc66dd9c48a6e00000000000000000000000000000000000000000000000000000000007ff4e20000000000000000000000000000000000000000000000000000000000000064c001a05d429597befe2835396206781b199122f2e8297327ed4a05483339e7a8b2022aa04c23a7f70fb29dda1b4ee342fb10a625e9b8ddc6a603fb4e170d4f6f37700cb8"; - /// let (tx, sig) = Cast::decode_raw_transaction(&tx)?; + /// let tx = "0x02f8f582a86a82058d8459682f008508351050808303fd84948e42f2f4101563bf679975178e880fd87d3efd4e80b884659ac74b00000000000000000000000080f0c1c49891dcfdd40b6e0f960f84e6042bcb6f000000000000000000000000b97ef9ef8734c71904d8002f8b6bc66dd9c48a6e00000000000000000000000000000000000000000000000000000000007ff4e20000000000000000000000000000000000000000000000000000000000000064c001a05d429597befe2835396206781b199122f2e8297327ed4a05483339e7a8b2022aa04c23a7f70fb29dda1b4ee342fb10a625e9b8ddc6a603fb4e170d4f6f37700cb8"; + /// let tx_envelope = Cast::decode_raw_transaction(&tx)?; /// # Ok::<(), eyre::Report>(()) pub fn decode_raw_transaction(tx: &str) -> Result { let tx_hex = hex::decode(strip_0x(tx))?; From f93a140ea085af3087517d5a7b99ebaf389b3297 Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Wed, 27 Mar 2024 21:55:08 +0400 Subject: [PATCH 40/63] fmt --- crates/anvil/src/tasks/mod.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/anvil/src/tasks/mod.rs b/crates/anvil/src/tasks/mod.rs index d39a5d3c3782..7d1cfa727798 100644 --- a/crates/anvil/src/tasks/mod.rs +++ b/crates/anvil/src/tasks/mod.rs @@ -52,10 +52,10 @@ impl TaskManager { /// block /// /// ``` - /// use anvil::{spawn, NodeConfig}; - /// use alloy_provider::RootProvider; /// use alloy_network::Ethereum; - /// + /// use alloy_provider::RootProvider; + /// use anvil::{spawn, NodeConfig}; + /// /// # async fn t() { /// let endpoint = "http://...."; /// let (api, handle) = spawn(NodeConfig::default().with_eth_rpc_url(Some(endpoint))).await; @@ -112,10 +112,10 @@ impl TaskManager { /// block /// /// ``` - /// use anvil::{spawn, NodeConfig}; - /// use alloy_provider::RootProvider; /// use alloy_network::Ethereum; - /// + /// use alloy_provider::RootProvider; + /// use anvil::{spawn, NodeConfig}; + /// /// # async fn t() { /// let (api, handle) = spawn(NodeConfig::default().with_eth_rpc_url(Some("http://...."))).await; /// From 7740eb1648542c44f3ec651b149585b3959a0abd Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Thu, 28 Mar 2024 17:06:18 +0400 Subject: [PATCH 41/63] fix clap --- crates/cast/bin/cmd/mktx.rs | 4 ++-- crates/cast/bin/opts.rs | 24 ++++++++++++------------ 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/crates/cast/bin/cmd/mktx.rs b/crates/cast/bin/cmd/mktx.rs index f34dbcfa5509..9c402c4768b2 100644 --- a/crates/cast/bin/cmd/mktx.rs +++ b/crates/cast/bin/cmd/mktx.rs @@ -2,7 +2,7 @@ use crate::tx; use alloy_network::{eip2718::Encodable2718, EthereumSigner, TransactionBuilder}; use alloy_provider::Provider; use alloy_signer::Signer; -use clap::Parser; +use clap::{Parser, Subcommand}; use eyre::Result; use foundry_cli::{ opts::{EthereumOpts, TransactionOpts}, @@ -44,7 +44,7 @@ pub struct MakeTxArgs { #[derive(Debug, Parser)] pub enum MakeTxSubcommands { /// Use to deploy raw contract bytecode. - #[clap(name = "--create")] + #[command(name = "--create")] Create { /// The initialization bytecode of the contract to deploy. code: String, diff --git a/crates/cast/bin/opts.rs b/crates/cast/bin/opts.rs index 628c3430e625..51f32b145c83 100644 --- a/crates/cast/bin/opts.rs +++ b/crates/cast/bin/opts.rs @@ -525,11 +525,11 @@ pub enum CastSubcommand { /// The block height to query at. /// /// Can also be the tags earliest, finalized, safe, latest, or pending. - #[clap(long, short = 'B')] + #[arg(long, short = 'B')] block: Option, /// The address to get the nonce for. - #[clap(value_parser = NameOrAddress::from_str)] + #[arg(value_parser = NameOrAddress::from_str)] who: NameOrAddress, #[command(flatten)] @@ -542,11 +542,11 @@ pub enum CastSubcommand { /// The block height to query at. /// /// Can also be the tags earliest, finalized, safe, latest, or pending. - #[clap(long, short = 'B')] + #[arg(long, short = 'B')] block: Option, /// The address to get the nonce for. - #[clap(value_parser = NameOrAddress::from_str)] + #[arg(value_parser = NameOrAddress::from_str)] who: NameOrAddress, #[command(flatten)] @@ -622,11 +622,11 @@ pub enum CastSubcommand { /// The block height to query at. /// /// Can also be the tags earliest, finalized, safe, latest, or pending. - #[clap(long, short = 'B')] + #[arg(long, short = 'B')] block: Option, /// The account to query. - #[clap(value_parser = NameOrAddress::from_str)] + #[arg(value_parser = NameOrAddress::from_str)] who: NameOrAddress, /// Format the balance in ether. @@ -660,11 +660,11 @@ pub enum CastSubcommand { /// The block height to query at. /// /// Can also be the tags earliest, finalized, safe, latest, or pending. - #[clap(long, short = 'B')] + #[arg(long, short = 'B')] block: Option, /// The contract address. - #[clap(value_parser = NameOrAddress::from_str)] + #[arg(value_parser = NameOrAddress::from_str)] who: NameOrAddress, /// Disassemble bytecodes into individual opcodes. @@ -681,11 +681,11 @@ pub enum CastSubcommand { /// The block height to query at. /// /// Can also be the tags earliest, finalized, safe, latest, or pending. - #[clap(long, short = 'B')] + #[arg(long, short = 'B')] block: Option, /// The contract address. - #[clap(value_parser = NameOrAddress::from_str)] + #[arg(value_parser = NameOrAddress::from_str)] who: NameOrAddress, #[command(flatten)] @@ -772,11 +772,11 @@ pub enum CastSubcommand { /// The block height to query at. /// /// Can also be the tags earliest, finalized, safe, latest, or pending. - #[clap(long, short = 'B')] + #[arg(long, short = 'B')] block: Option, /// The address to get the nonce for. - #[clap(value_parser = NameOrAddress::from_str)] + #[arg(value_parser = NameOrAddress::from_str)] who: NameOrAddress, #[command(flatten)] From 2800a41541cfc6ae629ae48d1a315228d3d3fef2 Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Thu, 28 Mar 2024 18:06:06 +0400 Subject: [PATCH 42/63] review fixes --- crates/cast/bin/cmd/mktx.rs | 2 +- crates/cast/bin/main.rs | 10 +-- crates/cheatcodes/src/fs.rs | 3 +- crates/common/src/ens.rs | 120 +++++++++++++++++++----------------- 4 files changed, 71 insertions(+), 64 deletions(-) diff --git a/crates/cast/bin/cmd/mktx.rs b/crates/cast/bin/cmd/mktx.rs index 9c402c4768b2..3317ff9c6c70 100644 --- a/crates/cast/bin/cmd/mktx.rs +++ b/crates/cast/bin/cmd/mktx.rs @@ -2,7 +2,7 @@ use crate::tx; use alloy_network::{eip2718::Encodable2718, EthereumSigner, TransactionBuilder}; use alloy_provider::Provider; use alloy_signer::Signer; -use clap::{Parser, Subcommand}; +use clap::Parser; use eyre::Result; use foundry_cli::{ opts::{EthereumOpts, TransactionOpts}, diff --git a/crates/cast/bin/main.rs b/crates/cast/bin/main.rs index 5f3ca57c94cf..ce8d1d5d735c 100644 --- a/crates/cast/bin/main.rs +++ b/crates/cast/bin/main.rs @@ -11,7 +11,7 @@ use eyre::Result; use foundry_cli::{handler, prompt, stdin, utils}; use foundry_common::{ abi::get_event, - ens::{lookup_address, resolve_name}, + ens::ProviderEnsExt, fmt::{format_tokens, format_uint_exp}, fs, selectors::{ @@ -449,9 +449,9 @@ async fn main() -> Result<()> { let provider = utils::get_alloy_provider(&config)?; let who = stdin::unwrap_line(who)?; - let name = lookup_address(who, &provider).await?; + let name = provider.lookup_address(who).await?; if verify { - let address = resolve_name(&name, &provider).await?; + let address = provider.resolve_name(&name).await?; eyre::ensure!( address == who, "Forward lookup verification failed: got `{name:?}`, expected `{who:?}`" @@ -464,9 +464,9 @@ async fn main() -> Result<()> { let provider = utils::get_alloy_provider(&config)?; let who = stdin::unwrap_line(who)?; - let address = resolve_name(&who, &provider).await?; + let address = provider.resolve_name(&who).await?; if verify { - let name = lookup_address(address, &provider).await?; + let name = provider.lookup_address(address).await?; assert_eq!( name, who, "forward lookup verification failed. got {name}, expected {who}" diff --git a/crates/cheatcodes/src/fs.rs b/crates/cheatcodes/src/fs.rs index a56a6de78cef..e533dfd670d7 100644 --- a/crates/cheatcodes/src/fs.rs +++ b/crates/cheatcodes/src/fs.rs @@ -422,10 +422,9 @@ fn prompt( #[cfg(test)] mod tests { - use alloy_primitives::Bytes; - use super::*; use crate::CheatsConfig; + use alloy_primitives::Bytes; use std::{path::PathBuf, sync::Arc}; fn cheats() -> Cheatcodes { diff --git a/crates/common/src/ens.rs b/crates/common/src/ens.rs index 5e1726dff8a1..62674690f49f 100644 --- a/crates/common/src/ens.rs +++ b/crates/common/src/ens.rs @@ -4,6 +4,7 @@ use alloy_primitives::{address, keccak256, Address, B256}; use alloy_provider::{Network, Provider}; use alloy_sol_types::sol; use alloy_transport::Transport; +use async_trait::async_trait; use std::str::FromStr; use self::EnsResolver::EnsResolverInstance; @@ -33,6 +34,17 @@ pub const ENS_ADDRESS: Address = address!("00000000000C2E074eC69A0dFb2997BA6C7d2 pub const ENS_REVERSE_REGISTRAR_DOMAIN: &str = "addr.reverse"; +/// Error type for ENS resolution. +#[derive(Debug, thiserror::Error)] +pub enum EnsResolutionError { + /// Failed to resolve ENS registry. + #[error("Failed to get resolver from ENS registry: {0}")] + EnsRegistryResolutionFailed(String), + /// Failed to resolve ENS name to an address. + #[error("Failed to resolve ENS name to an address: {0}")] + EnsResolutionFailed(String), +} + /// ENS name or Ethereum Address. #[derive(Clone, Debug, PartialEq, Eq)] pub enum NameOrAddress { @@ -49,7 +61,7 @@ impl NameOrAddress { provider: &P, ) -> Result { match self { - NameOrAddress::Name(name) => resolve_name(name, provider).await, + NameOrAddress::Name(name) => provider.resolve_name(name).await, NameOrAddress::Address(addr) => Ok(*addr), } } @@ -85,15 +97,57 @@ impl FromStr for NameOrAddress { } } -/// Error type for ENS resolution. -#[derive(Debug, thiserror::Error)] -pub enum EnsResolutionError { - /// Failed to resolve ENS registry. - #[error("Failed to get resolver from ENS registry: {0}")] - EnsRegistryResolutionFailed(String), - /// Failed to resolve ENS name to an address. - #[error("Failed to resolve ENS name to an address: {0}")] - EnsResolutionFailed(String), +#[async_trait] +pub trait ProviderEnsExt> { + async fn get_resolver(&self) -> Result, EnsResolutionError>; + + async fn resolve_name(&self, name: &str) -> Result { + let node = namehash(name); + let addr = self + .get_resolver() + .await? + .addr(node) + .call() + .await + .map_err(|err| EnsResolutionError::EnsResolutionFailed(err.to_string()))? + ._0; + + Ok(addr) + } + + async fn lookup_address(&self, address: Address) -> Result { + let node = namehash(&reverse_address(address)); + let name = self + .get_resolver() + .await? + .name(node) + .call() + .await + .map_err(|err| EnsResolutionError::EnsResolutionFailed(err.to_string()))? + ._0; + + Ok(name) + } +} + +#[async_trait] +impl ProviderEnsExt for P +where + P: Provider, + N: Network, + T: Transport + Clone, +{ + async fn get_resolver(&self) -> Result, EnsResolutionError> { + let registry = EnsRegistry::new(ENS_ADDRESS, self); + let address = registry + .resolver(namehash("eth")) + .call() + .await + .map_err(|err| EnsResolutionError::EnsRegistryResolutionFailed(err.to_string()))? + ._0; + + Ok(EnsResolverInstance::new(address, self)) + } } /// Returns the ENS namehash as specified in [EIP-137](https://eips.ethereum.org/EIPS/eip-137) @@ -116,52 +170,6 @@ pub fn reverse_address(addr: Address) -> String { format!("{addr:?}.{ENS_REVERSE_REGISTRAR_DOMAIN}")[2..].to_string() } -pub async fn get_resolver>( - node: B256, - provider: &P, -) -> Result, EnsResolutionError> { - let registry = EnsRegistry::new(ENS_ADDRESS, provider); - let address = registry - .resolver(node) - .call() - .await - .map_err(|err| EnsResolutionError::EnsRegistryResolutionFailed(err.to_string()))? - ._0; - - Ok(EnsResolver::new(address, provider)) -} - -pub async fn resolve_name>( - name: &str, - provider: &P, -) -> Result { - let node = namehash(name); - let resolver = get_resolver(node, provider).await?; - let addr = resolver - .addr(node) - .call() - .await - .map_err(|err| EnsResolutionError::EnsResolutionFailed(err.to_string()))? - ._0; - - Ok(addr) -} - -pub async fn lookup_address>( - address: Address, - provider: &P, -) -> Result { - let node = namehash(&reverse_address(address)); - let resolver = get_resolver(node, provider).await?; - let name = resolver - .name(node) - .call() - .await - .map_err(|err| EnsResolutionError::EnsResolutionFailed(err.to_string()))? - ._0; - - Ok(name) -} #[cfg(test)] mod test { use super::*; From 3ccde5bb08585ffd9ef2949ed012c867a85fa3e9 Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Thu, 28 Mar 2024 18:26:24 +0400 Subject: [PATCH 43/63] fmt --- crates/cheatcodes/src/utils.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/cheatcodes/src/utils.rs b/crates/cheatcodes/src/utils.rs index 9490a983a4d0..7544abc0a624 100644 --- a/crates/cheatcodes/src/utils.rs +++ b/crates/cheatcodes/src/utils.rs @@ -1,8 +1,8 @@ //! Implementations of [`Utils`](crate::Group::Utils) cheatcodes. use crate::{Cheatcode, Cheatcodes, CheatsCtxt, DatabaseExt, Result, Vm::*}; -use alloy_signer::{Signer, SignerSync}; use alloy_primitives::{keccak256, Address, B256, U256}; +use alloy_signer::{Signer, SignerSync}; use alloy_signer_wallet::{ coins_bip39::{ ChineseSimplified, ChineseTraditional, Czech, English, French, Italian, Japanese, Korean, From 3d4373d828d51f1c7faa97b7734e3b2b7e54c09d Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Thu, 4 Apr 2024 06:02:41 +0400 Subject: [PATCH 44/63] bump alloy --- Cargo.lock | 141 ++++----- Cargo.toml | 65 ++--- crates/anvil/Cargo.toml | 14 +- crates/anvil/core/Cargo.toml | 10 +- crates/anvil/core/src/eth/mod.rs | 18 +- crates/anvil/core/src/eth/transaction/mod.rs | 286 ++++++++++++------- crates/anvil/src/config.rs | 3 +- crates/anvil/src/eth/api.rs | 48 ++-- crates/anvil/src/eth/backend/executor.rs | 75 ++--- crates/anvil/src/eth/backend/fork.rs | 26 +- crates/anvil/src/eth/backend/mem/mod.rs | 210 ++++++-------- crates/anvil/src/eth/backend/mem/storage.rs | 12 +- crates/anvil/src/eth/fees.rs | 4 +- crates/anvil/src/eth/otterscan/api.rs | 8 +- crates/anvil/src/eth/otterscan/types.rs | 30 +- crates/anvil/src/pubsub.rs | 47 ++- crates/anvil/src/tasks/mod.rs | 9 +- crates/anvil/tests/it/api.rs | 6 +- crates/anvil/tests/it/fork.rs | 10 +- crates/anvil/tests/it/transaction.rs | 12 +- crates/cast/bin/cmd/access_list.rs | 4 +- crates/cast/bin/cmd/send.rs | 2 +- crates/cast/bin/cmd/storage.rs | 6 +- crates/cast/bin/tx.rs | 4 +- crates/cast/src/lib.rs | 6 +- crates/cheatcodes/src/evm/fork.rs | 12 +- crates/cli/src/utils/abi.rs | 6 +- crates/cli/src/utils/mod.rs | 4 +- crates/common/Cargo.toml | 3 +- crates/common/src/ens.rs | 12 +- crates/common/src/fmt/ui.rs | 87 ++++-- crates/common/src/provider/alloy.rs | 4 +- crates/common/src/transactions.rs | 14 +- crates/config/Cargo.toml | 2 +- crates/evm/core/src/fork/backend.rs | 12 +- crates/evm/core/src/fork/init.rs | 2 +- crates/forge/bin/cmd/create.rs | 6 +- crates/script/src/broadcast.rs | 23 +- crates/script/src/receipts.rs | 13 +- 39 files changed, 661 insertions(+), 595 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0ab894ebf350..aad1b7023d8a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -90,7 +90,7 @@ dependencies = [ [[package]] name = "alloy-consensus" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" +source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" dependencies = [ "alloy-eips", "alloy-primitives", @@ -105,7 +105,7 @@ dependencies = [ [[package]] name = "alloy-contract" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" +source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" dependencies = [ "alloy-dyn-abi", "alloy-json-abi", @@ -122,8 +122,9 @@ dependencies = [ [[package]] name = "alloy-dyn-abi" -version = "0.6.4" -source = "git+https://github.com/alloy-rs/core?rev=ff339696fa9b490698cb3edec3d4647fae0bd332#ff339696fa9b490698cb3edec3d4647fae0bd332" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872f239c15befa27cc4f0d3d82a70b3365c2d0202562bf906eb93b299fa31882" dependencies = [ "alloy-json-abi", "alloy-primitives", @@ -143,7 +144,7 @@ dependencies = [ [[package]] name = "alloy-eips" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" +source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -157,7 +158,7 @@ dependencies = [ [[package]] name = "alloy-genesis" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" +source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" dependencies = [ "alloy-primitives", "alloy-serde", @@ -166,8 +167,9 @@ dependencies = [ [[package]] name = "alloy-json-abi" -version = "0.6.4" -source = "git+https://github.com/alloy-rs/core?rev=ff339696fa9b490698cb3edec3d4647fae0bd332#ff339696fa9b490698cb3edec3d4647fae0bd332" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83a35ddfd27576474322a5869e4c123e5f3e7b2177297c18e4e82ea501cb125b" dependencies = [ "alloy-primitives", "alloy-sol-type-parser", @@ -178,7 +180,7 @@ dependencies = [ [[package]] name = "alloy-json-rpc" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" +source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" dependencies = [ "alloy-primitives", "serde", @@ -189,7 +191,7 @@ dependencies = [ [[package]] name = "alloy-network" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" +source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" dependencies = [ "alloy-consensus", "alloy-eips", @@ -205,8 +207,9 @@ dependencies = [ [[package]] name = "alloy-primitives" -version = "0.6.4" -source = "git+https://github.com/alloy-rs/core?rev=ff339696fa9b490698cb3edec3d4647fae0bd332#ff339696fa9b490698cb3edec3d4647fae0bd332" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99bbad0a6b588ef4aec1b5ddbbfdacd9ef04e00b979617765b03174318ee1f3a" dependencies = [ "alloy-rlp", "arbitrary", @@ -232,24 +235,22 @@ dependencies = [ [[package]] name = "alloy-provider" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" +source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" dependencies = [ "alloy-json-rpc", "alloy-network", "alloy-primitives", "alloy-pubsub", "alloy-rpc-client", - "alloy-rpc-trace-types", "alloy-rpc-types", + "alloy-rpc-types-trace", "alloy-transport", - "alloy-transport-http", "async-stream", "async-trait", "auto_impl", "dashmap", "futures", "lru", - "reqwest 0.12.2", "serde_json", "tokio", "tracing", @@ -258,7 +259,7 @@ dependencies = [ [[package]] name = "alloy-pubsub" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" +source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" dependencies = [ "alloy-json-rpc", "alloy-primitives", @@ -298,7 +299,7 @@ dependencies = [ [[package]] name = "alloy-rpc-client" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" +source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" dependencies = [ "alloy-json-rpc", "alloy-primitives", @@ -307,48 +308,48 @@ dependencies = [ "alloy-transport-http", "futures", "pin-project", - "reqwest 0.12.2", "serde", "serde_json", "tokio", "tokio-stream", "tower", "tracing", - "url", ] [[package]] -name = "alloy-rpc-trace-types" +name = "alloy-rpc-types" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" +source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" dependencies = [ + "alloy-consensus", + "alloy-eips", + "alloy-genesis", "alloy-primitives", - "alloy-rpc-types", + "alloy-rlp", "alloy-serde", + "alloy-sol-types", + "itertools 0.12.1", "serde", "serde_json", + "thiserror", ] [[package]] -name = "alloy-rpc-types" +name = "alloy-rpc-types-trace" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" +source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" dependencies = [ - "alloy-consensus", - "alloy-eips", "alloy-primitives", - "alloy-rlp", + "alloy-rpc-types", "alloy-serde", - "itertools 0.12.1", "serde", "serde_json", - "thiserror", ] [[package]] name = "alloy-serde" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" +source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" dependencies = [ "alloy-primitives", "serde", @@ -358,7 +359,7 @@ dependencies = [ [[package]] name = "alloy-signer" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" +source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" dependencies = [ "alloy-dyn-abi", "alloy-primitives", @@ -373,7 +374,7 @@ dependencies = [ [[package]] name = "alloy-signer-aws" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" +source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" dependencies = [ "alloy-consensus", "alloy-network", @@ -390,7 +391,7 @@ dependencies = [ [[package]] name = "alloy-signer-ledger" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" +source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" dependencies = [ "alloy-consensus", "alloy-network", @@ -407,7 +408,7 @@ dependencies = [ [[package]] name = "alloy-signer-trezor" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" +source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" dependencies = [ "alloy-consensus", "alloy-network", @@ -423,7 +424,7 @@ dependencies = [ [[package]] name = "alloy-signer-wallet" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" +source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" dependencies = [ "alloy-consensus", "alloy-network", @@ -441,8 +442,9 @@ dependencies = [ [[package]] name = "alloy-sol-macro" -version = "0.6.4" -source = "git+https://github.com/alloy-rs/core?rev=ff339696fa9b490698cb3edec3d4647fae0bd332#ff339696fa9b490698cb3edec3d4647fae0bd332" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "452d929748ac948a10481fff4123affead32c553cf362841c5103dd508bdfc16" dependencies = [ "alloy-json-abi", "alloy-sol-macro-input", @@ -459,8 +461,9 @@ dependencies = [ [[package]] name = "alloy-sol-macro-input" -version = "0.6.4" -source = "git+https://github.com/alloy-rs/core?rev=ff339696fa9b490698cb3edec3d4647fae0bd332#ff339696fa9b490698cb3edec3d4647fae0bd332" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df64e094f6d2099339f9e82b5b38440b159757b6920878f28316243f8166c8d1" dependencies = [ "alloy-json-abi", "const-hex", @@ -475,16 +478,18 @@ dependencies = [ [[package]] name = "alloy-sol-type-parser" -version = "0.6.4" -source = "git+https://github.com/alloy-rs/core?rev=ff339696fa9b490698cb3edec3d4647fae0bd332#ff339696fa9b490698cb3edec3d4647fae0bd332" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "715f4d09a330cc181fc7c361b5c5c2766408fa59a0bac60349dcb7baabd404cc" dependencies = [ "winnow 0.6.5", ] [[package]] name = "alloy-sol-types" -version = "0.6.4" -source = "git+https://github.com/alloy-rs/core?rev=ff339696fa9b490698cb3edec3d4647fae0bd332#ff339696fa9b490698cb3edec3d4647fae0bd332" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43bc2d6dfc2a19fd56644494479510f98b1ee929e04cf0d4aa45e98baa3e545b" dependencies = [ "alloy-json-abi", "alloy-primitives", @@ -496,7 +501,7 @@ dependencies = [ [[package]] name = "alloy-transport" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" +source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" dependencies = [ "alloy-json-rpc", "base64 0.22.0", @@ -514,7 +519,7 @@ dependencies = [ [[package]] name = "alloy-transport-http" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" +source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" dependencies = [ "alloy-json-rpc", "alloy-transport", @@ -527,7 +532,7 @@ dependencies = [ [[package]] name = "alloy-transport-ipc" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" +source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" dependencies = [ "alloy-json-rpc", "alloy-pubsub", @@ -545,7 +550,7 @@ dependencies = [ [[package]] name = "alloy-transport-ws" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=27a1e36#27a1e36bf5037100fcfdb31f378a16c8ac2c87ec" +source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" dependencies = [ "alloy-pubsub", "alloy-transport", @@ -653,8 +658,8 @@ dependencies = [ "alloy-primitives", "alloy-provider", "alloy-rlp", - "alloy-rpc-trace-types", "alloy-rpc-types", + "alloy-rpc-types-trace", "alloy-signer", "alloy-signer-wallet", "alloy-sol-types", @@ -717,8 +722,8 @@ dependencies = [ "alloy-network", "alloy-primitives", "alloy-rlp", - "alloy-rpc-trace-types", "alloy-rpc-types", + "alloy-rpc-types-trace", "anvil-core", "bytes", "c-kzg", @@ -3527,15 +3532,13 @@ dependencies = [ [[package]] name = "foundry-block-explorers" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a056d4aa33a639c0aa1e9e473c25b9b191be30cbea94b31445fac5c272418ae" +version = "0.2.4" dependencies = [ "alloy-chains", "alloy-json-abi", "alloy-primitives", "foundry-compilers", - "reqwest 0.11.27", + "reqwest 0.12.2", "semver 1.0.22", "serde", "serde_json", @@ -3632,6 +3635,7 @@ dependencies = [ name = "foundry-common" version = "0.2.0" dependencies = [ + "alloy-consensus", "alloy-contract", "alloy-dyn-abi", "alloy-json-abi", @@ -3685,8 +3689,6 @@ dependencies = [ [[package]] name = "foundry-compilers" version = "0.3.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "079ada1a2093e0fec67caa15ccf018a2d1b5747c16ba1c11a28df53530eb1a5f" dependencies = [ "alloy-json-abi", "alloy-primitives", @@ -3738,7 +3740,7 @@ dependencies = [ "path-slash", "pretty_assertions", "regex", - "reqwest 0.11.27", + "reqwest 0.12.2", "revm-primitives", "semver 1.0.22", "serde", @@ -6819,9 +6821,9 @@ dependencies = [ [[package]] name = "revm" -version = "7.2.0" +version = "8.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24fd3ed4b62dc61c647552d8b781811ae25ec74d23309055077e4dfb392444d2" +checksum = "72a454c1c650b2b2e23f0c461af09e6c31e1d15e1cbebe905a701c46b8a50afc" dependencies = [ "auto_impl", "cfg-if", @@ -6835,11 +6837,11 @@ dependencies = [ [[package]] name = "revm-inspectors" version = "0.1.0" -source = "git+https://github.com/klkvr/evm-inspectors?rev=9ff0c29#9ff0c29d3a1b8feee1c6176a58a4a485723f7a4c" +source = "git+https://github.com/paradigmxyz/evm-inspectors?rev=75c6ad0#75c6ad0b77dc9237de57c4fb5620b91e34c3d282" dependencies = [ "alloy-primitives", - "alloy-rpc-trace-types", "alloy-rpc-types", + "alloy-rpc-types-trace", "alloy-sol-types", "anstyle", "colorchoice", @@ -6851,9 +6853,9 @@ dependencies = [ [[package]] name = "revm-interpreter" -version = "3.4.0" +version = "4.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f0a1818f8c876b0d71a0714217c34da7df8a42c0462750768779d55680e4554" +checksum = "d322f2730cd300e99d271a1704a2dfb8973d832428f5aa282aaa40e2473b5eec" dependencies = [ "revm-primitives", "serde", @@ -6861,9 +6863,9 @@ dependencies = [ [[package]] name = "revm-precompile" -version = "5.1.0" +version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a9645a70f1df1e5bd7fa8718b9ba486fac9c3f0467aa6b58e7f590d5f6fd0f7" +checksum = "931f692f3f4fc72ec39d5d270f8e9d208c4a6008de7590ee96cf948e3b6d3f8d" dependencies = [ "aurora-engine-modexp", "c-kzg", @@ -6878,9 +6880,9 @@ dependencies = [ [[package]] name = "revm-primitives" -version = "3.1.0" +version = "3.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "323ad597cf75ac9cb1d161be29fcc3562426f0278a1d04741697fca556e1ceea" +checksum = "cbbc9640790cebcb731289afb7a7d96d16ad94afeb64b5d0b66443bd151e79d6" dependencies = [ "alloy-primitives", "auto_impl", @@ -7889,8 +7891,9 @@ dependencies = [ [[package]] name = "syn-solidity" -version = "0.6.4" -source = "git+https://github.com/alloy-rs/core?rev=ff339696fa9b490698cb3edec3d4647fae0bd332#ff339696fa9b490698cb3edec3d4647fae0bd332" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4497156948bd342b52038035a6fa514a89626e37af9d2c52a5e8d8ebcc7ee479" dependencies = [ "paste", "proc-macro2", diff --git a/Cargo.toml b/Cargo.toml index b7a1c3bb3e99..e9c36a4749a6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -136,14 +136,14 @@ foundry-wallets = { path = "crates/wallets" } foundry-linking = { path = "crates/linking" } # solc & compilation utilities -foundry-block-explorers = { version = "0.2.3", default-features = false } +foundry-block-explorers = { version = "0.2.4", default-features = false } foundry-compilers = { version = "0.3.13", default-features = false } ## revm # no default features to avoid c-kzg -revm = { version = "7.2", default-features = false } +revm = { version = "8", default-features = false } revm-primitives = { version = "3", default-features = false } -revm-inspectors = { git = "https://github.com/klkvr/evm-inspectors", rev = "9ff0c29", features = [ +revm-inspectors = { git = "https://github.com/paradigmxyz/evm-inspectors", rev = "75c6ad0", features = [ "serde", ] } @@ -157,32 +157,32 @@ ethers-signers = { version = "2.0.14", default-features = false } ethers-middleware = { version = "2.0.14", default-features = false } ## alloy -alloy-consensus = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } -alloy-contract = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } -alloy-eips = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } -alloy-genesis = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } -alloy-json-rpc = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } -alloy-network = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } -alloy-node-bindings = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } -alloy-provider = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } -alloy-pubsub = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } -alloy-rpc-client = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } -alloy-rpc-trace-types = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } -alloy-rpc-types = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } -alloy-signer = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } -alloy-signer-wallet = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } -alloy-signer-aws = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } -alloy-signer-ledger = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } -alloy-signer-trezor = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } -alloy-transport = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } -alloy-transport-http = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } -alloy-transport-ipc = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } -alloy-transport-ws = { git = "https://github.com/alloy-rs/alloy", rev = "27a1e36", default-features = false } -alloy-primitives = { version = "0.6.4", features = ["getrandom"] } -alloy-dyn-abi = "0.6.4" -alloy-json-abi = "0.6.4" -alloy-sol-types = "0.6.4" -syn-solidity = "0.6.4" +alloy-consensus = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } +alloy-contract = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } +alloy-eips = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } +alloy-genesis = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } +alloy-json-rpc = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } +alloy-network = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } +alloy-node-bindings = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } +alloy-provider = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } +alloy-pubsub = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } +alloy-rpc-client = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } +alloy-rpc-types-trace = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } +alloy-rpc-types = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } +alloy-signer = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } +alloy-signer-wallet = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } +alloy-signer-aws = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } +alloy-signer-ledger = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } +alloy-signer-trezor = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } +alloy-transport = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } +alloy-transport-http = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } +alloy-transport-ipc = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } +alloy-transport-ws = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } +alloy-primitives = { version = "0.7.0", features = ["getrandom"] } +alloy-dyn-abi = "0.7.0" +alloy-json-abi = "0.7.0" +alloy-sol-types = "0.7.0" +syn-solidity = "0.7.0" alloy-chains = "0.1" alloy-rlp = "0.3.3" solang-parser = "=0.3.3" @@ -221,8 +221,5 @@ tower = "0.4" tower-http = "0.4" [patch.crates-io] -alloy-primitives = { git = "https://github.com/alloy-rs/core", rev = "ff339696fa9b490698cb3edec3d4647fae0bd332" } -alloy-sol-types = { git = "https://github.com/alloy-rs/core", rev = "ff339696fa9b490698cb3edec3d4647fae0bd332" } -alloy-json-abi = { git = "https://github.com/alloy-rs/core", rev = "ff339696fa9b490698cb3edec3d4647fae0bd332" } -alloy-dyn-abi = { git = "https://github.com/alloy-rs/core", rev = "ff339696fa9b490698cb3edec3d4647fae0bd332" } -syn-solidity = { git = "https://github.com/alloy-rs/core", rev = "ff339696fa9b490698cb3edec3d4647fae0bd332" } +foundry-compilers = { path = "../compilers" } +foundry-block-explorers = { path = "../block-explorers" } diff --git a/crates/anvil/Cargo.toml b/crates/anvil/Cargo.toml index 038f32b56b3a..e26ac2d7577c 100644 --- a/crates/anvil/Cargo.toml +++ b/crates/anvil/Cargo.toml @@ -16,7 +16,11 @@ path = "src/anvil.rs" required-features = ["cli"] [build-dependencies] -vergen = { workspace = true, default-features = false, features = ["build", "git", "gitcl"] } +vergen = { workspace = true, default-features = false, features = [ + "build", + "git", + "gitcl", +] } [dependencies] # foundry internal @@ -43,7 +47,7 @@ alloy-signer-wallet = { workspace = true, features = ["mnemonic"] } alloy-sol-types = { workspace = true, features = ["std"] } alloy-dyn-abi = { workspace = true, features = ["std", "eip712"] } alloy-rpc-types.workspace = true -alloy-rpc-trace-types.workspace = true +alloy-rpc-types-trace.workspace = true alloy-provider = { workspace = true, features = ["pubsub"] } alloy-transport.workspace = true alloy-chains.workspace = true @@ -77,7 +81,11 @@ rand = "0.8" eyre.workspace = true # cli -clap = { version = "4", features = ["derive", "env", "wrap_help"], optional = true } +clap = { version = "4", features = [ + "derive", + "env", + "wrap_help", +], optional = true } clap_complete = { version = "4", optional = true } chrono.workspace = true auto_impl = "1" diff --git a/crates/anvil/core/Cargo.toml b/crates/anvil/core/Cargo.toml index 50faf7472d72..201fb4631995 100644 --- a/crates/anvil/core/Cargo.toml +++ b/crates/anvil/core/Cargo.toml @@ -12,15 +12,19 @@ repository.workspace = true [dependencies] foundry-common.workspace = true foundry-evm.workspace = true -revm = { workspace = true, default-features = false, features = ["std", "serde", "memory_limit"] } +revm = { workspace = true, default-features = false, features = [ + "std", + "serde", + "memory_limit", +] } alloy-primitives = { workspace = true, features = ["serde"] } alloy-rpc-types = { workspace = true } -alloy-rpc-trace-types.workspace = true +alloy-rpc-types-trace.workspace = true alloy-rlp.workspace = true alloy-eips.workspace = true alloy-network = { workspace = true, features = ["k256"] } -alloy-consensus = { workspace = true, features = ["k256", "kzg"]} +alloy-consensus = { workspace = true, features = ["k256", "kzg"] } alloy-dyn-abi = { workspace = true, features = ["std", "eip712"] } serde = { workspace = true, optional = true } diff --git a/crates/anvil/core/src/eth/mod.rs b/crates/anvil/core/src/eth/mod.rs index e5a394a8fa4c..7a2a153e8ed8 100644 --- a/crates/anvil/core/src/eth/mod.rs +++ b/crates/anvil/core/src/eth/mod.rs @@ -3,13 +3,13 @@ use crate::{ types::{EvmMineOptions, Forking, Index}, }; use alloy_primitives::{Address, Bytes, TxHash, B256, B64, U256}; -use alloy_rpc_trace_types::geth::{GethDebugTracingOptions, GethDefaultTracingOptions}; use alloy_rpc_types::{ pubsub::{Params as SubscriptionParams, SubscriptionKind}, request::TransactionRequest, state::StateOverride, - BlockId, BlockNumberOrTag as BlockNumber, Filter, + BlockId, BlockNumberOrTag as BlockNumber, Filter, WithOtherFields, }; +use alloy_rpc_types_trace::geth::{GethDebugTracingOptions, GethDefaultTracingOptions}; pub mod block; pub mod proof; @@ -143,7 +143,7 @@ pub enum EthRequest { EthSign(Address, Bytes), #[cfg_attr(feature = "serde", serde(rename = "eth_signTransaction"))] - EthSignTransaction(Box), + EthSignTransaction(Box>), /// Signs data via [EIP-712](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md). #[cfg_attr(feature = "serde", serde(rename = "eth_signTypedData"))] @@ -158,27 +158,27 @@ pub enum EthRequest { EthSignTypedDataV4(Address, alloy_dyn_abi::TypedData), #[cfg_attr(feature = "serde", serde(rename = "eth_sendTransaction", with = "sequence"))] - EthSendTransaction(Box), + EthSendTransaction(Box>), #[cfg_attr(feature = "serde", serde(rename = "eth_sendRawTransaction", with = "sequence"))] EthSendRawTransaction(Bytes), #[cfg_attr(feature = "serde", serde(rename = "eth_call"))] EthCall( - TransactionRequest, + WithOtherFields, #[cfg_attr(feature = "serde", serde(default))] Option, #[cfg_attr(feature = "serde", serde(default))] Option, ), #[cfg_attr(feature = "serde", serde(rename = "eth_createAccessList"))] EthCreateAccessList( - TransactionRequest, + WithOtherFields, #[cfg_attr(feature = "serde", serde(default))] Option, ), #[cfg_attr(feature = "serde", serde(rename = "eth_estimateGas"))] EthEstimateGas( - TransactionRequest, + WithOtherFields, #[cfg_attr(feature = "serde", serde(default))] Option, #[cfg_attr(feature = "serde", serde(default))] Option, ), @@ -272,7 +272,7 @@ pub enum EthRequest { /// geth's `debug_traceCall` endpoint #[cfg_attr(feature = "serde", serde(rename = "debug_traceCall"))] DebugTraceCall( - TransactionRequest, + WithOtherFields, #[cfg_attr(feature = "serde", serde(default))] Option, #[cfg_attr(feature = "serde", serde(default))] GethDefaultTracingOptions, ), @@ -597,7 +597,7 @@ pub enum EthRequest { feature = "serde", serde(rename = "eth_sendUnsignedTransaction", with = "sequence") )] - EthSendUnsignedTransaction(Box), + EthSendUnsignedTransaction(Box>), /// Turn on call traces for transactions that are returned to the user when they execute a /// transaction (instead of just txhash/receipt) diff --git a/crates/anvil/core/src/eth/transaction/mod.rs b/crates/anvil/core/src/eth/transaction/mod.rs index 32737dcbded3..21bb25f61b09 100644 --- a/crates/anvil/core/src/eth/transaction/mod.rs +++ b/crates/anvil/core/src/eth/transaction/mod.rs @@ -5,21 +5,23 @@ use crate::eth::{ utils::eip_to_revm_access_list, }; use alloy_consensus::{ - BlobTransactionSidecar, ReceiptWithBloom, Signed, TxEip1559, TxEip2930, TxEip4844, - TxEip4844Variant, TxEip4844WithSidecar, TxEnvelope, TxLegacy, + BlobTransactionSidecar, Receipt, ReceiptEnvelope, ReceiptWithBloom, Signed, TxEip1559, + TxEip2930, TxEip4844, TxEip4844Variant, TxEip4844WithSidecar, TxEnvelope, TxLegacy, TxReceipt, }; use alloy_eips::eip2718::Decodable2718; use alloy_primitives::{Address, Bloom, Bytes, Log, Signature, TxHash, TxKind, B256, U256, U8}; -use alloy_rlp::{Decodable, Encodable, Header}; +use alloy_rlp::{length_of_length, Decodable, Encodable, Header}; use alloy_rpc_types::{ request::TransactionRequest, AccessList, Signature as RpcSignature, - Transaction as RpcTransaction, + Transaction as RpcTransaction, TransactionReceipt, WithOtherFields, }; +use bytes::BufMut; use foundry_evm::traces::CallTraceNode; use revm::{ interpreter::InstructionResult, primitives::{CreateScheme, OptimismFields, TransactTo, TxEnv}, }; +use serde::{Deserialize, Serialize}; use std::ops::Deref; use super::utils::from_eip_to_alloy_access_list; @@ -35,24 +37,29 @@ pub fn impersonated_signature() -> Signature { /// Converts a [TransactionRequest] into a [TypedTransactionRequest]. /// Should be removed once the call builder abstraction for providers is in place. -pub fn transaction_request_to_typed(tx: TransactionRequest) -> Option { - let TransactionRequest { - from, - to, - gas_price, - max_fee_per_gas, - max_priority_fee_per_gas, - max_fee_per_blob_gas, - mut blob_versioned_hashes, - gas, - value, - input, - nonce, - mut access_list, - sidecar, - transaction_type, +pub fn transaction_request_to_typed( + tx: WithOtherFields, +) -> Option { + let WithOtherFields:: { + inner: + TransactionRequest { + from, + to, + gas_price, + max_fee_per_gas, + max_priority_fee_per_gas, + max_fee_per_blob_gas, + mut blob_versioned_hashes, + gas, + value, + input, + nonce, + mut access_list, + sidecar, + transaction_type, + .. + }, other, - .. } = tx; let transaction_type = transaction_type.map(|id| id.to::()); @@ -111,7 +118,7 @@ pub fn transaction_request_to_typed(tx: TransactionRequest) -> Option TxKind::Create, }, chain_id: 0, - access_list: to_eip_access_list(access_list.unwrap_or_default()), + access_list: access_list.unwrap_or_default(), })) } // EIP1559 @@ -132,7 +139,7 @@ pub fn transaction_request_to_typed(tx: TransactionRequest) -> Option TxKind::Create, }, chain_id: 0, - access_list: to_eip_access_list(access_list.unwrap_or_default()), + access_list: access_list.unwrap_or_default(), })) } // EIP4844 @@ -147,7 +154,7 @@ pub fn transaction_request_to_typed(tx: TransactionRequest) -> Option TransactionEssentials { kind: t.tx().to, @@ -727,7 +734,7 @@ impl TypedTransaction { blob_versioned_hashes: None, value: t.tx().value, chain_id: Some(t.tx().chain_id), - access_list: to_alloy_access_list(t.tx().access_list.clone()), + access_list: t.tx().access_list.clone(), }, TypedTransaction::EIP4844(t) => TransactionEssentials { kind: TxKind::Call(t.tx().tx().to), @@ -741,7 +748,7 @@ impl TypedTransaction { blob_versioned_hashes: Some(t.tx().tx().blob_versioned_hashes.clone()), value: t.tx().tx().value, chain_id: Some(t.tx().tx().chain_id), - access_list: to_alloy_access_list(t.tx().tx().access_list.clone()), + access_list: t.tx().tx().access_list.clone(), }, TypedTransaction::Deposit(t) => TransactionEssentials { kind: t.kind, @@ -978,63 +985,156 @@ pub struct TransactionInfo { pub from: Address, pub to: Option

, pub contract_address: Option
, - pub logs: Vec, - pub logs_bloom: Bloom, pub traces: Vec, pub exit: InstructionResult, pub out: Option, pub nonce: u64, + pub gas_used: u64, } -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum TypedReceipt { - Legacy(ReceiptWithBloom), - EIP2930(ReceiptWithBloom), - EIP1559(ReceiptWithBloom), - EIP4844(ReceiptWithBloom), - Deposit(ReceiptWithBloom), +#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)] +pub struct DepositReceipt { + #[serde(flatten)] + pub inner: ReceiptWithBloom, + pub deposit_nonce: Option, + pub deposit_nonce_version: Option, } -impl TypedReceipt { - pub fn gas_used(&self) -> U256 { - match self { - TypedReceipt::Legacy(r) | - TypedReceipt::EIP1559(r) | - TypedReceipt::EIP2930(r) | - TypedReceipt::EIP4844(r) | - TypedReceipt::Deposit(r) => U256::from(r.receipt.cumulative_gas_used), +impl DepositReceipt { + fn payload_len(&self) -> usize { + self.inner.receipt.status.length() + + self.inner.receipt.cumulative_gas_used.length() + + self.inner.logs_bloom.length() + + self.inner.receipt.logs.length() + + self.deposit_nonce.map_or(0, |n| n.length()) + + self.deposit_nonce_version.map_or(0, |n| n.length()) + } + + /// Returns the rlp header for the receipt payload. + fn receipt_rlp_header(&self) -> alloy_rlp::Header { + alloy_rlp::Header { list: true, payload_length: self.payload_len() } + } + + /// Encodes the receipt data. + fn encode_fields(&self, out: &mut dyn BufMut) { + self.receipt_rlp_header().encode(out); + self.inner.receipt.status.encode(out); + self.inner.receipt.cumulative_gas_used.encode(out); + self.inner.logs_bloom.encode(out); + self.inner.receipt.logs.encode(out); + if let Some(n) = self.deposit_nonce { + n.encode(out); + } + if let Some(n) = self.deposit_nonce_version { + n.encode(out); } } - pub fn logs_bloom(&self) -> &Bloom { - match self { - TypedReceipt::Legacy(r) | - TypedReceipt::EIP1559(r) | - TypedReceipt::EIP2930(r) | - TypedReceipt::EIP4844(r) | - TypedReceipt::Deposit(r) => &r.bloom, + /// Decodes the receipt payload + fn decode_receipt(buf: &mut &[u8]) -> alloy_rlp::Result { + let b: &mut &[u8] = &mut &**buf; + let rlp_head = alloy_rlp::Header::decode(b)?; + if !rlp_head.list { + return Err(alloy_rlp::Error::UnexpectedString); + } + let started_len = b.len(); + let remaining = |b: &[u8]| rlp_head.payload_length - (started_len - b.len()) > 0; + + let status = Decodable::decode(b)?; + let cumulative_gas_used = Decodable::decode(b)?; + let logs_bloom = Decodable::decode(b)?; + let logs = Decodable::decode(b)?; + let deposit_nonce = remaining(b).then(|| alloy_rlp::Decodable::decode(b)).transpose()?; + let deposit_nonce_version = + remaining(b).then(|| alloy_rlp::Decodable::decode(b)).transpose()?; + + let this = Self { + inner: ReceiptWithBloom { + receipt: Receipt { status, cumulative_gas_used, logs }, + logs_bloom, + }, + deposit_nonce, + deposit_nonce_version, + }; + + let consumed = started_len - b.len(); + if consumed != rlp_head.payload_length { + return Err(alloy_rlp::Error::ListLengthMismatch { + expected: rlp_head.payload_length, + got: consumed, + }); } + + *buf = *b; + Ok(this) + } +} + +impl alloy_rlp::Encodable for DepositReceipt { + fn encode(&self, out: &mut dyn BufMut) { + self.encode_fields(out); } - pub fn logs(&self) -> &Vec { + fn length(&self) -> usize { + let payload_length = self.payload_len(); + payload_length + length_of_length(payload_length) + } +} + +impl alloy_rlp::Decodable for DepositReceipt { + fn decode(buf: &mut &[u8]) -> alloy_rlp::Result { + Self::decode_receipt(buf) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "type")] +pub enum TypedReceipt { + #[serde(rename = "0x0", alias = "0x00")] + Legacy(ReceiptWithBloom), + #[serde(rename = "0x1", alias = "0x01")] + EIP2930(ReceiptWithBloom), + #[serde(rename = "0x2", alias = "0x02")] + EIP1559(ReceiptWithBloom), + #[serde(rename = "0x3", alias = "0x03")] + EIP4844(ReceiptWithBloom), + #[serde(rename = "0x7E", alias = "0x7e")] + Deposit(DepositReceipt), +} + +impl TypedReceipt { + pub fn as_receipt_with_bloom(&self) -> &ReceiptWithBloom { match self { TypedReceipt::Legacy(r) | TypedReceipt::EIP1559(r) | TypedReceipt::EIP2930(r) | - TypedReceipt::EIP4844(r) | - TypedReceipt::Deposit(r) => &r.receipt.logs, + TypedReceipt::EIP4844(r) => r, + TypedReceipt::Deposit(r) => &r.inner, } } } -impl From for ReceiptWithBloom { - fn from(val: TypedReceipt) -> Self { - match val { - TypedReceipt::Legacy(r) | - TypedReceipt::EIP1559(r) | - TypedReceipt::EIP2930(r) | - TypedReceipt::EIP4844(r) | - TypedReceipt::Deposit(r) => r, +impl TypedReceipt { + pub fn cumulative_gas_used(&self) -> u64 { + self.as_receipt_with_bloom().cumulative_gas_used() + } + + pub fn logs_bloom(&self) -> &Bloom { + &self.as_receipt_with_bloom().logs_bloom + } + + pub fn logs(&self) -> &[Log] { + self.as_receipt_with_bloom().logs() + } +} + +impl From> for TypedReceipt { + fn from(value: ReceiptEnvelope) -> Self { + match value { + ReceiptEnvelope::Legacy(r) => TypedReceipt::Legacy(r), + ReceiptEnvelope::Eip2930(r) => TypedReceipt::EIP2930(r), + ReceiptEnvelope::Eip1559(r) => TypedReceipt::EIP1559(r), + ReceiptEnvelope::Eip4844(r) => TypedReceipt::EIP4844(r), } } } @@ -1110,7 +1210,7 @@ impl Decodable for TypedReceipt { ::decode(buf).map(TypedReceipt::EIP4844) } else if receipt_type == 0x7E { buf.advance(1); - ::decode(buf).map(TypedReceipt::Deposit) + ::decode(buf).map(TypedReceipt::Deposit) } else { Err(alloy_rlp::Error::Custom("invalid receipt type")) } @@ -1125,36 +1225,24 @@ impl Decodable for TypedReceipt { } } -/// Translates an EIP-2930 access list to an alloy-rpc-types access list. -pub fn to_alloy_access_list( - access_list: alloy_eips::eip2930::AccessList, -) -> alloy_rpc_types::AccessList { - alloy_rpc_types::AccessList( - access_list - .0 - .into_iter() - .map(|item| alloy_rpc_types::AccessListItem { - address: item.address, - storage_keys: item.storage_keys, - }) - .collect(), - ) -} - -/// Translates an alloy-rpc-types access list to an EIP-2930 access list. -pub fn to_eip_access_list( - access_list: alloy_rpc_types::AccessList, -) -> alloy_eips::eip2930::AccessList { - alloy_eips::eip2930::AccessList( - access_list - .0 - .into_iter() - .map(|item| alloy_eips::eip2930::AccessListItem { - address: item.address, - storage_keys: item.storage_keys, - }) - .collect(), - ) +pub type ReceiptResponse = TransactionReceipt>; + +pub fn convert_to_anvil_receipt(receipt: TransactionReceipt) -> ReceiptResponse { + TransactionReceipt { + transaction_hash: receipt.transaction_hash, + transaction_index: receipt.transaction_index, + block_hash: receipt.block_hash, + block_number: receipt.block_number, + gas_used: receipt.gas_used, + contract_address: receipt.contract_address, + effective_gas_price: receipt.effective_gas_price, + from: receipt.from, + to: receipt.to, + blob_gas_price: receipt.blob_gas_price, + blob_gas_used: receipt.blob_gas_used, + state_root: receipt.state_root, + inner: receipt.inner.into(), + } } #[cfg(test)] @@ -1290,7 +1378,7 @@ mod tests { let mut data = vec![]; let receipt = TypedReceipt::Legacy(ReceiptWithBloom { receipt: Receipt { - success: false, + status: false, cumulative_gas_used: 0x1u64, logs: vec![Log { address: Address::from_str("0000000000000000000000000000000000000011").unwrap(), @@ -1309,7 +1397,7 @@ mod tests { ), }], }, - bloom: [0; 256].into(), + logs_bloom: [0; 256].into(), }); receipt.encode(&mut data); @@ -1325,7 +1413,7 @@ mod tests { let expected = TypedReceipt::Legacy(ReceiptWithBloom { receipt: Receipt { - success: false, + status: false, cumulative_gas_used: 0x1u64, logs: vec![Log { address: Address::from_str("0000000000000000000000000000000000000011").unwrap(), @@ -1344,7 +1432,7 @@ mod tests { ), }], }, - bloom: [0; 256].into(), + logs_bloom: [0; 256].into(), }); let receipt = TypedReceipt::decode(&mut &data[..]).unwrap(); diff --git a/crates/anvil/src/config.rs b/crates/anvil/src/config.rs index 4023898f9adf..ca8dcdde581b 100644 --- a/crates/anvil/src/config.rs +++ b/crates/anvil/src/config.rs @@ -16,7 +16,6 @@ use crate::{ FeeManager, Hardfork, }; use alloy_genesis::Genesis; -use alloy_network::Ethereum; use alloy_primitives::{hex, utils::Unit, U256}; use alloy_provider::Provider; use alloy_rpc_types::BlockNumberOrTag; @@ -1233,7 +1232,7 @@ pub fn anvil_tmp_dir() -> Option { /// /// This fetches the "latest" block and checks whether the `Block` is fully populated (`hash` field /// is present). This prevents edge cases where anvil forks the "latest" block but `eth_getBlockByNumber` still returns a pending block, -async fn find_latest_fork_block, T: Transport + Clone>( +async fn find_latest_fork_block, T: Transport + Clone>( provider: P, ) -> Result { let mut num = provider.get_block_number().await?; diff --git a/crates/anvil/src/eth/api.rs b/crates/anvil/src/eth/api.rs index 24eb613217d0..5c99f3d9c841 100644 --- a/crates/anvil/src/eth/api.rs +++ b/crates/anvil/src/eth/api.rs @@ -34,24 +34,24 @@ use crate::{ use alloy_dyn_abi::TypedData; use alloy_network::eip2718::Decodable2718; use alloy_primitives::{Address, Bytes, TxHash, TxKind, B256, B64, U256, U64}; -use alloy_rpc_trace_types::{ - geth::{DefaultFrame, GethDebugTracingOptions, GethDefaultTracingOptions, GethTrace}, - parity::LocalizedTransactionTrace, -}; use alloy_rpc_types::{ request::TransactionRequest, state::StateOverride, txpool::{TxpoolContent, TxpoolInspect, TxpoolInspectSummary, TxpoolStatus}, AccessList, AccessListWithGasUsed, Block, BlockId, BlockNumberOrTag as BlockNumber, BlockTransactions, EIP1186AccountProofResponse, FeeHistory, Filter, FilteredParams, Log, - Transaction, TransactionReceipt, + Transaction, WithOtherFields, +}; +use alloy_rpc_types_trace::{ + geth::{DefaultFrame, GethDebugTracingOptions, GethDefaultTracingOptions, GethTrace}, + parity::LocalizedTransactionTrace, }; use alloy_transport::TransportErrorKind; use anvil_core::{ eth::{ block::BlockInfo, transaction::{ - transaction_request_to_typed, PendingTransaction, TypedTransaction, + transaction_request_to_typed, PendingTransaction, ReceiptResponse, TypedTransaction, TypedTransactionRequest, }, EthRequest, @@ -843,7 +843,10 @@ impl EthApi { /// Signs a transaction /// /// Handler for ETH RPC call: `eth_signTransaction` - pub async fn sign_transaction(&self, mut request: TransactionRequest) -> Result { + pub async fn sign_transaction( + &self, + mut request: WithOtherFields, + ) -> Result { node_info!("eth_signTransaction"); let from = request.from.map(Ok).unwrap_or_else(|| { @@ -870,7 +873,10 @@ impl EthApi { /// Sends a transaction /// /// Handler for ETH RPC call: `eth_sendTransaction` - pub async fn send_transaction(&self, mut request: TransactionRequest) -> Result { + pub async fn send_transaction( + &self, + mut request: WithOtherFields, + ) -> Result { node_info!("eth_sendTransaction"); let from = request.from.map(Ok).unwrap_or_else(|| { @@ -950,7 +956,7 @@ impl EthApi { /// Handler for ETH RPC call: `eth_call` pub async fn call( &self, - request: TransactionRequest, + request: WithOtherFields, block_number: Option, overrides: Option, ) -> Result { @@ -1003,7 +1009,7 @@ impl EthApi { /// Handler for ETH RPC call: `eth_createAccessList` pub async fn create_access_list( &self, - mut request: TransactionRequest, + mut request: WithOtherFields, block_number: Option, ) -> Result { node_info!("eth_createAccessList"); @@ -1052,7 +1058,7 @@ impl EthApi { /// Handler for ETH RPC call: `eth_estimateGas` pub async fn estimate_gas( &self, - request: TransactionRequest, + request: WithOtherFields, block_number: Option, overrides: Option, ) -> Result { @@ -1121,7 +1127,7 @@ impl EthApi { /// Returns transaction receipt by transaction hash. /// /// Handler for ETH RPC call: `eth_getTransactionReceipt` - pub async fn transaction_receipt(&self, hash: B256) -> Result> { + pub async fn transaction_receipt(&self, hash: B256) -> Result> { node_info!("eth_getTransactionReceipt"); let tx = self.pool.get_transaction(hash); if tx.is_some() { @@ -1136,7 +1142,7 @@ impl EthApi { pub async fn block_receipts( &self, number: BlockNumber, - ) -> Result>> { + ) -> Result>> { node_info!("eth_getBlockReceipts"); self.backend.block_receipts(number).await } @@ -1430,7 +1436,7 @@ impl EthApi { /// Handler for RPC call: `debug_traceCall` pub async fn debug_trace_call( &self, - request: TransactionRequest, + request: WithOtherFields, block_number: Option, opts: GethDefaultTracingOptions, ) -> Result { @@ -1890,7 +1896,7 @@ impl EthApi { if let Some(receipt) = self.backend.mined_transaction_receipt(tx.hash) { if let Some(output) = receipt.out { // insert revert reason if failure - if receipt.inner.status_code.unwrap_or_default().to::() == 0 { + if !receipt.inner.inner.as_receipt_with_bloom().receipt.status { if let Some(reason) = RevertDecoder::new().maybe_decode(&output, None) { @@ -1963,7 +1969,7 @@ impl EthApi { /// Handler for ETH RPC call: `eth_sendUnsignedTransaction` pub async fn eth_send_unsigned_transaction( &self, - request: TransactionRequest, + request: WithOtherFields, ) -> Result { node_info!("eth_sendUnsignedTransaction"); // either use the impersonated account of the request's `from` field @@ -2129,7 +2135,7 @@ impl EthApi { async fn do_estimate_gas( &self, - request: TransactionRequest, + request: WithOtherFields, block_number: Option, overrides: Option, ) -> Result { @@ -2166,7 +2172,7 @@ impl EthApi { /// This will execute the [CallRequest] and find the best gas limit via binary search fn do_estimate_gas_with_state( &self, - mut request: TransactionRequest, + mut request: WithOtherFields, state: D, block_env: BlockEnv, ) -> Result @@ -2460,7 +2466,7 @@ impl EthApi { fn build_typed_tx_request( &self, - request: TransactionRequest, + request: WithOtherFields, nonce: U256, ) -> Result { let chain_id = request.chain_id.unwrap_or_else(|| self.chain_id()); @@ -2618,7 +2624,7 @@ fn ensure_return_ok(exit: InstructionResult, out: &Option) -> Result( - mut request: TransactionRequest, + mut request: WithOtherFields, state: D, backend: Arc, block_env: BlockEnv, @@ -2652,7 +2658,7 @@ where /// Determines the minimum gas needed for a transaction depending on the transaction kind. #[inline] -fn determine_base_gas_by_kind(request: &TransactionRequest) -> U256 { +fn determine_base_gas_by_kind(request: &WithOtherFields) -> U256 { match transaction_request_to_typed(request.clone()) { Some(request) => match request { TypedTransactionRequest::Legacy(req) => match req.to { diff --git a/crates/anvil/src/eth/backend/executor.rs b/crates/anvil/src/eth/backend/executor.rs index 5e68924c95c3..416c3f32bc81 100644 --- a/crates/anvil/src/eth/backend/executor.rs +++ b/crates/anvil/src/eth/backend/executor.rs @@ -10,7 +10,9 @@ use alloy_consensus::{Header, Receipt, ReceiptWithBloom}; use alloy_primitives::{Bloom, BloomInput, Log, B256, U256}; use anvil_core::eth::{ block::{Block, BlockInfo, PartialHeader}, - transaction::{PendingTransaction, TransactionInfo, TypedReceipt, TypedTransaction}, + transaction::{ + DepositReceipt, PendingTransaction, TransactionInfo, TypedReceipt, TypedTransaction, + }, trie, }; use foundry_evm::{ @@ -43,54 +45,25 @@ pub struct ExecutedTransaction { impl ExecutedTransaction { /// Creates the receipt for the transaction - fn create_receipt(&self) -> TypedReceipt { - let used_gas = U256::from(self.gas_used); - let mut bloom = Bloom::default(); - logs_bloom(self.logs.clone(), &mut bloom); + fn create_receipt(&self, cumulative_gas_used: &mut u64) -> TypedReceipt { let logs = self.logs.clone(); + *cumulative_gas_used = cumulative_gas_used.saturating_add(self.gas_used); // successful return see [Return] let status_code = u8::from(self.exit_reason as u8 <= InstructionResult::SelfDestruct as u8); + let receipt_with_bloom: ReceiptWithBloom = + Receipt { status: status_code == 1, cumulative_gas_used: *cumulative_gas_used, logs } + .into(); + match &self.transaction.pending_transaction.transaction.transaction { - TypedTransaction::Legacy(_) => TypedReceipt::Legacy(ReceiptWithBloom { - receipt: Receipt { - success: status_code == 1, - cumulative_gas_used: used_gas.to::(), - logs, - }, - bloom, - }), - TypedTransaction::EIP2930(_) => TypedReceipt::EIP2930(ReceiptWithBloom { - receipt: Receipt { - success: status_code == 1, - cumulative_gas_used: used_gas.to::(), - logs, - }, - bloom, - }), - TypedTransaction::EIP1559(_) => TypedReceipt::EIP1559(ReceiptWithBloom { - receipt: Receipt { - success: status_code == 1, - cumulative_gas_used: used_gas.to::(), - logs, - }, - bloom, - }), - TypedTransaction::EIP4844(_) => TypedReceipt::EIP4844(ReceiptWithBloom { - receipt: Receipt { - success: status_code == 1, - cumulative_gas_used: used_gas.to::(), - logs, - }, - bloom, - }), - TypedTransaction::Deposit(_) => TypedReceipt::Deposit(ReceiptWithBloom { - receipt: Receipt { - success: status_code == 1, - cumulative_gas_used: used_gas.to::(), - logs, - }, - bloom, + TypedTransaction::Legacy(_) => TypedReceipt::Legacy(receipt_with_bloom), + TypedTransaction::EIP2930(_) => TypedReceipt::EIP2930(receipt_with_bloom), + TypedTransaction::EIP1559(_) => TypedReceipt::EIP1559(receipt_with_bloom), + TypedTransaction::EIP4844(_) => TypedReceipt::EIP4844(receipt_with_bloom), + TypedTransaction::Deposit(tx) => TypedReceipt::Deposit(DepositReceipt { + inner: receipt_with_bloom, + deposit_nonce: Some(tx.nonce), + deposit_nonce_version: Some(1), }), } } @@ -132,7 +105,7 @@ impl<'a, DB: Db + ?Sized, Validator: TransactionValidator> TransactionExecutor<' let mut transaction_infos = Vec::new(); let mut receipts = Vec::new(); let mut bloom = Bloom::default(); - let mut cumulative_gas_used = U256::ZERO; + let mut cumulative_gas_used: u64 = 0; let mut invalid = Vec::new(); let mut included = Vec::new(); let gas_limit = self.block_env.gas_limit; @@ -169,10 +142,9 @@ impl<'a, DB: Db + ?Sized, Validator: TransactionValidator> TransactionExecutor<' continue } }; - let receipt = tx.create_receipt(); - cumulative_gas_used = cumulative_gas_used.saturating_add(receipt.gas_used()); + let receipt = tx.create_receipt(&mut cumulative_gas_used); let ExecutedTransaction { transaction, logs, out, traces, exit_reason: exit, .. } = tx; - logs_bloom(logs.clone(), &mut bloom); + build_logs_bloom(logs.clone(), &mut bloom); let contract_address = out.as_ref().and_then(|out| { if let Output::Create(_, contract_address) = out { @@ -190,8 +162,6 @@ impl<'a, DB: Db + ?Sized, Validator: TransactionValidator> TransactionExecutor<' from: *transaction.pending_transaction.sender(), to: transaction.pending_transaction.transaction.to(), contract_address, - logs, - logs_bloom: *receipt.logs_bloom(), traces, exit, out: match out { @@ -200,6 +170,7 @@ impl<'a, DB: Db + ?Sized, Validator: TransactionValidator> TransactionExecutor<' _ => None, }, nonce: tx.nonce, + gas_used: tx.gas_used, }; transaction_infos.push(info); @@ -219,7 +190,7 @@ impl<'a, DB: Db + ?Sized, Validator: TransactionValidator> TransactionExecutor<' difficulty, number: block_number.to::(), gas_limit: gas_limit.to::(), - gas_used: cumulative_gas_used.to::(), + gas_used: cumulative_gas_used, timestamp, extra_data: Default::default(), mix_hash: Default::default(), @@ -366,7 +337,7 @@ impl<'a, 'b, DB: Db + ?Sized, Validator: TransactionValidator> Iterator } /// Inserts all logs into the bloom -fn logs_bloom(logs: Vec, bloom: &mut Bloom) { +fn build_logs_bloom(logs: Vec, bloom: &mut Bloom) { for log in logs { bloom.accrue(BloomInput::Raw(&log.address[..])); for topic in log.topics() { diff --git a/crates/anvil/src/eth/backend/fork.rs b/crates/anvil/src/eth/backend/fork.rs index 499cb08a936c..fa91d2f52400 100644 --- a/crates/anvil/src/eth/backend/fork.rs +++ b/crates/anvil/src/eth/backend/fork.rs @@ -3,16 +3,17 @@ use crate::eth::{backend::db::Db, error::BlockchainError}; use alloy_primitives::{Address, Bytes, StorageValue, B256, U256, U64}; use alloy_provider::Provider; -use alloy_rpc_trace_types::{ - geth::{GethDebugTracingOptions, GethTrace}, - parity::LocalizedTransactionTrace as Trace, -}; use alloy_rpc_types::{ request::TransactionRequest, AccessListWithGasUsed, Block, BlockId, BlockNumberOrTag as BlockNumber, BlockTransactions, EIP1186AccountProofResponse, FeeHistory, - Filter, Log, Transaction, TransactionReceipt, + Filter, Log, Transaction, WithOtherFields, +}; +use alloy_rpc_types_trace::{ + geth::{GethDebugTracingOptions, GethTrace}, + parity::LocalizedTransactionTrace as Trace, }; use alloy_transport::TransportError; +use anvil_core::eth::transaction::{convert_to_anvil_receipt, ReceiptResponse}; use foundry_common::provider::alloy::{ProviderBuilder, RetryProvider}; use parking_lot::{ lock_api::{RwLockReadGuard, RwLockWriteGuard}, @@ -191,7 +192,7 @@ impl ClientFork { /// Sends `eth_createAccessList` pub async fn create_access_list( &self, - request: &TransactionRequest, + request: &WithOtherFields, block: Option, ) -> Result { self.provider().create_access_list(request, block.map(|b| b.into())).await @@ -367,12 +368,14 @@ impl ClientFork { pub async fn transaction_receipt( &self, hash: B256, - ) -> Result, TransportError> { + ) -> Result, TransportError> { if let Some(receipt) = self.storage_read().transaction_receipts.get(&hash).cloned() { return Ok(Some(receipt)); } - if let Some(receipt) = self.provider().get_transaction_receipt(hash).await? { + if let Some(receipt) = + self.provider().get_transaction_receipt(hash).await?.map(convert_to_anvil_receipt) + { let mut storage = self.storage_write(); storage.transaction_receipts.insert(hash, receipt.clone()); return Ok(Some(receipt)); @@ -384,7 +387,7 @@ impl ClientFork { pub async fn block_receipts( &self, number: u64, - ) -> Result>, TransportError> { + ) -> Result>, TransportError> { if let receipts @ Some(_) = self.storage_read().block_receipts.get(&number).cloned() { return Ok(receipts); } @@ -394,6 +397,7 @@ impl ClientFork { // this is being temporarily implemented in anvil. if self.predates_fork_inclusive(number) { let receipts = self.provider().get_block_receipts(BlockNumber::Number(number)).await?; + let receipts = receipts.map(|r| r.into_iter().map(convert_to_anvil_receipt).collect()); if let Some(receipts) = receipts.clone() { let mut storage = self.storage_write(); @@ -632,12 +636,12 @@ pub struct ForkedStorage { pub blocks: HashMap, pub hashes: HashMap, pub transactions: HashMap, - pub transaction_receipts: HashMap, + pub transaction_receipts: HashMap, pub transaction_traces: HashMap>, pub logs: HashMap>, pub geth_transaction_traces: HashMap, pub block_traces: HashMap>, - pub block_receipts: HashMap>, + pub block_receipts: HashMap>, pub code_at: HashMap<(Address, u64), Bytes>, } diff --git a/crates/anvil/src/eth/backend/mem/mod.rs b/crates/anvil/src/eth/backend/mem/mod.rs index 4618e066c1bf..0093a2d5f997 100644 --- a/crates/anvil/src/eth/backend/mem/mod.rs +++ b/crates/anvil/src/eth/backend/mem/mod.rs @@ -30,25 +30,25 @@ use crate::{ NodeConfig, }; use alloy_consensus::{Header, Receipt, ReceiptWithBloom}; -use alloy_primitives::{keccak256, Address, Bytes, TxHash, B256, B64, U128, U256, U64, U8}; +use alloy_primitives::{keccak256, Address, Bytes, TxHash, B256, B64, U256, U64}; use alloy_rlp::Decodable; -use alloy_rpc_trace_types::{ - geth::{DefaultFrame, GethDebugTracingOptions, GethDefaultTracingOptions, GethTrace}, - parity::LocalizedTransactionTrace, -}; use alloy_rpc_types::{ request::TransactionRequest, serde_helpers::JsonStorageKey, state::StateOverride, AccessList, Block as AlloyBlock, BlockId, BlockNumberOrTag as BlockNumber, EIP1186AccountProofResponse as AccountProof, EIP1186StorageProof as StorageProof, Filter, - FilteredParams, Header as AlloyHeader, Log, Transaction, TransactionReceipt, + FilteredParams, Header as AlloyHeader, Log, Transaction, TransactionReceipt, WithOtherFields, +}; +use alloy_rpc_types_trace::{ + geth::{DefaultFrame, GethDebugTracingOptions, GethDefaultTracingOptions, GethTrace}, + parity::LocalizedTransactionTrace, }; use anvil_core::{ eth::{ block::{Block, BlockInfo}, proof::BasicAccount, transaction::{ - MaybeImpersonatedTransaction, PendingTransaction, TransactionInfo, TypedReceipt, - TypedTransaction, + DepositReceipt, MaybeImpersonatedTransaction, PendingTransaction, ReceiptResponse, + TransactionInfo, TypedReceipt, TypedTransaction, }, trie::RefTrieDB, utils::{alloy_to_revm_access_list, meets_eip155}, @@ -972,7 +972,7 @@ impl Backend { if let Some(contract) = &info.contract_address { node_info!(" Contract created: {contract:?}"); } - node_info!(" Gas used: {}", receipt.gas_used()); + node_info!(" Gas used: {}", receipt.cumulative_gas_used()); if !info.exit.is_ok() { let r = RevertDecoder::new().decode( info.out.as_ref().map(|b| &b[..]).unwrap_or_default(), @@ -1039,7 +1039,7 @@ impl Backend { /// Returns an error if the `block_number` is greater than the current height pub async fn call( &self, - request: TransactionRequest, + request: WithOtherFields, fee_details: FeeDetails, block_request: Option, overrides: Option, @@ -1060,11 +1060,14 @@ impl Backend { fn build_call_env( &self, - request: TransactionRequest, + request: WithOtherFields, fee_details: FeeDetails, block_env: BlockEnv, ) -> EnvWithHandlerCfg { - let TransactionRequest { from, to, gas, value, input, nonce, access_list, .. } = request; + let WithOtherFields:: { + inner: TransactionRequest { from, to, gas, value, input, nonce, access_list, .. }, + .. + } = request; let FeeDetails { gas_price, max_fee_per_gas, max_priority_fee_per_gas } = fee_details; @@ -1111,7 +1114,7 @@ impl Backend { pub fn call_with_state( &self, state: D, - request: TransactionRequest, + request: WithOtherFields, fee_details: FeeDetails, block_env: BlockEnv, ) -> Result<(InstructionResult, Option, u64, State), BlockchainError> @@ -1138,7 +1141,7 @@ impl Backend { pub async fn call_with_tracing( &self, - request: TransactionRequest, + request: WithOtherFields, fee_details: FeeDetails, block_request: Option, opts: GethDefaultTracingOptions, @@ -1171,7 +1174,7 @@ impl Backend { pub fn build_access_list_with_state( &self, state: D, - request: TransactionRequest, + request: WithOtherFields, fee_details: FeeDetails, block_env: BlockEnv, ) -> Result<(InstructionResult, Option, u64, AccessList), BlockchainError> @@ -1247,50 +1250,41 @@ impl Backend { let block_hash = block.header.hash_slow(); let mut block_log_index = 0u32; - let transactions: Vec<_> = { - let storage = self.blockchain.storage.read(); - block - .transactions - .iter() - .filter_map(|tx| storage.transactions.get(&tx.hash()).map(|tx| tx.info.clone())) - .collect() - }; + let storage = self.blockchain.storage.read(); - for transaction in transactions { - let logs = transaction.logs.clone(); - let transaction_hash = transaction.transaction_hash; - - for log in logs.into_iter() { - let mut log = Log { - address: log.address, - topics: log.topics().to_vec(), - data: log.data.data, - block_hash: None, - block_number: None, - transaction_hash: None, - transaction_index: None, - log_index: None, - removed: false, - }; + for tx in block.transactions { + let Some(tx) = storage.transactions.get(&tx.hash()) else { + continue; + }; + let logs = tx.receipt.logs(); + let transaction_hash = tx.info.transaction_hash; + + for log in logs { let mut is_match: bool = true; if !filter.address.is_empty() && filter.has_topics() { - if !params.filter_address(&log.address) || !params.filter_topics(&log.topics) { + if !params.filter_address(&log.address) || !params.filter_topics(log.topics()) + { is_match = false; } } else if !filter.address.is_empty() { if !params.filter_address(&log.address) { is_match = false; } - } else if filter.has_topics() && !params.filter_topics(&log.topics) { + } else if filter.has_topics() && !params.filter_topics(log.topics()) { is_match = false; } if is_match { - log.block_hash = Some(block_hash); - log.block_number = Some(block.header.number.to_alloy()); - log.transaction_hash = Some(transaction_hash); - log.transaction_index = Some(U256::from(transaction.transaction_index)); - log.log_index = Some(U256::from(block_log_index)); + let log = Log { + inner: log.clone(), + block_hash: Some(block_hash), + block_number: Some(block.header.number), + block_timestamp: Some(block.header.timestamp), + transaction_hash: Some(transaction_hash), + transaction_index: Some(tx.info.transaction_index as u64), + log_index: Some(block_log_index as u64), + removed: false, + }; all_logs.push(log); } block_log_index += 1; @@ -1897,7 +1891,7 @@ impl Backend { pub async fn transaction_receipt( &self, hash: B256, - ) -> Result, BlockchainError> { + ) -> Result, BlockchainError> { if let Some(receipt) = self.mined_transaction_receipt(hash) { return Ok(Some(receipt.inner)); } @@ -1905,10 +1899,7 @@ impl Backend { if let Some(fork) = self.get_fork() { let receipt = fork.transaction_receipt(hash).await?; let number = self.convert_block_number( - receipt - .clone() - .and_then(|r| r.block_number) - .map(|n| BlockNumber::from(n.to::())), + receipt.clone().and_then(|r| r.block_number).map(BlockNumber::from), ); if fork.predates_fork_inclusive(number) { @@ -1932,7 +1923,7 @@ impl Backend { } /// Returns all transaction receipts of the block - pub fn mined_block_receipts(&self, id: impl Into) -> Option> { + pub fn mined_block_receipts(&self, id: impl Into) -> Option> { let mut receipts = Vec::new(); let block = self.get_block(id)?; @@ -1946,34 +1937,13 @@ impl Backend { /// Returns the transaction receipt for the given hash pub(crate) fn mined_transaction_receipt(&self, hash: B256) -> Option { - let MinedTransaction { info, receipt, block_hash, .. } = + let MinedTransaction { info, receipt: tx_receipt, block_hash, .. } = self.blockchain.get_transaction_by_hash(&hash)?; - let ReceiptWithBloom { receipt, bloom } = receipt.into(); - let Receipt { success, cumulative_gas_used: _, logs } = receipt; - let logs_bloom = bloom; - let index = info.transaction_index as usize; - let block = self.blockchain.get_block_by_hash(&block_hash)?; - - // TODO store cumulative gas used in receipt instead - let receipts = self.get_receipts(block.transactions.iter().map(|tx| tx.hash())); - - let mut cumulative_gas_used = U256::ZERO; - for receipt in receipts.iter().take(index + 1) { - cumulative_gas_used = cumulative_gas_used.saturating_add(receipt.gas_used()); - } - - // cumulative_gas_used = cumulative_gas_used.saturating_sub(gas_used); - - let mut cumulative_receipts = receipts; - cumulative_receipts.truncate(index + 1); - let transaction = block.transactions[index].clone(); - let transaction_type = transaction.transaction.r#type(); - let effective_gas_price = match transaction.transaction { TypedTransaction::Legacy(t) => t.tx().gas_price, TypedTransaction::EIP2930(t) => t.tx().gas_price, @@ -1992,58 +1962,62 @@ impl Backend { TypedTransaction::Deposit(_) => 0_u128, }; - let deposit_nonce = transaction_type.and_then(|x| (x == 0x7E).then_some(info.nonce)); + let receipts = self.get_receipts(block.transactions.iter().map(|tx| tx.hash())); + let next_log_index = receipts[..index].iter().map(|r| r.logs().len()).sum::(); + + let receipt = tx_receipt.as_receipt_with_bloom().receipt.clone(); + let receipt = Receipt { + status: receipt.status, + cumulative_gas_used: receipt.cumulative_gas_used, + logs: receipt + .logs + .into_iter() + .enumerate() + .map(|(index, log)| alloy_rpc_types::Log { + inner: log, + block_hash: Some(block_hash), + block_number: Some(block.header.number), + block_timestamp: Some(block.header.timestamp), + transaction_hash: Some(info.transaction_hash), + transaction_index: Some(info.transaction_index as u64), + log_index: Some((next_log_index + index) as u64), + removed: false, + }) + .collect(), + }; + let receipt_with_bloom = ReceiptWithBloom { + receipt, + logs_bloom: tx_receipt.as_receipt_with_bloom().logs_bloom, + }; + + let inner = match tx_receipt { + TypedReceipt::EIP1559(_) => TypedReceipt::EIP1559(receipt_with_bloom), + TypedReceipt::Legacy(_) => TypedReceipt::Legacy(receipt_with_bloom), + TypedReceipt::EIP2930(_) => TypedReceipt::EIP2930(receipt_with_bloom), + TypedReceipt::EIP4844(_) => TypedReceipt::EIP4844(receipt_with_bloom), + TypedReceipt::Deposit(r) => TypedReceipt::Deposit(DepositReceipt { + inner: receipt_with_bloom, + deposit_nonce: r.deposit_nonce, + deposit_nonce_version: r.deposit_nonce_version, + }), + }; - let mut inner = TransactionReceipt { + let inner = TransactionReceipt { + inner, transaction_hash: info.transaction_hash, - transaction_index: U64::from(info.transaction_index), + transaction_index: info.transaction_index as u64, + block_number: Some(block.header.number), + gas_used: Some(info.gas_used), + contract_address: info.contract_address, + effective_gas_price: effective_gas_price as u64, block_hash: Some(block_hash), - block_number: Some(U256::from(block.header.number)), from: info.from, to: info.to, - cumulative_gas_used, - gas_used: Some(cumulative_gas_used), - contract_address: info.contract_address, - logs: { - let mut pre_receipts_log_index = None; - if !cumulative_receipts.is_empty() { - cumulative_receipts.truncate(cumulative_receipts.len() - 1); - pre_receipts_log_index = Some( - cumulative_receipts.iter().map(|r| r.logs().len() as u32).sum::(), - ); - } - logs.iter() - .enumerate() - .map(|(i, log)| Log { - address: log.address, - topics: log.topics().to_vec(), - data: log.data.data.clone(), - block_hash: Some(block_hash), - block_number: Some(U256::from(block.header.number)), - transaction_hash: Some(info.transaction_hash), - transaction_index: Some(U256::from(info.transaction_index)), - log_index: Some(U256::from( - (pre_receipts_log_index.unwrap_or(0)) + i as u32, - )), - removed: false, - }) - .collect() - }, - status_code: Some(U64::from(success)), - state_root: None, - logs_bloom, - transaction_type: transaction_type.map(U8::from).unwrap_or_default(), - effective_gas_price: U128::from(effective_gas_price), + state_root: Some(block.header.state_root), blob_gas_price: None, blob_gas_used: None, - other: Default::default(), }; - inner.other.insert( - "depositNonce".to_string(), - serde_json::to_value(deposit_nonce).expect("Infallible"), - ); - Some(MinedTransactionReceipt { inner, out: info.out.map(|o| o.0.into()) }) } @@ -2051,7 +2025,7 @@ impl Backend { pub async fn block_receipts( &self, number: BlockNumber, - ) -> Result>, BlockchainError> { + ) -> Result>, BlockchainError> { if let Some(receipts) = self.mined_block_receipts(number) { return Ok(Some(receipts)); } diff --git a/crates/anvil/src/eth/backend/mem/storage.rs b/crates/anvil/src/eth/backend/mem/storage.rs index d3b13df6155a..a6fc4874e670 100644 --- a/crates/anvil/src/eth/backend/mem/storage.rs +++ b/crates/anvil/src/eth/backend/mem/storage.rs @@ -7,16 +7,14 @@ use crate::eth::{ pool::transactions::PoolTransaction, }; use alloy_primitives::{Bytes, TxHash, B256, U256, U64}; -use alloy_rpc_trace_types::{ +use alloy_rpc_types::{BlockId, BlockNumberOrTag, TransactionInfo as RethTransactionInfo}; +use alloy_rpc_types_trace::{ geth::{DefaultFrame, GethDefaultTracingOptions}, parity::LocalizedTransactionTrace, }; -use alloy_rpc_types::{ - BlockId, BlockNumberOrTag, TransactionInfo as RethTransactionInfo, TransactionReceipt, -}; use anvil_core::eth::{ block::{Block, PartialHeader}, - transaction::{MaybeImpersonatedTransaction, TransactionInfo, TypedReceipt}, + transaction::{MaybeImpersonatedTransaction, ReceiptResponse, TransactionInfo, TypedReceipt}, }; use foundry_evm::{ revm::primitives::Env, @@ -417,7 +415,7 @@ impl MinedTransaction { pub fn geth_trace(&self, opts: GethDefaultTracingOptions) -> DefaultFrame { GethTraceBuilder::new(self.info.traces.clone(), TracingInspectorConfig::default_geth()) .geth_traces( - self.receipt.gas_used().to::(), + self.receipt.cumulative_gas_used(), self.info.out.clone().unwrap_or_default().0.into(), opts, ) @@ -428,7 +426,7 @@ impl MinedTransaction { #[derive(Clone, Debug)] pub struct MinedTransactionReceipt { /// The actual json rpc receipt object - pub inner: TransactionReceipt, + pub inner: ReceiptResponse, /// Output data fo the transaction pub out: Option, } diff --git a/crates/anvil/src/eth/fees.rs b/crates/anvil/src/eth/fees.rs index 38a90f6c2da8..d60df7d4c4c5 100644 --- a/crates/anvil/src/eth/fees.rs +++ b/crates/anvil/src/eth/fees.rs @@ -245,7 +245,7 @@ impl FeeHistoryService { .iter() .enumerate() .map(|(i, receipt)| { - let gas_used = receipt.gas_used(); + let gas_used = receipt.cumulative_gas_used(); let effective_reward = match block.transactions.get(i).map(|tx| &tx.transaction) { Some(TypedTransaction::Legacy(t)) => { @@ -272,7 +272,7 @@ impl FeeHistoryService { None => 0, }; - (gas_used.to::(), effective_reward) + (gas_used, effective_reward) }) .collect(); diff --git a/crates/anvil/src/eth/otterscan/api.rs b/crates/anvil/src/eth/otterscan/api.rs index ac092f36c7f7..604a5d373e88 100644 --- a/crates/anvil/src/eth/otterscan/api.rs +++ b/crates/anvil/src/eth/otterscan/api.rs @@ -7,11 +7,11 @@ use crate::eth::{ macros::node_info, EthApi, }; -use alloy_primitives::{Address, Bytes, B256, U256, U64}; -use alloy_rpc_trace_types::parity::{ +use alloy_primitives::{Address, Bytes, B256, U256}; +use alloy_rpc_types::{Block, BlockId, BlockNumberOrTag as BlockNumber, Transaction}; +use alloy_rpc_types_trace::parity::{ Action, CallAction, CreateAction, CreateOutput, RewardAction, TraceOutput, }; -use alloy_rpc_types::{Block, BlockId, BlockNumberOrTag as BlockNumber, Transaction}; use itertools::Itertools; impl EthApi { @@ -68,7 +68,7 @@ impl EthApi { node_info!("ots_getTransactionError"); if let Some(receipt) = self.backend.mined_transaction_receipt(hash) { - if receipt.inner.status_code == Some(U64::ZERO) { + if !receipt.inner.inner.as_receipt_with_bloom().receipt.status { return Ok(receipt.out.map(|b| b.0.into())) } } diff --git a/crates/anvil/src/eth/otterscan/types.rs b/crates/anvil/src/eth/otterscan/types.rs index ff1f99ce5d13..13bfab2fd197 100644 --- a/crates/anvil/src/eth/otterscan/types.rs +++ b/crates/anvil/src/eth/otterscan/types.rs @@ -3,8 +3,9 @@ use crate::eth::{ error::{BlockchainError, Result}, }; use alloy_primitives::{Address, Bytes, B256, U256 as rU256, U256}; -use alloy_rpc_trace_types::parity::{Action, CallType, LocalizedTransactionTrace}; -use alloy_rpc_types::{Block, BlockTransactions, Transaction, TransactionReceipt}; +use alloy_rpc_types::{Block, BlockTransactions, Transaction}; +use alloy_rpc_types_trace::parity::{Action, CallType, LocalizedTransactionTrace}; +use anvil_core::eth::transaction::ReceiptResponse; use foundry_evm::{revm::interpreter::InstructionResult, traces::CallKind}; use futures::future::join_all; use serde::Serialize; @@ -40,7 +41,7 @@ pub struct Issuance { #[derive(Clone, Serialize, Debug)] pub struct OtsBlockTransactions { pub fullblock: OtsBlock, - pub receipts: Vec, + pub receipts: Vec, } /// Patched Receipt struct, to include the additional `timestamp` field expected by Otterscan @@ -48,7 +49,7 @@ pub struct OtsBlockTransactions { #[serde(rename_all = "camelCase")] pub struct OtsTransactionReceipt { #[serde(flatten)] - receipt: TransactionReceipt, + receipt: ReceiptResponse, timestamp: u64, } @@ -132,22 +133,22 @@ impl OtsBlockDetails { block_txs.iter().map(|tx| async { backend.transaction_receipt(*tx).await }); // fetch all receipts - let receipts: Vec = join_all(receipts_futs) + let receipts = join_all(receipts_futs) .await .into_iter() .map(|r| match r { Ok(Some(r)) => Ok(r), _ => Err(BlockchainError::DataUnavailable), }) - .collect::>()?; + .collect::>>()?; - let total_fees = receipts.iter().fold(U256::ZERO, |acc, receipt| { - acc + receipt.gas_used.unwrap() * (U256::from(receipt.effective_gas_price)) - }); + let total_fees = receipts + .iter() + .fold(0, |acc, receipt| acc + receipt.gas_used.unwrap() * receipt.effective_gas_price); Ok(Self { block: block.into(), - total_fees, + total_fees: U256::from(total_fees), // issuance has no meaningful value in anvil's backend. just default to 0 issuance: Default::default(), }) @@ -198,7 +199,7 @@ impl OtsBlockTransactions { let receipt_futs = block_txs.iter().map(|tx| async { backend.transaction_receipt(*tx).await }); - let receipts: Vec = join_all(receipt_futs) + let receipts = join_all(receipt_futs) .await .into_iter() .map(|r| match r { @@ -237,11 +238,8 @@ impl OtsSearchTransactions { join_all(hashes.iter().map(|hash| async { match backend.transaction_receipt(*hash).await { Ok(Some(receipt)) => { - let timestamp = backend - .get_block(receipt.block_number.unwrap().to::()) - .unwrap() - .header - .timestamp; + let timestamp = + backend.get_block(receipt.block_number.unwrap()).unwrap().header.timestamp; Ok(OtsTransactionReceipt { receipt, timestamp }) } Ok(None) => Err(BlockchainError::DataUnavailable), diff --git a/crates/anvil/src/pubsub.rs b/crates/anvil/src/pubsub.rs index 2c0c614fc254..a063ee6697b2 100644 --- a/crates/anvil/src/pubsub.rs +++ b/crates/anvil/src/pubsub.rs @@ -2,9 +2,8 @@ use crate::{ eth::{backend::notifications::NewBlockNotifications, error::to_rpc_result}, StorageInfo, }; -use alloy_consensus::ReceiptWithBloom; -use alloy_primitives::{Log, TxHash, B256, U256}; -use alloy_rpc_types::{pubsub::SubscriptionResult, FilteredParams, Log as AlloyLog}; +use alloy_primitives::{TxHash, B256}; +use alloy_rpc_types::{pubsub::SubscriptionResult, FilteredParams, Log}; use anvil_core::eth::{block::Block, subscription::SubscriptionId, transaction::TypedReceipt}; use anvil_rpc::{request::Version, response::ResponseResult}; use futures::{channel::mpsc::Receiver, ready, Stream, StreamExt}; @@ -21,7 +20,7 @@ pub struct LogsSubscription { pub blocks: NewBlockNotifications, pub storage: StorageInfo, pub filter: FilteredParams, - pub queued: VecDeque, + pub queued: VecDeque, pub id: SubscriptionId, } @@ -144,13 +143,14 @@ impl Stream for EthSubscription { } /// Returns all the logs that match the given filter -pub fn filter_logs( - block: Block, - receipts: Vec, - filter: &FilteredParams, -) -> Vec { +pub fn filter_logs(block: Block, receipts: Vec, filter: &FilteredParams) -> Vec { /// Determines whether to add this log - fn add_log(block_hash: B256, l: &Log, block: &Block, params: &FilteredParams) -> bool { + fn add_log( + block_hash: B256, + l: &alloy_primitives::Log, + block: &Block, + params: &FilteredParams, + ) -> bool { if params.filter.is_some() { let block_number = block.header.number; if !params.filter_block_range(block_number) || @@ -168,25 +168,18 @@ pub fn filter_logs( let mut logs = vec![]; let mut log_index: u32 = 0; for (receipt_index, receipt) in receipts.into_iter().enumerate() { - let receipt: ReceiptWithBloom = receipt.into(); - let receipt_logs = receipt.receipt.logs; - let transaction_hash: Option = if !receipt_logs.is_empty() { - Some(block.transactions[receipt_index].hash()) - } else { - None - }; - for log in receipt_logs.into_iter() { - if add_log(block_hash, &log, &block, filter) { - logs.push(AlloyLog { - address: log.address, - topics: log.topics().to_vec(), - data: log.data.data, + let transaction_hash = block.transactions[receipt_index].hash(); + for log in receipt.logs() { + if add_log(block_hash, log, &block, filter) { + logs.push(Log { + inner: log.clone(), block_hash: Some(block_hash), - block_number: Some(U256::from(block.header.number)), - transaction_hash, - transaction_index: Some(U256::from(receipt_index)), - log_index: Some(U256::from(log_index)), + block_number: Some(block.header.number), + transaction_hash: Some(transaction_hash), + transaction_index: Some(receipt_index as u64), + log_index: Some(log_index as u64), removed: false, + block_timestamp: Some(block.header.timestamp), }); } log_index += 1; diff --git a/crates/anvil/src/tasks/mod.rs b/crates/anvil/src/tasks/mod.rs index 7d1cfa727798..952ff15cd20e 100644 --- a/crates/anvil/src/tasks/mod.rs +++ b/crates/anvil/src/tasks/mod.rs @@ -1,7 +1,6 @@ //! Task management support use crate::{shutdown::Shutdown, tasks::block_listener::BlockListener, EthApi}; -use alloy_network::Ethereum; use alloy_primitives::B256; use alloy_provider::Provider; use alloy_rpc_types::Block; @@ -67,7 +66,7 @@ impl TaskManager { /// ``` pub fn spawn_reset_on_new_polled_blocks(&self, provider: P, api: EthApi) where - P: Provider + Clone + Unpin + 'static, + P: Provider + Clone + Unpin + 'static, T: Transport + Clone, { self.spawn_block_poll_listener(provider.clone(), move |hash| { @@ -91,7 +90,7 @@ impl TaskManager { /// block hash pub fn spawn_block_poll_listener(&self, provider: P, task_factory: F) where - P: Provider + 'static, + P: Provider + 'static, T: Transport + Clone, F: Fn(B256) -> Fut + Unpin + Send + Sync + 'static, Fut: Future + Send, @@ -127,7 +126,7 @@ impl TaskManager { /// ``` pub fn spawn_reset_on_subscribed_blocks(&self, provider: P, api: EthApi) where - P: Provider + 'static, + P: Provider + 'static, T: Transport + Clone, { self.spawn_block_subscription(provider, move |block| { @@ -148,7 +147,7 @@ impl TaskManager { /// new block hash pub fn spawn_block_subscription(&self, provider: P, task_factory: F) where - P: Provider + 'static, + P: Provider + 'static, T: Transport + Clone, F: Fn(Block) -> Fut + Unpin + Send + Sync + 'static, Fut: Future + Send, diff --git a/crates/anvil/tests/it/api.rs b/crates/anvil/tests/it/api.rs index 7ae68e190744..9486a9900076 100644 --- a/crates/anvil/tests/it/api.rs +++ b/crates/anvil/tests/it/api.rs @@ -8,7 +8,7 @@ use alloy_primitives::{Address as rAddress, B256, U256 as rU256}; use alloy_provider::Provider; use alloy_rpc_types::{ request::{TransactionInput as CallInput, TransactionRequest as CallRequest}, - state::{AccountOverride, StateOverride}, + state::{AccountOverride, StateOverride}, WithOtherFields, }; use anvil::{ eth::{api::CLIENT_VERSION, EthApi}, @@ -243,11 +243,11 @@ where { let result = api .call( - CallRequest { + WithOtherFields::new(CallRequest { input: CallInput::maybe_input(call.tx.data().cloned().map(|b| b.0.into())), to: Some(to.to_alloy()), ..Default::default() - }, + }), None, Some(overrides), ) diff --git a/crates/anvil/tests/it/fork.rs b/crates/anvil/tests/it/fork.rs index 5e61c231c5c0..fe150e712bcd 100644 --- a/crates/anvil/tests/it/fork.rs +++ b/crates/anvil/tests/it/fork.rs @@ -8,7 +8,7 @@ use alloy_primitives::{address, U256 as rU256, U64 as rU64}; use alloy_provider::Provider as AlloyProvider; use alloy_rpc_types::{ request::{TransactionInput, TransactionRequest as CallRequest}, - BlockNumberOrTag, + BlockNumberOrTag, WithOtherFields, }; use anvil::{eth::EthApi, spawn, NodeConfig, NodeHandle}; use anvil_core::types::Forking; @@ -802,11 +802,11 @@ async fn test_fork_call() { let res1 = api .call( - CallRequest { + WithOtherFields::new(CallRequest { to: Some(to.to_alloy()), input: input.to_alloy().into(), ..Default::default() - }, + }), None, None, ) @@ -1194,11 +1194,11 @@ async fn test_fork_execution_reverted() { let resp = api .call( - CallRequest { + WithOtherFields::new(CallRequest { to: Some(address!("Fd6CC4F251eaE6d02f9F7B41D1e80464D3d2F377")), input: TransactionInput::new("0x8f283b3c".as_bytes().into()), ..Default::default() - }, + }), Some(target.into()), None, ) diff --git a/crates/anvil/tests/it/transaction.rs b/crates/anvil/tests/it/transaction.rs index 538f6401193c..28dc1a4088b7 100644 --- a/crates/anvil/tests/it/transaction.rs +++ b/crates/anvil/tests/it/transaction.rs @@ -6,7 +6,7 @@ use alloy_primitives::{Bytes, U256 as rU256}; use alloy_rpc_types::{ request::TransactionRequest as AlloyTransactionRequest, state::{AccountOverride, StateOverride}, - BlockNumberOrTag, + BlockNumberOrTag, WithOtherFields, }; use anvil::{spawn, Hardfork, NodeConfig}; use ethers::{ @@ -966,7 +966,7 @@ async fn estimates_gas_on_pending_by_default() { .to(Some(sender.to_alloy())) .value(rU256::from(1e10)) .input(Bytes::from(vec![0x42]).into()); - api.estimate_gas(tx, None, None).await.unwrap(); + api.estimate_gas(WithOtherFields::new(tx), None, None).await.unwrap(); } #[tokio::test(flavor = "multi_thread")] @@ -983,7 +983,7 @@ async fn test_estimate_gas() { .value(rU256::from(1e10)) .input(Bytes::from(vec![0x42]).into()); // Expect the gas estimation to fail due to insufficient funds. - let error_result = api.estimate_gas(tx.clone(), None, None).await; + let error_result = api.estimate_gas(WithOtherFields::new(tx.clone()), None, None).await; assert!(error_result.is_err(), "Expected an error due to insufficient funds"); let error_message = error_result.unwrap_err().to_string(); @@ -1002,7 +1002,7 @@ async fn test_estimate_gas() { // Estimate gas with state override implying sufficient funds. let gas_estimate = api - .estimate_gas(tx, None, Some(state_override)) + .estimate_gas(WithOtherFields::new(tx), None, Some(state_override)) .await .expect("Failed to estimate gas with state override"); @@ -1098,8 +1098,8 @@ async fn can_mine_multiple_in_block() { }; // broadcast it via the eth_sendTransaction API - let first = api.send_transaction(tx.clone()).await.unwrap(); - let second = api.send_transaction(tx.clone()).await.unwrap(); + let first = api.send_transaction(WithOtherFields::new(tx.clone())).await.unwrap(); + let second = api.send_transaction(WithOtherFields::new(tx.clone())).await.unwrap(); api.anvil_mine(Some(rU256::from(1)), Some(rU256::ZERO)).await.unwrap(); diff --git a/crates/cast/bin/cmd/access_list.rs b/crates/cast/bin/cmd/access_list.rs index bf6aedd5e513..656d04836130 100644 --- a/crates/cast/bin/cmd/access_list.rs +++ b/crates/cast/bin/cmd/access_list.rs @@ -1,4 +1,4 @@ -use alloy_network::{Ethereum, TransactionBuilder}; +use alloy_network::TransactionBuilder; use alloy_primitives::Address; use alloy_provider::Provider; use alloy_rpc_types::{BlockId, TransactionRequest}; @@ -91,7 +91,7 @@ impl AccessListArgs { } #[allow(clippy::too_many_arguments)] -async fn access_list, T: Transport + Clone>( +async fn access_list, T: Transport + Clone>( provider: P, etherscan_api_key: Option<&str>, from: Address, diff --git a/crates/cast/bin/cmd/send.rs b/crates/cast/bin/cmd/send.rs index 86aebbe3e001..5ce625f992af 100644 --- a/crates/cast/bin/cmd/send.rs +++ b/crates/cast/bin/cmd/send.rs @@ -198,7 +198,7 @@ impl SendTxArgs { } #[allow(clippy::too_many_arguments)] -async fn cast_send, T: Transport + Clone>( +async fn cast_send, T: Transport + Clone>( provider: P, from: Address, to: Option
, diff --git a/crates/cast/bin/cmd/storage.rs b/crates/cast/bin/cmd/storage.rs index 970186634ef5..be2ff07739aa 100644 --- a/crates/cast/bin/cmd/storage.rs +++ b/crates/cast/bin/cmd/storage.rs @@ -1,6 +1,6 @@ use crate::opts::parse_slot; use alloy_primitives::{Address, B256, U256}; -use alloy_provider::{network::Ethereum, Provider}; +use alloy_provider::Provider; use alloy_rpc_types::BlockId; use alloy_transport::Transport; use cast::Cast; @@ -204,7 +204,7 @@ impl StorageValue { } } -async fn fetch_and_print_storage, T: Transport + Clone>( +async fn fetch_and_print_storage, T: Transport + Clone>( provider: P, address: Address, block: Option, @@ -221,7 +221,7 @@ async fn fetch_and_print_storage, T: Transport + Clone> } } -async fn fetch_storage_slots, T: Transport + Clone>( +async fn fetch_storage_slots, T: Transport + Clone>( provider: P, address: Address, block: Option, diff --git a/crates/cast/bin/tx.rs b/crates/cast/bin/tx.rs index 7504cdffd58b..6816d307b5bc 100644 --- a/crates/cast/bin/tx.rs +++ b/crates/cast/bin/tx.rs @@ -1,7 +1,7 @@ use alloy_json_abi::Function; use alloy_network::TransactionBuilder; use alloy_primitives::Address; -use alloy_provider::{network::Ethereum, Provider}; +use alloy_provider::Provider; use alloy_rpc_types::TransactionRequest; use alloy_transport::Transport; use eyre::Result; @@ -38,7 +38,7 @@ pub fn validate_to_address(code: &Option, to: &Option) -> #[allow(clippy::too_many_arguments)] pub async fn build_tx< - P: Provider, + P: Provider, T: Transport + Clone, F: Into, TO: Into, diff --git a/crates/cast/src/lib.rs b/crates/cast/src/lib.rs index dac565365340..a030a0297ee4 100644 --- a/crates/cast/src/lib.rs +++ b/crates/cast/src/lib.rs @@ -66,7 +66,7 @@ pub struct Cast { impl Cast where T: Transport + Clone, - P: Provider, + P: Provider, { /// Creates a new Cast instance from the provided client /// @@ -244,7 +244,7 @@ where pub async fn send( &self, tx: TransactionRequest, - ) -> Result> { + ) -> Result> { let res = self.provider.send_transaction(tx).await?; Ok(res) @@ -269,7 +269,7 @@ where pub async fn publish( &self, mut raw_tx: String, - ) -> Result> { + ) -> Result> { raw_tx = match raw_tx.strip_prefix("0x") { Some(s) => s.to_string(), None => raw_tx, diff --git a/crates/cheatcodes/src/evm/fork.rs b/crates/cheatcodes/src/evm/fork.rs index 4ff2bb4ae098..617d0b1e027e 100644 --- a/crates/cheatcodes/src/evm/fork.rs +++ b/crates/cheatcodes/src/evm/fork.rs @@ -274,14 +274,14 @@ impl Cheatcode for eth_getLogsCall { let eth_logs = logs .into_iter() .map(|log| EthGetLogs { - emitter: log.address, - topics: log.topics.into_iter().collect(), - data: log.data.0.into(), + emitter: log.address(), + topics: log.topics().to_vec(), + data: log.inner.data.data, blockHash: log.block_hash.unwrap_or_default(), - blockNumber: log.block_number.unwrap_or_default().to(), + blockNumber: log.block_number.unwrap_or_default(), transactionHash: log.transaction_hash.unwrap_or_default(), - transactionIndex: log.transaction_index.unwrap_or_default().to(), - logIndex: log.log_index.unwrap_or_default(), + transactionIndex: log.transaction_index.unwrap_or_default(), + logIndex: U256::from(log.log_index.unwrap_or_default()), removed: log.removed, }) .collect::>(); diff --git a/crates/cli/src/utils/abi.rs b/crates/cli/src/utils/abi.rs index afe05336aeff..395ea1127e99 100644 --- a/crates/cli/src/utils/abi.rs +++ b/crates/cli/src/utils/abi.rs @@ -1,7 +1,7 @@ use alloy_chains::Chain; use alloy_json_abi::Function; use alloy_primitives::Address; -use alloy_provider::{network::Ethereum, Provider}; +use alloy_provider::Provider; use alloy_transport::Transport; use eyre::{OptionExt, Result}; use foundry_common::{ @@ -10,7 +10,7 @@ use foundry_common::{ }; use futures::future::join_all; -async fn resolve_name_args>( +async fn resolve_name_args>( args: &[String], provider: &P, ) -> Vec { @@ -28,7 +28,7 @@ async fn resolve_name_args>( .await } -pub async fn parse_function_args>( +pub async fn parse_function_args>( sig: &str, args: Vec, to: Option
, diff --git a/crates/cli/src/utils/mod.rs b/crates/cli/src/utils/mod.rs index a3c0ecd8ec94..9c7740ba57d1 100644 --- a/crates/cli/src/utils/mod.rs +++ b/crates/cli/src/utils/mod.rs @@ -1,6 +1,6 @@ use alloy_json_abi::JsonAbi; use alloy_primitives::U256; -use alloy_provider::{network::Ethereum, Provider}; +use alloy_provider::{Provider}; use alloy_transport::Transport; use eyre::{ContextCompat, Result}; use foundry_config::{Chain, Config}; @@ -144,7 +144,7 @@ pub fn get_alloy_provider_builder( pub async fn get_chain(chain: Option, provider: P) -> Result where - P: Provider, + P: Provider, T: Transport + Clone, { match chain { diff --git a/crates/common/Cargo.toml b/crates/common/Cargo.toml index 632b9ec8e81a..a2ed4a402afa 100644 --- a/crates/common/Cargo.toml +++ b/crates/common/Cargo.toml @@ -34,13 +34,14 @@ alloy-rpc-client.workspace = true alloy-provider.workspace = true alloy-transport.workspace = true alloy-signer-wallet.workspace = true -alloy-transport-http = { workspace = true, features = ["reqwest-rustls-tls"] } +alloy-transport-http = { workspace = true, features = ["reqwest", "reqwest-rustls-tls"] } alloy-transport-ws.workspace = true alloy-transport-ipc.workspace = true alloy-json-rpc.workspace = true alloy-pubsub.workspace = true alloy-sol-types.workspace = true alloy-contract.workspace = true +alloy-consensus.workspace = true tower.workspace = true diff --git a/crates/common/src/ens.rs b/crates/common/src/ens.rs index 62674690f49f..cb1058384131 100644 --- a/crates/common/src/ens.rs +++ b/crates/common/src/ens.rs @@ -56,7 +56,7 @@ pub enum NameOrAddress { impl NameOrAddress { /// Resolves the name to an Ethereum Address. - pub async fn resolve>( + pub async fn resolve>( &self, provider: &P, ) -> Result { @@ -98,8 +98,8 @@ impl FromStr for NameOrAddress { } #[async_trait] -pub trait ProviderEnsExt> { - async fn get_resolver(&self) -> Result, EnsResolutionError>; +pub trait ProviderEnsExt> { + async fn get_resolver(&self) -> Result, EnsResolutionError>; async fn resolve_name(&self, name: &str) -> Result { let node = namehash(name); @@ -131,13 +131,13 @@ pub trait ProviderEnsExt> { } #[async_trait] -impl ProviderEnsExt for P +impl ProviderEnsExt for P where - P: Provider, + P: Provider, N: Network, T: Transport + Clone, { - async fn get_resolver(&self) -> Result, EnsResolutionError> { + async fn get_resolver(&self) -> Result, EnsResolutionError> { let registry = EnsRegistry::new(ENS_ADDRESS, self); let address = registry .resolver(namehash("eth")) diff --git a/crates/common/src/fmt/ui.rs b/crates/common/src/fmt/ui.rs index fe984f8b3812..59863af1a601 100644 --- a/crates/common/src/fmt/ui.rs +++ b/crates/common/src/fmt/ui.rs @@ -1,6 +1,7 @@ //! Helper trait and functions to format Ethereum types. use crate::TransactionReceiptWithRevertReason; +use alloy_consensus::{Receipt, ReceiptWithBloom, TxType}; use alloy_primitives::*; use alloy_rpc_types::{ other::OtherFields, Block, BlockTransactions, Log, Transaction, TransactionReceipt, @@ -25,6 +26,12 @@ pub trait UIfmt { fn pretty(&self) -> String; } +impl UIfmt for &T { + fn pretty(&self) -> String { + (*self).pretty() + } +} + impl UIfmt for Option { fn pretty(&self) -> String { if let Some(ref inner) = self { @@ -35,7 +42,7 @@ impl UIfmt for Option { } } -impl UIfmt for Vec { +impl UIfmt for [T] { fn pretty(&self) -> String { if !self.is_empty() { let mut s = String::with_capacity(self.len() * 64); @@ -61,6 +68,12 @@ impl UIfmt for String { } } +impl UIfmt for u64 { + fn pretty(&self) -> String { + self.to_string() + } +} + impl UIfmt for bool { fn pretty(&self) -> String { self.to_string() @@ -91,6 +104,12 @@ impl UIfmt for Bloom { } } +impl UIfmt for TxType { + fn pretty(&self) -> String { + (*self as u8).to_string() + } +} + impl UIfmt for Vec { fn pretty(&self) -> String { self[..].pretty() @@ -123,6 +142,7 @@ impl UIfmt for [u8] { impl UIfmt for TransactionReceipt { fn pretty(&self) -> String { + let transaction_type = self.transaction_type(); let Self { transaction_hash, transaction_index, @@ -130,19 +150,28 @@ impl UIfmt for TransactionReceipt { block_number, from, to, - cumulative_gas_used, gas_used, contract_address, - logs, - status_code, state_root, - logs_bloom, - transaction_type, effective_gas_price, - other, - .. + inner, + blob_gas_price, + blob_gas_used, } = self; + let (logs_bloom, status, cumulative_gas_used, logs) = if let Some(receipt) = + inner.as_receipt_with_bloom() + { + let ReceiptWithBloom { + logs_bloom, + receipt: Receipt { status, cumulative_gas_used, logs }, + } = receipt; + + (Some(logs_bloom), Some(status), Some(cumulative_gas_used), Some(logs)) + } else { + Default::default() + }; + let mut pretty = format!( " blockHash {} @@ -158,7 +187,9 @@ root {} status {} transactionHash {} transactionIndex {} -type {}", +type {} +blobGasPrice {} +blobGasUsed {}", block_hash.pretty(), block_number.pretty(), contract_address.pretty(), @@ -166,13 +197,15 @@ type {}", effective_gas_price.pretty(), from.pretty(), gas_used.pretty(), - serde_json::to_string(logs).unwrap(), + serde_json::to_string(&logs).unwrap(), logs_bloom.pretty(), state_root.pretty(), - status_code.pretty(), + status.pretty(), transaction_hash.pretty(), transaction_index.pretty(), - transaction_type.pretty() + transaction_type.pretty(), + blob_gas_price.pretty(), + blob_gas_used.pretty(), ); if let Some(to) = to { @@ -180,9 +213,9 @@ type {}", } // additional captured fields - for (key, val) in other.iter() { - pretty.push_str(&format!("\n{} {}", key, val)); - } + // for (key, val) in other.iter() { + // pretty.push_str(&format!("\n{} {}", key, val)); + // } pretty } @@ -201,13 +234,13 @@ removed: {} topics: {} transactionHash: {} transactionIndex: {}", - self.address.pretty(), + self.address().pretty(), self.block_hash.pretty(), self.block_number.pretty(), - self.data.pretty(), + self.data().data.pretty(), self.log_index.pretty(), self.removed.pretty(), - self.topics.pretty(), + self.topics().pretty(), self.transaction_hash.pretty(), self.transaction_index.pretty(), ) @@ -397,21 +430,23 @@ pub fn get_pretty_tx_receipt_attr( "blockNumber" | "block_number" => Some(receipt.receipt.block_number.pretty()), "contractAddress" | "contract_address" => Some(receipt.receipt.contract_address.pretty()), "cumulativeGasUsed" | "cumulative_gas_used" => { - Some(receipt.receipt.cumulative_gas_used.pretty()) + Some(receipt.receipt.inner.as_receipt().map(|r| r.cumulative_gas_used).pretty()) } "effectiveGasPrice" | "effective_gas_price" => { - Some(receipt.receipt.effective_gas_price.pretty()) + Some(receipt.receipt.effective_gas_price.to_string()) + } + "gasUsed" | "gas_used" => receipt.receipt.gas_used.map(|g| g.to_string()), + "logs" => receipt.receipt.inner.as_receipt().map(|r| r.logs.as_slice().pretty()), + "logsBloom" | "logs_bloom" => { + Some(receipt.receipt.inner.as_receipt_with_bloom().map(|r| r.logs_bloom).pretty()) } - "gasUsed" | "gas_used" => Some(receipt.receipt.gas_used.pretty()), - "logs" => Some(receipt.receipt.logs.pretty()), - "logsBloom" | "logs_bloom" => Some(receipt.receipt.logs_bloom.pretty()), "root" | "stateRoot" | "state_root " => Some(receipt.receipt.state_root.pretty()), - "status" | "statusCode" | "status_code" => Some(receipt.receipt.status_code.pretty()), + "status" | "statusCode" | "status_code" => Some(receipt.receipt.status().pretty()), "transactionHash" | "transaction_hash" => Some(receipt.receipt.transaction_hash.pretty()), "transactionIndex" | "transaction_index" => { - Some(receipt.receipt.transaction_index.pretty()) + Some(receipt.receipt.transaction_index.to_string()) } - "type" | "transaction_type" => Some(receipt.receipt.transaction_type.pretty()), + "type" | "transaction_type" => Some(receipt.receipt.transaction_type().pretty()), "revertReason" | "revert_reason" => Some(receipt.revert_reason.pretty()), _ => None, } diff --git a/crates/common/src/provider/alloy.rs b/crates/common/src/provider/alloy.rs index 2c1099d1c772..5d083f1769c5 100644 --- a/crates/common/src/provider/alloy.rs +++ b/crates/common/src/provider/alloy.rs @@ -28,7 +28,7 @@ use super::{ }; /// Helper type alias for a retry provider -pub type RetryProvider = RootProvider>; +pub type RetryProvider = RootProvider>; /// Helper type alias for a rpc url pub type RpcUrl = String; @@ -255,7 +255,7 @@ impl ProviderBuilder { /// - polygon /// /// Fallback is the default [`Provider::estimate_eip1559_fees`] implementation -pub async fn estimate_eip1559_fees, T: Transport + Clone>( +pub async fn estimate_eip1559_fees, T: Transport + Clone>( provider: &P, chain: Option, ) -> Result { diff --git a/crates/common/src/transactions.rs b/crates/common/src/transactions.rs index 74510f548c64..fa27c837db05 100644 --- a/crates/common/src/transactions.rs +++ b/crates/common/src/transactions.rs @@ -1,12 +1,12 @@ //! wrappers for transactions -use alloy_provider::{network::Ethereum, Provider}; +use alloy_provider::{Provider}; use alloy_rpc_types::{BlockId, TransactionReceipt}; use alloy_transport::Transport; use eyre::Result; use serde::{Deserialize, Serialize}; /// Helper type to carry a transaction along with an optional revert reason -#[derive(Clone, Debug, Default, Serialize, Deserialize)] +#[derive(Clone, Debug, Serialize, Deserialize)] pub struct TransactionReceiptWithRevertReason { /// The underlying transaction receipt #[serde(flatten)] @@ -19,13 +19,13 @@ pub struct TransactionReceiptWithRevertReason { impl TransactionReceiptWithRevertReason { /// Returns if the status of the transaction is 0 (failure) - pub fn is_failure(&self) -> Option { - self.receipt.status_code.map(|status| status.is_zero()) + pub fn is_failure(&self) -> bool { + self.receipt.status() } /// Updates the revert reason field using `eth_call` and returns an Err variant if the revert /// reason was not successfully updated - pub async fn update_revert_reason>( + pub async fn update_revert_reason>( &mut self, provider: &P, ) -> Result<()> { @@ -33,11 +33,11 @@ impl TransactionReceiptWithRevertReason { Ok(()) } - async fn fetch_revert_reason>( + async fn fetch_revert_reason>( &self, provider: &P, ) -> Result> { - if let Some(false) | None = self.is_failure() { + if !self.is_failure() { return Ok(None) } diff --git a/crates/config/Cargo.toml b/crates/config/Cargo.toml index 99a7023af72b..f00aa8da9e8d 100644 --- a/crates/config/Cargo.toml +++ b/crates/config/Cargo.toml @@ -29,7 +29,7 @@ Inflector = "0.11" number_prefix = "0.4" once_cell = "1" regex = "1" -reqwest = { version = "0.11", default-features = false } +reqwest = { version = "0.12", default-features = false, features = ["rustls-tls"] } semver = { version = "1", features = ["serde"] } serde_json.workspace = true serde_regex = "1" diff --git a/crates/evm/core/src/fork/backend.rs b/crates/evm/core/src/fork/backend.rs index 93f1187bb3b1..a14742dc103d 100644 --- a/crates/evm/core/src/fork/backend.rs +++ b/crates/evm/core/src/fork/backend.rs @@ -4,7 +4,7 @@ use crate::{ fork::{cache::FlushJsonBlockCacheDB, BlockchainDb}, }; use alloy_primitives::{keccak256, Address, Bytes, B256, U256, U64}; -use alloy_provider::{network::Ethereum, Provider}; +use alloy_provider::{ Provider}; use alloy_rpc_types::{Block, BlockId, Transaction}; use alloy_transport::Transport; use eyre::WrapErr; @@ -103,7 +103,7 @@ pub struct BackendHandler { impl BackendHandler where T: Transport + Clone, - P: Provider + Clone + Unpin + 'static, + P: Provider + Clone + Unpin + 'static, { fn new( provider: P, @@ -291,7 +291,7 @@ where impl Future for BackendHandler where T: Transport + Clone + Unpin, - P: Provider + Clone + Unpin + 'static, + P: Provider + Clone + Unpin + 'static, { type Output = (); @@ -525,7 +525,7 @@ impl SharedBackend { ) -> Self where T: Transport + Clone + Unpin, - P: Provider + Unpin + 'static + Clone, + P: Provider + Unpin + 'static + Clone, { let (shared, handler) = Self::new(provider, db, pin_block); // spawn the provider handler to a task @@ -543,7 +543,7 @@ impl SharedBackend { ) -> Self where T: Transport + Clone + Unpin, - P: Provider + Unpin + 'static + Clone, + P: Provider + Unpin + 'static + Clone, { let (shared, handler) = Self::new(provider, db, pin_block); @@ -573,7 +573,7 @@ impl SharedBackend { ) -> (Self, BackendHandler) where T: Transport + Clone + Unpin, - P: Provider + Unpin + 'static + Clone, + P: Provider + Unpin + 'static + Clone, { let (backend, backend_rx) = channel(1); let cache = Arc::new(FlushJsonBlockCacheDB(Arc::clone(db.cache()))); diff --git a/crates/evm/core/src/fork/init.rs b/crates/evm/core/src/fork/init.rs index decc00c3aa84..c43d28955a7b 100644 --- a/crates/evm/core/src/fork/init.rs +++ b/crates/evm/core/src/fork/init.rs @@ -11,7 +11,7 @@ use revm::primitives::{BlockEnv, CfgEnv, Env, TxEnv}; /// Initializes a REVM block environment based on a forked /// ethereum provider. // todo(onbjerg): these bounds needed cus of the bounds in `Provider`, can simplify? -pub async fn environment>( +pub async fn environment>( provider: &P, memory_limit: u64, gas_price: Option, diff --git a/crates/forge/bin/cmd/create.rs b/crates/forge/bin/cmd/create.rs index 4b73e47faebd..51d65fa5eed5 100644 --- a/crates/forge/bin/cmd/create.rs +++ b/crates/forge/bin/cmd/create.rs @@ -201,7 +201,7 @@ impl CreateArgs { } /// Deploys the contract - async fn deploy, T: Transport + Clone>( + async fn deploy, T: Transport + Clone>( self, abi: JsonAbi, bin: BytecodeObject, @@ -433,7 +433,7 @@ where impl Deployer where B: Borrow

+ Clone, - P: Provider, + P: Provider, T: Transport + Clone, { /// Broadcasts the contract deployment transaction and after waiting for it to @@ -522,7 +522,7 @@ where impl DeploymentTxFactory where B: Borrow

+ Clone, - P: Provider, + P: Provider, T: Transport + Clone, { /// Creates a factory for deployment of the Contract with bytecode, and the diff --git a/crates/script/src/broadcast.rs b/crates/script/src/broadcast.rs index cfb0cf7a7c8c..7da5725e8109 100644 --- a/crates/script/src/broadcast.rs +++ b/crates/script/src/broadcast.rs @@ -5,7 +5,7 @@ use crate::{ }; use alloy_chains::Chain; use alloy_eips::eip2718::Encodable2718; -use alloy_network::{Ethereum, EthereumSigner, TransactionBuilder}; +use alloy_network::{EthereumSigner, TransactionBuilder}; use alloy_primitives::{utils::format_units, Address, TxHash, U256}; use alloy_provider::{utils::Eip1559Estimation, Provider}; use alloy_rpc_types::TransactionRequest; @@ -37,7 +37,7 @@ pub async fn estimate_gas( estimate_multiplier: u64, ) -> Result<()> where - P: Provider, + P: Provider, T: Transport + Clone, { // if already set, some RPC endpoints might simply return the gas value that is already @@ -371,22 +371,15 @@ impl BundledState { shell::println("\n\n==========================")?; shell::println("\nONCHAIN EXECUTION COMPLETE & SUCCESSFUL.")?; - let (total_gas, total_gas_price, total_paid) = sequence.receipts.iter().fold( - (U256::ZERO, U256::ZERO, U256::ZERO), - |acc, receipt| { + let (total_gas, total_gas_price, total_paid) = + sequence.receipts.iter().fold((0, 0, 0), |acc, receipt| { let gas_used = receipt.gas_used.unwrap_or_default(); let gas_price = receipt.effective_gas_price; - ( - acc.0 + gas_used, - acc.1 + U256::from(gas_price), - acc.2 + gas_used * U256::from(gas_price), - ) - }, - ); + (acc.0 + gas_used, acc.1 + gas_price, acc.2 + gas_used * gas_price) + }); let paid = format_units(total_paid, 18).unwrap_or_else(|_| "N/A".to_string()); - let avg_gas_price = - format_units(total_gas_price / U256::from(sequence.receipts.len()), 9) - .unwrap_or_else(|_| "N/A".to_string()); + let avg_gas_price = format_units(total_gas_price / sequence.receipts.len() as u64, 9) + .unwrap_or_else(|_| "N/A".to_string()); shell::println(format!( "Total Paid: {} ETH ({} gas * avg {} gwei)", diff --git a/crates/script/src/receipts.rs b/crates/script/src/receipts.rs index a3bf398aca42..15106bcef76f 100644 --- a/crates/script/src/receipts.rs +++ b/crates/script/src/receipts.rs @@ -18,8 +18,7 @@ enum TxStatus { impl From for TxStatus { fn from(receipt: TransactionReceipt) -> Self { - let status = receipt.status_code.expect("receipt is from an ancient, pre-EIP658 block"); - if status.is_zero() { + if !receipt.status() { TxStatus::Revert(receipt) } else { TxStatus::Success(receipt) @@ -157,11 +156,7 @@ pub fn print_receipt(chain: Chain, receipt: &TransactionReceipt) { let gas_price = receipt.effective_gas_price; foundry_common::shell::println(format!( "\n##### {chain}\n{status}Hash: {tx_hash:?}{caddr}\nBlock: {bn}\n{gas}\n", - status = if receipt.status_code.map_or(true, |s| s.is_zero()) { - "❌ [Failed]" - } else { - "✅ [Success]" - }, + status = if !receipt.status() { "❌ [Failed]" } else { "✅ [Success]" }, tx_hash = receipt.transaction_hash, caddr = if let Some(addr) = &receipt.contract_address { format!("\nContract Address: {}", addr.to_checksum(None)) @@ -169,10 +164,10 @@ pub fn print_receipt(chain: Chain, receipt: &TransactionReceipt) { String::new() }, bn = receipt.block_number.unwrap_or_default(), - gas = if gas_price.is_zero() { + gas = if gas_price == 0 { format!("Gas Used: {gas_used}") } else { - let paid = format_units(gas_used.saturating_mul(gas_price.to()), 18) + let paid = format_units(gas_used.saturating_mul(gas_price), 18) .unwrap_or_else(|_| "N/A".into()); let gas_price = format_units(U256::from(gas_price), 9).unwrap_or_else(|_| "N/A".into()); format!( From 5204f61aa945c2088f6d4326e5e971fbbee6ce4d Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Thu, 4 Apr 2024 06:16:24 +0400 Subject: [PATCH 45/63] Update cargo.toml --- Cargo.lock | 8 ++++++-- Cargo.toml | 8 ++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index aad1b7023d8a..796f5bd425bb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3532,7 +3532,9 @@ dependencies = [ [[package]] name = "foundry-block-explorers" -version = "0.2.4" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee75d972291181ae98bd1b48647ca8d8832159012b240ca1b7225085d4a63f00" dependencies = [ "alloy-chains", "alloy-json-abi", @@ -3688,7 +3690,9 @@ dependencies = [ [[package]] name = "foundry-compilers" -version = "0.3.13" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd3323f90e9f256a2c359dbb1cc7e1b7e4fef9e04e5a82693895e959a6efe010" dependencies = [ "alloy-json-abi", "alloy-primitives", diff --git a/Cargo.toml b/Cargo.toml index e9c36a4749a6..6b47a23e3b70 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -136,8 +136,8 @@ foundry-wallets = { path = "crates/wallets" } foundry-linking = { path = "crates/linking" } # solc & compilation utilities -foundry-block-explorers = { version = "0.2.4", default-features = false } -foundry-compilers = { version = "0.3.13", default-features = false } +foundry-block-explorers = { version = "0.2.5", default-features = false } +foundry-compilers = { version = "0.3.14", default-features = false } ## revm # no default features to avoid c-kzg @@ -219,7 +219,3 @@ axum = "0.6" hyper = "0.14" tower = "0.4" tower-http = "0.4" - -[patch.crates-io] -foundry-compilers = { path = "../compilers" } -foundry-block-explorers = { path = "../block-explorers" } From 879153abe777d0f7989ea5a5afff7cbac561ab3f Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Thu, 4 Apr 2024 06:26:23 +0400 Subject: [PATCH 46/63] fmt --- crates/anvil/src/eth/backend/mem/mod.rs | 9 +++------ crates/anvil/tests/it/api.rs | 3 ++- crates/cli/src/utils/mod.rs | 2 +- crates/common/src/fmt/ui.rs | 23 +++++++++++------------ crates/common/src/transactions.rs | 2 +- crates/evm/core/src/fork/backend.rs | 2 +- 6 files changed, 19 insertions(+), 22 deletions(-) diff --git a/crates/anvil/src/eth/backend/mem/mod.rs b/crates/anvil/src/eth/backend/mem/mod.rs index 0093a2d5f997..e75c116afed0 100644 --- a/crates/anvil/src/eth/backend/mem/mod.rs +++ b/crates/anvil/src/eth/backend/mem/mod.rs @@ -1262,8 +1262,7 @@ impl Backend { for log in logs { let mut is_match: bool = true; if !filter.address.is_empty() && filter.has_topics() { - if !params.filter_address(&log.address) || !params.filter_topics(log.topics()) - { + if !params.filter_address(&log.address) || !params.filter_topics(log.topics()) { is_match = false; } } else if !filter.address.is_empty() { @@ -1985,10 +1984,8 @@ impl Backend { }) .collect(), }; - let receipt_with_bloom = ReceiptWithBloom { - receipt, - logs_bloom: tx_receipt.as_receipt_with_bloom().logs_bloom, - }; + let receipt_with_bloom = + ReceiptWithBloom { receipt, logs_bloom: tx_receipt.as_receipt_with_bloom().logs_bloom }; let inner = match tx_receipt { TypedReceipt::EIP1559(_) => TypedReceipt::EIP1559(receipt_with_bloom), diff --git a/crates/anvil/tests/it/api.rs b/crates/anvil/tests/it/api.rs index 9486a9900076..d34499a3e782 100644 --- a/crates/anvil/tests/it/api.rs +++ b/crates/anvil/tests/it/api.rs @@ -8,7 +8,8 @@ use alloy_primitives::{Address as rAddress, B256, U256 as rU256}; use alloy_provider::Provider; use alloy_rpc_types::{ request::{TransactionInput as CallInput, TransactionRequest as CallRequest}, - state::{AccountOverride, StateOverride}, WithOtherFields, + state::{AccountOverride, StateOverride}, + WithOtherFields, }; use anvil::{ eth::{api::CLIENT_VERSION, EthApi}, diff --git a/crates/cli/src/utils/mod.rs b/crates/cli/src/utils/mod.rs index 9c7740ba57d1..ae3220cebd97 100644 --- a/crates/cli/src/utils/mod.rs +++ b/crates/cli/src/utils/mod.rs @@ -1,6 +1,6 @@ use alloy_json_abi::JsonAbi; use alloy_primitives::U256; -use alloy_provider::{Provider}; +use alloy_provider::Provider; use alloy_transport::Transport; use eyre::{ContextCompat, Result}; use foundry_config::{Chain, Config}; diff --git a/crates/common/src/fmt/ui.rs b/crates/common/src/fmt/ui.rs index 59863af1a601..188437ed60a3 100644 --- a/crates/common/src/fmt/ui.rs +++ b/crates/common/src/fmt/ui.rs @@ -159,18 +159,17 @@ impl UIfmt for TransactionReceipt { blob_gas_used, } = self; - let (logs_bloom, status, cumulative_gas_used, logs) = if let Some(receipt) = - inner.as_receipt_with_bloom() - { - let ReceiptWithBloom { - logs_bloom, - receipt: Receipt { status, cumulative_gas_used, logs }, - } = receipt; - - (Some(logs_bloom), Some(status), Some(cumulative_gas_used), Some(logs)) - } else { - Default::default() - }; + let (logs_bloom, status, cumulative_gas_used, logs) = + if let Some(receipt) = inner.as_receipt_with_bloom() { + let ReceiptWithBloom { + logs_bloom, + receipt: Receipt { status, cumulative_gas_used, logs }, + } = receipt; + + (Some(logs_bloom), Some(status), Some(cumulative_gas_used), Some(logs)) + } else { + Default::default() + }; let mut pretty = format!( " diff --git a/crates/common/src/transactions.rs b/crates/common/src/transactions.rs index fa27c837db05..dcafaeb10065 100644 --- a/crates/common/src/transactions.rs +++ b/crates/common/src/transactions.rs @@ -1,5 +1,5 @@ //! wrappers for transactions -use alloy_provider::{Provider}; +use alloy_provider::Provider; use alloy_rpc_types::{BlockId, TransactionReceipt}; use alloy_transport::Transport; use eyre::Result; diff --git a/crates/evm/core/src/fork/backend.rs b/crates/evm/core/src/fork/backend.rs index a14742dc103d..b78eec975af4 100644 --- a/crates/evm/core/src/fork/backend.rs +++ b/crates/evm/core/src/fork/backend.rs @@ -4,7 +4,7 @@ use crate::{ fork::{cache::FlushJsonBlockCacheDB, BlockchainDb}, }; use alloy_primitives::{keccak256, Address, Bytes, B256, U256, U64}; -use alloy_provider::{ Provider}; +use alloy_provider::Provider; use alloy_rpc_types::{Block, BlockId, Transaction}; use alloy_transport::Transport; use eyre::WrapErr; From 0431bb3bee592bf1041aa3716d356fbafc168426 Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Thu, 4 Apr 2024 06:43:52 +0400 Subject: [PATCH 47/63] fixes --- crates/anvil/core/src/eth/transaction/mod.rs | 2 +- crates/anvil/src/tasks/mod.rs | 4 ++-- crates/common/src/transactions.rs | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/anvil/core/src/eth/transaction/mod.rs b/crates/anvil/core/src/eth/transaction/mod.rs index 21bb25f61b09..79347e21bd9d 100644 --- a/crates/anvil/core/src/eth/transaction/mod.rs +++ b/crates/anvil/core/src/eth/transaction/mod.rs @@ -993,6 +993,7 @@ pub struct TransactionInfo { } #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] pub struct DepositReceipt { #[serde(flatten)] pub inner: ReceiptWithBloom, @@ -1247,7 +1248,6 @@ pub fn convert_to_anvil_receipt(receipt: TransactionReceipt) -> ReceiptResponse #[cfg(test)] mod tests { - use alloy_consensus::Receipt; use alloy_primitives::{b256, hex, LogData}; use std::str::FromStr; diff --git a/crates/anvil/src/tasks/mod.rs b/crates/anvil/src/tasks/mod.rs index 952ff15cd20e..0d25abccd082 100644 --- a/crates/anvil/src/tasks/mod.rs +++ b/crates/anvil/src/tasks/mod.rs @@ -59,7 +59,7 @@ impl TaskManager { /// let endpoint = "http://...."; /// let (api, handle) = spawn(NodeConfig::default().with_eth_rpc_url(Some(endpoint))).await; /// - /// let provider = RootProvider::::connect_builtin(endpoint).await.unwrap(); + /// let provider = RootProvider::connect_builtin(endpoint).await.unwrap(); /// /// handle.task_manager().spawn_reset_on_new_polled_blocks(provider, api); /// # } @@ -118,7 +118,7 @@ impl TaskManager { /// # async fn t() { /// let (api, handle) = spawn(NodeConfig::default().with_eth_rpc_url(Some("http://...."))).await; /// - /// let provider = RootProvider::::connect_builtin("ws://...").await.unwrap(); + /// let provider = RootProvider::connect_builtin("ws://...").await.unwrap(); /// /// handle.task_manager().spawn_reset_on_subscribed_blocks(provider, api); /// diff --git a/crates/common/src/transactions.rs b/crates/common/src/transactions.rs index dcafaeb10065..1eae8421e565 100644 --- a/crates/common/src/transactions.rs +++ b/crates/common/src/transactions.rs @@ -20,7 +20,7 @@ pub struct TransactionReceiptWithRevertReason { impl TransactionReceiptWithRevertReason { /// Returns if the status of the transaction is 0 (failure) pub fn is_failure(&self) -> bool { - self.receipt.status() + !self.receipt.status() } /// Updates the revert reason field using `eth_call` and returns an Err variant if the revert From 472d4ff256ebc99abd410d4c3ed4fd135ff504bc Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Sat, 6 Apr 2024 01:11:36 +0400 Subject: [PATCH 48/63] ethers clean-up --- Cargo.lock | 5 ++-- crates/cast/bin/cmd/access_list.rs | 2 +- crates/cast/bin/cmd/call.rs | 2 +- crates/cast/bin/cmd/estimate.rs | 2 +- crates/cast/bin/cmd/find_block.rs | 2 +- crates/cast/bin/cmd/logs.rs | 2 +- crates/cast/bin/cmd/mktx.rs | 6 ++-- crates/cast/bin/cmd/rpc.rs | 2 +- crates/cast/bin/cmd/send.rs | 2 +- crates/cast/bin/cmd/storage.rs | 2 +- crates/cast/bin/main.rs | 42 +++++++++++++------------- crates/cheatcodes/src/evm/fork.rs | 11 ++++--- crates/cli/src/utils/mod.rs | 38 ++---------------------- crates/forge/bin/cmd/create.rs | 2 +- crates/forge/tests/it/repros.rs | 32 +++++++------------- crates/script/src/lib.rs | 2 +- crates/script/src/simulate.rs | 2 +- crates/script/src/transaction.rs | 2 +- crates/test-utils/Cargo.toml | 4 +-- crates/test-utils/src/script.rs | 47 ++++++++++-------------------- crates/verify/Cargo.toml | 2 +- crates/verify/src/etherscan/mod.rs | 15 ++++------ crates/verify/src/lib.rs | 2 +- 23 files changed, 81 insertions(+), 147 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f67e3c55a38d..de645b2a3a47 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3501,10 +3501,10 @@ version = "0.2.0" dependencies = [ "alloy-json-abi", "alloy-primitives", + "alloy-provider", "async-trait", "clap", "const-hex", - "ethers-providers", "eyre", "foundry-block-explorers", "foundry-cli", @@ -3939,8 +3939,7 @@ name = "foundry-test-utils" version = "0.2.0" dependencies = [ "alloy-primitives", - "ethers-core", - "ethers-providers", + "alloy-provider", "eyre", "fd-lock 4.0.2", "foundry-common", diff --git a/crates/cast/bin/cmd/access_list.rs b/crates/cast/bin/cmd/access_list.rs index 656d04836130..5a5ce3ee5575 100644 --- a/crates/cast/bin/cmd/access_list.rs +++ b/crates/cast/bin/cmd/access_list.rs @@ -62,7 +62,7 @@ impl AccessListArgs { let AccessListArgs { to, sig, args, data, tx, eth, block, json: to_json } = self; let config = Config::from(ð); - let provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_provider(&config)?; let chain = utils::get_chain(config.chain, &provider).await?; let sender = eth.wallet.sender().await; let etherscan_api_key = config.get_etherscan_api_key(Some(chain)); diff --git a/crates/cast/bin/cmd/call.rs b/crates/cast/bin/cmd/call.rs index 228cab71c31b..3ad1cf3a977c 100644 --- a/crates/cast/bin/cmd/call.rs +++ b/crates/cast/bin/cmd/call.rs @@ -111,7 +111,7 @@ impl CallArgs { } = self; let config = Config::from(ð); - let provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_provider(&config)?; let chain = utils::get_chain(config.chain, &provider).await?; let sender = eth.wallet.sender().await; let etherscan_api_key = config.get_etherscan_api_key(Some(chain)); diff --git a/crates/cast/bin/cmd/estimate.rs b/crates/cast/bin/cmd/estimate.rs index c024768a49fc..545181b264a9 100644 --- a/crates/cast/bin/cmd/estimate.rs +++ b/crates/cast/bin/cmd/estimate.rs @@ -83,7 +83,7 @@ impl EstimateArgs { let figment = Figment::from(Config::figment()).merge(etherscan).merge(rpc); let config = Config::try_from(figment)?; - let provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_provider(&config)?; let chain = utils::get_chain(config.chain, &provider).await?; let api_key = config.get_etherscan_api_key(Some(chain)); diff --git a/crates/cast/bin/cmd/find_block.rs b/crates/cast/bin/cmd/find_block.rs index 48c23a9613f4..f75f2c82f263 100644 --- a/crates/cast/bin/cmd/find_block.rs +++ b/crates/cast/bin/cmd/find_block.rs @@ -22,7 +22,7 @@ impl FindBlockArgs { let ts_target = timestamp; let config = Config::from(&rpc); - let provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_provider(&config)?; let last_block_num = provider.get_block_number().await?; let cast_provider = Cast::new(provider); diff --git a/crates/cast/bin/cmd/logs.rs b/crates/cast/bin/cmd/logs.rs index 0f831a613b91..fbdbecf27825 100644 --- a/crates/cast/bin/cmd/logs.rs +++ b/crates/cast/bin/cmd/logs.rs @@ -75,7 +75,7 @@ impl LogsArgs { } = self; let config = Config::from(ð); - let provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_provider(&config)?; let cast = Cast::new(&provider); diff --git a/crates/cast/bin/cmd/mktx.rs b/crates/cast/bin/cmd/mktx.rs index 3317ff9c6c70..5cd08a63dec9 100644 --- a/crates/cast/bin/cmd/mktx.rs +++ b/crates/cast/bin/cmd/mktx.rs @@ -6,7 +6,7 @@ use clap::Parser; use eyre::Result; use foundry_cli::{ opts::{EthereumOpts, TransactionOpts}, - utils::{self, get_alloy_provider}, + utils::{self, get_provider}, }; use foundry_common::ens::NameOrAddress; use foundry_config::Config; @@ -77,7 +77,7 @@ impl MakeTxArgs { tx::validate_to_address(&code, &to)?; let config = Config::from(ð); - let provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_provider(&config)?; let chain = utils::get_chain(config.chain, &provider).await?; let api_key = config.get_etherscan_api_key(Some(chain)); @@ -91,7 +91,7 @@ impl MakeTxArgs { tx.nonce = Some(provider.get_transaction_count(from, None).await?); } - let provider = get_alloy_provider(&config)?; + let provider = get_provider(&config)?; let (tx, _) = tx::build_tx(&provider, from, to, code, sig, args, tx, chain, api_key).await?; diff --git a/crates/cast/bin/cmd/rpc.rs b/crates/cast/bin/cmd/rpc.rs index bd0a55ce4258..9dffcfd18de5 100644 --- a/crates/cast/bin/cmd/rpc.rs +++ b/crates/cast/bin/cmd/rpc.rs @@ -38,7 +38,7 @@ impl RpcArgs { let RpcArgs { raw, method, params, rpc } = self; let config = Config::from(&rpc); - let provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_provider(&config)?; let params = if raw { if params.is_empty() { diff --git a/crates/cast/bin/cmd/send.rs b/crates/cast/bin/cmd/send.rs index 5ce625f992af..e926dc6009bb 100644 --- a/crates/cast/bin/cmd/send.rs +++ b/crates/cast/bin/cmd/send.rs @@ -108,7 +108,7 @@ impl SendTxArgs { tx::validate_to_address(&code, &to)?; let config = Config::from(ð); - let provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_provider(&config)?; let chain = utils::get_chain(config.chain, &provider).await?; let api_key = config.get_etherscan_api_key(Some(chain)); diff --git a/crates/cast/bin/cmd/storage.rs b/crates/cast/bin/cmd/storage.rs index be2ff07739aa..bfa1b7228d9c 100644 --- a/crates/cast/bin/cmd/storage.rs +++ b/crates/cast/bin/cmd/storage.rs @@ -80,7 +80,7 @@ impl StorageArgs { let config = Config::from(&self); let Self { address, slot, block, build, .. } = self; - let provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_provider(&config)?; let address = address.resolve(&provider).await?; // Slot was provided, perform a simple RPC call diff --git a/crates/cast/bin/main.rs b/crates/cast/bin/main.rs index 4154ef8c7d55..8c0181367b70 100644 --- a/crates/cast/bin/main.rs +++ b/crates/cast/bin/main.rs @@ -204,7 +204,7 @@ async fn main() -> Result<()> { CastSubcommand::AccessList(cmd) => cmd.run().await?, CastSubcommand::Age { block, rpc } => { let config = Config::from(&rpc); - let provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_provider(&config)?; println!( "{}", Cast::new(provider).age(block.unwrap_or(BlockId::Number(Latest))).await? @@ -212,7 +212,7 @@ async fn main() -> Result<()> { } CastSubcommand::Balance { block, who, ether, rpc, erc20 } => { let config = Config::from(&rpc); - let provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_provider(&config)?; let account_addr = who.resolve(&provider).await?; match erc20 { @@ -233,7 +233,7 @@ async fn main() -> Result<()> { } CastSubcommand::BaseFee { block, rpc } => { let config = Config::from(&rpc); - let provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_provider(&config)?; println!( "{}", Cast::new(provider).base_fee(block.unwrap_or(BlockId::Number(Latest))).await? @@ -241,7 +241,7 @@ async fn main() -> Result<()> { } CastSubcommand::Block { block, full, field, json, rpc } => { let config = Config::from(&rpc); - let provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_provider(&config)?; println!( "{}", Cast::new(provider) @@ -251,39 +251,39 @@ async fn main() -> Result<()> { } CastSubcommand::BlockNumber { rpc } => { let config = Config::from(&rpc); - let provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_provider(&config)?; println!("{}", Cast::new(provider).block_number().await?); } CastSubcommand::Chain { rpc } => { let config = Config::from(&rpc); - let provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_provider(&config)?; println!("{}", Cast::new(provider).chain().await?); } CastSubcommand::ChainId { rpc } => { let config = Config::from(&rpc); - let provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_provider(&config)?; println!("{}", Cast::new(provider).chain_id().await?); } CastSubcommand::Client { rpc } => { let config = Config::from(&rpc); - let provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_provider(&config)?; println!("{}", provider.get_client_version().await?); } CastSubcommand::Code { block, who, disassemble, rpc } => { let config = Config::from(&rpc); - let provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_provider(&config)?; let who = who.resolve(&provider).await?; println!("{}", Cast::new(provider).code(who, block, disassemble).await?); } CastSubcommand::Codesize { block, who, rpc } => { let config = Config::from(&rpc); - let provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_provider(&config)?; let who = who.resolve(&provider).await?; println!("{}", Cast::new(provider).codesize(who, block).await?); } CastSubcommand::ComputeAddress { address, nonce, rpc } => { let config = Config::from(&rpc); - let provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_provider(&config)?; let address: Address = stdin::unwrap_line(address)?.parse()?; let computed = Cast::new(provider).compute_address(address, nonce).await?; @@ -318,7 +318,7 @@ async fn main() -> Result<()> { CastSubcommand::FindBlock(cmd) => cmd.run().await?, CastSubcommand::GasPrice { rpc } => { let config = Config::from(&rpc); - let provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_provider(&config)?; println!("{}", Cast::new(provider).gas_price().await?); } CastSubcommand::Index { key_type, key, slot_number } => { @@ -326,25 +326,25 @@ async fn main() -> Result<()> { } CastSubcommand::Implementation { block, who, rpc } => { let config = Config::from(&rpc); - let provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_provider(&config)?; let who = who.resolve(&provider).await?; println!("{}", Cast::new(provider).implementation(who, block).await?); } CastSubcommand::Admin { block, who, rpc } => { let config = Config::from(&rpc); - let provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_provider(&config)?; let who = who.resolve(&provider).await?; println!("{}", Cast::new(provider).admin(who, block).await?); } CastSubcommand::Nonce { block, who, rpc } => { let config = Config::from(&rpc); - let provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_provider(&config)?; let who = who.resolve(&provider).await?; println!("{}", Cast::new(provider).nonce(who, block).await?); } CastSubcommand::Proof { address, slots, rpc, block } => { let config = Config::from(&rpc); - let provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_provider(&config)?; let address = address.resolve(&provider).await?; let value = provider.get_proof(address, slots.into_iter().collect(), block).await?; println!("{}", serde_json::to_string(&value)?); @@ -358,7 +358,7 @@ async fn main() -> Result<()> { CastSubcommand::MakeTx(cmd) => cmd.run().await?, CastSubcommand::PublishTx { raw_tx, cast_async, rpc } => { let config = Config::from(&rpc); - let provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_provider(&config)?; let cast = Cast::new(&provider); let pending_tx = cast.publish(raw_tx).await?; let tx_hash = pending_tx.inner().tx_hash(); @@ -372,7 +372,7 @@ async fn main() -> Result<()> { } CastSubcommand::Receipt { tx_hash, field, json, cast_async, confirmations, rpc } => { let config = Config::from(&rpc); - let provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_provider(&config)?; println!( "{}", Cast::new(provider) @@ -384,7 +384,7 @@ async fn main() -> Result<()> { CastSubcommand::SendTx(cmd) => cmd.run().await?, CastSubcommand::Tx { tx_hash, field, raw, json, rpc } => { let config = Config::from(&rpc); - let provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_provider(&config)?; // Can use either --raw or specify raw as a field let raw = raw || field.as_ref().is_some_and(|f| f == "raw"); @@ -450,7 +450,7 @@ async fn main() -> Result<()> { } CastSubcommand::LookupAddress { who, rpc, verify } => { let config = Config::from(&rpc); - let provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_provider(&config)?; let who = stdin::unwrap_line(who)?; let name = provider.lookup_address(who).await?; @@ -465,7 +465,7 @@ async fn main() -> Result<()> { } CastSubcommand::ResolveName { who, rpc, verify } => { let config = Config::from(&rpc); - let provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_provider(&config)?; let who = stdin::unwrap_line(who)?; let address = provider.resolve_name(&who).await?; diff --git a/crates/cheatcodes/src/evm/fork.rs b/crates/cheatcodes/src/evm/fork.rs index 617d0b1e027e..fdf29f8b24b9 100644 --- a/crates/cheatcodes/src/evm/fork.rs +++ b/crates/cheatcodes/src/evm/fork.rs @@ -4,7 +4,7 @@ use alloy_provider::Provider; use alloy_rpc_types::Filter; use alloy_sol_types::SolValue; use eyre::WrapErr; -use foundry_common::{provider::alloy::ProviderBuilder, types::ToEthers}; +use foundry_common::provider::alloy::ProviderBuilder; use foundry_compilers::utils::RuntimeOrHandle; use foundry_evm_core::fork::CreateFork; @@ -252,16 +252,15 @@ impl Cheatcode for eth_getLogsCall { let provider = ProviderBuilder::new(&url).build()?; let mut filter = Filter::new().address(*target).from_block(from_block).to_block(to_block); for (i, topic) in topics.iter().enumerate() { - let topic = topic.to_ethers(); // todo: needed because rust wants to convert FixedBytes<32> to U256 to convert it back // to FixedBytes<32> and then to Topic for some reason removing the // From impl in alloy does not fix the situation, and it is not possible to impl // From> either because of a conflicting impl match i { - 0 => filter = filter.event_signature(U256::from_be_bytes(topic.to_fixed_bytes())), - 1 => filter = filter.topic1(U256::from_be_bytes(topic.to_fixed_bytes())), - 2 => filter = filter.topic2(U256::from_be_bytes(topic.to_fixed_bytes())), - 3 => filter = filter.topic3(U256::from_be_bytes(topic.to_fixed_bytes())), + 0 => filter = filter.event_signature(*topic), + 1 => filter = filter.topic1(*topic), + 2 => filter = filter.topic2(*topic), + 3 => filter = filter.topic3(*topic), _ => unreachable!(), }; } diff --git a/crates/cli/src/utils/mod.rs b/crates/cli/src/utils/mod.rs index ae3220cebd97..7e659b47fe0e 100644 --- a/crates/cli/src/utils/mod.rs +++ b/crates/cli/src/utils/mod.rs @@ -82,49 +82,17 @@ pub fn abi_to_solidity(abi: &JsonAbi, name: &str) -> Result { Ok(s) } -/// Returns a [RetryProvider](foundry_common::RetryProvider) instantiated using [Config]'s RPC URL -/// and chain. -/// -/// Defaults to `http://localhost:8545` and `Mainnet`. -pub fn get_provider(config: &Config) -> Result { - get_provider_builder(config)?.build() -} - /// Returns a [RetryProvider](foundry_common::alloy::RetryProvider) instantiated using [Config]'s /// RPC -pub fn get_alloy_provider( - config: &Config, -) -> Result { - get_alloy_provider_builder(config)?.build() -} - -/// Returns a [ProviderBuilder](foundry_common::ProviderBuilder) instantiated using [Config]'s RPC -/// URL and chain. -/// -/// Defaults to `http://localhost:8545` and `Mainnet`. -pub fn get_provider_builder( - config: &Config, -) -> Result { - let url = config.get_rpc_url_or_localhost_http()?; - let mut builder = foundry_common::provider::ethers::ProviderBuilder::new(url.as_ref()); - - if let Ok(chain) = config.chain.unwrap_or_default().try_into() { - builder = builder.chain(chain); - } - - let jwt = config.get_rpc_jwt_secret()?; - if let Some(jwt) = jwt { - builder = builder.jwt(jwt.as_ref()); - } - - Ok(builder) +pub fn get_provider(config: &Config) -> Result { + get_provider_builder(config)?.build() } /// Returns a [ProviderBuilder](foundry_common::provider::alloy::ProviderBuilder) instantiated using /// [Config] values. /// /// Defaults to `http://localhost:8545` and `Mainnet`. -pub fn get_alloy_provider_builder( +pub fn get_provider_builder( config: &Config, ) -> Result { let url = config.get_rpc_url_or_localhost_http()?; diff --git a/crates/forge/bin/cmd/create.rs b/crates/forge/bin/cmd/create.rs index 51d65fa5eed5..a768cc40fedd 100644 --- a/crates/forge/bin/cmd/create.rs +++ b/crates/forge/bin/cmd/create.rs @@ -111,7 +111,7 @@ impl CreateArgs { // Add arguments to constructor let config = self.eth.try_load_config_emit_warnings()?; - let provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_provider(&config)?; let params = match abi.constructor { Some(ref v) => { let constructor_args = diff --git a/crates/forge/tests/it/repros.rs b/crates/forge/tests/it/repros.rs index 02f1aa15eea2..b1f8efc49162 100644 --- a/crates/forge/tests/it/repros.rs +++ b/crates/forge/tests/it/repros.rs @@ -4,10 +4,10 @@ use crate::{ config::*, test_helpers::{ForgeTestData, TEST_DATA_DEFAULT}, }; -use alloy_primitives::{address, Address}; -use ethers_core::abi::{Event, EventParam, Log, LogParam, ParamType, RawLog, Token}; +use alloy_dyn_abi::{DecodedEvent, DynSolValue, EventExt}; +use alloy_json_abi::Event; +use alloy_primitives::{address, Address, U256}; use forge::result::TestStatus; -use foundry_common::types::ToEthers; use foundry_config::{fs_permissions::PathPermission, FsPermissions}; use foundry_evm::{ constants::HARDHAT_CONSOLE_ADDRESS, @@ -125,25 +125,15 @@ test_repro!(3347, false, None, |res| { let mut res = res.remove("default/repros/Issue3347.t.sol:Issue3347Test").unwrap(); let test = res.test_results.remove("test()").unwrap(); assert_eq!(test.logs.len(), 1); - let event = Event { - name: "log2".to_string(), - inputs: vec![ - EventParam { name: "x".to_string(), kind: ParamType::Uint(256), indexed: false }, - EventParam { name: "y".to_string(), kind: ParamType::Uint(256), indexed: false }, - ], - anonymous: false, - }; - let raw_log = RawLog { - topics: test.logs[0].data.topics().iter().map(|t| t.to_ethers()).collect(), - data: test.logs[0].data.data.clone().to_vec(), - }; - let log = event.parse_log(raw_log).unwrap(); + let event = Event::parse("event log2(uint256, uint256)").unwrap(); + let decoded = event.decode_log(&test.logs[0].data, false).unwrap(); assert_eq!( - log, - Log { - params: vec![ - LogParam { name: "x".to_string(), value: Token::Uint(1u64.into()) }, - LogParam { name: "y".to_string(), value: Token::Uint(2u64.into()) } + decoded, + DecodedEvent { + indexed: vec![], + body: vec![ + DynSolValue::Uint(U256::from(1), 256), + DynSolValue::Uint(U256::from(2), 256) ] } ); diff --git a/crates/script/src/lib.rs b/crates/script/src/lib.rs index 73e38d99a01c..80537eea7932 100644 --- a/crates/script/src/lib.rs +++ b/crates/script/src/lib.rs @@ -20,7 +20,7 @@ use foundry_common::{ compile::SkipBuildFilter, errors::UnlinkedByteCode, evm::{Breakpoints, EvmArgs}, - provider::ethers::RpcUrl, + provider::alloy::RpcUrl, shell, CONTRACT_MAX_SIZE, SELECTOR_LEN, }; use foundry_compilers::{artifacts::ContractBytecodeSome, ArtifactId}; diff --git a/crates/script/src/simulate.rs b/crates/script/src/simulate.rs index 17d21500ff3f..5ccf7d346f74 100644 --- a/crates/script/src/simulate.rs +++ b/crates/script/src/simulate.rs @@ -18,7 +18,7 @@ use alloy_primitives::{utils::format_units, Address, U256}; use eyre::{Context, Result}; use foundry_cheatcodes::{BroadcastableTransactions, ScriptWallets}; use foundry_cli::utils::{has_different_gas_calc, now}; -use foundry_common::{get_contract_name, provider::ethers::RpcUrl, shell, ContractsByArtifact}; +use foundry_common::{get_contract_name, provider::alloy::RpcUrl, shell, ContractsByArtifact}; use foundry_evm::traces::render_trace_arena; use futures::future::{join_all, try_join_all}; use parking_lot::RwLock; diff --git a/crates/script/src/transaction.rs b/crates/script/src/transaction.rs index 061eba64b6b9..0dc038c05075 100644 --- a/crates/script/src/transaction.rs +++ b/crates/script/src/transaction.rs @@ -3,7 +3,7 @@ use alloy_dyn_abi::JsonAbiExt; use alloy_primitives::{Address, Bytes, B256}; use alloy_rpc_types::request::TransactionRequest; use eyre::{ContextCompat, Result, WrapErr}; -use foundry_common::{fmt::format_token_raw, provider::ethers::RpcUrl, SELECTOR_LEN}; +use foundry_common::{fmt::format_token_raw, provider::alloy::RpcUrl, SELECTOR_LEN}; use foundry_evm::{constants::DEFAULT_CREATE2_DEPLOYER, traces::CallTraceDecoder}; use itertools::Itertools; use revm_inspectors::tracing::types::CallKind; diff --git a/crates/test-utils/Cargo.toml b/crates/test-utils/Cargo.toml index 8e2b75931734..09025e27c6f3 100644 --- a/crates/test-utils/Cargo.toml +++ b/crates/test-utils/Cargo.toml @@ -17,9 +17,7 @@ foundry-compilers = { workspace = true, features = ["project-util"] } foundry-config.workspace = true alloy-primitives.workspace = true - -ethers-core.workspace = true -ethers-providers.workspace = true +alloy-provider.workspace = true eyre.workspace = true fd-lock = "4.0.0" diff --git a/crates/test-utils/src/script.rs b/crates/test-utils/src/script.rs index b60723d9d8d2..8eecdd785310 100644 --- a/crates/test-utils/src/script.rs +++ b/crates/test-utils/src/script.rs @@ -1,12 +1,8 @@ use crate::{init_tracing, TestCommand}; -use alloy_primitives::{Address, U256}; -use ethers_core::types::NameOrAddress; -use ethers_providers::Middleware; +use alloy_primitives::{Address, U64}; +use alloy_provider::Provider; use eyre::Result; -use foundry_common::{ - provider::ethers::{get_http_provider, RetryProvider}, - types::{ToAlloy, ToEthers}, -}; +use foundry_common::provider::alloy::{get_http_provider, RetryProvider}; use std::{collections::BTreeMap, fs, path::Path, str::FromStr}; const BROADCAST_TEST_PATH: &str = "src/Broadcast.t.sol"; @@ -17,8 +13,8 @@ pub struct ScriptTester { pub accounts_pub: Vec

, pub accounts_priv: Vec, pub provider: Option, - pub nonces: BTreeMap, - pub address_nonces: BTreeMap, + pub nonces: BTreeMap, + pub address_nonces: BTreeMap, pub cmd: TestCommand, } @@ -121,13 +117,10 @@ impl ScriptTester { if let Some(provider) = &self.provider { let nonce = provider - .get_transaction_count( - NameOrAddress::Address(self.accounts_pub[index as usize].to_ethers()), - None, - ) + .get_transaction_count(self.accounts_pub[index as usize], None) .await .unwrap(); - self.nonces.insert(index, nonce.to_alloy()); + self.nonces.insert(index, nonce); } } self @@ -135,14 +128,9 @@ impl ScriptTester { pub async fn load_addresses(&mut self, addresses: &[Address]) -> &mut Self { for &address in addresses { - let nonce = self - .provider - .as_ref() - .unwrap() - .get_transaction_count(NameOrAddress::Address(address.to_ethers()), None) - .await - .unwrap(); - self.address_nonces.insert(address, nonce.to_alloy()); + let nonce = + self.provider.as_ref().unwrap().get_transaction_count(address, None).await.unwrap(); + self.address_nonces.insert(address, nonce); } self } @@ -181,18 +169,13 @@ impl ScriptTester { pub async fn assert_nonce_increment(&mut self, keys_indexes: &[(u32, u32)]) -> &mut Self { for &(private_key_slot, expected_increment) in keys_indexes { let addr = self.accounts_pub[private_key_slot as usize]; - let nonce = self - .provider - .as_ref() - .unwrap() - .get_transaction_count(NameOrAddress::Address(addr.to_ethers()), None) - .await - .unwrap(); + let nonce = + self.provider.as_ref().unwrap().get_transaction_count(addr, None).await.unwrap(); let prev_nonce = self.nonces.get(&private_key_slot).unwrap(); assert_eq!( nonce, - (prev_nonce + U256::from(expected_increment)).to_ethers(), + (prev_nonce + U64::from(expected_increment)), "nonce not incremented correctly for {addr}: \ {prev_nonce} + {expected_increment} != {nonce}" ); @@ -210,12 +193,12 @@ impl ScriptTester { .provider .as_ref() .unwrap() - .get_transaction_count(NameOrAddress::Address(address.to_ethers()), None) + .get_transaction_count(*address, None) .await .unwrap(); let prev_nonce = self.address_nonces.get(address).unwrap(); - assert_eq!(nonce, (prev_nonce + U256::from(*expected_increment)).to_ethers()); + assert_eq!(nonce, (prev_nonce + U64::from(*expected_increment))); } self } diff --git a/crates/verify/Cargo.toml b/crates/verify/Cargo.toml index a735b39af57b..832cf1c6b39c 100644 --- a/crates/verify/Cargo.toml +++ b/crates/verify/Cargo.toml @@ -22,7 +22,7 @@ alloy-json-abi.workspace = true alloy-primitives.workspace = true serde.workspace = true eyre.workspace = true -ethers-providers.workspace = true +alloy-provider.workspace = true tracing.workspace = true foundry-compilers = { workspace = true, features = ["full"] } foundry-block-explorers = { workspace = true, features = ["foundry-compilers"] } diff --git a/crates/verify/src/etherscan/mod.rs b/crates/verify/src/etherscan/mod.rs index 5922f64add1a..ec218e714e90 100644 --- a/crates/verify/src/etherscan/mod.rs +++ b/crates/verify/src/etherscan/mod.rs @@ -1,7 +1,7 @@ use super::{provider::VerificationProvider, VerifyArgs, VerifyCheckArgs}; use crate::retry::RETRY_CHECK_ON_VERIFY; use alloy_json_abi::Function; -use ethers_providers::Middleware; +use alloy_provider::Provider; use eyre::{eyre, Context, OptionExt, Result}; use foundry_block_explorers::{ errors::EtherscanError, @@ -10,7 +10,7 @@ use foundry_block_explorers::{ Client, }; use foundry_cli::utils::{self, get_cached_entry_by_name, read_constructor_args_file, LoadConfig}; -use foundry_common::{abi::encode_function_args, retry::Retry, types::ToEthers}; +use foundry_common::{abi::encode_function_args, retry::Retry}; use foundry_compilers::{ artifacts::{BytecodeObject, CompactContract}, cache::CacheEntry, @@ -498,20 +498,17 @@ impl EtherscanVerificationProvider { )?; let creation_data = client.contract_creation_data(args.address).await?; - let transaction = provider - .get_transaction(creation_data.transaction_hash.to_ethers()) - .await? - .ok_or_eyre("Couldn't fetch transaction data from RPC")?; + let transaction = provider.get_transaction_by_hash(creation_data.transaction_hash).await?; let receipt = provider - .get_transaction_receipt(creation_data.transaction_hash.to_ethers()) + .get_transaction_receipt(creation_data.transaction_hash) .await? .ok_or_eyre("Couldn't fetch transaction receipt from RPC")?; let maybe_creation_code: &[u8]; - if receipt.contract_address == Some(args.address.to_ethers()) { + if receipt.contract_address == Some(args.address) { maybe_creation_code = &transaction.input; - } else if transaction.to == Some(DEFAULT_CREATE2_DEPLOYER.to_ethers()) { + } else if transaction.to == Some(DEFAULT_CREATE2_DEPLOYER) { maybe_creation_code = &transaction.input[32..]; } else { eyre::bail!("Fetching of constructor arguments is not supported for contracts created by contracts") diff --git a/crates/verify/src/lib.rs b/crates/verify/src/lib.rs index e06c4bb61e30..be451d83fbb2 100644 --- a/crates/verify/src/lib.rs +++ b/crates/verify/src/lib.rs @@ -185,7 +185,7 @@ impl VerifyArgs { // If RPC is not set, the default chain is used let chain = match config.get_rpc_url() { Some(_) => { - let provider = utils::get_alloy_provider(&config)?; + let provider = utils::get_provider(&config)?; utils::get_chain(config.chain, provider).await? } None => config.chain.unwrap_or_default(), From ecfcca05a17873c4d8761aac50eb851713e0f71c Mon Sep 17 00:00:00 2001 From: grandizzy <38490174+grandizzy@users.noreply.github.com> Date: Thu, 4 Apr 2024 13:33:28 +0300 Subject: [PATCH 49/63] fix(fmt): fix indent closing parenthesis enclosed in { } (#7557) * fix(fmt): fix indent closing parenthesis enclosed in { } * Fix testdata bad formatting --- crates/fmt/src/formatter.rs | 2 +- crates/fmt/testdata/Repros/fmt.sol | 12 ++++++++++++ crates/fmt/testdata/Repros/original.sol | 12 ++++++++++++ testdata/default/cheats/RecordAccountAccesses.t.sol | 2 +- 4 files changed, 26 insertions(+), 2 deletions(-) diff --git a/crates/fmt/src/formatter.rs b/crates/fmt/src/formatter.rs index bf69651003f6..d10cf4b38235 100644 --- a/crates/fmt/src/formatter.rs +++ b/crates/fmt/src/formatter.rs @@ -895,7 +895,7 @@ impl<'a, W: Write> Formatter<'a, W> { write_chunk!(fmt, "{}", stringified.trim_start()) })?; if !last.content.trim_start().is_empty() { - self.write_whitespace_separator(true)?; + self.indented(1, |fmt| fmt.write_whitespace_separator(true))?; } let last_chunk = self.chunk_at(last.loc_before(), last.loc_next(), last.spaced, &last.content); diff --git a/crates/fmt/testdata/Repros/fmt.sol b/crates/fmt/testdata/Repros/fmt.sol index 8439563ab4e7..dc1ac24eb3a0 100644 --- a/crates/fmt/testdata/Repros/fmt.sol +++ b/crates/fmt/testdata/Repros/fmt.sol @@ -5,3 +5,15 @@ function errorIdentifier() { bytes memory error = bytes(""); if (error.length > 0) {} } + +// https://github.com/foundry-rs/foundry/issues/7549 +function one() external { + this.other({ + data: abi.encodeCall( + this.other, + ( + "bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla" + ) + ) + }); +} diff --git a/crates/fmt/testdata/Repros/original.sol b/crates/fmt/testdata/Repros/original.sol index 8439563ab4e7..cee4fc97a6af 100644 --- a/crates/fmt/testdata/Repros/original.sol +++ b/crates/fmt/testdata/Repros/original.sol @@ -5,3 +5,15 @@ function errorIdentifier() { bytes memory error = bytes(""); if (error.length > 0) {} } + +// https://github.com/foundry-rs/foundry/issues/7549 +function one() external { + this.other({ + data: abi.encodeCall( + this.other, + ( + "bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla" + ) + ) + }); +} diff --git a/testdata/default/cheats/RecordAccountAccesses.t.sol b/testdata/default/cheats/RecordAccountAccesses.t.sol index bea20570ae34..a0aa2cb5332d 100644 --- a/testdata/default/cheats/RecordAccountAccesses.t.sol +++ b/testdata/default/cheats/RecordAccountAccesses.t.sol @@ -943,7 +943,7 @@ contract RecordAccountAccessesTest is DSTest { data: abi.encodeCall( Create2or.create2, (bytes32(0), abi.encodePacked(type(ConstructorStorer).creationCode, abi.encode(true))) - ), + ), reverted: false, storageAccesses: new Vm.StorageAccess[](0), depth: 1 From 5efa20e01686859677bf51721c1facd8aea5840b Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Thu, 4 Apr 2024 22:35:45 +0400 Subject: [PATCH 50/63] feat(test): only compile files needed for tests (#7334) * feat(forge test): only compile files needed for tests * remove comment * clippy * update fixtures * getCode + getDeployedCode updates * fixes * fix path matching * clippy * add config flag * fix * docs * fmt * patch compilers * fix Cargo.toml * update patch * update patch * doc * rm space * cargo cheats * new output selection fn * log compiler errors on failure * fixes --- Cargo.lock | 1 + crates/cheatcodes/Cargo.toml | 1 + crates/cheatcodes/assets/cheatcodes.json | 4 +- crates/cheatcodes/spec/src/vm.rs | 6 +- crates/cheatcodes/src/config.rs | 20 ++- crates/cheatcodes/src/fs.rs | 67 +++++++++- crates/chisel/src/executor.rs | 1 + crates/common/src/contracts.rs | 16 +-- crates/config/src/lib.rs | 8 +- crates/forge/bin/cmd/coverage.rs | 9 +- crates/forge/bin/cmd/test/mod.rs | 115 +++++++++++++----- crates/forge/src/lib.rs | 2 +- crates/forge/src/multi_runner.rs | 2 +- crates/forge/tests/cli/config.rs | 1 + .../suggest_when_no_tests_match.stdout | 4 - .../forge/tests/fixtures/warn_no_tests.stdout | 4 - .../tests/fixtures/warn_no_tests_match.stdout | 4 - crates/forge/tests/it/test_helpers.rs | 3 +- crates/script/src/build.rs | 12 +- crates/script/src/execute.rs | 6 +- crates/script/src/lib.rs | 8 +- testdata/default/cheats/GetCode.t.sol | 10 ++ testdata/default/cheats/GetDeployedCode.t.sol | 12 ++ 23 files changed, 241 insertions(+), 75 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index de645b2a3a47..509f0149a317 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3582,6 +3582,7 @@ dependencies = [ "parking_lot", "revm", "rustc-hash", + "semver 1.0.22", "serde_json", "thiserror", "toml 0.8.12", diff --git a/crates/cheatcodes/Cargo.toml b/crates/cheatcodes/Cargo.toml index bb38b840b5d7..17cddc6076c2 100644 --- a/crates/cheatcodes/Cargo.toml +++ b/crates/cheatcodes/Cargo.toml @@ -43,5 +43,6 @@ k256.workspace = true walkdir = "2" p256 = "0.13.2" thiserror = "1" +semver = "1" rustc-hash.workspace = true dialoguer = "0.11.0" diff --git a/crates/cheatcodes/assets/cheatcodes.json b/crates/cheatcodes/assets/cheatcodes.json index dea51432227f..0245890f9c3f 100644 --- a/crates/cheatcodes/assets/cheatcodes.json +++ b/crates/cheatcodes/assets/cheatcodes.json @@ -4621,7 +4621,7 @@ { "func": { "id": "getCode", - "description": "Gets the creation bytecode from an artifact file. Takes in the relative path to the json file.", + "description": "Gets the creation bytecode from an artifact file. Takes in the relative path to the json file or the path to the\nartifact in the form of :: where and parts are optional.", "declaration": "function getCode(string calldata artifactPath) external view returns (bytes memory creationBytecode);", "visibility": "external", "mutability": "view", @@ -4641,7 +4641,7 @@ { "func": { "id": "getDeployedCode", - "description": "Gets the deployed bytecode from an artifact file. Takes in the relative path to the json file.", + "description": "Gets the deployed bytecode from an artifact file. Takes in the relative path to the json file or the path to the\nartifact in the form of :: where and parts are optional.", "declaration": "function getDeployedCode(string calldata artifactPath) external view returns (bytes memory runtimeBytecode);", "visibility": "external", "mutability": "view", diff --git a/crates/cheatcodes/spec/src/vm.rs b/crates/cheatcodes/spec/src/vm.rs index 8f0de363a7fa..42bc15678e5e 100644 --- a/crates/cheatcodes/spec/src/vm.rs +++ b/crates/cheatcodes/spec/src/vm.rs @@ -1397,11 +1397,13 @@ interface Vm { #[cheatcode(group = Filesystem)] function writeLine(string calldata path, string calldata data) external; - /// Gets the creation bytecode from an artifact file. Takes in the relative path to the json file. + /// Gets the creation bytecode from an artifact file. Takes in the relative path to the json file or the path to the + /// artifact in the form of :: where and parts are optional. #[cheatcode(group = Filesystem)] function getCode(string calldata artifactPath) external view returns (bytes memory creationBytecode); - /// Gets the deployed bytecode from an artifact file. Takes in the relative path to the json file. + /// Gets the deployed bytecode from an artifact file. Takes in the relative path to the json file or the path to the + /// artifact in the form of :: where and parts are optional. #[cheatcode(group = Filesystem)] function getDeployedCode(string calldata artifactPath) external view returns (bytes memory runtimeBytecode); diff --git a/crates/cheatcodes/src/config.rs b/crates/cheatcodes/src/config.rs index 1048f6b6937d..9d0ca2ea460d 100644 --- a/crates/cheatcodes/src/config.rs +++ b/crates/cheatcodes/src/config.rs @@ -2,7 +2,7 @@ use super::Result; use crate::{script::ScriptWallets, Vm::Rpc}; use alloy_primitives::Address; use foundry_common::fs::normalize_path; -use foundry_compilers::{utils::canonicalize, ProjectPathsConfig}; +use foundry_compilers::{utils::canonicalize, ArtifactId, ProjectPathsConfig}; use foundry_config::{ cache::StorageCachingConfig, fs_permissions::FsAccessKind, Config, FsPermissions, ResolvedRpcEndpoints, @@ -43,11 +43,20 @@ pub struct CheatsConfig { pub labels: HashMap, /// Script wallets pub script_wallets: Option, + /// Artifacts which are guaranteed to be fresh (either recompiled or cached). + /// If Some, `vm.getDeployedCode` invocations are validated to be in scope of this list. + /// If None, no validation is performed. + pub available_artifacts: Option>, } impl CheatsConfig { /// Extracts the necessary settings from the Config - pub fn new(config: &Config, evm_opts: EvmOpts, script_wallets: Option) -> Self { + pub fn new( + config: &Config, + evm_opts: EvmOpts, + available_artifacts: Option>, + script_wallets: Option, + ) -> Self { let mut allowed_paths = vec![config.__root.0.clone()]; allowed_paths.extend(config.libs.clone()); allowed_paths.extend(config.allow_paths.clone()); @@ -55,6 +64,10 @@ impl CheatsConfig { let rpc_endpoints = config.rpc_endpoints.clone().resolved(); trace!(?rpc_endpoints, "using resolved rpc endpoints"); + // If user explicitly disabled safety checks, do not set available_artifacts + let available_artifacts = + if config.unchecked_cheatcode_artifacts { None } else { available_artifacts }; + Self { ffi: evm_opts.ffi, always_use_create_2_factory: evm_opts.always_use_create_2_factory, @@ -68,6 +81,7 @@ impl CheatsConfig { evm_opts, labels: config.labels.clone(), script_wallets, + available_artifacts, } } @@ -185,6 +199,7 @@ impl Default for CheatsConfig { evm_opts: Default::default(), labels: Default::default(), script_wallets: None, + available_artifacts: Default::default(), } } } @@ -199,6 +214,7 @@ mod tests { &Config { __root: PathBuf::from(root).into(), fs_permissions, ..Default::default() }, Default::default(), None, + None, ) } diff --git a/crates/cheatcodes/src/fs.rs b/crates/cheatcodes/src/fs.rs index e533dfd670d7..037c6ec61e79 100644 --- a/crates/cheatcodes/src/fs.rs +++ b/crates/cheatcodes/src/fs.rs @@ -5,12 +5,13 @@ use alloy_json_abi::ContractObject; use alloy_primitives::U256; use alloy_sol_types::SolValue; use dialoguer::{Input, Password}; -use foundry_common::{fs, get_artifact_path}; +use foundry_common::fs; use foundry_config::fs_permissions::FsAccessKind; +use semver::Version; use std::{ collections::hash_map::Entry, io::{BufRead, BufReader, Write}, - path::Path, + path::{Path, PathBuf}, process::Command, sync::mpsc, thread, @@ -269,9 +270,69 @@ impl Cheatcode for getDeployedCodeCall { } } +/// Returns the path to the json artifact depending on the input +fn get_artifact_path(state: &Cheatcodes, path: &str) -> Result { + if path.ends_with(".json") { + Ok(PathBuf::from(path)) + } else { + let mut parts = path.split(':'); + let file = PathBuf::from(parts.next().unwrap()); + let contract_name = parts.next(); + let version = parts.next(); + + let version = if let Some(version) = version { + Some(Version::parse(version).map_err(|_| fmt_err!("Error parsing version"))?) + } else { + None + }; + + // Use available artifacts list if available + if let Some(available_ids) = &state.config.available_artifacts { + let mut artifact = None; + + for id in available_ids.iter() { + // name might be in the form of "Counter.0.8.23" + let id_name = id.name.split('.').next().unwrap(); + + if !id.source.ends_with(&file) { + continue; + } + if let Some(name) = contract_name { + if id_name != name { + continue; + } + } + if let Some(ref version) = version { + if id.version.minor != version.minor || + id.version.major != version.major || + id.version.patch != version.patch + { + continue; + } + } + if artifact.is_some() { + return Err(fmt_err!("Multiple matching artifacts found")); + } + artifact = Some(id); + } + + let artifact = artifact.ok_or_else(|| fmt_err!("No matching artifact found"))?; + Ok(artifact.path.clone()) + } else { + let file = file.to_string_lossy(); + let contract_name = if let Some(contract_name) = contract_name { + contract_name.to_owned() + } else { + file.replace(".sol", "") + }; + Ok(state.config.paths.artifacts.join(format!("{file}/{contract_name}.json"))) + } + } +} + /// Reads the bytecode object(s) from the matching artifact fn read_bytecode(state: &Cheatcodes, path: &str) -> Result { - let path = get_artifact_path(&state.config.paths, path); + let path = get_artifact_path(state, path)?; let path = state.config.ensure_path_allowed(path, FsAccessKind::Read)?; let data = fs::read_to_string(path)?; serde_json::from_str::(&data).map_err(Into::into) diff --git a/crates/chisel/src/executor.rs b/crates/chisel/src/executor.rs index 69e35f9477ce..b5b440959a5c 100644 --- a/crates/chisel/src/executor.rs +++ b/crates/chisel/src/executor.rs @@ -307,6 +307,7 @@ impl SessionSource { &self.config.foundry_config, self.config.evm_opts.clone(), None, + None, ) .into(), ) diff --git a/crates/common/src/contracts.rs b/crates/common/src/contracts.rs index 2687b93e3784..c406d0e45172 100644 --- a/crates/common/src/contracts.rs +++ b/crates/common/src/contracts.rs @@ -5,13 +5,12 @@ use alloy_primitives::{hex, Address, Selector, B256}; use eyre::Result; use foundry_compilers::{ artifacts::{CompactContractBytecode, ContractBytecodeSome}, - ArtifactId, ProjectPathsConfig, + ArtifactId, }; use std::{ collections::BTreeMap, fmt, ops::{Deref, DerefMut}, - path::PathBuf, }; type ArtifactWithContractRef<'a> = (&'a ArtifactId, &'a (JsonAbi, Vec)); @@ -170,19 +169,6 @@ pub fn get_file_name(id: &str) -> &str { id.split(':').next().unwrap_or(id) } -/// Returns the path to the json artifact depending on the input -pub fn get_artifact_path(paths: &ProjectPathsConfig, path: &str) -> PathBuf { - if path.ends_with(".json") { - PathBuf::from(path) - } else { - let parts: Vec<&str> = path.split(':').collect(); - let file = parts[0]; - let contract_name = - if parts.len() == 1 { parts[0].replace(".sol", "") } else { parts[1].to_string() }; - paths.artifacts.join(format!("{file}/{contract_name}.json")) - } -} - /// Helper function to convert CompactContractBytecode ~> ContractBytecodeSome pub fn compact_to_contract(contract: CompactContractBytecode) -> Result { Ok(ContractBytecodeSome { diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs index e49aa4559cd3..51769ab314a0 100644 --- a/crates/config/src/lib.rs +++ b/crates/config/src/lib.rs @@ -387,6 +387,10 @@ pub struct Config { /// Address labels pub labels: HashMap, + /// Whether to enable safety checks for `vm.getCode` and `vm.getDeployedCode` invocations. + /// If disabled, it is possible to access artifacts which were not recompiled or cached. + pub unchecked_cheatcode_artifacts: bool, + /// The root path where the config detection started from, `Config::with_root` #[doc(hidden)] // We're skipping serialization here, so it won't be included in the [`Config::to_string()`] @@ -662,7 +666,8 @@ impl Config { self.create_project(false, true) } - fn create_project(&self, cached: bool, no_artifacts: bool) -> Result { + /// Creates a [Project] with the given `cached` and `no_artifacts` flags + pub fn create_project(&self, cached: bool, no_artifacts: bool) -> Result { let mut project = Project::builder() .artifacts(self.configured_artifacts_handler()) .paths(self.project_paths()) @@ -1925,6 +1930,7 @@ impl Default for Config { fmt: Default::default(), doc: Default::default(), labels: Default::default(), + unchecked_cheatcode_artifacts: false, __non_exhaustive: (), __warnings: vec![], } diff --git a/crates/forge/bin/cmd/coverage.rs b/crates/forge/bin/cmd/coverage.rs index 9b6d19e74bee..8dc4629b9f7e 100644 --- a/crates/forge/bin/cmd/coverage.rs +++ b/crates/forge/bin/cmd/coverage.rs @@ -303,6 +303,8 @@ impl CoverageArgs { ) -> Result<()> { let root = project.paths.root; + let artifact_ids = output.artifact_ids().map(|(id, _)| id).collect(); + // Build the contract runner let env = evm_opts.evm_env().await?; let mut runner = MultiContractRunnerBuilder::default() @@ -310,7 +312,12 @@ impl CoverageArgs { .evm_spec(config.evm_spec_id()) .sender(evm_opts.sender) .with_fork(evm_opts.get_fork(&config, env.clone())) - .with_cheats_config(CheatsConfig::new(&config, evm_opts.clone(), None)) + .with_cheats_config(CheatsConfig::new( + &config, + evm_opts.clone(), + Some(artifact_ids), + None, + )) .with_test_options(TestOptions { fuzz: config.fuzz, invariant: config.invariant, diff --git a/crates/forge/bin/cmd/test/mod.rs b/crates/forge/bin/cmd/test/mod.rs index 78000de61871..b4c26e7ee175 100644 --- a/crates/forge/bin/cmd/test/mod.rs +++ b/crates/forge/bin/cmd/test/mod.rs @@ -6,9 +6,10 @@ use forge::{ decode::decode_console_logs, gas_report::GasReport, inspectors::CheatsConfig, + multi_runner::matches_contract, result::{SuiteResult, TestOutcome, TestStatus}, traces::{identifier::SignaturesIdentifier, CallTraceDecoderBuilder, TraceKind}, - MultiContractRunner, MultiContractRunnerBuilder, TestOptions, TestOptionsBuilder, + MultiContractRunner, MultiContractRunnerBuilder, TestFilter, TestOptions, TestOptionsBuilder, }; use foundry_cli::{ opts::CoreBuildArgs, @@ -19,6 +20,7 @@ use foundry_common::{ evm::EvmArgs, shell, }; +use foundry_compilers::artifacts::output_selection::OutputSelection; use foundry_config::{ figment, figment::{ @@ -30,7 +32,12 @@ use foundry_config::{ use foundry_debugger::Debugger; use foundry_evm::traces::identifier::TraceIdentifiers; use regex::Regex; -use std::{sync::mpsc::channel, time::Instant}; +use std::{ + collections::{BTreeMap, BTreeSet}, + path::PathBuf, + sync::mpsc::channel, + time::Instant, +}; use watchexec::config::{InitConfig, RuntimeConfig}; use yansi::Paint; @@ -134,6 +141,69 @@ impl TestArgs { self.execute_tests().await } + /// Returns sources which include any tests to be executed. + /// If no filters are provided, sources are filtered by existence of test/invariant methods in + /// them, If filters are provided, sources are additionaly filtered by them. + pub fn get_sources_to_compile( + &self, + config: &Config, + filter: &ProjectPathsAwareFilter, + ) -> Result> { + let mut project = config.create_project(true, true)?; + project.solc_config.settings.output_selection = + OutputSelection::common_output_selection(["abi".to_string()]); + let output = project.compile()?; + + if output.has_compiler_errors() { + println!("{}", output); + eyre::bail!("Compilation failed"); + } + + // ABIs of all sources + let abis = output + .into_artifacts() + .filter_map(|(id, artifact)| artifact.abi.map(|abi| (id, abi))) + .collect::>(); + + // Filter sources by their abis and contract names. + let sources = abis + .iter() + .filter(|(id, abi)| matches_contract(id, abi, filter)) + .map(|(id, _)| id.source.clone()) + .collect::>(); + + if sources.is_empty() { + if filter.is_empty() { + println!( + "No tests found in project! \ + Forge looks for functions that starts with `test`." + ); + } else { + println!("No tests match the provided pattern:"); + print!("{filter}"); + + // Try to suggest a test when there's no match + if let Some(test_pattern) = &filter.args().test_pattern { + let test_name = test_pattern.as_str(); + let candidates = abis + .into_iter() + .filter(|(id, _)| { + filter.matches_path(&id.source) && filter.matches_contract(&id.name) + }) + .flat_map(|(_, abi)| abi.functions.into_keys()) + .collect::>(); + if let Some(suggestion) = utils::did_you_mean(test_name, candidates).pop() { + println!("\nDid you mean `{suggestion}`?"); + } + } + } + + eyre::bail!("No tests to run"); + } + + Ok(sources) + } + /// Executes all the tests in the project. /// /// This will trigger the build process first. On success all test contracts that match the @@ -168,10 +238,12 @@ impl TestArgs { let mut filter = self.filter(&config); trace!(target: "forge::test", ?filter, "using filter"); - let mut compiler = ProjectCompiler::new().quiet_if(self.json || self.opts.silent); - if config.sparse_mode { - compiler = compiler.filter(Box::new(filter.clone())); - } + let sources_to_compile = self.get_sources_to_compile(&config, &filter)?; + + let compiler = ProjectCompiler::new() + .quiet_if(self.json || self.opts.silent) + .files(sources_to_compile); + let output = compiler.compile(&project)?; // Create test options from general project settings and compiler output. @@ -199,13 +271,20 @@ impl TestArgs { // Clone the output only if we actually need it later for the debugger. let output_clone = should_debug.then(|| output.clone()); + let artifact_ids = output.artifact_ids().map(|(id, _)| id).collect(); + let runner = MultiContractRunnerBuilder::default() .set_debug(should_debug) .initial_balance(evm_opts.initial_balance) .evm_spec(config.evm_spec_id()) .sender(evm_opts.sender) .with_fork(evm_opts.get_fork(&config, env.clone())) - .with_cheats_config(CheatsConfig::new(&config, evm_opts.clone(), None)) + .with_cheats_config(CheatsConfig::new( + &config, + evm_opts.clone(), + Some(artifact_ids), + None, + )) .with_test_options(test_options) .enable_isolation(evm_opts.isolate) .build(project_root, output, env, evm_opts)?; @@ -270,28 +349,6 @@ impl TestArgs { trace!(target: "forge::test", "running all tests"); let num_filtered = runner.matching_test_functions(filter).count(); - if num_filtered == 0 { - println!(); - if filter.is_empty() { - println!( - "No tests found in project! \ - Forge looks for functions that starts with `test`." - ); - } else { - println!("No tests match the provided pattern:"); - print!("{filter}"); - - // Try to suggest a test when there's no match - if let Some(test_pattern) = &filter.args().test_pattern { - let test_name = test_pattern.as_str(); - // Filter contracts but not test functions. - let candidates = runner.all_test_functions(filter).map(|f| &f.name); - if let Some(suggestion) = utils::did_you_mean(test_name, candidates).pop() { - println!("\nDid you mean `{suggestion}`?"); - } - } - } - } if self.debug.is_some() && num_filtered != 1 { eyre::bail!( "{num_filtered} tests matched your criteria, but exactly 1 test must match in order to run the debugger.\n\n\ diff --git a/crates/forge/src/lib.rs b/crates/forge/src/lib.rs index d163f819cc62..98dc0aa4783e 100644 --- a/crates/forge/src/lib.rs +++ b/crates/forge/src/lib.rs @@ -15,7 +15,7 @@ pub mod coverage; pub mod gas_report; -mod multi_runner; +pub mod multi_runner; pub use multi_runner::{MultiContractRunner, MultiContractRunnerBuilder}; mod runner; diff --git a/crates/forge/src/multi_runner.rs b/crates/forge/src/multi_runner.rs index d545d773d820..94d0b0155a8e 100644 --- a/crates/forge/src/multi_runner.rs +++ b/crates/forge/src/multi_runner.rs @@ -383,7 +383,7 @@ impl MultiContractRunnerBuilder { } } -fn matches_contract(id: &ArtifactId, abi: &JsonAbi, filter: &dyn TestFilter) -> bool { +pub fn matches_contract(id: &ArtifactId, abi: &JsonAbi, filter: &dyn TestFilter) -> bool { (filter.matches_path(&id.source) && filter.matches_contract(&id.name)) && abi.functions().any(|func| is_matching_test(func, filter)) } diff --git a/crates/forge/tests/cli/config.rs b/crates/forge/tests/cli/config.rs index 81884f3bcd9f..22d885af4931 100644 --- a/crates/forge/tests/cli/config.rs +++ b/crates/forge/tests/cli/config.rs @@ -126,6 +126,7 @@ forgetest!(can_extract_config_values, |prj, cmd| { labels: Default::default(), cancun: true, isolate: true, + unchecked_cheatcode_artifacts: false, __non_exhaustive: (), __warnings: vec![], }; diff --git a/crates/forge/tests/fixtures/suggest_when_no_tests_match.stdout b/crates/forge/tests/fixtures/suggest_when_no_tests_match.stdout index 1c27d8005cdc..1cf6ad73f895 100644 --- a/crates/forge/tests/fixtures/suggest_when_no_tests_match.stdout +++ b/crates/forge/tests/fixtures/suggest_when_no_tests_match.stdout @@ -1,7 +1,3 @@ -Compiling 1 files with 0.8.23 -Solc 0.8.23 finished in 185.25ms -Compiler run successful! - No tests match the provided pattern: match-test: `testA.*` no-match-test: `testB.*` diff --git a/crates/forge/tests/fixtures/warn_no_tests.stdout b/crates/forge/tests/fixtures/warn_no_tests.stdout index 9b2b8bff4748..a9a7e7fc6711 100644 --- a/crates/forge/tests/fixtures/warn_no_tests.stdout +++ b/crates/forge/tests/fixtures/warn_no_tests.stdout @@ -1,5 +1 @@ -Compiling 1 files with 0.8.23 -Solc 0.8.23 -Compiler run successful! - No tests found in project! Forge looks for functions that starts with `test`. diff --git a/crates/forge/tests/fixtures/warn_no_tests_match.stdout b/crates/forge/tests/fixtures/warn_no_tests_match.stdout index 56f068238d26..4b4080f15fae 100644 --- a/crates/forge/tests/fixtures/warn_no_tests_match.stdout +++ b/crates/forge/tests/fixtures/warn_no_tests_match.stdout @@ -1,7 +1,3 @@ -Compiling 1 files with 0.8.23 -Solc 0.8.23 -Compiler run successful! - No tests match the provided pattern: match-test: `testA.*` no-match-test: `testB.*` diff --git a/crates/forge/tests/it/test_helpers.rs b/crates/forge/tests/it/test_helpers.rs index 0112d4bb96cc..8d54976cc786 100644 --- a/crates/forge/tests/it/test_helpers.rs +++ b/crates/forge/tests/it/test_helpers.rs @@ -204,8 +204,9 @@ impl ForgeTestData { let opts = self.evm_opts.clone(); let env = opts.local_evm_env(); let output = self.output.clone(); + let artifact_ids = output.artifact_ids().map(|(id, _)| id).collect(); self.base_runner() - .with_cheats_config(CheatsConfig::new(&config, opts.clone(), None)) + .with_cheats_config(CheatsConfig::new(&config, opts.clone(), Some(artifact_ids), None)) .sender(config.sender) .with_test_options(self.test_opts.clone()) .build(root, output, env, opts.clone()) diff --git a/crates/script/src/build.rs b/crates/script/src/build.rs index 565c8d0e1227..5f2929c222dd 100644 --- a/crates/script/src/build.rs +++ b/crates/script/src/build.rs @@ -34,6 +34,9 @@ pub struct BuildData { pub output: ProjectCompileOutput, /// Id of target contract artifact. pub target: ArtifactId, + /// Artifact ids of the contracts. Passed to cheatcodes to enable usage of + /// `vm.getDeployedCode`. + pub artifact_ids: Vec, } impl BuildData { @@ -210,6 +213,8 @@ impl PreprocessedState { let mut target_id: Option = None; + let artifact_ids = output.artifact_ids().map(|(id, _)| id).collect(); + // Find target artfifact id by name and path in compilation artifacts. for (id, contract) in output.artifact_ids().filter(|(id, _)| id.source == target_path) { if let Some(name) = &target_name { @@ -246,7 +251,12 @@ impl PreprocessedState { args, script_config, script_wallets, - build_data: BuildData { output, target, project_root: project.root().clone() }, + build_data: BuildData { + output, + target, + project_root: project.root().clone(), + artifact_ids, + }, }) } } diff --git a/crates/script/src/execute.rs b/crates/script/src/execute.rs index 67fd9f96cba7..ece762400c36 100644 --- a/crates/script/src/execute.rs +++ b/crates/script/src/execute.rs @@ -98,7 +98,11 @@ impl PreExecutionState { pub async fn execute(mut self) -> Result { let mut runner = self .script_config - .get_runner_with_cheatcodes(self.script_wallets.clone(), self.args.debug) + .get_runner_with_cheatcodes( + self.build_data.build_data.artifact_ids.clone(), + self.script_wallets.clone(), + self.args.debug, + ) .await?; let mut result = self.execute_with_runner(&mut runner).await?; diff --git a/crates/script/src/lib.rs b/crates/script/src/lib.rs index 80537eea7932..44e824e83295 100644 --- a/crates/script/src/lib.rs +++ b/crates/script/src/lib.rs @@ -548,15 +548,16 @@ impl ScriptConfig { async fn get_runner_with_cheatcodes( &mut self, + artifact_ids: Vec, script_wallets: ScriptWallets, debug: bool, ) -> Result { - self._get_runner(Some(script_wallets), debug).await + self._get_runner(Some((artifact_ids, script_wallets)), debug).await } async fn _get_runner( &mut self, - script_wallets: Option, + cheats_data: Option<(Vec, ScriptWallets)>, debug: bool, ) -> Result { trace!("preparing script runner"); @@ -585,7 +586,7 @@ impl ScriptConfig { .spec(self.config.evm_spec_id()) .gas_limit(self.evm_opts.gas_limit()); - if let Some(script_wallets) = script_wallets { + if let Some((artifact_ids, script_wallets)) = cheats_data { builder = builder.inspectors(|stack| { stack .debug(debug) @@ -593,6 +594,7 @@ impl ScriptConfig { CheatsConfig::new( &self.config, self.evm_opts.clone(), + Some(artifact_ids), Some(script_wallets), ) .into(), diff --git a/testdata/default/cheats/GetCode.t.sol b/testdata/default/cheats/GetCode.t.sol index 8f47188d554d..d308712e9d6b 100644 --- a/testdata/default/cheats/GetCode.t.sol +++ b/testdata/default/cheats/GetCode.t.sol @@ -4,6 +4,8 @@ pragma solidity 0.8.18; import "ds-test/test.sol"; import "cheats/Vm.sol"; +contract TestContract {} + contract GetCodeTest is DSTest { Vm constant vm = Vm(HEVM_ADDRESS); @@ -70,4 +72,12 @@ contract GetCodeTest is DSTest { function testFailGetUnlinked() public { vm.getCode("UnlinkedContract.sol"); } + + function testWithVersion() public { + bytes memory code = vm.getCode("cheats/GetCode.t.sol:TestContract:0.8.18"); + assertEq(type(TestContract).creationCode, code); + + vm._expectCheatcodeRevert("No matching artifact found"); + vm.getCode("cheats/GetCode.t.sol:TestContract:0.8.19"); + } } diff --git a/testdata/default/cheats/GetDeployedCode.t.sol b/testdata/default/cheats/GetDeployedCode.t.sol index fc8ed609eda9..8d95b243ce56 100644 --- a/testdata/default/cheats/GetDeployedCode.t.sol +++ b/testdata/default/cheats/GetDeployedCode.t.sol @@ -4,6 +4,8 @@ pragma solidity 0.8.18; import "ds-test/test.sol"; import "cheats/Vm.sol"; +contract TestContract {} + contract GetDeployedCodeTest is DSTest { Vm constant vm = Vm(HEVM_ADDRESS); @@ -36,6 +38,16 @@ contract GetDeployedCodeTest is DSTest { emit Payload(address(this), address(0), "hello"); over.emitPayload(address(0), "hello"); } + + function testWithVersion() public { + TestContract test = new TestContract(); + bytes memory code = vm.getDeployedCode("cheats/GetDeployedCode.t.sol:TestContract:0.8.18"); + + assertEq(address(test).code, code); + + vm._expectCheatcodeRevert("No matching artifact found"); + vm.getDeployedCode("cheats/GetDeployedCode.t.sol:TestContract:0.8.19"); + } } interface Override { From 398ff1fd09e6ec67129ea9b3f52f0fc3c50dd550 Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Thu, 4 Apr 2024 22:43:20 +0400 Subject: [PATCH 51/63] fix: do not flood dictionary with data dependent on fuzz inputs (#7552) * fix dictionary * clippy + fmt * fix --- crates/evm/evm/src/executors/fuzz/mod.rs | 15 +- crates/evm/evm/src/executors/invariant/mod.rs | 24 +- crates/evm/fuzz/src/inspector.rs | 7 +- crates/evm/fuzz/src/strategies/calldata.rs | 2 +- crates/evm/fuzz/src/strategies/mod.rs | 3 +- crates/evm/fuzz/src/strategies/param.rs | 4 +- crates/evm/fuzz/src/strategies/state.rs | 230 +++++++++++------- crates/forge/src/runner.rs | 14 +- 8 files changed, 170 insertions(+), 129 deletions(-) diff --git a/crates/evm/evm/src/executors/fuzz/mod.rs b/crates/evm/evm/src/executors/fuzz/mod.rs index 41beb7e43317..ae63d2386bae 100644 --- a/crates/evm/evm/src/executors/fuzz/mod.rs +++ b/crates/evm/evm/src/executors/fuzz/mod.rs @@ -10,10 +10,7 @@ use foundry_evm_core::{ }; use foundry_evm_coverage::HitMaps; use foundry_evm_fuzz::{ - strategies::{ - build_initial_state, collect_state_from_call, fuzz_calldata, fuzz_calldata_from_state, - EvmFuzzState, - }, + strategies::{build_initial_state, fuzz_calldata, fuzz_calldata_from_state, EvmFuzzState}, BaseCounterExample, CounterExample, FuzzCase, FuzzError, FuzzTestResult, }; use foundry_evm_traces::CallTraceArena; @@ -89,7 +86,7 @@ impl FuzzedExecutor { ]; debug!(func=?func.name, should_fail, "fuzzing"); let run_result = self.runner.clone().run(&strat, |calldata| { - let fuzz_res = self.single_fuzz(&state, address, should_fail, calldata)?; + let fuzz_res = self.single_fuzz(address, should_fail, calldata)?; match fuzz_res { FuzzOutcome::Case(case) => { @@ -195,7 +192,6 @@ impl FuzzedExecutor { /// or a `CounterExampleOutcome` pub fn single_fuzz( &self, - state: &EvmFuzzState, address: Address, should_fail: bool, calldata: alloy_primitives::Bytes, @@ -206,9 +202,6 @@ impl FuzzedExecutor { .map_err(|_| TestCaseError::fail(FuzzError::FailedContractCall))?; let state_changeset = call.state_changeset.take().unwrap(); - // Build fuzzer state - collect_state_from_call(&call.logs, &state_changeset, state, &self.config.dictionary); - // When the `assume` cheatcode is called it returns a special string if call.result.as_ref() == MAGIC_ASSUME { return Err(TestCaseError::reject(FuzzError::AssumeReject)) @@ -247,9 +240,9 @@ impl FuzzedExecutor { /// Stores fuzz state for use with [fuzz_calldata_from_state] pub fn build_fuzz_state(&self) -> EvmFuzzState { if let Some(fork_db) = self.executor.backend.active_fork_db() { - build_initial_state(fork_db, &self.config.dictionary) + build_initial_state(fork_db, self.config.dictionary) } else { - build_initial_state(self.executor.backend.mem_db(), &self.config.dictionary) + build_initial_state(self.executor.backend.mem_db(), self.config.dictionary) } } } diff --git a/crates/evm/evm/src/executors/invariant/mod.rs b/crates/evm/evm/src/executors/invariant/mod.rs index 5ed7998ac3e1..835a2bc877bf 100644 --- a/crates/evm/evm/src/executors/invariant/mod.rs +++ b/crates/evm/evm/src/executors/invariant/mod.rs @@ -6,7 +6,7 @@ use alloy_primitives::{Address, FixedBytes, U256}; use alloy_sol_types::{sol, SolCall}; use eyre::{eyre, ContextCompat, Result}; use foundry_common::contracts::{ContractsByAddress, ContractsByArtifact}; -use foundry_config::{FuzzDictionaryConfig, InvariantConfig}; +use foundry_config::InvariantConfig; use foundry_evm_core::{ constants::{CALLER, CHEATCODE_ADDRESS, HARDHAT_CONSOLE_ADDRESS, MAGIC_ASSUME}, utils::{get_function, StateChangeset}, @@ -17,8 +17,8 @@ use foundry_evm_fuzz::{ RandomCallGenerator, SenderFilters, TargetedContracts, }, strategies::{ - build_initial_state, collect_created_contracts, collect_state_from_call, invariant_strat, - override_call_strat, CalldataFuzzDictionary, EvmFuzzState, + build_initial_state, collect_created_contracts, invariant_strat, override_call_strat, + CalldataFuzzDictionary, EvmFuzzState, }, FuzzCase, FuzzedCases, }; @@ -246,13 +246,7 @@ impl<'a> InvariantExecutor<'a> { let mut state_changeset = call_result.state_changeset.to_owned().expect("no changesets"); - collect_data( - &mut state_changeset, - sender, - &call_result, - &fuzz_state, - &self.config.dictionary, - ); + collect_data(&mut state_changeset, sender, &call_result, &fuzz_state); if let Err(error) = collect_created_contracts( &state_changeset, @@ -325,11 +319,14 @@ impl<'a> InvariantExecutor<'a> { } fuzz_cases.borrow_mut().push(FuzzedCases::new(fuzz_runs)); + // Revert state to not persist values between runs. + fuzz_state.revert(); + Ok(()) }); trace!(target: "forge::test::invariant::calldata_address_fuzz_dictionary", "{:?}", calldata_fuzz_dictionary.inner.addresses); - trace!(target: "forge::test::invariant::dictionary", "{:?}", fuzz_state.read().values().iter().map(hex::encode).collect::>()); + trace!(target: "forge::test::invariant::dictionary", "{:?}", fuzz_state.dictionary_read().values().iter().map(hex::encode).collect::>()); let (reverts, error) = failures.into_inner().into_inner(); @@ -361,7 +358,7 @@ impl<'a> InvariantExecutor<'a> { // Stores fuzz state for use with [fuzz_calldata_from_state]. let fuzz_state: EvmFuzzState = - build_initial_state(self.executor.backend.mem_db(), &self.config.dictionary); + build_initial_state(self.executor.backend.mem_db(), self.config.dictionary); // During execution, any newly created contract is added here and used through the rest of // the fuzz run. @@ -668,7 +665,6 @@ fn collect_data( sender: &Address, call_result: &RawCallResult, fuzz_state: &EvmFuzzState, - config: &FuzzDictionaryConfig, ) { // Verify it has no code. let mut has_code = false; @@ -683,7 +679,7 @@ fn collect_data( sender_changeset = state_changeset.remove(sender); } - collect_state_from_call(&call_result.logs, &*state_changeset, fuzz_state, config); + fuzz_state.collect_state_from_call(&call_result.logs, &*state_changeset); // Re-add changes if let Some(changed) = sender_changeset { diff --git a/crates/evm/fuzz/src/inspector.rs b/crates/evm/fuzz/src/inspector.rs index e58afb214fee..5e7e644b11d6 100644 --- a/crates/evm/fuzz/src/inspector.rs +++ b/crates/evm/fuzz/src/inspector.rs @@ -1,4 +1,5 @@ use crate::{invariant::RandomCallGenerator, strategies::EvmFuzzState}; +use alloy_primitives::U256; use revm::{ interpreter::{CallInputs, CallOutcome, CallScheme, Interpreter}, Database, EvmContext, Inspector, @@ -61,11 +62,7 @@ impl Inspector for Fuzzer { impl Fuzzer { /// Collects `stack` and `memory` values into the fuzz dictionary. fn collect_data(&mut self, interpreter: &Interpreter) { - let mut state = self.fuzz_state.write(); - - for slot in interpreter.stack().data() { - state.values_mut().insert(slot.to_be_bytes()); - } + self.fuzz_state.collect_values(interpreter.stack().data().iter().map(U256::to_be_bytes)); // TODO: disabled for now since it's flooding the dictionary // for index in 0..interpreter.shared_memory.len() / 32 { diff --git a/crates/evm/fuzz/src/strategies/calldata.rs b/crates/evm/fuzz/src/strategies/calldata.rs index b3d41bfadbbd..ff3bb5713446 100644 --- a/crates/evm/fuzz/src/strategies/calldata.rs +++ b/crates/evm/fuzz/src/strategies/calldata.rs @@ -41,7 +41,7 @@ impl CalldataFuzzDictionaryConfig { if dict_size > 0 { addresses.extend(std::iter::repeat_with(Address::random).take(dict_size)); // Add all addresses that already had their PUSH bytes collected. - addresses.extend(state.read().addresses()); + addresses.extend(state.dictionary_read().addresses()); } Self { addresses: addresses.into_iter().collect() } diff --git a/crates/evm/fuzz/src/strategies/mod.rs b/crates/evm/fuzz/src/strategies/mod.rs index 63e008ec0c96..0e82a4d4b8d6 100644 --- a/crates/evm/fuzz/src/strategies/mod.rs +++ b/crates/evm/fuzz/src/strategies/mod.rs @@ -14,8 +14,7 @@ pub use calldata::{ mod state; pub use state::{ - build_initial_state, collect_created_contracts, collect_state_from_call, - fuzz_calldata_from_state, EvmFuzzState, + build_initial_state, collect_created_contracts, fuzz_calldata_from_state, EvmFuzzState, }; mod invariants; diff --git a/crates/evm/fuzz/src/strategies/param.rs b/crates/evm/fuzz/src/strategies/param.rs index f287c75dfde1..20e69a27e725 100644 --- a/crates/evm/fuzz/src/strategies/param.rs +++ b/crates/evm/fuzz/src/strategies/param.rs @@ -89,7 +89,7 @@ pub fn fuzz_param_from_state( let state = state.clone(); // Use `Index` instead of `Selector` to not iterate over the entire dictionary. any::().prop_map(move |index| { - let state = state.read(); + let state = state.dictionary_read(); let values = state.values(); let index = index.index(values.len()); *values.iter().nth(index).unwrap() @@ -184,7 +184,7 @@ mod tests { let f = "testArray(uint64[2] calldata values)"; let func = get_func(f).unwrap(); let db = CacheDB::new(EmptyDB::default()); - let state = build_initial_state(&db, &FuzzDictionaryConfig::default()); + let state = build_initial_state(&db, FuzzDictionaryConfig::default()); let strat = proptest::prop_oneof![ 60 => fuzz_calldata(func.clone()), 40 => fuzz_calldata_from_state(func, &state), diff --git a/crates/evm/fuzz/src/strategies/state.rs b/crates/evm/fuzz/src/strategies/state.rs index a8965a884557..8c98c472e1ab 100644 --- a/crates/evm/fuzz/src/strategies/state.rs +++ b/crates/evm/fuzz/src/strategies/state.rs @@ -7,7 +7,7 @@ use foundry_common::contracts::{ContractsByAddress, ContractsByArtifact}; use foundry_config::FuzzDictionaryConfig; use foundry_evm_core::utils::StateChangeset; use indexmap::IndexSet; -use parking_lot::RwLock; +use parking_lot::{lock_api::RwLockReadGuard, RawRwLock, RwLock}; use proptest::prelude::{BoxedStrategy, Strategy}; use revm::{ db::{CacheDB, DatabaseRef}, @@ -19,16 +19,103 @@ use std::{fmt, sync::Arc}; /// A set of arbitrary 32 byte data from the VM used to generate values for the strategy. /// /// Wrapped in a shareable container. -pub type EvmFuzzState = Arc>; +#[derive(Clone, Debug)] +pub struct EvmFuzzState { + inner: Arc>, +} + +impl EvmFuzzState { + pub fn new(dictionary: FuzzDictionary) -> Self { + Self { inner: Arc::new(RwLock::new(dictionary)) } + } + + pub fn collect_values(&self, values: impl IntoIterator) { + let mut dict = self.inner.write(); + for value in values { + dict.insert_value(value); + } + } + + /// Collects state changes from a [StateChangeset] and logs into an [EvmFuzzState] according to + /// the given [FuzzDictionaryConfig]. + pub fn collect_state_from_call(&self, logs: &[Log], state_changeset: &StateChangeset) { + let mut dict = self.inner.write(); + + // Insert log topics and data. + for log in logs { + for topic in log.topics() { + dict.insert_value(topic.0); + } + let chunks = log.data.data.chunks_exact(32); + let rem = chunks.remainder(); + for chunk in chunks { + dict.insert_value(chunk.try_into().unwrap()); + } + if !rem.is_empty() { + dict.insert_value(B256::right_padding_from(rem).0); + } + } + + for (address, account) in state_changeset { + // Insert basic account information + dict.insert_value(address.into_word().into()); + + if dict.config.include_push_bytes { + // Insert push bytes + if let Some(code) = &account.info.code { + dict.insert_address(*address); + for push_byte in collect_push_bytes(code.bytes()) { + dict.insert_value(push_byte); + } + } + } + + if dict.config.include_storage { + // Insert storage + for (slot, value) in &account.storage { + let value = value.present_value; + dict.insert_value(B256::from(*slot).0); + dict.insert_value(B256::from(value).0); + // also add the value below and above the storage value to the dictionary. + if value != U256::ZERO { + let below_value = value - U256::from(1); + dict.insert_value(B256::from(below_value).0); + } + if value != U256::MAX { + let above_value = value + U256::from(1); + dict.insert_value(B256::from(above_value).0); + } + } + } + } + } + + /// Removes all newly added entries from the dictionary. + /// + /// Should be called between fuzz/invariant runs to avoid accumumlating data derived from fuzz + /// inputs. + pub fn revert(&self) { + self.inner.write().revert(); + } + + pub fn dictionary_read(&self) -> RwLockReadGuard<'_, RawRwLock, FuzzDictionary> { + self.inner.read() + } +} // We're using `IndexSet` to have a stable element order when restoring persisted state, as well as // for performance when iterating over the sets. -#[derive(Default)] pub struct FuzzDictionary { /// Collected state values. state_values: IndexSet<[u8; 32]>, /// Addresses that already had their PUSH bytes collected. addresses: IndexSet
, + /// Configuration for the dictionary. + config: FuzzDictionaryConfig, + /// New keys added to the dictionary since container initialization. + new_values: IndexSet<[u8; 32]>, + /// New addresses added to the dictionary since container initialization. + new_addreses: IndexSet
, } impl fmt::Debug for FuzzDictionary { @@ -41,14 +128,39 @@ impl fmt::Debug for FuzzDictionary { } impl FuzzDictionary { - #[inline] - pub fn values(&self) -> &IndexSet<[u8; 32]> { - &self.state_values + pub fn new( + initial_values: IndexSet<[u8; 32]>, + initial_addresses: IndexSet
, + config: FuzzDictionaryConfig, + ) -> Self { + Self { + state_values: initial_values, + addresses: initial_addresses, + config, + new_values: IndexSet::new(), + new_addreses: IndexSet::new(), + } + } + + pub fn insert_value(&mut self, value: [u8; 32]) { + if self.state_values.len() < self.config.max_fuzz_dictionary_values && + self.state_values.insert(value) + { + self.new_values.insert(value); + } + } + + pub fn insert_address(&mut self, address: Address) { + if self.addresses.len() < self.config.max_fuzz_dictionary_addresses && + self.addresses.insert(address) + { + self.new_addreses.insert(address); + } } #[inline] - pub fn values_mut(&mut self) -> &mut IndexSet<[u8; 32]> { - &mut self.state_values + pub fn values(&self) -> &IndexSet<[u8; 32]> { + &self.state_values } #[inline] @@ -56,9 +168,16 @@ impl FuzzDictionary { &self.addresses } - #[inline] - pub fn addresses_mut(&mut self) -> &mut IndexSet
{ - &mut self.addresses + pub fn revert(&mut self) { + for key in self.new_values.iter() { + self.state_values.swap_remove(key); + } + for address in self.new_addreses.iter() { + self.addresses.swap_remove(address); + } + + self.new_values.clear(); + self.new_addreses.clear(); } } @@ -88,9 +207,10 @@ pub fn fuzz_calldata_from_state(func: Function, state: &EvmFuzzState) -> BoxedSt /// Builds the initial [EvmFuzzState] from a database. pub fn build_initial_state( db: &CacheDB, - config: &FuzzDictionaryConfig, + config: FuzzDictionaryConfig, ) -> EvmFuzzState { - let mut state = FuzzDictionary::default(); + let mut values = IndexSet::new(); + let mut addresses = IndexSet::new(); // Sort accounts to ensure deterministic dictionary generation from the same setUp state. let mut accs = db.accounts.iter().collect::>(); @@ -99,15 +219,14 @@ pub fn build_initial_state( for (address, account) in accs { let address: Address = *address; // Insert basic account information - state.values_mut().insert(address.into_word().into()); + values.insert(address.into_word().into()); // Insert push bytes if config.include_push_bytes { if let Some(code) = &account.info.code { - if state.addresses_mut().insert(address) { - for push_byte in collect_push_bytes(code.bytes()) { - state.values_mut().insert(push_byte); - } + addresses.insert(address); + for push_byte in collect_push_bytes(code.bytes()) { + values.insert(push_byte); } } } @@ -115,16 +234,16 @@ pub fn build_initial_state( if config.include_storage { // Insert storage for (slot, value) in &account.storage { - state.values_mut().insert(B256::from(*slot).0); - state.values_mut().insert(B256::from(*value).0); + values.insert(B256::from(*slot).0); + values.insert(B256::from(*value).0); // also add the value below and above the storage value to the dictionary. if *value != U256::ZERO { let below_value = value - U256::from(1); - state.values_mut().insert(B256::from(below_value).0); + values.insert(B256::from(below_value).0); } if *value != U256::MAX { let above_value = value + U256::from(1); - state.values_mut().insert(B256::from(above_value).0); + values.insert(B256::from(above_value).0); } } } @@ -132,73 +251,12 @@ pub fn build_initial_state( // need at least some state data if db is empty otherwise we can't select random data for state // fuzzing - if state.values().is_empty() { + if values.is_empty() { // prefill with a random addresses - state.values_mut().insert(Address::random().into_word().into()); + values.insert(Address::random().into_word().into()); } - Arc::new(RwLock::new(state)) -} - -/// Collects state changes from a [StateChangeset] and logs into an [EvmFuzzState] according to the -/// given [FuzzDictionaryConfig]. -pub fn collect_state_from_call( - logs: &[Log], - state_changeset: &StateChangeset, - state: &EvmFuzzState, - config: &FuzzDictionaryConfig, -) { - let mut state = state.write(); - - // Insert log topics and data. - for log in logs { - for topic in log.topics() { - state.values_mut().insert(topic.0); - } - let chunks = log.data.data.chunks_exact(32); - let rem = chunks.remainder(); - for chunk in chunks { - state.values_mut().insert(chunk.try_into().unwrap()); - } - if !rem.is_empty() { - state.values_mut().insert(B256::right_padding_from(rem).0); - } - } - - for (address, account) in state_changeset { - // Insert basic account information - state.values_mut().insert(address.into_word().into()); - - if config.include_push_bytes && state.addresses.len() < config.max_fuzz_dictionary_addresses - { - // Insert push bytes - if let Some(code) = &account.info.code { - if state.addresses_mut().insert(*address) { - for push_byte in collect_push_bytes(code.bytes()) { - state.values_mut().insert(push_byte); - } - } - } - } - - if config.include_storage && state.state_values.len() < config.max_fuzz_dictionary_values { - // Insert storage - for (slot, value) in &account.storage { - let value = value.present_value; - state.values_mut().insert(B256::from(*slot).0); - state.values_mut().insert(B256::from(value).0); - // also add the value below and above the storage value to the dictionary. - if value != U256::ZERO { - let below_value = value - U256::from(1); - state.values_mut().insert(B256::from(below_value).0); - } - if value != U256::MAX { - let above_value = value + U256::from(1); - state.values_mut().insert(B256::from(above_value).0); - } - } - } - } + EvmFuzzState::new(FuzzDictionary::new(values, addresses, config)) } /// The maximum number of bytes we will look at in bytecodes to find push bytes (24 KiB). diff --git a/crates/forge/src/runner.rs b/crates/forge/src/runner.rs index 7f3258e359fa..508ee9234423 100644 --- a/crates/forge/src/runner.rs +++ b/crates/forge/src/runner.rs @@ -611,7 +611,6 @@ impl<'a> ContractRunner<'a> { self.sender, fuzz_config.clone(), ); - let state = fuzzed_executor.build_fuzz_state(); let result = fuzzed_executor.fuzz(func, address, should_fail, self.revert_decoder); let mut debug = Default::default(); @@ -650,13 +649,12 @@ impl<'a> ContractRunner<'a> { result.first_case.calldata.clone() }; // rerun the last relevant test with traces - let debug_result = FuzzedExecutor::new( - debug_executor, - runner, - self.sender, - fuzz_config, - ) - .single_fuzz(&state, address, should_fail, calldata); + let debug_result = + FuzzedExecutor::new(debug_executor, runner, self.sender, fuzz_config).single_fuzz( + address, + should_fail, + calldata, + ); (debug, breakpoints) = match debug_result { Ok(fuzz_outcome) => match fuzz_outcome { From ec8f6de5dc65d40e8de0ff3448cd03aac919de75 Mon Sep 17 00:00:00 2001 From: Krishang <93703995+kamuik16@users.noreply.github.com> Date: Fri, 5 Apr 2024 00:34:59 +0530 Subject: [PATCH 52/63] Feat: Index cheatcode for Strings (#7539) * feat: index cheatcode * some nits to make it work * nit: use as_str() * final changes * chore: reviewed changes --- crates/cheatcodes/assets/cheatcodes.json | 20 ++++++++++++++++++++ crates/cheatcodes/spec/src/vm.rs | 5 +++++ crates/cheatcodes/src/string.rs | 9 +++++++++ testdata/cheats/Vm.sol | 1 + testdata/default/cheats/StringUtils.t.sol | 12 ++++++++++++ 5 files changed, 47 insertions(+) diff --git a/crates/cheatcodes/assets/cheatcodes.json b/crates/cheatcodes/assets/cheatcodes.json index 0245890f9c3f..360d5de1c442 100644 --- a/crates/cheatcodes/assets/cheatcodes.json +++ b/crates/cheatcodes/assets/cheatcodes.json @@ -4798,6 +4798,26 @@ "status": "stable", "safety": "safe" }, + { + "func": { + "id": "indexOf", + "description": "Returns the index of the first occurrence of a `key` in an `input` string.\nReturns `NOT_FOUND` (i.e. `type(uint256).max`) if the `key` is not found.\nReturns 0 in case of an empty `key`.", + "declaration": "function indexOf(string memory input, string memory key) external pure returns (uint256);", + "visibility": "external", + "mutability": "pure", + "signature": "indexOf(string,string)", + "selector": "0x8a0807b7", + "selectorBytes": [ + 138, + 8, + 7, + 183 + ] + }, + "group": "string", + "status": "stable", + "safety": "safe" + }, { "func": { "id": "isDir", diff --git a/crates/cheatcodes/spec/src/vm.rs b/crates/cheatcodes/spec/src/vm.rs index 42bc15678e5e..93042c1991ff 100644 --- a/crates/cheatcodes/spec/src/vm.rs +++ b/crates/cheatcodes/spec/src/vm.rs @@ -1680,6 +1680,11 @@ interface Vm { /// Splits the given `string` into an array of strings divided by the `delimiter`. #[cheatcode(group = String)] function split(string calldata input, string calldata delimiter) external pure returns (string[] memory outputs); + /// Returns the index of the first occurrence of a `key` in an `input` string. + /// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `key` is not found. + /// Returns 0 in case of an empty `key`. + #[cheatcode(group = String)] + function indexOf(string memory input, string memory key) external pure returns (uint256); // ======== JSON Parsing and Manipulation ======== diff --git a/crates/cheatcodes/src/string.rs b/crates/cheatcodes/src/string.rs index b7992b9450fd..c98560a72f06 100644 --- a/crates/cheatcodes/src/string.rs +++ b/crates/cheatcodes/src/string.rs @@ -2,6 +2,7 @@ use crate::{Cheatcode, Cheatcodes, Result, Vm::*}; use alloy_dyn_abi::{DynSolType, DynSolValue}; +use alloy_primitives::U256; use alloy_sol_types::SolValue; // address @@ -135,6 +136,14 @@ impl Cheatcode for splitCall { } } +// indexOf +impl Cheatcode for indexOfCall { + fn apply(&self, _state: &mut Cheatcodes) -> Result { + let Self { input, key } = self; + Ok(input.find(key).map(U256::from).unwrap_or(U256::MAX).abi_encode()) + } +} + pub(super) fn parse(s: &str, ty: &DynSolType) -> Result { parse_value(s, ty).map(|v| v.abi_encode()) } diff --git a/testdata/cheats/Vm.sol b/testdata/cheats/Vm.sol index 2116acf2b8ff..aff05c278740 100644 --- a/testdata/cheats/Vm.sol +++ b/testdata/cheats/Vm.sol @@ -237,6 +237,7 @@ interface Vm { function getNonce(address account) external view returns (uint64 nonce); function getNonce(Wallet calldata wallet) external returns (uint64 nonce); function getRecordedLogs() external returns (Log[] memory logs); + function indexOf(string memory input, string memory key) external pure returns (uint256); function isDir(string calldata path) external returns (bool result); function isFile(string calldata path) external returns (bool result); function isPersistent(address account) external view returns (bool persistent); diff --git a/testdata/default/cheats/StringUtils.t.sol b/testdata/default/cheats/StringUtils.t.sol index 471d628be018..136164a413d7 100644 --- a/testdata/default/cheats/StringUtils.t.sol +++ b/testdata/default/cheats/StringUtils.t.sol @@ -39,4 +39,16 @@ contract StringManipulationTest is DSTest { assertEq("World", splitResult[1]); assertEq("Reth", splitResult[2]); } + + function testIndexOf() public { + string memory input = "Hello, World!"; + string memory key1 = "Hello,"; + string memory key2 = "World!"; + string memory key3 = ""; + string memory key4 = "foundry"; + assertEq(vm.indexOf(input, key1), 0); + assertEq(vm.indexOf(input, key2), 7); + assertEq(vm.indexOf(input, key3), 0); + assertEq(vm.indexOf(input, key4), type(uint256).max); + } } From 1b846d9058ecc4f518e9ff1334c0ac3785156fde Mon Sep 17 00:00:00 2001 From: DaniPopes <57450786+DaniPopes@users.noreply.github.com> Date: Fri, 5 Apr 2024 15:07:35 +0200 Subject: [PATCH 53/63] chore: reduce logs in tests (#7566) --- crates/chisel/src/executor.rs | 3 --- 1 file changed, 3 deletions(-) diff --git a/crates/chisel/src/executor.rs b/crates/chisel/src/executor.rs index b5b440959a5c..e0774a2b6878 100644 --- a/crates/chisel/src/executor.rs +++ b/crates/chisel/src/executor.rs @@ -1782,9 +1782,6 @@ mod tests { } fn init_tracing() { - if std::env::var_os("RUST_LOG").is_none() { - std::env::set_var("RUST_LOG", "debug"); - } let _ = tracing_subscriber::FmtSubscriber::builder() .with_env_filter(tracing_subscriber::EnvFilter::from_default_env()) .try_init(); From 03d900a89dc667a39da520fa77ce5698d3cb8246 Mon Sep 17 00:00:00 2001 From: grandizzy <38490174+grandizzy@users.noreply.github.com> Date: Fri, 5 Apr 2024 16:30:25 +0300 Subject: [PATCH 54/63] fix(script): decode custom error in script fail message (#7563) --- crates/forge/tests/cli/script.rs | 34 ++++++++++++++++++++++++++++++++ crates/script/src/execute.rs | 6 +++--- 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/crates/forge/tests/cli/script.rs b/crates/forge/tests/cli/script.rs index a2d4dc4fb625..8af676efd0dd 100644 --- a/crates/forge/tests/cli/script.rs +++ b/crates/forge/tests/cli/script.rs @@ -1197,3 +1197,37 @@ contract Script { cmd.arg("script").args([&script.to_string_lossy(), "--sig", "run"]); assert!(cmd.stderr_lossy().contains("Multiple functions with the same name")); }); + +forgetest_async!(can_decode_custom_errors, |prj, cmd| { + cmd.args(["init", "--force"]).arg(prj.root()); + cmd.assert_non_empty_stdout(); + cmd.forge_fuse(); + + let script = prj + .add_script( + "CustomErrorScript.s.sol", + r#" +import { Script } from "forge-std/Script.sol"; + +contract ContractWithCustomError { + error CustomError(); + + constructor() { + revert CustomError(); + } +} + +contract CustomErrorScript is Script { + ContractWithCustomError test; + + function run() public { + test = new ContractWithCustomError(); + } +} +"#, + ) + .unwrap(); + + cmd.arg("script").arg(script).args(["--tc", "CustomErrorScript"]); + assert!(cmd.stderr_lossy().contains("script failed: CustomError()")); +}); diff --git a/crates/script/src/execute.rs b/crates/script/src/execute.rs index ece762400c36..648c49faa3a1 100644 --- a/crates/script/src/execute.rs +++ b/crates/script/src/execute.rs @@ -23,7 +23,7 @@ use foundry_compilers::artifacts::ContractBytecodeSome; use foundry_config::{Config, NamedChain}; use foundry_debugger::Debugger; use foundry_evm::{ - decode::{decode_console_logs, RevertDecoder}, + decode::decode_console_logs, inspectors::cheatcodes::{BroadcastableTransaction, BroadcastableTransactions}, traces::{ identifier::{SignaturesIdentifier, TraceIdentifiers}, @@ -423,7 +423,7 @@ impl PreSimulationState { if !self.execution_result.success { return Err(eyre::eyre!( "script failed: {}", - RevertDecoder::new().decode(&self.execution_result.returned[..], None) + &self.execution_artifacts.decoder.revert_decoder.decode(&result.returned[..], None) )); } @@ -504,7 +504,7 @@ impl PreSimulationState { if !result.success { return Err(eyre::eyre!( "script failed: {}", - RevertDecoder::new().decode(&result.returned[..], None) + &self.execution_artifacts.decoder.revert_decoder.decode(&result.returned[..], None) )); } From 3ebf3ab3a634b3406fdb9ed4bc67952f6c46fd74 Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Sat, 6 Apr 2024 04:29:49 +0400 Subject: [PATCH 55/63] clippy --- crates/cheatcodes/src/utils.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/cheatcodes/src/utils.rs b/crates/cheatcodes/src/utils.rs index 7544abc0a624..a8aae0bf54de 100644 --- a/crates/cheatcodes/src/utils.rs +++ b/crates/cheatcodes/src/utils.rs @@ -284,7 +284,7 @@ mod tests { use alloy_primitives::FixedBytes; use hex::FromHex; use p256::ecdsa::signature::hazmat::PrehashVerifier; - use std::{path::PathBuf, sync::Arc}; + use std::sync::Arc; fn cheats() -> Cheatcodes { let config = CheatsConfig { From c734de43988ddfc8447daadd0a079ca471f13ba8 Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Sat, 6 Apr 2024 08:10:51 +0400 Subject: [PATCH 56/63] bump alloy --- Cargo.lock | 45 +++--- Cargo.toml | 44 +++--- crates/anvil/core/src/eth/block.rs | 18 +-- crates/anvil/core/src/eth/transaction/mod.rs | 111 +++++++-------- .../core/src/eth/transaction/optimism.rs | 10 +- crates/anvil/core/src/types.rs | 6 +- crates/anvil/src/cmd.rs | 12 +- crates/anvil/src/config.rs | 48 +++---- crates/anvil/src/eth/api.rs | 124 ++++++++--------- crates/anvil/src/eth/backend/executor.rs | 43 +++--- crates/anvil/src/eth/backend/fork.rs | 14 +- crates/anvil/src/eth/backend/mem/mod.rs | 119 ++++++++-------- crates/anvil/src/eth/backend/mem/storage.rs | 10 +- crates/anvil/src/eth/error.rs | 4 +- crates/anvil/src/eth/fees.rs | 129 ++++++++---------- crates/anvil/src/eth/pool/transactions.rs | 10 +- crates/anvil/src/lib.rs | 2 +- crates/anvil/tests/it/anvil_api.rs | 6 +- crates/anvil/tests/it/fork.rs | 32 ++--- crates/anvil/tests/it/gas.rs | 27 ++-- crates/anvil/tests/it/genesis.rs | 4 +- crates/anvil/tests/it/otterscan.rs | 4 +- crates/anvil/tests/it/transaction.rs | 8 +- crates/cast/bin/cmd/access_list.rs | 2 +- crates/cast/bin/cmd/mktx.rs | 3 +- crates/cast/bin/cmd/run.rs | 13 +- crates/cast/bin/cmd/send.rs | 9 +- crates/cast/bin/tx.rs | 27 ++-- crates/cast/src/lib.rs | 14 +- crates/cheatcodes/src/inspector.rs | 4 +- crates/cheatcodes/src/utils.rs | 2 +- crates/cli/src/utils/mod.rs | 2 +- crates/common/src/constants.rs | 2 +- crates/common/src/fmt/ui.rs | 6 + crates/common/src/provider/alloy.rs | 8 +- crates/evm/core/src/backend/mod.rs | 6 +- crates/evm/core/src/fork/backend.rs | 6 +- crates/evm/core/src/fork/init.rs | 6 +- crates/evm/core/src/opts.rs | 2 +- crates/evm/core/src/utils.rs | 6 +- crates/forge/bin/cmd/create.rs | 23 ++-- crates/script/src/broadcast.rs | 22 +-- crates/script/src/build.rs | 2 +- crates/script/src/execute.rs | 3 +- crates/script/src/providers.rs | 7 +- crates/script/src/simulate.rs | 11 +- crates/test-utils/src/script.rs | 10 +- 47 files changed, 481 insertions(+), 545 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 509f0149a317..38b996997d0d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -90,7 +90,7 @@ dependencies = [ [[package]] name = "alloy-consensus" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" +source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" dependencies = [ "alloy-eips", "alloy-primitives", @@ -105,7 +105,7 @@ dependencies = [ [[package]] name = "alloy-contract" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" +source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" dependencies = [ "alloy-dyn-abi", "alloy-json-abi", @@ -144,7 +144,7 @@ dependencies = [ [[package]] name = "alloy-eips" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" +source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -158,7 +158,7 @@ dependencies = [ [[package]] name = "alloy-genesis" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" +source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" dependencies = [ "alloy-primitives", "alloy-serde", @@ -180,7 +180,7 @@ dependencies = [ [[package]] name = "alloy-json-rpc" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" +source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" dependencies = [ "alloy-primitives", "serde", @@ -191,7 +191,7 @@ dependencies = [ [[package]] name = "alloy-network" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" +source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" dependencies = [ "alloy-consensus", "alloy-eips", @@ -201,7 +201,6 @@ dependencies = [ "alloy-signer", "async-trait", "futures-utils-wasm", - "serde", "thiserror", ] @@ -235,7 +234,7 @@ dependencies = [ [[package]] name = "alloy-provider" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" +source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" dependencies = [ "alloy-json-rpc", "alloy-network", @@ -259,7 +258,7 @@ dependencies = [ [[package]] name = "alloy-pubsub" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" +source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" dependencies = [ "alloy-json-rpc", "alloy-primitives", @@ -299,7 +298,7 @@ dependencies = [ [[package]] name = "alloy-rpc-client" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" +source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" dependencies = [ "alloy-json-rpc", "alloy-primitives", @@ -319,7 +318,7 @@ dependencies = [ [[package]] name = "alloy-rpc-types" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" +source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" dependencies = [ "alloy-consensus", "alloy-eips", @@ -337,7 +336,7 @@ dependencies = [ [[package]] name = "alloy-rpc-types-trace" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" +source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" dependencies = [ "alloy-primitives", "alloy-rpc-types", @@ -349,7 +348,7 @@ dependencies = [ [[package]] name = "alloy-serde" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" +source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" dependencies = [ "alloy-primitives", "serde", @@ -359,7 +358,7 @@ dependencies = [ [[package]] name = "alloy-signer" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" +source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" dependencies = [ "alloy-dyn-abi", "alloy-primitives", @@ -374,7 +373,7 @@ dependencies = [ [[package]] name = "alloy-signer-aws" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" +source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" dependencies = [ "alloy-consensus", "alloy-network", @@ -391,7 +390,7 @@ dependencies = [ [[package]] name = "alloy-signer-ledger" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" +source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" dependencies = [ "alloy-consensus", "alloy-network", @@ -408,7 +407,7 @@ dependencies = [ [[package]] name = "alloy-signer-trezor" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" +source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" dependencies = [ "alloy-consensus", "alloy-network", @@ -424,7 +423,7 @@ dependencies = [ [[package]] name = "alloy-signer-wallet" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" +source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" dependencies = [ "alloy-consensus", "alloy-network", @@ -501,7 +500,7 @@ dependencies = [ [[package]] name = "alloy-transport" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" +source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" dependencies = [ "alloy-json-rpc", "base64 0.22.0", @@ -519,7 +518,7 @@ dependencies = [ [[package]] name = "alloy-transport-http" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" +source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" dependencies = [ "alloy-json-rpc", "alloy-transport", @@ -532,7 +531,7 @@ dependencies = [ [[package]] name = "alloy-transport-ipc" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" +source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" dependencies = [ "alloy-json-rpc", "alloy-pubsub", @@ -550,7 +549,7 @@ dependencies = [ [[package]] name = "alloy-transport-ws" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=bfd0fda#bfd0fda492e560c3463d521958793c81bbeadfc1" +source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" dependencies = [ "alloy-pubsub", "alloy-transport", @@ -6846,7 +6845,7 @@ dependencies = [ [[package]] name = "revm-inspectors" version = "0.1.0" -source = "git+https://github.com/paradigmxyz/evm-inspectors?rev=75c6ad0#75c6ad0b77dc9237de57c4fb5620b91e34c3d282" +source = "git+https://github.com/paradigmxyz/evm-inspectors?rev=c34b770#c34b77089b508bea7221aaa4bfeb33d444a62ea3" dependencies = [ "alloy-primitives", "alloy-rpc-types", diff --git a/Cargo.toml b/Cargo.toml index 6b47a23e3b70..ea6f420ccdee 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -143,7 +143,7 @@ foundry-compilers = { version = "0.3.14", default-features = false } # no default features to avoid c-kzg revm = { version = "8", default-features = false } revm-primitives = { version = "3", default-features = false } -revm-inspectors = { git = "https://github.com/paradigmxyz/evm-inspectors", rev = "75c6ad0", features = [ +revm-inspectors = { git = "https://github.com/paradigmxyz/evm-inspectors", rev = "c34b770", features = [ "serde", ] } @@ -157,27 +157,27 @@ ethers-signers = { version = "2.0.14", default-features = false } ethers-middleware = { version = "2.0.14", default-features = false } ## alloy -alloy-consensus = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } -alloy-contract = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } -alloy-eips = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } -alloy-genesis = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } -alloy-json-rpc = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } -alloy-network = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } -alloy-node-bindings = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } -alloy-provider = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } -alloy-pubsub = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } -alloy-rpc-client = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } -alloy-rpc-types-trace = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } -alloy-rpc-types = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } -alloy-signer = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } -alloy-signer-wallet = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } -alloy-signer-aws = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } -alloy-signer-ledger = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } -alloy-signer-trezor = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } -alloy-transport = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } -alloy-transport-http = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } -alloy-transport-ipc = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } -alloy-transport-ws = { git = "https://github.com/alloy-rs/alloy", rev = "bfd0fda", default-features = false } +alloy-consensus = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } +alloy-contract = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } +alloy-eips = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } +alloy-genesis = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } +alloy-json-rpc = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } +alloy-network = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } +alloy-node-bindings = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } +alloy-provider = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } +alloy-pubsub = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } +alloy-rpc-client = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } +alloy-rpc-types-trace = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } +alloy-rpc-types = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } +alloy-signer = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } +alloy-signer-wallet = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } +alloy-signer-aws = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } +alloy-signer-ledger = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } +alloy-signer-trezor = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } +alloy-transport = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } +alloy-transport-http = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } +alloy-transport-ipc = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } +alloy-transport-ws = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } alloy-primitives = { version = "0.7.0", features = ["getrandom"] } alloy-dyn-abi = "0.7.0" alloy-json-abi = "0.7.0" diff --git a/crates/anvil/core/src/eth/block.rs b/crates/anvil/core/src/eth/block.rs index 4f6c5a94188a..719bf8d25dca 100644 --- a/crates/anvil/core/src/eth/block.rs +++ b/crates/anvil/core/src/eth/block.rs @@ -60,8 +60,8 @@ impl Block { logs_bloom: partial_header.logs_bloom, difficulty: partial_header.difficulty, number: partial_header.number, - gas_limit: partial_header.gas_limit, - gas_used: partial_header.gas_used, + gas_limit: partial_header.gas_limit as u64, + gas_used: partial_header.gas_used as u64, timestamp: partial_header.timestamp, extra_data: partial_header.extra_data, mix_hash: partial_header.mix_hash, @@ -70,7 +70,7 @@ impl Block { excess_blob_gas: None, parent_beacon_block_root: None, nonce: partial_header.nonce, - base_fee_per_gas: partial_header.base_fee, + base_fee_per_gas: partial_header.base_fee.map(|v| v as u64), }, transactions, ommers, @@ -88,13 +88,13 @@ pub struct PartialHeader { pub logs_bloom: Bloom, pub difficulty: U256, pub number: u64, - pub gas_limit: u64, - pub gas_used: u64, + pub gas_limit: u128, + pub gas_used: u128, pub timestamp: u64, pub extra_data: Bytes, pub mix_hash: B256, pub nonce: u64, - pub base_fee: Option, + pub base_fee: Option, } impl From
for PartialHeader { @@ -107,13 +107,13 @@ impl From
for PartialHeader { logs_bloom: value.logs_bloom, difficulty: value.difficulty, number: value.number, - gas_limit: value.gas_limit, - gas_used: value.gas_used, + gas_limit: value.gas_limit as u128, + gas_used: value.gas_used as u128, timestamp: value.timestamp, extra_data: value.extra_data, mix_hash: value.mix_hash, nonce: value.nonce, - base_fee: value.base_fee_per_gas, + base_fee: value.base_fee_per_gas.map(|v| v as u128), } } } diff --git a/crates/anvil/core/src/eth/transaction/mod.rs b/crates/anvil/core/src/eth/transaction/mod.rs index 79347e21bd9d..bbe983a3444e 100644 --- a/crates/anvil/core/src/eth/transaction/mod.rs +++ b/crates/anvil/core/src/eth/transaction/mod.rs @@ -9,7 +9,7 @@ use alloy_consensus::{ TxEip2930, TxEip4844, TxEip4844Variant, TxEip4844WithSidecar, TxEnvelope, TxLegacy, TxReceipt, }; use alloy_eips::eip2718::Decodable2718; -use alloy_primitives::{Address, Bloom, Bytes, Log, Signature, TxHash, TxKind, B256, U256, U8}; +use alloy_primitives::{Address, Bloom, Bytes, Log, Signature, TxHash, TxKind, B256, U256}; use alloy_rlp::{length_of_length, Decodable, Encodable, Header}; use alloy_rpc_types::{ request::TransactionRequest, AccessList, Signature as RpcSignature, @@ -61,7 +61,6 @@ pub fn transaction_request_to_typed( }, other, } = tx; - let transaction_type = transaction_type.map(|id| id.to::()); // Special case: OP-stack deposit tx if transaction_type == Some(126) { @@ -93,8 +92,8 @@ pub fn transaction_request_to_typed( (None, Some(_), None, None, None, None, None, None, _) => { Some(TypedTransactionRequest::Legacy(TxLegacy { nonce: nonce.unwrap_or_default(), - gas_price: gas_price.unwrap_or_default().to::(), - gas_limit: gas.unwrap_or_default().to::(), + gas_price: gas_price.unwrap_or_default(), + gas_limit: gas.unwrap_or_default(), value: value.unwrap_or(U256::ZERO), input: input.into_input().unwrap_or_default(), to: match to { @@ -109,8 +108,8 @@ pub fn transaction_request_to_typed( (None, _, None, None, Some(_), None, None, None, _) => { Some(TypedTransactionRequest::EIP2930(TxEip2930 { nonce: nonce.unwrap_or_default(), - gas_price: gas_price.unwrap_or_default().to(), - gas_limit: gas.unwrap_or_default().to::(), + gas_price: gas_price.unwrap_or_default(), + gas_limit: gas.unwrap_or_default(), value: value.unwrap_or(U256::ZERO), input: input.into_input().unwrap_or_default(), to: match to { @@ -129,9 +128,9 @@ pub fn transaction_request_to_typed( // Empty fields fall back to the canonical transaction schema. Some(TypedTransactionRequest::EIP1559(TxEip1559 { nonce: nonce.unwrap_or_default(), - max_fee_per_gas: max_fee_per_gas.unwrap_or_default().to::(), - max_priority_fee_per_gas: max_priority_fee_per_gas.unwrap_or_default().to::(), - gas_limit: gas.unwrap_or_default().to::(), + max_fee_per_gas: max_fee_per_gas.unwrap_or_default(), + max_priority_fee_per_gas: max_priority_fee_per_gas.unwrap_or_default(), + gas_limit: gas.unwrap_or_default(), value: value.unwrap_or(U256::ZERO), input: input.into_input().unwrap_or_default(), to: match to { @@ -146,10 +145,10 @@ pub fn transaction_request_to_typed( (Some(3), None, _, _, _, Some(_), Some(_), Some(sidecar), Some(to)) => { let tx = TxEip4844 { nonce: nonce.unwrap_or_default(), - max_fee_per_gas: max_fee_per_gas.unwrap_or_default().to::(), - max_priority_fee_per_gas: max_priority_fee_per_gas.unwrap_or_default().to::(), - max_fee_per_blob_gas: max_fee_per_blob_gas.unwrap_or_default().to::(), - gas_limit: gas.unwrap_or_default().to::(), + max_fee_per_gas: max_fee_per_gas.unwrap_or_default(), + max_priority_fee_per_gas: max_priority_fee_per_gas.unwrap_or_default(), + max_fee_per_blob_gas: max_fee_per_blob_gas.unwrap_or_default(), + gas_limit: gas.unwrap_or_default(), value: value.unwrap_or(U256::ZERO), input: input.into_input().unwrap_or_default(), to, @@ -300,10 +299,10 @@ pub fn to_alloy_transaction_with_hash_and_sender( from, to: None, value: t.tx().value, - gas_price: Some(U256::from(t.tx().gas_price)), - max_fee_per_gas: Some(U256::from(t.tx().gas_price)), - max_priority_fee_per_gas: Some(U256::from(t.tx().gas_price)), - gas: U256::from(t.tx().gas_limit), + gas_price: Some(t.tx().gas_price), + max_fee_per_gas: Some(t.tx().gas_price), + max_priority_fee_per_gas: Some(t.tx().gas_price), + gas: t.tx().gas_limit, input: t.tx().input.clone(), chain_id: t.tx().chain_id, signature: Some(RpcSignature { @@ -327,10 +326,10 @@ pub fn to_alloy_transaction_with_hash_and_sender( from, to: None, value: t.tx().value, - gas_price: Some(U256::from(t.tx().gas_price)), - max_fee_per_gas: Some(U256::from(t.tx().gas_price)), - max_priority_fee_per_gas: Some(U256::from(t.tx().gas_price)), - gas: U256::from(t.tx().gas_limit), + gas_price: Some(t.tx().gas_price), + max_fee_per_gas: Some(t.tx().gas_price), + max_priority_fee_per_gas: Some(t.tx().gas_price), + gas: t.tx().gas_limit, input: t.tx().input.clone(), chain_id: Some(t.tx().chain_id), signature: Some(RpcSignature { @@ -340,7 +339,7 @@ pub fn to_alloy_transaction_with_hash_and_sender( y_parity: Some(alloy_rpc_types::Parity::from(t.signature().v().y_parity())), }), access_list: Some(t.tx().access_list.clone()), - transaction_type: Some(U8::from(1)), + transaction_type: Some(1), max_fee_per_blob_gas: None, blob_versioned_hashes: None, other: Default::default(), @@ -355,9 +354,9 @@ pub fn to_alloy_transaction_with_hash_and_sender( to: None, value: t.tx().value, gas_price: None, - max_fee_per_gas: Some(U256::from(t.tx().max_fee_per_gas)), - max_priority_fee_per_gas: Some(U256::from(t.tx().max_priority_fee_per_gas)), - gas: U256::from(t.tx().gas_limit), + max_fee_per_gas: Some(t.tx().max_fee_per_gas), + max_priority_fee_per_gas: Some(t.tx().max_priority_fee_per_gas), + gas: t.tx().gas_limit, input: t.tx().input.clone(), chain_id: Some(t.tx().chain_id), signature: Some(RpcSignature { @@ -367,7 +366,7 @@ pub fn to_alloy_transaction_with_hash_and_sender( y_parity: Some(alloy_rpc_types::Parity::from(t.signature().v().y_parity())), }), access_list: Some(t.tx().access_list.clone()), - transaction_type: Some(U8::from(2)), + transaction_type: Some(2), max_fee_per_blob_gas: None, blob_versioned_hashes: None, other: Default::default(), @@ -381,10 +380,10 @@ pub fn to_alloy_transaction_with_hash_and_sender( from, to: None, value: t.tx().tx().value, - gas_price: Some(U256::from(t.tx().tx().max_fee_per_gas)), - max_fee_per_gas: Some(U256::from(t.tx().tx().max_fee_per_gas)), - max_priority_fee_per_gas: Some(U256::from(t.tx().tx().max_priority_fee_per_gas)), - gas: U256::from(t.tx().tx().gas_limit), + gas_price: Some(t.tx().tx().max_fee_per_gas), + max_fee_per_gas: Some(t.tx().tx().max_fee_per_gas), + max_priority_fee_per_gas: Some(t.tx().tx().max_priority_fee_per_gas), + gas: t.tx().tx().gas_limit, input: t.tx().tx().input.clone(), chain_id: Some(t.tx().tx().chain_id), signature: Some(RpcSignature { @@ -394,8 +393,8 @@ pub fn to_alloy_transaction_with_hash_and_sender( y_parity: Some(alloy_rpc_types::Parity::from(t.signature().v().y_parity())), }), access_list: Some(from_eip_to_alloy_access_list(t.tx().tx().access_list.clone())), - transaction_type: Some(U8::from(3)), - max_fee_per_blob_gas: Some(U256::from(t.tx().tx().max_fee_per_blob_gas)), + transaction_type: Some(3), + max_fee_per_blob_gas: Some(t.tx().tx().max_fee_per_blob_gas), blob_versioned_hashes: Some(t.tx().tx().blob_versioned_hashes.clone()), other: Default::default(), }, @@ -411,7 +410,7 @@ pub fn to_alloy_transaction_with_hash_and_sender( gas_price: None, max_fee_per_gas: None, max_priority_fee_per_gas: None, - gas: U256::from(t.gas_limit), + gas: t.gas_limit, input: t.input.clone().0.into(), chain_id: t.chain_id().map(u64::from), signature: None, @@ -488,7 +487,7 @@ impl PendingTransaction { value: (*value), gas_price: U256::from(*gas_price), gas_priority_fee: None, - gas_limit: *gas_limit, + gas_limit: *gas_limit as u64, access_list: vec![], ..Default::default() } @@ -514,7 +513,7 @@ impl PendingTransaction { value: *value, gas_price: U256::from(*gas_price), gas_priority_fee: None, - gas_limit: *gas_limit, + gas_limit: *gas_limit as u64, access_list: eip_to_revm_access_list(access_list.0.clone()), ..Default::default() } @@ -541,7 +540,7 @@ impl PendingTransaction { value: *value, gas_price: U256::from(*max_fee_per_gas), gas_priority_fee: Some(U256::from(*max_priority_fee_per_gas)), - gas_limit: *gas_limit, + gas_limit: *gas_limit as u64, access_list: eip_to_revm_access_list(access_list.0.clone()), ..Default::default() } @@ -572,7 +571,7 @@ impl PendingTransaction { gas_priority_fee: Some(U256::from(*max_priority_fee_per_gas)), max_fee_per_blob_gas: Some(U256::from(*max_fee_per_blob_gas)), blob_hashes: blob_versioned_hashes.clone(), - gas_limit: *gas_limit, + gas_limit: *gas_limit as u64, access_list: eip_to_revm_access_list(access_list.0.clone()), ..Default::default() } @@ -599,7 +598,7 @@ impl PendingTransaction { value: *value, gas_price: U256::ZERO, gas_priority_fee: None, - gas_limit: gas_limit.to::(), + gas_limit: *gas_limit as u64, access_list: vec![], optimism: OptimismFields { source_hash: Some(*source_hash), @@ -635,24 +634,24 @@ impl TypedTransaction { matches!(self, TypedTransaction::EIP1559(_)) } - pub fn gas_price(&self) -> U256 { - U256::from(match self { + pub fn gas_price(&self) -> u128 { + match self { TypedTransaction::Legacy(tx) => tx.tx().gas_price, TypedTransaction::EIP2930(tx) => tx.tx().gas_price, TypedTransaction::EIP1559(tx) => tx.tx().max_fee_per_gas, TypedTransaction::EIP4844(tx) => tx.tx().tx().max_fee_per_blob_gas, TypedTransaction::Deposit(_) => 0, - }) + } } - pub fn gas_limit(&self) -> U256 { - U256::from(match self { + pub fn gas_limit(&self) -> u128 { + match self { TypedTransaction::Legacy(tx) => tx.tx().gas_limit, TypedTransaction::EIP2930(tx) => tx.tx().gas_limit, TypedTransaction::EIP1559(tx) => tx.tx().gas_limit, TypedTransaction::EIP4844(tx) => tx.tx().tx().gas_limit, - TypedTransaction::Deposit(tx) => tx.gas_limit.to::(), - }) + TypedTransaction::Deposit(tx) => tx.gas_limit, + } } pub fn value(&self) -> U256 { @@ -687,7 +686,7 @@ impl TypedTransaction { } /// Max cost of the transaction - pub fn max_cost(&self) -> U256 { + pub fn max_cost(&self) -> u128 { self.gas_limit().saturating_mul(self.gas_price()) } @@ -698,7 +697,7 @@ impl TypedTransaction { kind: t.tx().to, input: t.tx().input.clone(), nonce: t.tx().nonce, - gas_limit: U256::from(t.tx().gas_limit), + gas_limit: t.tx().gas_limit, gas_price: Some(U256::from(t.tx().gas_price)), max_fee_per_gas: None, max_priority_fee_per_gas: None, @@ -712,7 +711,7 @@ impl TypedTransaction { kind: t.tx().to, input: t.tx().input.clone(), nonce: t.tx().nonce, - gas_limit: U256::from(t.tx().gas_limit), + gas_limit: t.tx().gas_limit, gas_price: Some(U256::from(t.tx().gas_price)), max_fee_per_gas: None, max_priority_fee_per_gas: None, @@ -726,7 +725,7 @@ impl TypedTransaction { kind: t.tx().to, input: t.tx().input.clone(), nonce: t.tx().nonce, - gas_limit: U256::from(t.tx().gas_limit), + gas_limit: t.tx().gas_limit, gas_price: None, max_fee_per_gas: Some(U256::from(t.tx().max_fee_per_gas)), max_priority_fee_per_gas: Some(U256::from(t.tx().max_priority_fee_per_gas)), @@ -740,7 +739,7 @@ impl TypedTransaction { kind: TxKind::Call(t.tx().tx().to), input: t.tx().tx().input.clone(), nonce: t.tx().tx().nonce, - gas_limit: U256::from(t.tx().tx().gas_limit), + gas_limit: t.tx().tx().gas_limit, gas_price: Some(U256::from(t.tx().tx().max_fee_per_blob_gas)), max_fee_per_gas: Some(U256::from(t.tx().tx().max_fee_per_gas)), max_priority_fee_per_gas: Some(U256::from(t.tx().tx().max_priority_fee_per_gas)), @@ -938,7 +937,7 @@ impl Decodable2718 for TypedTransaction { TxEnvelope::Eip2930(tx) => Ok(Self::EIP2930(tx)), TxEnvelope::Eip1559(tx) => Ok(Self::EIP1559(tx)), TxEnvelope::Eip4844(tx) => Ok(Self::EIP4844(tx)), - TxEnvelope::Legacy(_) => unreachable!(), + _ => unreachable!(), } } @@ -957,6 +956,7 @@ impl From for TypedTransaction { TxEnvelope::Eip2930(tx) => TypedTransaction::EIP2930(tx), TxEnvelope::Eip1559(tx) => TypedTransaction::EIP1559(tx), TxEnvelope::Eip4844(tx) => TypedTransaction::EIP4844(tx), + _ => unreachable!(), } } } @@ -966,7 +966,7 @@ pub struct TransactionEssentials { pub kind: TxKind, pub input: Bytes, pub nonce: u64, - pub gas_limit: U256, + pub gas_limit: u128, pub gas_price: Option, pub max_fee_per_gas: Option, pub max_priority_fee_per_gas: Option, @@ -981,7 +981,7 @@ pub struct TransactionEssentials { #[derive(Clone, Debug, PartialEq, Eq)] pub struct TransactionInfo { pub transaction_hash: B256, - pub transaction_index: u32, + pub transaction_index: u64, pub from: Address, pub to: Option
, pub contract_address: Option
, @@ -1136,6 +1136,7 @@ impl From> for TypedReceipt TypedReceipt::EIP2930(r), ReceiptEnvelope::Eip1559(r) => TypedReceipt::EIP1559(r), ReceiptEnvelope::Eip4844(r) => TypedReceipt::EIP4844(r), + _ => unreachable!(), } } } @@ -1260,8 +1261,8 @@ mod tests { let tx = TxLegacy { nonce: 2u64, - gas_price: 1000000000u64.into(), - gas_limit: 100000u64, + gas_price: 1000000000u128, + gas_limit: 100000u128, to: TxKind::Call(Address::from_slice( &hex::decode("d3e8763675e4c425df46cc3b5c0f6cbdac396046").unwrap()[..], )), diff --git a/crates/anvil/core/src/eth/transaction/optimism.rs b/crates/anvil/core/src/eth/transaction/optimism.rs index 6cec804d3aa0..dedaffaf3458 100644 --- a/crates/anvil/core/src/eth/transaction/optimism.rs +++ b/crates/anvil/core/src/eth/transaction/optimism.rs @@ -12,7 +12,7 @@ pub struct DepositTransactionRequest { pub kind: TxKind, pub mint: U256, pub value: U256, - pub gas_limit: U256, + pub gas_limit: u128, pub is_system_tx: bool, pub input: Bytes, } @@ -171,12 +171,12 @@ impl Transaction for DepositTransactionRequest { } /// Get `gas_limit`. - fn gas_limit(&self) -> u64 { - self.gas_limit.to() + fn gas_limit(&self) -> u128 { + self.gas_limit } /// Get `gas_price`. - fn gas_price(&self) -> Option { + fn gas_price(&self) -> Option { None } } @@ -236,7 +236,7 @@ pub struct DepositTransaction { pub kind: TxKind, pub mint: U256, pub value: U256, - pub gas_limit: U256, + pub gas_limit: u128, pub is_system_tx: bool, pub input: Bytes, } diff --git a/crates/anvil/core/src/types.rs b/crates/anvil/core/src/types.rs index db966d956d20..2e0c63b13485 100644 --- a/crates/anvil/core/src/types.rs +++ b/crates/anvil/core/src/types.rs @@ -190,10 +190,10 @@ pub struct NodeInfo { #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))] pub struct NodeEnvironment { - pub base_fee: U256, + pub base_fee: u128, pub chain_id: u64, - pub gas_limit: U256, - pub gas_price: U256, + pub gas_limit: u128, + pub gas_price: u128, } #[derive(Clone, Debug, Default, PartialEq, Eq)] diff --git a/crates/anvil/src/cmd.rs b/crates/anvil/src/cmd.rs index 2d67a9e89f0c..8e29152410ee 100644 --- a/crates/anvil/src/cmd.rs +++ b/crates/anvil/src/cmd.rs @@ -194,9 +194,9 @@ impl NodeArgs { }; NodeConfig::default() - .with_gas_limit(self.evm_opts.gas_limit.map(U256::from)) + .with_gas_limit(self.evm_opts.gas_limit) .disable_block_gas_limit(self.evm_opts.disable_block_gas_limit) - .with_gas_price(self.evm_opts.gas_price.map(U256::from)) + .with_gas_price(self.evm_opts.gas_price) .with_hardfork(self.hardfork) .with_blocktime(self.block_time) .with_no_mining(self.no_mining) @@ -216,7 +216,7 @@ impl NodeArgs { .fork_retry_backoff(self.evm_opts.fork_retry_backoff.map(Duration::from_millis)) .fork_compute_units_per_second(compute_units_per_second) .with_eth_rpc_url(self.evm_opts.fork_url.map(|fork| fork.url)) - .with_base_fee(self.evm_opts.block_base_fee_per_gas.map(U256::from)) + .with_base_fee(self.evm_opts.block_base_fee_per_gas) .with_storage_caching(self.evm_opts.no_storage_caching) .with_server_config(self.server_config) .with_host(self.host) @@ -455,7 +455,7 @@ pub struct AnvilEvmArgs { /// The block gas limit. #[arg(long, alias = "block-gas-limit", help_heading = "Environment config")] - pub gas_limit: Option, + pub gas_limit: Option, /// Disable the `call.gas_limit <= block.gas_limit` constraint. #[arg( @@ -474,7 +474,7 @@ pub struct AnvilEvmArgs { /// The gas price. #[arg(long, help_heading = "Environment config")] - pub gas_price: Option, + pub gas_price: Option, /// The base fee in a block. #[arg( @@ -483,7 +483,7 @@ pub struct AnvilEvmArgs { value_name = "FEE", help_heading = "Environment config" )] - pub block_base_fee_per_gas: Option, + pub block_base_fee_per_gas: Option, /// The chain ID. #[arg(long, alias = "chain", help_heading = "Environment config")] diff --git a/crates/anvil/src/config.rs b/crates/anvil/src/config.rs index ca8dcdde581b..dbecd15b86c0 100644 --- a/crates/anvil/src/config.rs +++ b/crates/anvil/src/config.rs @@ -92,13 +92,13 @@ pub struct NodeConfig { /// Chain ID of the EVM chain pub chain_id: Option, /// Default gas limit for all txs - pub gas_limit: U256, + pub gas_limit: u128, /// If set to `true`, disables the block gas limit pub disable_block_gas_limit: bool, /// Default gas price for all txs - pub gas_price: Option, + pub gas_price: Option, /// Default base fee - pub base_fee: Option, + pub base_fee: Option, /// The hardfork to use pub hardfork: Option, /// Signer accounts that will be initialised with `genesis_balance` in the genesis block @@ -367,7 +367,7 @@ impl Default for NodeConfig { let genesis_accounts = AccountGenerator::new(10).phrase(DEFAULT_MNEMONIC).gen(); Self { chain_id: None, - gas_limit: U256::from(30_000_000), + gas_limit: 30_000_000, disable_block_gas_limit: false, gas_price: None, hardfork: None, @@ -423,15 +423,15 @@ impl NodeConfig { self } /// Returns the base fee to use - pub fn get_base_fee(&self) -> U256 { + pub fn get_base_fee(&self) -> u128 { self.base_fee - .or_else(|| self.genesis.as_ref().and_then(|g| g.base_fee_per_gas.map(U256::from))) - .unwrap_or_else(|| U256::from(INITIAL_BASE_FEE)) + .or_else(|| self.genesis.as_ref().and_then(|g| g.base_fee_per_gas.map(|b| b as u128))) + .unwrap_or(INITIAL_BASE_FEE) } /// Returns the base fee to use - pub fn get_gas_price(&self) -> U256 { - self.gas_price.unwrap_or_else(|| U256::from(INITIAL_GAS_PRICE)) + pub fn get_gas_price(&self) -> u128 { + self.gas_price.unwrap_or(INITIAL_GAS_PRICE) } /// Returns the base fee to use @@ -488,7 +488,7 @@ impl NodeConfig { /// Sets the gas limit #[must_use] - pub fn with_gas_limit(mut self, gas_limit: Option) -> Self { + pub fn with_gas_limit(mut self, gas_limit: Option) -> Self { if let Some(gas_limit) = gas_limit { self.gas_limit = gas_limit; } @@ -506,8 +506,8 @@ impl NodeConfig { /// Sets the gas price #[must_use] - pub fn with_gas_price(mut self, gas_price: Option) -> Self { - self.gas_price = gas_price.map(Into::into); + pub fn with_gas_price(mut self, gas_price: Option) -> Self { + self.gas_price = gas_price; self } @@ -530,8 +530,8 @@ impl NodeConfig { /// Sets the base fee #[must_use] - pub fn with_base_fee(mut self, base_fee: Option) -> Self { - self.base_fee = base_fee.map(Into::into); + pub fn with_base_fee(mut self, base_fee: Option) -> Self { + self.base_fee = base_fee; self } @@ -848,8 +848,8 @@ impl NodeConfig { let env = revm::primitives::Env { cfg: cfg.cfg_env, block: BlockEnv { - gas_limit: self.gas_limit, - basefee: self.get_base_fee(), + gas_limit: U256::from(self.gas_limit), + basefee: U256::from(self.get_base_fee()), ..Default::default() }, tx: TxEnv { chain_id: self.get_chain_id().into(), ..Default::default() }, @@ -976,7 +976,7 @@ impl NodeConfig { // but only if we're forking mainnet let chain_id = provider.get_chain_id().await.expect("Failed to fetch network chain ID"); - if alloy_chains::NamedChain::Mainnet == chain_id.to::() { + if alloy_chains::NamedChain::Mainnet == chain_id { let hardfork: Hardfork = fork_block_number.into(); env.handler_cfg.spec_id = hardfork.into(); self.hardfork = Some(hardfork); @@ -1043,17 +1043,17 @@ latest block number: {latest_block}" // if not set explicitly we use the base fee of the latest block if self.base_fee.is_none() { if let Some(base_fee) = block.header.base_fee_per_gas { - self.base_fee = Some(base_fee); + self.base_fee = Some(base_fee.to()); env.block.basefee = base_fee; // this is the base fee of the current block, but we need the base fee of // the next block let next_block_base_fee = fees.get_next_block_base_fee_per_gas( - block.header.gas_used, - block.header.gas_limit, - block.header.base_fee_per_gas.unwrap_or_default(), + block.header.gas_used.to(), + block.header.gas_limit.to(), + block.header.base_fee_per_gas.unwrap_or_default().to(), ); // update next base fee - fees.set_base_fee(U256::from(next_block_base_fee)); + fees.set_base_fee(next_block_base_fee); } } @@ -1071,9 +1071,9 @@ latest block number: {latest_block}" chain_id } else { let chain_id = if let Some(fork_chain_id) = fork_chain_id { - fork_chain_id.to::() + fork_chain_id.to() } else { - provider.get_chain_id().await.unwrap().to::() + provider.get_chain_id().await.unwrap() }; // need to update the dev signers and env with the chain id diff --git a/crates/anvil/src/eth/api.rs b/crates/anvil/src/eth/api.rs index 7132c04238fe..bb46019ccd55 100644 --- a/crates/anvil/src/eth/api.rs +++ b/crates/anvil/src/eth/api.rs @@ -445,11 +445,6 @@ impl EthApi { Err(BlockchainError::NoSignerAvailable) } - /// Queries the current gas limit - fn current_gas_limit(&self) -> Result { - Ok(self.backend.gas_limit()) - } - async fn block_request(&self, block_number: Option) -> Result { let block_request = match block_number { Some(BlockId::Number(BlockNumber::Pending)) => { @@ -548,7 +543,7 @@ impl EthApi { /// Returns the current gas price pub fn gas_price(&self) -> Result { - Ok(self.backend.gas_price()) + Ok(U256::from(self.backend.gas_price())) } /// Returns a fee per gas that is an estimate of how much you can pay as a priority fee, or @@ -556,12 +551,12 @@ impl EthApi { /// /// Handler for ETH RPC call: `eth_maxPriorityFeePerGas` pub fn gas_max_priority_fee_per_gas(&self) -> Result { - Ok(self.backend.max_priority_fee_per_gas()) + Ok(U256::from(self.backend.max_priority_fee_per_gas())) } /// Returns the block gas limit pub fn gas_limit(&self) -> U256 { - self.backend.gas_limit() + U256::from(self.backend.gas_limit()) } /// Returns the accounts list @@ -688,7 +683,7 @@ impl EthApi { block_number: Option, ) -> Result { node_info!("eth_getTransactionCount"); - self.get_transaction_count(address, block_number).await + self.get_transaction_count(address, block_number).await.map(U256::from) } /// Returns the number of transactions in a block with given hash. @@ -907,8 +902,8 @@ impl EthApi { // pre-validate self.backend.validate_pool_transaction(&pending_transaction).await?; - let requires = required_marker(nonce.to(), on_chain_nonce.to(), from); - let provides = vec![to_marker(nonce.to::(), from)]; + let requires = required_marker(nonce, on_chain_nonce, from); + let provides = vec![to_marker(nonce, from)]; debug_assert!(requires != provides); self.add_pending_transaction(pending_transaction, requires, provides) @@ -1061,7 +1056,7 @@ impl EthApi { request: WithOtherFields, block_number: Option, overrides: Option, - ) -> Result { + ) -> Result { node_info!("eth_estimateGas"); self.do_estimate_gas( request, @@ -1255,7 +1250,7 @@ impl EthApi { // efficiently, instead we fetch it from the fork if fork.predates_fork_inclusive(number) { return fork - .fee_history(block_count, BlockNumber::Number(number), &reward_percentiles) + .fee_history(block_count.to(), BlockNumber::Number(number), &reward_percentiles) .await .map_err(BlockchainError::AlloyForkProvider); } @@ -1274,7 +1269,7 @@ impl EthApi { } let mut response = FeeHistory { - oldest_block: U256::from(lowest), + oldest_block: lowest, base_fee_per_gas: Vec::new(), gas_used_ratio: Vec::new(), reward: Some(Default::default()), @@ -1290,7 +1285,7 @@ impl EthApi { for n in lowest..=highest { // if let Some(block) = fee_history.get(&n) { - response.base_fee_per_gas.push(U256::from(block.base_fee)); + response.base_fee_per_gas.push(block.base_fee); response.gas_used_ratio.push(block.gas_used_ratio); // requested percentiles @@ -1300,11 +1295,7 @@ impl EthApi { for p in &reward_percentiles { let p = p.clamp(0.0, 100.0); let index = ((p.round() / 2f64) * 2f64) * resolution_per_percentile; - let reward = if let Some(r) = block.rewards.get(index as usize) { - U256::from(*r) - } else { - U256::ZERO - }; + let reward = block.rewards.get(index as usize).map_or(0, |r| *r); block_rewards.push(reward); } rewards.push(block_rewards); @@ -1323,20 +1314,20 @@ impl EthApi { (response.gas_used_ratio.last(), response.base_fee_per_gas.last()) { let elasticity = self.backend.elasticity(); - let last_fee_per_gas = last_fee_per_gas.to::() as f64; + let last_fee_per_gas = *last_fee_per_gas as f64; if last_gas_used > &0.5 { // increase base gas let increase = ((last_gas_used - 0.5) * 2f64) * elasticity; - let new_base_fee = (last_fee_per_gas + (last_fee_per_gas * increase)) as u64; - response.base_fee_per_gas.push(U256::from(new_base_fee)); + let new_base_fee = (last_fee_per_gas + (last_fee_per_gas * increase)) as u128; + response.base_fee_per_gas.push(new_base_fee); } else if last_gas_used < &0.5 { // decrease gas let increase = ((0.5 - last_gas_used) * 2f64) * elasticity; - let new_base_fee = (last_fee_per_gas - (last_fee_per_gas * increase)) as u64; - response.base_fee_per_gas.push(U256::from(new_base_fee)); + let new_base_fee = (last_fee_per_gas - (last_fee_per_gas * increase)) as u128; + response.base_fee_per_gas.push(new_base_fee); } else { // same base gas - response.base_fee_per_gas.push(U256::from(last_fee_per_gas as u64)); + response.base_fee_per_gas.push(last_fee_per_gas as u128); } } @@ -1351,7 +1342,7 @@ impl EthApi { /// Handler for ETH RPC call: `eth_maxPriorityFeePerGas` pub fn max_priority_fee_per_gas(&self) -> Result { node_info!("eth_maxPriorityFeePerGas"); - Ok(self.backend.max_priority_fee_per_gas()) + Ok(U256::from(self.backend.max_priority_fee_per_gas())) } /// Creates a filter object, based on filter options, to notify when the state changes (logs). @@ -1660,7 +1651,7 @@ impl EthApi { ) .into()); } - self.backend.set_gas_price(gas); + self.backend.set_gas_price(gas.to()); Ok(()) } @@ -1675,7 +1666,7 @@ impl EthApi { ) .into()); } - self.backend.set_base_fee(basefee); + self.backend.set_base_fee(basefee.to()); Ok(()) } @@ -1831,7 +1822,7 @@ impl EthApi { /// Handler for RPC call: `evm_setBlockGasLimit` pub fn evm_set_block_gas_limit(&self, gas_limit: U256) -> Result { node_info!("evm_setBlockGasLimit"); - self.backend.set_gas_limit(gas_limit); + self.backend.set_gas_limit(gas_limit.to()); Ok(true) } @@ -1989,8 +1980,8 @@ impl EthApi { // pre-validate self.backend.validate_pool_transaction(&pending_transaction).await?; - let requires = required_marker(nonce.to(), on_chain_nonce.to(), from); - let provides = vec![to_marker(nonce.to::(), from)]; + let requires = required_marker(nonce, on_chain_nonce, from); + let provides = vec![to_marker(nonce, from)]; self.add_pending_transaction(pending_transaction, requires, provides) } @@ -2018,9 +2009,9 @@ impl EthApi { fn convert(tx: Arc) -> TxpoolInspectSummary { let tx = &tx.pending_transaction.transaction; let to = tx.to(); - let gas_price = tx.gas_price(); + let gas_price = U256::from(tx.gas_price()); let value = tx.value(); - let gas = tx.gas_limit(); + let gas = U256::from(tx.gas_limit()); TxpoolInspectSummary { to, value, gas, gas_price } } @@ -2138,7 +2129,7 @@ impl EthApi { request: WithOtherFields, block_number: Option, overrides: Option, - ) -> Result { + ) -> Result { let block_request = self.block_request(block_number).await?; // check if the number predates the fork, if in fork mode if let BlockRequest::Number(number) = block_request { @@ -2175,7 +2166,7 @@ impl EthApi { mut request: WithOtherFields, state: D, block_env: BlockEnv, - ) -> Result + ) -> Result where D: DatabaseRef, { @@ -2201,11 +2192,11 @@ 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); + let mut highest_gas_limit = request.gas.unwrap_or(block_env.gas_limit.to()); let gas_price = fees.gas_price.unwrap_or_default(); // If we have non-zero gas price, cap gas limit by sender balance - if !gas_price.is_zero() { + if gas_price > 0 { if let Some(from) = request.from { let mut available_funds = self.backend.get_balance_with_state(&state, from)?; if let Some(value) = request.value { @@ -2216,7 +2207,8 @@ impl EthApi { available_funds -= value; } // amount of gas the sender can afford with the `gas_price` - let allowance = available_funds.checked_div(gas_price).unwrap_or_default(); + let allowance = + available_funds.to::().checked_div(gas_price).unwrap_or_default(); highest_gas_limit = std::cmp::min(highest_gas_limit, allowance); } } @@ -2229,7 +2221,7 @@ impl EthApi { self.backend.call_with_state(&state, call_to_estimate, fees.clone(), block_env.clone()); let gas_used = match ethres.try_into()? { - GasEstimationCallResult::Success(gas) => Ok(U256::from(gas)), + GasEstimationCallResult::Success(gas) => Ok(gas), GasEstimationCallResult::OutOfGas => { Err(InvalidTransactionError::BasicOutOfGas(highest_gas_limit).into()) } @@ -2251,13 +2243,11 @@ impl EthApi { let mut lowest_gas_limit = determine_base_gas_by_kind(&request); // pick a point that's close to the estimated gas - let mut mid_gas_limit = std::cmp::min( - gas_used * U256::from(3), - (highest_gas_limit + lowest_gas_limit) / U256::from(2), - ); + let mut mid_gas_limit = + std::cmp::min(gas_used * 3, (highest_gas_limit + lowest_gas_limit) / 2); // Binary search for the ideal gas limit - while (highest_gas_limit - lowest_gas_limit) > U256::from(1) { + while (highest_gas_limit - lowest_gas_limit) > 1 { request.gas = Some(mid_gas_limit); let ethres = self.backend.call_with_state( &state, @@ -2286,7 +2276,7 @@ impl EthApi { } }; // new midpoint - mid_gas_limit = (highest_gas_limit + lowest_gas_limit) / U256::from(2); + mid_gas_limit = (highest_gas_limit + lowest_gas_limit) / 2; } trace!(target : "node", "Estimated Gas for call {:?}", highest_gas_limit); @@ -2396,39 +2386,39 @@ impl EthApi { fn build_typed_tx_request( &self, request: WithOtherFields, - nonce: U256, + nonce: u64, ) -> Result { let chain_id = request.chain_id.unwrap_or_else(|| self.chain_id()); let max_fee_per_gas = request.max_fee_per_gas; let gas_price = request.gas_price; - let gas_limit = request.gas.map(Ok).unwrap_or_else(|| self.current_gas_limit())?; + let gas_limit = request.gas.unwrap_or(self.backend.gas_limit()); let request = match transaction_request_to_typed(request) { Some(TypedTransactionRequest::Legacy(mut m)) => { - m.nonce = nonce.to::(); + m.nonce = nonce; m.chain_id = Some(chain_id); - m.gas_limit = gas_limit.to::(); + m.gas_limit = gas_limit; if gas_price.is_none() { - m.gas_price = self.gas_price().unwrap_or_default().to::(); + m.gas_price = self.backend.gas_price() } TypedTransactionRequest::Legacy(m) } Some(TypedTransactionRequest::EIP2930(mut m)) => { - m.nonce = nonce.to::(); + m.nonce = nonce; m.chain_id = chain_id; - m.gas_limit = gas_limit.to::(); + m.gas_limit = gas_limit; if gas_price.is_none() { - m.gas_price = self.gas_price().unwrap_or_default().to::(); + m.gas_price = self.backend.gas_price(); } TypedTransactionRequest::EIP2930(m) } Some(TypedTransactionRequest::EIP1559(mut m)) => { - m.nonce = nonce.to::(); + m.nonce = nonce; m.chain_id = chain_id; - m.gas_limit = gas_limit.to::(); + m.gas_limit = gas_limit; if max_fee_per_gas.is_none() { - m.max_fee_per_gas = self.gas_price().unwrap_or_default().to::(); + m.max_fee_per_gas = self.backend.gas_price(); } TypedTransactionRequest::EIP1559(m) } @@ -2451,20 +2441,18 @@ impl EthApi { &self, address: Address, block_number: Option, - ) -> Result { + ) -> Result { let block_request = self.block_request(block_number).await?; if let BlockRequest::Number(number) = block_request { if let Some(fork) = self.get_fork() { if fork.predates_fork_inclusive(number) { - return Ok(fork.get_nonce(address, number).await?.to()); + return Ok(fork.get_nonce(address, number).await?); } } } - let nonce = self.backend.get_nonce(address, block_request).await?; - - Ok(nonce) + self.backend.get_nonce(address, block_request).await } /// Returns the nonce for this request @@ -2478,10 +2466,10 @@ impl EthApi { &self, request: &TransactionRequest, from: Address, - ) -> Result<(U256, U256)> { + ) -> Result<(u64, u64)> { let highest_nonce = self.get_transaction_count(from, Some(BlockId::Number(BlockNumber::Pending))).await?; - let nonce = request.nonce.map(U256::from).unwrap_or(highest_nonce); + let nonce = request.nonce.unwrap_or(highest_nonce); Ok((nonce, highest_nonce)) } @@ -2551,7 +2539,7 @@ fn ensure_return_ok(exit: InstructionResult, out: &Option) -> Result) -> U256 { +fn determine_base_gas_by_kind(request: &WithOtherFields) -> u128 { match transaction_request_to_typed(request.clone()) { Some(request) => match request { TypedTransactionRequest::Legacy(req) => match req.to { @@ -2580,17 +2568,17 @@ fn determine_base_gas_by_kind(request: &WithOtherFields) -> /// Keeps result of a call to revm EVM used for gas estimation enum GasEstimationCallResult { - Success(u64), + Success(u128), OutOfGas, Revert(Option), EvmError(InstructionResult), } /// Converts the result of a call to revm EVM into a [GasEstimationCallRes]. -impl TryFrom, u64, State)>> for GasEstimationCallResult { +impl TryFrom, u128, State)>> for GasEstimationCallResult { type Error = BlockchainError; - fn try_from(res: Result<(InstructionResult, Option, u64, State)>) -> Result { + fn try_from(res: Result<(InstructionResult, Option, u128, State)>) -> Result { match res { // Exceptional case: init used too much gas, treated as out of gas error Err(BlockchainError::InvalidTransaction(InvalidTransactionError::GasTooHigh(_))) => { diff --git a/crates/anvil/src/eth/backend/executor.rs b/crates/anvil/src/eth/backend/executor.rs index 416c3f32bc81..d4dcec912da7 100644 --- a/crates/anvil/src/eth/backend/executor.rs +++ b/crates/anvil/src/eth/backend/executor.rs @@ -7,7 +7,7 @@ use crate::{ mem::inspector::Inspector, }; use alloy_consensus::{Header, Receipt, ReceiptWithBloom}; -use alloy_primitives::{Bloom, BloomInput, Log, B256, U256}; +use alloy_primitives::{Bloom, BloomInput, Log, B256}; use anvil_core::eth::{ block::{Block, BlockInfo, PartialHeader}, transaction::{ @@ -35,7 +35,7 @@ pub struct ExecutedTransaction { transaction: Arc, exit_reason: InstructionResult, out: Option, - gas_used: u64, + gas_used: u128, logs: Vec, traces: Vec, nonce: u64, @@ -45,15 +45,18 @@ pub struct ExecutedTransaction { impl ExecutedTransaction { /// Creates the receipt for the transaction - fn create_receipt(&self, cumulative_gas_used: &mut u64) -> TypedReceipt { + fn create_receipt(&self, cumulative_gas_used: &mut u128) -> TypedReceipt { let logs = self.logs.clone(); *cumulative_gas_used = cumulative_gas_used.saturating_add(self.gas_used); // successful return see [Return] let status_code = u8::from(self.exit_reason as u8 <= InstructionResult::SelfDestruct as u8); - let receipt_with_bloom: ReceiptWithBloom = - Receipt { status: status_code == 1, cumulative_gas_used: *cumulative_gas_used, logs } - .into(); + let receipt_with_bloom: ReceiptWithBloom = Receipt { + status: status_code == 1, + cumulative_gas_used: *cumulative_gas_used as u64, + logs, + } + .into(); match &self.transaction.pending_transaction.transaction.transaction { TypedTransaction::Legacy(_) => TypedReceipt::Legacy(receipt_with_bloom), @@ -94,7 +97,7 @@ pub struct TransactionExecutor<'a, Db: ?Sized, Validator: TransactionValidator> pub cfg_env: CfgEnvWithHandlerCfg, pub parent_hash: B256, /// Cumulative gas used by all executed transactions - pub gas_used: U256, + pub gas_used: u128, pub enable_steps_tracing: bool, } @@ -105,17 +108,17 @@ impl<'a, DB: Db + ?Sized, Validator: TransactionValidator> TransactionExecutor<' let mut transaction_infos = Vec::new(); let mut receipts = Vec::new(); let mut bloom = Bloom::default(); - let mut cumulative_gas_used: u64 = 0; + let mut cumulative_gas_used: u128 = 0; let mut invalid = Vec::new(); let mut included = Vec::new(); - let gas_limit = self.block_env.gas_limit; + let gas_limit = self.block_env.gas_limit.to::(); let parent_hash = self.parent_hash; - let block_number = self.block_env.number; + let block_number = self.block_env.number.to::(); let difficulty = self.block_env.difficulty; let beneficiary = self.block_env.coinbase; let timestamp = self.block_env.timestamp.to::(); let base_fee = if (self.cfg_env.handler_cfg.spec_id as u8) >= (SpecId::LONDON as u8) { - Some(self.block_env.basefee) + Some(self.block_env.basefee.to::()) } else { None }; @@ -155,7 +158,7 @@ impl<'a, DB: Db + ?Sized, Validator: TransactionValidator> TransactionExecutor<' } }); - let transaction_index = transaction_infos.len() as u32; + let transaction_index = transaction_infos.len() as u64; let info = TransactionInfo { transaction_hash: transaction.hash(), transaction_index, @@ -170,7 +173,7 @@ impl<'a, DB: Db + ?Sized, Validator: TransactionValidator> TransactionExecutor<' _ => None, }, nonce: tx.nonce, - gas_used: tx.gas_used, + gas_used: tx.gas_used as u64, }; transaction_infos.push(info); @@ -188,14 +191,14 @@ impl<'a, DB: Db + ?Sized, Validator: TransactionValidator> TransactionExecutor<' receipts_root, logs_bloom: bloom, difficulty, - number: block_number.to::(), - gas_limit: gas_limit.to::(), + number: block_number, + gas_limit, gas_used: cumulative_gas_used, timestamp, extra_data: Default::default(), mix_hash: Default::default(), nonce: Default::default(), - base_fee: base_fee.map(|b| b.to::()), + base_fee, }; let block = Block::new(partial_header, transactions.clone(), ommers); @@ -239,8 +242,8 @@ 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 { + let max_gas = self.gas_used.saturating_add(env.tx.gas_limit as u128); + if max_gas > env.block.gas_limit.to::() { return Some(TransactionExecutionOutcome::Exhausted(transaction)) } @@ -313,7 +316,7 @@ impl<'a, 'b, DB: Db + ?Sized, Validator: TransactionValidator> Iterator trace!(target: "backend", ?exit_reason, ?gas_used, "[{:?}] executed with out={:?}", transaction.hash(), out); - self.gas_used = self.gas_used.saturating_add(U256::from(gas_used)); + self.gas_used = self.gas_used.saturating_add(gas_used as u128); trace!(target: "backend::executor", "transacted [{:?}], result: {:?} gas {}", transaction.hash(), exit_reason, gas_used); @@ -321,7 +324,7 @@ impl<'a, 'b, DB: Db + ?Sized, Validator: TransactionValidator> Iterator transaction, exit_reason, out, - gas_used, + gas_used: gas_used as u128, logs: logs.unwrap_or_default(), traces: inspector .tracer diff --git a/crates/anvil/src/eth/backend/fork.rs b/crates/anvil/src/eth/backend/fork.rs index fa91d2f52400..849baaeabfb2 100644 --- a/crates/anvil/src/eth/backend/fork.rs +++ b/crates/anvil/src/eth/backend/fork.rs @@ -67,7 +67,7 @@ impl ClientFork { let chain_id = if let Some(chain_id) = override_chain_id { chain_id } else { - self.provider().get_chain_id().await?.to::() + self.provider().get_chain_id().await? }; self.config.write().chain_id = chain_id; } @@ -148,7 +148,7 @@ impl ClientFork { /// Returns the fee history `eth_feeHistory` pub async fn fee_history( &self, - block_count: U256, + block_count: u64, newest_block: BlockNumber, reward_percentiles: &[f64], ) -> Result { @@ -182,7 +182,7 @@ impl ClientFork { &self, request: &TransactionRequest, block: Option, - ) -> Result { + ) -> Result { let block = block.unwrap_or(BlockNumber::Latest); let res = self.provider().estimate_gas(request, Some(block.into())).await?; @@ -248,13 +248,9 @@ impl ClientFork { self.provider().get_balance(address, Some(blocknumber.into())).await } - pub async fn get_nonce( - &self, - address: Address, - blocknumber: u64, - ) -> Result { + pub async fn get_nonce(&self, address: Address, block: u64) -> Result { trace!(target: "backend::fork", "get_nonce={:?}", address); - self.provider().get_transaction_count(address, Some(blocknumber.into())).await + self.provider().get_transaction_count(address, Some(block.into())).await } pub async fn transaction_by_block_number_and_index( diff --git a/crates/anvil/src/eth/backend/mem/mod.rs b/crates/anvil/src/eth/backend/mem/mod.rs index e75c116afed0..f96f765a3adf 100644 --- a/crates/anvil/src/eth/backend/mem/mod.rs +++ b/crates/anvil/src/eth/backend/mem/mod.rs @@ -97,9 +97,9 @@ pub mod state; pub mod storage; // Gas per transaction not creating a contract. -pub const MIN_TRANSACTION_GAS: U256 = U256::from_limbs([21_000, 0, 0, 0]); +pub const MIN_TRANSACTION_GAS: u128 = 21000; // Gas per transaction creating a contract. -pub const MIN_CREATE_GAS: U256 = U256::from_limbs([53_000, 0, 0, 0]); +pub const MIN_CREATE_GAS: u128 = 53000; pub type State = foundry_evm::utils::StateChangeset; @@ -425,12 +425,12 @@ impl Backend { // this is the base fee of the current block, but we need the base fee of // the next block let next_block_base_fee = self.fees.get_next_block_base_fee_per_gas( - fork_block.header.gas_used, - fork_block.header.gas_limit, - fork_block.header.base_fee_per_gas.unwrap_or_default(), + fork_block.header.gas_used.to(), + fork_block.header.gas_limit.to(), + fork_block.header.base_fee_per_gas.unwrap_or_default().to(), ); - self.fees.set_base_fee(U256::from(next_block_base_fee)); + self.fees.set_base_fee(next_block_base_fee); // also reset the total difficulty self.blockchain.storage.write().total_difficulty = fork.total_difficulty(); @@ -619,37 +619,37 @@ impl Backend { } /// Returns the block gas limit - pub fn gas_limit(&self) -> U256 { - self.env.read().block.gas_limit + pub fn gas_limit(&self) -> u128 { + self.env.read().block.gas_limit.to() } /// Sets the block gas limit - pub fn set_gas_limit(&self, gas_limit: U256) { - self.env.write().block.gas_limit = gas_limit; + pub fn set_gas_limit(&self, gas_limit: u128) { + self.env.write().block.gas_limit = U256::from(gas_limit); } /// Returns the current base fee - pub fn base_fee(&self) -> U256 { + pub fn base_fee(&self) -> u128 { self.fees.base_fee() } /// Sets the current basefee - pub fn set_base_fee(&self, basefee: U256) { + pub fn set_base_fee(&self, basefee: u128) { self.fees.set_base_fee(basefee) } /// Returns the current gas price - pub fn gas_price(&self) -> U256 { + pub fn gas_price(&self) -> u128 { self.fees.gas_price() } /// Returns the suggested fee cap - pub fn max_priority_fee_per_gas(&self) -> U256 { + pub fn max_priority_fee_per_gas(&self) -> u128 { self.fees.max_priority_fee_per_gas() } /// Sets the gas price - pub fn set_gas_price(&self, price: U256) { + pub fn set_gas_price(&self, price: u128) { self.fees.set_gas_price(price) } @@ -795,9 +795,9 @@ impl Backend { fn next_env(&self) -> EnvWithHandlerCfg { let mut env = self.env.read().clone(); // increase block number for this block - env.block.number = env.block.number.saturating_add(rU256::from(1)); - env.block.basefee = self.base_fee(); - env.block.timestamp = rU256::from(self.time.current_call_timestamp()); + env.block.number = env.block.number.saturating_add(U256::from(1)); + env.block.basefee = U256::from(self.base_fee()); + env.block.timestamp = U256::from(self.time.current_call_timestamp()); env } @@ -864,7 +864,7 @@ impl Backend { block_env: env.block.clone(), cfg_env, parent_hash: storage.best_hash, - gas_used: U256::ZERO, + gas_used: 0, enable_steps_tracing: self.enable_steps_tracing, }; @@ -903,7 +903,7 @@ impl Backend { // increase block number for this block env.block.number = env.block.number.saturating_add(rU256::from(1)); - env.block.basefee = current_base_fee; + env.block.basefee = U256::from(current_base_fee); env.block.timestamp = rU256::from(self.time.next_timestamp()); let best_hash = self.blockchain.storage.read().best_hash; @@ -923,7 +923,7 @@ impl Backend { block_env: env.block.clone(), cfg_env: CfgEnvWithHandlerCfg::new(env.cfg.clone(), env.handler_cfg), parent_hash: best_hash, - gas_used: U256::ZERO, + gas_used: 0, enable_steps_tracing: self.enable_steps_tracing, }; let executed_tx = executor.execute(); @@ -1018,16 +1018,16 @@ impl Backend { (outcome, header, block_hash) }; let next_block_base_fee = self.fees.get_next_block_base_fee_per_gas( - U256::from(header.gas_used), - U256::from(header.gas_limit), - U256::from(header.base_fee_per_gas.unwrap_or_default()), + header.gas_used as u128, + header.gas_limit as u128, + header.base_fee_per_gas.unwrap_or_default() as u128, ); // notify all listeners self.notify_on_new_block(header, block_hash); // update next base fee - self.fees.set_base_fee(U256::from(next_block_base_fee)); + self.fees.set_base_fee(next_block_base_fee); outcome } @@ -1043,7 +1043,7 @@ impl Backend { fee_details: FeeDetails, block_request: Option, overrides: Option, - ) -> Result<(InstructionResult, Option, u64, State), BlockchainError> { + ) -> Result<(InstructionResult, Option, u128, State), BlockchainError> { self.with_database_at(block_request, |state, block| { let block_number = block.number.to::(); let (exit, out, gas, state) = match overrides { @@ -1071,7 +1071,7 @@ impl Backend { let FeeDetails { gas_price, max_fee_per_gas, max_priority_fee_per_gas } = fee_details; - let gas_limit = gas.unwrap_or(block_env.gas_limit); + let gas_limit = gas.unwrap_or(block_env.gas_limit.to()); let mut env = self.env.read().clone(); env.block = block_env; // we want to disable this in eth_call, since this is common practice used by other node @@ -1079,7 +1079,7 @@ impl Backend { env.cfg.disable_block_gas_limit = true; if let Some(base) = max_fee_per_gas { - env.block.basefee = base; + env.block.basefee = U256::from(base); } let gas_price = gas_price.or(max_fee_per_gas).unwrap_or_else(|| self.gas_price()); @@ -1087,9 +1087,9 @@ impl Backend { env.tx = TxEnv { caller, - gas_limit: gas_limit.to::(), - gas_price, - gas_priority_fee: max_priority_fee_per_gas, + gas_limit: gas_limit as u64, + gas_price: U256::from(gas_price), + gas_priority_fee: max_priority_fee_per_gas.map(U256::from), transact_to: match to { Some(addr) => TransactTo::Call(addr), None => TransactTo::Create(CreateScheme::Create), @@ -1117,7 +1117,7 @@ impl Backend { request: WithOtherFields, fee_details: FeeDetails, block_env: BlockEnv, - ) -> Result<(InstructionResult, Option, u64, State), BlockchainError> + ) -> Result<(InstructionResult, Option, u128, State), BlockchainError> where D: DatabaseRef, { @@ -1136,7 +1136,7 @@ impl Backend { ExecutionResult::Halt { reason, gas_used } => (reason.into(), gas_used, None), }; inspector.print_logs(); - Ok((exit_reason, out, gas_used, state)) + Ok((exit_reason, out, gas_used as u128, state)) } pub async fn call_with_tracing( @@ -1280,7 +1280,7 @@ impl Backend { block_number: Some(block.header.number), block_timestamp: Some(block.header.timestamp), transaction_hash: Some(transaction_hash), - transaction_index: Some(tx.info.transaction_index as u64), + transaction_index: Some(tx.info.transaction_index), log_index: Some(block_log_index as u64), removed: false, }; @@ -1408,7 +1408,7 @@ impl Backend { tx, Some(block), Some(info), - base_fee.map(|f| f.to_alloy()), + base_fee.map(|f| f as u128), ); transactions.push(tx); } @@ -1782,10 +1782,10 @@ impl Backend { &self, address: Address, block_request: BlockRequest, - ) -> Result { + ) -> Result { if let BlockRequest::Pending(pool_transactions) = &block_request { if let Some(value) = get_pool_transactions_nonce(pool_transactions, address) { - return Ok(U256::from(value)); + return Ok(value); } } let final_block_request = match block_request { @@ -1795,7 +1795,7 @@ impl Backend { self.with_database_at(Some(final_block_request), |db, _| { trace!(target: "backend", "get nonce for {:?}", address); - Ok(U256::from(db.basic_ref(address)?.unwrap_or_default().nonce)) + Ok(db.basic_ref(address)?.unwrap_or_default().nonce) }) .await? } @@ -1949,15 +1949,13 @@ impl Backend { TypedTransaction::EIP1559(t) => block .header .base_fee_per_gas - .map_or(self.base_fee().to::(), |b| b as u128) - .checked_add(t.tx().max_priority_fee_per_gas) - .unwrap_or(u128::MAX), + .map_or(self.base_fee(), |b| b as u128) + .saturating_add(t.tx().max_priority_fee_per_gas), TypedTransaction::EIP4844(t) => block .header .base_fee_per_gas - .map_or(self.base_fee().to::(), |b| b as u128) - .checked_add(t.tx().tx().max_priority_fee_per_gas) - .unwrap_or(u128::MAX), + .map_or(self.base_fee(), |b| b as u128) + .saturating_add(t.tx().tx().max_priority_fee_per_gas), TypedTransaction::Deposit(_) => 0_u128, }; @@ -1978,7 +1976,7 @@ impl Backend { block_number: Some(block.header.number), block_timestamp: Some(block.header.timestamp), transaction_hash: Some(info.transaction_hash), - transaction_index: Some(info.transaction_index as u64), + transaction_index: Some(info.transaction_index), log_index: Some((next_log_index + index) as u64), removed: false, }) @@ -2002,7 +2000,7 @@ impl Backend { let inner = TransactionReceipt { inner, transaction_hash: info.transaction_hash, - transaction_index: info.transaction_index as u64, + transaction_index: info.transaction_index, block_number: Some(block.header.number), gas_used: Some(info.gas_used), contract_address: info.contract_address, @@ -2097,7 +2095,7 @@ impl Backend { tx, Some(&block), Some(info), - block.header.base_fee_per_gas.map(|g| g.to_alloy()), + block.header.base_fee_per_gas.map(|g| g as u128), )) } @@ -2132,7 +2130,7 @@ impl Backend { tx, Some(&block), Some(info), - block.header.base_fee_per_gas.map(|g| g.to_alloy()), + block.header.base_fee_per_gas.map(|g| g as u128), )) } @@ -2303,7 +2301,7 @@ impl TransactionValidator for Backend { } // Check gas limit, iff block gas limit is set. - if !env.cfg.disable_block_gas_limit && tx.gas_limit() > env.block.gas_limit { + if !env.cfg.disable_block_gas_limit && tx.gas_limit() > env.block.gas_limit.to() { warn!(target: "backend", "[{:?}] gas too high", tx.hash()); return Err(InvalidTransactionError::GasTooHigh(ErrDetail { detail: String::from("tx.gas_limit > env.block.gas_limit"), @@ -2320,7 +2318,7 @@ impl TransactionValidator for Backend { } if (env.handler_cfg.spec_id as u8) >= (SpecId::LONDON as u8) { - if tx.gas_price() < env.block.basefee && !is_deposit_tx { + if tx.gas_price() < env.block.basefee.to() && !is_deposit_tx { warn!(target: "backend", "max fee per gas={}, too low, block basefee={}",tx.gas_price(), env.block.basefee); return Err(InvalidTransactionError::FeeCapTooLow); } @@ -2338,12 +2336,12 @@ impl TransactionValidator for Backend { let max_cost = tx.max_cost(); let value = tx.value(); // check sufficient funds: `gas * price + value` - let req_funds = max_cost.checked_add(value).ok_or_else(|| { + let req_funds = max_cost.checked_add(value.to()).ok_or_else(|| { warn!(target: "backend", "[{:?}] cost too high", tx.hash()); InvalidTransactionError::InsufficientFunds })?; - if account.balance < req_funds { + if account.balance < U256::from(req_funds) { warn!(target: "backend", "[{:?}] insufficient allowance={}, required={} account={:?}", tx.hash(), account.balance, req_funds, *pending.sender()); return Err(InvalidTransactionError::InsufficientFunds); } @@ -2371,10 +2369,10 @@ pub fn transaction_build( eth_transaction: MaybeImpersonatedTransaction, block: Option<&Block>, info: Option, - base_fee: Option, + base_fee: Option, ) -> Transaction { let mut transaction: Transaction = eth_transaction.clone().into(); - if info.is_some() && transaction.transaction_type.unwrap_or_default().to::() == 0x7E { + if info.is_some() && transaction.transaction_type == Some(0x7E) { transaction.nonce = info.as_ref().unwrap().nonce; } @@ -2385,11 +2383,9 @@ pub fn transaction_build( } else { // if transaction is already mined, gas price is considered base fee + priority fee: the // effective gas price. - let base_fee = base_fee.unwrap_or(U256::ZERO); - let max_priority_fee_per_gas = - transaction.max_priority_fee_per_gas.map(|g| g.to::()).unwrap_or(U256::ZERO); - transaction.gas_price = - Some(base_fee.checked_add(max_priority_fee_per_gas).unwrap_or(U256::MAX)); + let base_fee = base_fee.unwrap_or(0); + let max_priority_fee_per_gas = transaction.max_priority_fee_per_gas.unwrap_or(0); + transaction.gas_price = Some(base_fee.saturating_add(max_priority_fee_per_gas)); } } else { transaction.max_fee_per_gas = None; @@ -2399,10 +2395,9 @@ pub fn transaction_build( transaction.block_hash = block.as_ref().map(|block| B256::from(keccak256(alloy_rlp::encode(&block.header)))); - transaction.block_number = block.as_ref().map(|block| U256::from(block.header.number)); + transaction.block_number = block.as_ref().map(|block| block.header.number); - transaction.transaction_index = - info.as_ref().map(|status| U256::from(status.transaction_index)); + transaction.transaction_index = info.as_ref().map(|info| info.transaction_index); // need to check if the signature of the transaction is impersonated, if so then we // can't recover the sender, instead we use the sender from the executed transaction and set the diff --git a/crates/anvil/src/eth/backend/mem/storage.rs b/crates/anvil/src/eth/backend/mem/storage.rs index a6fc4874e670..7ef240d2f0a6 100644 --- a/crates/anvil/src/eth/backend/mem/storage.rs +++ b/crates/anvil/src/eth/backend/mem/storage.rs @@ -225,12 +225,12 @@ pub struct BlockchainStorage { impl BlockchainStorage { /// Creates a new storage with a genesis block - pub fn new(env: &Env, base_fee: Option, timestamp: u64) -> Self { + pub fn new(env: &Env, base_fee: Option, timestamp: u64) -> Self { // create a dummy genesis block let partial_header = PartialHeader { timestamp, - base_fee: base_fee.map(|b| b.to::()), - gas_limit: env.block.gas_limit.to::(), + base_fee, + gas_limit: env.block.gas_limit.to::(), beneficiary: env.block.coinbase, difficulty: env.block.difficulty, ..Default::default() @@ -336,7 +336,7 @@ pub struct Blockchain { impl Blockchain { /// Creates a new storage with a genesis block - pub fn new(env: &Env, base_fee: Option, timestamp: u64) -> Self { + pub fn new(env: &Env, base_fee: Option, timestamp: u64) -> Self { Self { storage: Arc::new(RwLock::new(BlockchainStorage::new(env, base_fee, timestamp))) } } @@ -405,7 +405,7 @@ impl MinedTransaction { ) .into_localized_transaction_traces(RethTransactionInfo { hash: Some(self.info.transaction_hash), - index: Some(self.info.transaction_index as u64), + index: Some(self.info.transaction_index), block_hash: Some(self.block_hash), block_number: Some(self.block_number), base_fee: None, diff --git a/crates/anvil/src/eth/error.rs b/crates/anvil/src/eth/error.rs index 57436503965d..1e35e78e14d4 100644 --- a/crates/anvil/src/eth/error.rs +++ b/crates/anvil/src/eth/error.rs @@ -1,7 +1,7 @@ //! Aggregated error type for this module use crate::eth::pool::transactions::PoolTransaction; -use alloy_primitives::{Bytes, SignatureError as AlloySignatureError, U256}; +use alloy_primitives::{Bytes, SignatureError as AlloySignatureError}; use alloy_signer::Error as AlloySignerError; use alloy_transport::TransportError; use anvil_rpc::{ @@ -180,7 +180,7 @@ pub enum InvalidTransactionError { FeeCapTooLow, /// Thrown during estimate if caller has insufficient funds to cover the tx. #[error("Out of gas: gas required exceeds allowance: {0:?}")] - BasicOutOfGas(U256), + BasicOutOfGas(u128), /// Thrown if executing a transaction failed during estimate/call #[error("execution reverted: {0:?}")] Revert(Option), diff --git a/crates/anvil/src/eth/fees.rs b/crates/anvil/src/eth/fees.rs index d60df7d4c4c5..eef25d543a93 100644 --- a/crates/anvil/src/eth/fees.rs +++ b/crates/anvil/src/eth/fees.rs @@ -2,7 +2,7 @@ use crate::eth::{ backend::{info::StorageInfo, notifications::NewBlockNotifications}, error::BlockchainError, }; -use alloy_primitives::{B256, U256}; +use alloy_primitives::B256; use anvil_core::eth::transaction::TypedTransaction; use foundry_evm::revm::primitives::SpecId; use futures::StreamExt; @@ -20,16 +20,16 @@ use std::{ pub const MAX_FEE_HISTORY_CACHE_SIZE: u64 = 2048u64; /// Initial base fee for EIP-1559 blocks. -pub const INITIAL_BASE_FEE: u64 = 1_000_000_000; +pub const INITIAL_BASE_FEE: u128 = 1_000_000_000; /// Initial default gas price for the first block -pub const INITIAL_GAS_PRICE: u64 = 1_875_000_000; +pub const INITIAL_GAS_PRICE: u128 = 1_875_000_000; /// Bounds the amount the base fee can change between blocks. -pub const BASE_FEE_CHANGE_DENOMINATOR: u64 = 8; +pub const BASE_FEE_CHANGE_DENOMINATOR: u128 = 8; /// Elasticity multiplier as defined in [EIP-1559](https://eips.ethereum.org/EIPS/eip-1559) -pub const EIP1559_ELASTICITY_MULTIPLIER: u64 = 2; +pub const EIP1559_ELASTICITY_MULTIPLIER: u128 = 2; pub fn default_elasticity() -> f64 { 1f64 / BASE_FEE_CHANGE_DENOMINATOR as f64 @@ -43,18 +43,18 @@ pub struct FeeManager { /// Tracks the base fee for the next block post London /// /// This value will be updated after a new block was mined - base_fee: Arc>, + base_fee: Arc>, /// The base price to use Pre London /// /// This will be constant value unless changed manually - gas_price: Arc>, + gas_price: Arc>, elasticity: Arc>, } // === impl FeeManager === impl FeeManager { - pub fn new(spec_id: SpecId, base_fee: U256, gas_price: U256) -> Self { + pub fn new(spec_id: SpecId, base_fee: u128, gas_price: u128) -> Self { Self { spec_id, base_fee: Arc::new(RwLock::new(base_fee)), @@ -73,7 +73,7 @@ impl FeeManager { } /// Calculates the current gas price - pub fn gas_price(&self) -> U256 { + pub fn gas_price(&self) -> u128 { if self.is_eip1559() { self.base_fee().saturating_add(self.suggested_priority_fee()) } else { @@ -82,33 +82,33 @@ impl FeeManager { } /// Suggested priority fee to add to the base fee - pub fn suggested_priority_fee(&self) -> U256 { - U256::from(1e9 as u64) + pub fn suggested_priority_fee(&self) -> u128 { + 1e9 as u128 } - pub fn base_fee(&self) -> U256 { + pub fn base_fee(&self) -> u128 { if self.is_eip1559() { *self.base_fee.read() } else { - U256::ZERO + 0 } } /// Returns the suggested fee cap /// /// Note: This currently returns a constant value: [Self::suggested_priority_fee] - pub fn max_priority_fee_per_gas(&self) -> U256 { + pub fn max_priority_fee_per_gas(&self) -> u128 { self.suggested_priority_fee() } /// Returns the current gas price - pub fn set_gas_price(&self, price: U256) { + pub fn set_gas_price(&self, price: u128) { let mut gas = self.gas_price.write(); *gas = price; } /// Returns the current base fee - pub fn set_base_fee(&self, fee: U256) { + pub fn set_base_fee(&self, fee: u128) { trace!(target: "backend::fees", "updated base fee {:?}", fee); let mut base = self.base_fee.write(); *base = fee; @@ -117,26 +117,22 @@ impl FeeManager { /// Calculates the base fee for the next block pub fn get_next_block_base_fee_per_gas( &self, - gas_used: U256, - gas_limit: U256, - last_fee_per_gas: U256, - ) -> u64 { + gas_used: u128, + gas_limit: u128, + last_fee_per_gas: u128, + ) -> u128 { // It's naturally impossible for base fee to be 0; // It means it was set by the user deliberately and therefore we treat it as a constant. // Therefore, we skip the base fee calculation altogether and we return 0. - if self.base_fee().is_zero() { + if self.base_fee() == 0 { return 0 } - calculate_next_block_base_fee( - gas_used.to::(), - gas_limit.to::(), - last_fee_per_gas.to::(), - ) + calculate_next_block_base_fee(gas_used, gas_limit, last_fee_per_gas) } } /// Calculate base fee for next block. [EIP-1559](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md) spec -pub fn calculate_next_block_base_fee(gas_used: u64, gas_limit: u64, base_fee: u64) -> u64 { +pub fn calculate_next_block_base_fee(gas_used: u128, gas_limit: u128, base_fee: u128) -> u128 { let gas_target = gas_limit / EIP1559_ELASTICITY_MULTIPLIER; if gas_used == gas_target { @@ -144,20 +140,15 @@ pub fn calculate_next_block_base_fee(gas_used: u64, gas_limit: u64, base_fee: u6 } if gas_used > gas_target { let gas_used_delta = gas_used - gas_target; - let base_fee_delta = std::cmp::max( - 1, - base_fee as u128 * gas_used_delta as u128 / - gas_target as u128 / - BASE_FEE_CHANGE_DENOMINATOR as u128, - ); - base_fee + (base_fee_delta as u64) + let base_fee_delta = + std::cmp::max(1, base_fee * gas_used_delta / gas_target / BASE_FEE_CHANGE_DENOMINATOR); + base_fee + base_fee_delta } else { let gas_used_delta = gas_target - gas_used; - let base_fee_per_gas_delta = base_fee as u128 * gas_used_delta as u128 / - gas_target as u128 / - BASE_FEE_CHANGE_DENOMINATOR as u128; + let base_fee_per_gas_delta = + base_fee * gas_used_delta / gas_target / BASE_FEE_CHANGE_DENOMINATOR; - base_fee.saturating_sub(base_fee_per_gas_delta as u64) + base_fee.saturating_sub(base_fee_per_gas_delta) } } @@ -222,11 +213,7 @@ impl FeeHistoryService { let mut block_number: Option = None; let base_fee = self.fees.base_fee(); - let mut item = FeeHistoryCacheItem { - base_fee: base_fee.to::(), - gas_used_ratio: 0f64, - rewards: Vec::new(), - }; + let mut item = FeeHistoryCacheItem { base_fee, gas_used_ratio: 0f64, rewards: Vec::new() }; let current_block = self.storage_info.block(hash); let current_receipts = self.storage_info.receipts(hash); @@ -241,7 +228,7 @@ impl FeeHistoryService { item.gas_used_ratio = gas_used / (gas_target * elasticity); // extract useful tx info (gas_used, effective_reward) - let mut transactions: Vec<(u64, u64)> = receipts + let mut transactions: Vec<(u64, u128)> = receipts .iter() .enumerate() .map(|(i, receipt)| { @@ -249,25 +236,21 @@ impl FeeHistoryService { let effective_reward = match block.transactions.get(i).map(|tx| &tx.transaction) { Some(TypedTransaction::Legacy(t)) => { - U256::from(t.tx().gas_price).saturating_sub(base_fee).to::() + t.tx().gas_price.saturating_sub(base_fee) } Some(TypedTransaction::EIP2930(t)) => { - U256::from(t.tx().gas_price).saturating_sub(base_fee).to::() - } - Some(TypedTransaction::EIP1559(t)) => { - U256::from(t.tx().max_priority_fee_per_gas) - .min(U256::from(t.tx().max_fee_per_gas).saturating_sub(base_fee)) - .to::() + t.tx().gas_price.saturating_sub(base_fee) } + Some(TypedTransaction::EIP1559(t)) => t + .tx() + .max_priority_fee_per_gas + .min(t.tx().max_fee_per_gas.saturating_sub(base_fee)), // TODO: This probably needs to be extended to extract 4844 info. - Some(TypedTransaction::EIP4844(t)) => { - U256::from(t.tx().tx().max_priority_fee_per_gas) - .min( - U256::from(t.tx().tx().max_fee_per_gas) - .saturating_sub(base_fee), - ) - .to::() - } + Some(TypedTransaction::EIP4844(t)) => t + .tx() + .tx() + .max_priority_fee_per_gas + .min(t.tx().tx().max_fee_per_gas.saturating_sub(base_fee)), Some(TypedTransaction::Deposit(_)) => 0, None => 0, }; @@ -341,26 +324,22 @@ pub type FeeHistoryCache = Arc>>; /// A single item in the whole fee history cache #[derive(Clone, Debug)] pub struct FeeHistoryCacheItem { - pub base_fee: u64, + pub base_fee: u128, pub gas_used_ratio: f64, - pub rewards: Vec, + pub rewards: Vec, } #[derive(Clone, Default)] pub struct FeeDetails { - pub gas_price: Option, - pub max_fee_per_gas: Option, - pub max_priority_fee_per_gas: Option, + pub gas_price: Option, + pub max_fee_per_gas: Option, + pub max_priority_fee_per_gas: Option, } impl FeeDetails { /// All values zero pub fn zero() -> Self { - Self { - gas_price: Some(U256::ZERO), - max_fee_per_gas: Some(U256::ZERO), - max_priority_fee_per_gas: Some(U256::ZERO), - } + Self { gas_price: Some(0), max_fee_per_gas: Some(0), max_priority_fee_per_gas: Some(0) } } /// If neither `gas_price` nor `max_fee_per_gas` is `Some`, this will set both to `0` @@ -368,23 +347,23 @@ impl FeeDetails { let FeeDetails { gas_price, max_fee_per_gas, max_priority_fee_per_gas } = self; let no_fees = gas_price.is_none() && max_fee_per_gas.is_none(); - let gas_price = if no_fees { Some(U256::ZERO) } else { gas_price }; - let max_fee_per_gas = if no_fees { Some(U256::ZERO) } else { max_fee_per_gas }; + let gas_price = if no_fees { Some(0) } else { gas_price }; + let max_fee_per_gas = if no_fees { Some(0) } else { max_fee_per_gas }; Self { gas_price, max_fee_per_gas, max_priority_fee_per_gas } } /// Turns this type into a tuple - pub fn split(self) -> (Option, Option, Option) { + pub fn split(self) -> (Option, Option, Option) { let Self { gas_price, max_fee_per_gas, max_priority_fee_per_gas } = self; (gas_price, max_fee_per_gas, max_priority_fee_per_gas) } /// Creates a new instance from the request's gas related values pub fn new( - request_gas_price: Option, - request_max_fee: Option, - request_priority: Option, + request_gas_price: Option, + request_max_fee: Option, + request_priority: Option, ) -> Result { match (request_gas_price, request_max_fee, request_priority) { (gas_price, None, None) => { diff --git a/crates/anvil/src/eth/pool/transactions.rs b/crates/anvil/src/eth/pool/transactions.rs index 312bde4818bf..a88bc369cd94 100644 --- a/crates/anvil/src/eth/pool/transactions.rs +++ b/crates/anvil/src/eth/pool/transactions.rs @@ -1,5 +1,5 @@ use crate::eth::{error::PoolError, util::hex_fmt_many}; -use alloy_primitives::{Address, TxHash, U256}; +use alloy_primitives::{Address, TxHash}; use anvil_core::eth::transaction::{PendingTransaction, TypedTransaction}; use parking_lot::RwLock; use std::{ @@ -65,10 +65,10 @@ impl FromStr for TransactionOrder { /// Metric value for the priority of a transaction. /// -/// The `TransactionPriority` determines the ordering of two transactions that have all their +/// The `TransactionPriority` determines the ordering of two transactions that have all their /// markers satisfied. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] -pub struct TransactionPriority(pub U256); +pub struct TransactionPriority(pub u128); /// Internal Transaction type #[derive(Clone, PartialEq, Eq)] @@ -92,7 +92,7 @@ impl PoolTransaction { } /// Returns the gas pric of this transaction - pub fn gas_price(&self) -> U256 { + pub fn gas_price(&self) -> u128 { self.pending_transaction.transaction.gas_price() } } @@ -679,7 +679,7 @@ impl ReadyTransaction { &self.transaction.transaction.provides } - pub fn gas_price(&self) -> U256 { + pub fn gas_price(&self) -> u128 { self.transaction.transaction.gas_price() } } diff --git a/crates/anvil/src/lib.rs b/crates/anvil/src/lib.rs index d8988baf30f8..11a860bc385b 100644 --- a/crates/anvil/src/lib.rs +++ b/crates/anvil/src/lib.rs @@ -311,7 +311,7 @@ impl NodeHandle { } /// Default gas price for all txs - pub fn gas_price(&self) -> U256 { + pub fn gas_price(&self) -> u128 { self.config.get_gas_price() } diff --git a/crates/anvil/tests/it/anvil_api.rs b/crates/anvil/tests/it/anvil_api.rs index 2f37f9b56d10..ed933363d34d 100644 --- a/crates/anvil/tests/it/anvil_api.rs +++ b/crates/anvil/tests/it/anvil_api.rs @@ -445,10 +445,10 @@ async fn can_get_node_info() { hard_fork: SpecId::CANCUN, transaction_order: "fees".to_owned(), environment: NodeEnvironment { - base_fee: U256::from_str("0x3b9aca00").unwrap().to_alloy(), + base_fee: alloy_primitives::U256::from_str("0x3b9aca00").unwrap().to(), chain_id: 0x7a69, - gas_limit: U256::from_str("0x1c9c380").unwrap().to_alloy(), - gas_price: U256::from_str("0x77359400").unwrap().to_alloy(), + gas_limit: alloy_primitives::U256::from_str("0x1c9c380").unwrap().to(), + gas_price: alloy_primitives::U256::from_str("0x77359400").unwrap().to(), }, fork_config: NodeForkConfig { fork_url: None, diff --git a/crates/anvil/tests/it/fork.rs b/crates/anvil/tests/it/fork.rs index fe150e712bcd..9c402b71de3e 100644 --- a/crates/anvil/tests/it/fork.rs +++ b/crates/anvil/tests/it/fork.rs @@ -4,7 +4,7 @@ use crate::{ abi::*, utils::{self, ethers_http_provider}, }; -use alloy_primitives::{address, U256 as rU256, U64 as rU64}; +use alloy_primitives::{address, U256 as rU256}; use alloy_provider::Provider as AlloyProvider; use alloy_rpc_types::{ request::{TransactionInput, TransactionRequest as CallRequest}, @@ -289,7 +289,7 @@ async fn test_fork_snapshotting() { let provider = handle.http_provider(); let nonce = provider.get_transaction_count(from, None).await.unwrap(); - assert_eq!(nonce, initial_nonce + rU64::from(1)); + assert_eq!(nonce, initial_nonce + 1); let to_balance = provider.get_balance(to, None).await.unwrap(); assert_eq!(balance_before.saturating_add(amount), to_balance); @@ -328,7 +328,7 @@ async fn test_fork_snapshotting_repeated() { let _ = tx_provider.send_transaction(tx, None).await.unwrap().await.unwrap().unwrap(); let nonce = provider.get_transaction_count(from, None).await.unwrap(); - assert_eq!(nonce, initial_nonce + rU64::from(1)); + assert_eq!(nonce, initial_nonce + 1); let to_balance = provider.get_balance(to, None).await.unwrap(); assert_eq!(balance_before.saturating_add(amount), to_balance); @@ -382,7 +382,7 @@ async fn test_fork_snapshotting_blocks() { assert_eq!(block_number_after, block_number + 1); let nonce = provider.get_transaction_count(from, None).await.unwrap(); - assert_eq!(nonce, initial_nonce + rU64::from(1)); + assert_eq!(nonce, initial_nonce + 1); let to_balance = provider.get_balance(to, None).await.unwrap(); assert_eq!(balance_before.saturating_add(amount), to_balance); @@ -396,12 +396,12 @@ async fn test_fork_snapshotting_blocks() { // repeat transaction let _ = tx_provider.send_transaction(tx.clone(), None).await.unwrap().await.unwrap().unwrap(); let nonce = provider.get_transaction_count(from, None).await.unwrap(); - assert_eq!(nonce, initial_nonce + rU64::from(1)); + assert_eq!(nonce, initial_nonce + 1); // revert again: nothing to revert since snapshot gone assert!(!api.evm_revert(snapshot).await.unwrap()); let nonce = provider.get_transaction_count(from, None).await.unwrap(); - assert_eq!(nonce, initial_nonce + rU64::from(1)); + assert_eq!(nonce, initial_nonce + 1); let block_number_after = provider.get_block_number().await.unwrap(); assert_eq!(block_number_after, block_number + 1); } @@ -470,20 +470,14 @@ async fn can_reset_properly() { let origin_nonce = 1u64; origin_api.anvil_set_nonce(account, rU256::from(origin_nonce)).await.unwrap(); - assert_eq!( - origin_nonce, - origin_provider.get_transaction_count(account, None).await.unwrap().to::() - ); + assert_eq!(origin_nonce, origin_provider.get_transaction_count(account, None).await.unwrap()); let (fork_api, fork_handle) = spawn(NodeConfig::test().with_eth_rpc_url(Some(origin_handle.http_endpoint()))).await; let fork_provider = fork_handle.http_provider(); let fork_tx_provider = ethers_http_provider(&fork_handle.http_endpoint()); - assert_eq!( - origin_nonce, - fork_provider.get_transaction_count(account, None).await.unwrap().to::() - ); + assert_eq!(origin_nonce, fork_provider.get_transaction_count(account, None).await.unwrap()); let to = Address::random(); let to_balance = fork_provider.get_balance(to.to_alloy(), None).await.unwrap(); @@ -491,19 +485,13 @@ async fn can_reset_properly() { let tx = fork_tx_provider.send_transaction(tx, None).await.unwrap().await.unwrap().unwrap(); // nonce incremented by 1 - assert_eq!( - origin_nonce + rU256::from(1).to::(), - fork_provider.get_transaction_count(account, None).await.unwrap().to::() - ); + assert_eq!(origin_nonce + 1, fork_provider.get_transaction_count(account, None).await.unwrap()); // resetting to origin state fork_api.anvil_reset(Some(Forking::default())).await.unwrap(); // nonce reset to origin - assert_eq!( - origin_nonce, - fork_provider.get_transaction_count(account, None).await.unwrap().to::() - ); + assert_eq!(origin_nonce, fork_provider.get_transaction_count(account, None).await.unwrap()); // balance is reset assert_eq!(to_balance, fork_provider.get_balance(to.to_alloy(), None).await.unwrap()); diff --git a/crates/anvil/tests/it/gas.rs b/crates/anvil/tests/it/gas.rs index 4f6098bfb2df..e2d194340c57 100644 --- a/crates/anvil/tests/it/gas.rs +++ b/crates/anvil/tests/it/gas.rs @@ -1,7 +1,6 @@ //! Gas related tests use crate::utils::ethers_http_provider; -use alloy_primitives::U256; use anvil::{eth::fees::INITIAL_BASE_FEE, spawn, NodeConfig}; use ethers::{ prelude::Middleware, @@ -10,16 +9,13 @@ use ethers::{ TransactionRequest, }, }; -use foundry_common::types::ToAlloy; -const GAS_TRANSFER: u64 = 21_000u64; +const GAS_TRANSFER: u128 = 21_000; #[tokio::test(flavor = "multi_thread")] async fn test_basefee_full_block() { let (_api, handle) = spawn( - NodeConfig::test() - .with_base_fee(Some(INITIAL_BASE_FEE.to_alloy())) - .with_gas_limit(Some(GAS_TRANSFER.to_alloy())), + NodeConfig::test().with_base_fee(Some(INITIAL_BASE_FEE)).with_gas_limit(Some(GAS_TRANSFER)), ) .await; let provider = ethers_http_provider(&handle.http_endpoint()); @@ -34,15 +30,15 @@ async fn test_basefee_full_block() { assert!(next_base_fee > base_fee); // max increase, full block - assert_eq!(next_base_fee.as_u64(), INITIAL_BASE_FEE + 125_000_000); + assert_eq!(next_base_fee.as_u128(), INITIAL_BASE_FEE + 125_000_000); } #[tokio::test(flavor = "multi_thread")] async fn test_basefee_half_block() { let (_api, handle) = spawn( NodeConfig::test() - .with_base_fee(Some(INITIAL_BASE_FEE.to_alloy())) - .with_gas_limit(Some(GAS_TRANSFER.to_alloy() * U256::from(2))), + .with_base_fee(Some(INITIAL_BASE_FEE)) + .with_gas_limit(Some(GAS_TRANSFER * 2)), ) .await; let provider = ethers_http_provider(&handle.http_endpoint()); @@ -54,12 +50,11 @@ async fn test_basefee_half_block() { provider.get_block(BlockNumber::Latest).await.unwrap().unwrap().base_fee_per_gas.unwrap(); // unchanged, half block - assert_eq!(next_base_fee.as_u64(), INITIAL_BASE_FEE); + assert_eq!(next_base_fee.as_u128(), INITIAL_BASE_FEE); } #[tokio::test(flavor = "multi_thread")] async fn test_basefee_empty_block() { - let (api, handle) = - spawn(NodeConfig::test().with_base_fee(Some(INITIAL_BASE_FEE.to_alloy()))).await; + let (api, handle) = spawn(NodeConfig::test().with_base_fee(Some(INITIAL_BASE_FEE))).await; let provider = ethers_http_provider(&handle.http_endpoint()); let tx = TransactionRequest::new().to(Address::random()).value(1337u64); @@ -79,8 +74,8 @@ async fn test_basefee_empty_block() { #[tokio::test(flavor = "multi_thread")] async fn test_respect_base_fee() { - let base_fee = 50u64; - let (_api, handle) = spawn(NodeConfig::test().with_base_fee(Some(base_fee.to_alloy()))).await; + let base_fee = 50u128; + let (_api, handle) = spawn(NodeConfig::test().with_base_fee(Some(base_fee))).await; let provider = ethers_http_provider(&handle.http_endpoint()); let mut tx = TypedTransaction::default(); tx.set_value(100u64); @@ -99,8 +94,8 @@ async fn test_respect_base_fee() { #[tokio::test(flavor = "multi_thread")] async fn test_tip_above_fee_cap() { - let base_fee = 50u64; - let (_api, handle) = spawn(NodeConfig::test().with_base_fee(Some(base_fee.to_alloy()))).await; + let base_fee = 50u128; + let (_api, handle) = spawn(NodeConfig::test().with_base_fee(Some(base_fee))).await; let provider = ethers_http_provider(&handle.http_endpoint()); let tx = TypedTransaction::Eip1559( Eip1559TransactionRequest::new() diff --git a/crates/anvil/tests/it/genesis.rs b/crates/anvil/tests/it/genesis.rs index bc5af367f5aa..0b243db3edb9 100644 --- a/crates/anvil/tests/it/genesis.rs +++ b/crates/anvil/tests/it/genesis.rs @@ -3,7 +3,7 @@ use std::str::FromStr; use alloy_genesis::Genesis; -use alloy_primitives::{Address, U256, U64}; +use alloy_primitives::{Address, U256}; use alloy_provider::Provider; use anvil::{spawn, NodeConfig}; @@ -41,7 +41,7 @@ async fn can_apply_genesis() { let provider = handle.http_provider(); - assert_eq!(provider.get_chain_id().await.unwrap(), U64::from(19763u64)); + assert_eq!(provider.get_chain_id().await.unwrap(), 19763u64); let addr: Address = Address::from_str("71562b71999873db5b286df957af199ec94617f7").unwrap(); let balance = provider.get_balance(addr, None).await.unwrap(); diff --git a/crates/anvil/tests/it/otterscan.rs b/crates/anvil/tests/it/otterscan.rs index e675f810bcf0..c40c3653e4ed 100644 --- a/crates/anvil/tests/it/otterscan.rs +++ b/crates/anvil/tests/it/otterscan.rs @@ -527,7 +527,7 @@ async fn can_call_ots_search_transactions_before() { assert_eq!(hashes.pop(), Some(tx.hash.to_ethers())); }); - block = result.txs.last().unwrap().block_number.unwrap().to::() - 1; + block = result.txs.last().unwrap().block_number.unwrap() - 1; } assert!(hashes.is_empty()); @@ -563,7 +563,7 @@ async fn can_call_ots_search_transactions_after() { assert_eq!(hashes.pop_back(), Some(tx.hash.to_ethers())); }); - block = result.txs.last().unwrap().block_number.unwrap().to::() + 1; + block = result.txs.last().unwrap().block_number.unwrap() + 1; } assert!(hashes.is_empty()); diff --git a/crates/anvil/tests/it/transaction.rs b/crates/anvil/tests/it/transaction.rs index 28dc1a4088b7..685dc43c82b9 100644 --- a/crates/anvil/tests/it/transaction.rs +++ b/crates/anvil/tests/it/transaction.rs @@ -1007,10 +1007,7 @@ async fn test_estimate_gas() { .expect("Failed to estimate gas with state override"); // Assert the gas estimate meets the expected minimum. - assert!( - gas_estimate >= alloy_primitives::U256::from(21000), - "Gas estimate is lower than expected minimum" - ); + assert!(gas_estimate >= 21000, "Gas estimate is lower than expected minimum"); } #[tokio::test(flavor = "multi_thread")] @@ -1036,8 +1033,7 @@ async fn test_reject_gas_too_low() { // #[tokio::test(flavor = "multi_thread")] async fn can_call_with_high_gas_limit() { - let (_api, handle) = - spawn(NodeConfig::test().with_gas_limit(Some(U256::from(100_000_000).to_alloy()))).await; + let (_api, handle) = spawn(NodeConfig::test().with_gas_limit(Some(100_000_000))).await; let provider = ethers_http_provider(&handle.http_endpoint()); let wallet = handle.dev_wallets().next().unwrap().to_ethers(); diff --git a/crates/cast/bin/cmd/access_list.rs b/crates/cast/bin/cmd/access_list.rs index 5a5ce3ee5575..780e835bbb42 100644 --- a/crates/cast/bin/cmd/access_list.rs +++ b/crates/cast/bin/cmd/access_list.rs @@ -111,7 +111,7 @@ async fn access_list, T: Transport + Clone>( .with_chain_id(chain.id()); if let Some(gas_limit) = tx.gas_limit { - req.set_gas_limit(gas_limit); + req.set_gas_limit(gas_limit.to()); } if let Some(nonce) = tx.nonce { diff --git a/crates/cast/bin/cmd/mktx.rs b/crates/cast/bin/cmd/mktx.rs index 5cd08a63dec9..def6d46f4b27 100644 --- a/crates/cast/bin/cmd/mktx.rs +++ b/crates/cast/bin/cmd/mktx.rs @@ -1,5 +1,6 @@ use crate::tx; use alloy_network::{eip2718::Encodable2718, EthereumSigner, TransactionBuilder}; +use alloy_primitives::U64; use alloy_provider::Provider; use alloy_signer::Signer; use clap::Parser; @@ -88,7 +89,7 @@ impl MakeTxArgs { tx::validate_from_address(eth.wallet.from, from)?; if resend { - tx.nonce = Some(provider.get_transaction_count(from, None).await?); + tx.nonce = Some(U64::from(provider.get_transaction_count(from, None).await?)); } let provider = get_provider(&config)?; diff --git a/crates/cast/bin/cmd/run.rs b/crates/cast/bin/cmd/run.rs index 3149a337d848..a1e01fe23c4a 100644 --- a/crates/cast/bin/cmd/run.rs +++ b/crates/cast/bin/cmd/run.rs @@ -109,19 +109,15 @@ impl RunArgs { .wrap_err_with(|| format!("tx not found: {:?}", tx_hash))?; // check if the tx is a system transaction - if is_known_system_sender(tx.from) || - tx.transaction_type.map(|ty| ty.to::()) == Some(SYSTEM_TRANSACTION_TYPE) - { + if is_known_system_sender(tx.from) || tx.transaction_type == Some(SYSTEM_TRANSACTION_TYPE) { return Err(eyre::eyre!( "{:?} is a system transaction.\nReplaying system transactions is currently not supported.", tx.hash )); } - let tx_block_number = tx - .block_number - .ok_or_else(|| eyre::eyre!("tx may still be pending: {:?}", tx_hash))? - .to::(); + let tx_block_number = + tx.block_number.ok_or_else(|| eyre::eyre!("tx may still be pending: {:?}", tx_hash))?; // fetch the block the transaction was mined in let block = provider.get_block(tx_block_number.into(), true).await?; @@ -174,8 +170,7 @@ impl RunArgs { // we skip them otherwise this would cause // reverts if is_known_system_sender(tx.from) || - tx.transaction_type.map(|ty| ty.to::()) == - Some(SYSTEM_TRANSACTION_TYPE) + tx.transaction_type == Some(SYSTEM_TRANSACTION_TYPE) { update_progress!(pb, index); continue; diff --git a/crates/cast/bin/cmd/send.rs b/crates/cast/bin/cmd/send.rs index e926dc6009bb..3d40bd0133d9 100644 --- a/crates/cast/bin/cmd/send.rs +++ b/crates/cast/bin/cmd/send.rs @@ -1,6 +1,6 @@ use crate::tx; use alloy_network::{Ethereum, EthereumSigner}; -use alloy_primitives::Address; +use alloy_primitives::{Address, U64}; use alloy_provider::{Provider, ProviderBuilder}; use alloy_signer::Signer; use alloy_transport::Transport; @@ -124,7 +124,7 @@ impl SendTxArgs { if unlocked { // only check current chain id if it was specified in the config if let Some(config_chain) = config.chain { - let current_chain_id: u64 = provider.get_chain_id().await?.to(); + let current_chain_id = provider.get_chain_id().await?; let config_chain_id = config_chain.id(); // switch chain if current chain id is not the same as the one specified in the // config @@ -142,7 +142,8 @@ impl SendTxArgs { } if resend { - tx.nonce = Some(provider.get_transaction_count(config.sender, None).await?); + tx.nonce = + Some(U64::from(provider.get_transaction_count(config.sender, None).await?)); } cast_send( @@ -172,7 +173,7 @@ impl SendTxArgs { tx::validate_from_address(eth.wallet.from, from)?; if resend { - tx.nonce = Some(provider.get_transaction_count(from, None).await?); + tx.nonce = Some(U64::from(provider.get_transaction_count(from, None).await?)); } let signer = EthereumSigner::from(signer); diff --git a/crates/cast/bin/tx.rs b/crates/cast/bin/tx.rs index 6816d307b5bc..57718cc8fc2c 100644 --- a/crates/cast/bin/tx.rs +++ b/crates/cast/bin/tx.rs @@ -1,6 +1,6 @@ use alloy_json_abi::Function; use alloy_network::TransactionBuilder; -use alloy_primitives::Address; +use alloy_primitives::{Address, U256}; use alloy_provider::Provider; use alloy_rpc_types::TransactionRequest; use alloy_transport::Transport; @@ -64,18 +64,15 @@ pub async fn build_tx< .with_value(tx.value.unwrap_or_default()) .with_chain_id(chain.id()); - req.set_nonce( - if let Some(nonce) = tx.nonce { - nonce - } else { - provider.get_transaction_count(from, None).await? - } - .to(), - ); + req.set_nonce(if let Some(nonce) = tx.nonce { + nonce.to() + } else { + provider.get_transaction_count(from, None).await? + }); if tx.legacy || chain.is_legacy() { req.set_gas_price(if let Some(gas_price) = tx.gas_price { - gas_price + gas_price.to() } else { provider.get_gas_price().await? }); @@ -85,14 +82,14 @@ pub async fn build_tx< (_, _) => { let estimate = provider.estimate_eip1559_fees(None).await?; ( - tx.gas_price.unwrap_or(estimate.max_fee_per_gas), - tx.priority_gas_price.unwrap_or(estimate.max_priority_fee_per_gas), + tx.gas_price.unwrap_or(U256::from(estimate.max_fee_per_gas)), + tx.priority_gas_price.unwrap_or(U256::from(estimate.max_priority_fee_per_gas)), ) } }; - req.set_max_fee_per_gas(max_fee); - req.set_max_priority_fee_per_gas(priority_fee); + req.set_max_fee_per_gas(max_fee.to()); + req.set_max_priority_fee_per_gas(priority_fee.to()); } let params = sig.as_deref().map(|sig| (sig, args)); @@ -116,7 +113,7 @@ pub async fn build_tx< req.set_input(data.into()); req.set_gas_limit(if let Some(gas_limit) = tx.gas_limit { - gas_limit + gas_limit.to() } else { provider.estimate_gas(&req, None).await? }); diff --git a/crates/cast/src/lib.rs b/crates/cast/src/lib.rs index a030a0297ee4..c4549f5a683f 100644 --- a/crates/cast/src/lib.rs +++ b/crates/cast/src/lib.rs @@ -3,7 +3,7 @@ use alloy_dyn_abi::{DynSolType, DynSolValue, FunctionExt}; use alloy_json_abi::{ContractObject, Function}; use alloy_primitives::{ utils::{keccak256, ParseUnits, Unit}, - Address, Keccak256, TxHash, B256, I256, U256, U64, + Address, Keccak256, TxHash, B256, I256, U256, }; use alloy_provider::{ network::{ @@ -424,15 +424,15 @@ where }) } - pub async fn chain_id(&self) -> Result { - Ok(U256::from(self.provider.get_chain_id().await?)) + pub async fn chain_id(&self) -> Result { + Ok(self.provider.get_chain_id().await?) } - pub async fn block_number(&self) -> Result { - Ok(U64::from(self.provider.get_block_number().await?)) + pub async fn block_number(&self) -> Result { + Ok(self.provider.get_block_number().await?) } - pub async fn gas_price(&self) -> Result { + pub async fn gas_price(&self) -> Result { Ok(self.provider.get_gas_price().await?) } @@ -454,7 +454,7 @@ where /// # } /// ``` pub async fn nonce(&self, who: Address, block: Option) -> Result { - Ok(self.provider.get_transaction_count(who, block).await?.to()) + Ok(self.provider.get_transaction_count(who, block).await?) } /// # Example diff --git a/crates/cheatcodes/src/inspector.rs b/crates/cheatcodes/src/inspector.rs index 4ca59bcf276e..e4a7cdea0ef3 100644 --- a/crates/cheatcodes/src/inspector.rs +++ b/crates/cheatcodes/src/inspector.rs @@ -868,7 +868,7 @@ impl Inspector for Cheatcodes { input: TransactionInput::new(call.input.clone()), nonce: Some(account.info.nonce), gas: if is_fixed_gas_limit { - Some(U256::from(call.gas_limit)) + Some(call.gas_limit as u128) } else { None }, @@ -1277,7 +1277,7 @@ impl Inspector for Cheatcodes { input: TransactionInput::new(bytecode), nonce: Some(nonce), gas: if is_fixed_gas_limit { - Some(U256::from(call.gas_limit)) + Some(call.gas_limit as u128) } else { None }, diff --git a/crates/cheatcodes/src/utils.rs b/crates/cheatcodes/src/utils.rs index a8aae0bf54de..7544abc0a624 100644 --- a/crates/cheatcodes/src/utils.rs +++ b/crates/cheatcodes/src/utils.rs @@ -284,7 +284,7 @@ mod tests { use alloy_primitives::FixedBytes; use hex::FromHex; use p256::ecdsa::signature::hazmat::PrehashVerifier; - use std::sync::Arc; + use std::{path::PathBuf, sync::Arc}; fn cheats() -> Cheatcodes { let config = CheatsConfig { diff --git a/crates/cli/src/utils/mod.rs b/crates/cli/src/utils/mod.rs index 7e659b47fe0e..08eda672cbb0 100644 --- a/crates/cli/src/utils/mod.rs +++ b/crates/cli/src/utils/mod.rs @@ -117,7 +117,7 @@ where { match chain { Some(chain) => Ok(chain), - None => Ok(Chain::from_id(provider.get_chain_id().await?.to())), + None => Ok(Chain::from_id(provider.get_chain_id().await?)), } } diff --git a/crates/common/src/constants.rs b/crates/common/src/constants.rs index 23ca0abab43f..0ba0514c2b87 100644 --- a/crates/common/src/constants.rs +++ b/crates/common/src/constants.rs @@ -38,7 +38,7 @@ pub const ARBITRUM_SENDER: Address = address!("000000000000000000000000000000000 pub const OPTIMISM_SYSTEM_ADDRESS: Address = address!("deaddeaddeaddeaddeaddeaddeaddeaddead0001"); /// Transaction identifier of System transaction types -pub const SYSTEM_TRANSACTION_TYPE: u64 = 126u64; +pub const SYSTEM_TRANSACTION_TYPE: u8 = 126; /// Returns whether the sender is a known L2 system sender that is the first tx in every block. /// diff --git a/crates/common/src/fmt/ui.rs b/crates/common/src/fmt/ui.rs index 188437ed60a3..37e6695df0c4 100644 --- a/crates/common/src/fmt/ui.rs +++ b/crates/common/src/fmt/ui.rs @@ -74,6 +74,12 @@ impl UIfmt for u64 { } } +impl UIfmt for u128 { + fn pretty(&self) -> String { + self.to_string() + } +} + impl UIfmt for bool { fn pretty(&self) -> String { self.to_string() diff --git a/crates/common/src/provider/alloy.rs b/crates/common/src/provider/alloy.rs index 5d083f1769c5..39a53fab7f5c 100644 --- a/crates/common/src/provider/alloy.rs +++ b/crates/common/src/provider/alloy.rs @@ -28,7 +28,7 @@ use super::{ }; /// Helper type alias for a retry provider -pub type RetryProvider = RootProvider>; +pub type RetryProvider = RootProvider, N>; /// Helper type alias for a rpc url pub type RpcUrl = String; @@ -262,7 +262,7 @@ pub async fn estimate_eip1559_fees, T: Transport + Clone>( let chain = if let Some(chain) = chain { chain } else { - provider.get_chain_id().await.wrap_err("Failed to get chain id")?.to() + provider.get_chain_id().await.wrap_err("Failed to get chain id")? }; if let Ok(chain) = NamedChain::try_from(chain) { @@ -279,8 +279,8 @@ pub async fn estimate_eip1559_fees, T: Transport + Clone>( let (a, b) = estimator.estimate_eip1559_fees().await?; let estimation = Eip1559Estimation { - max_fee_per_gas: a.to_alloy(), - max_priority_fee_per_gas: b.to_alloy(), + max_fee_per_gas: a.to_alloy().to(), + max_priority_fee_per_gas: b.to_alloy().to(), }; return Ok(estimation) } diff --git a/crates/evm/core/src/backend/mod.rs b/crates/evm/core/src/backend/mod.rs index 15f29f8e2a70..fc5eff27dde2 100644 --- a/crates/evm/core/src/backend/mod.rs +++ b/crates/evm/core/src/backend/mod.rs @@ -863,11 +863,11 @@ impl Backend { // get the block number we need to fork if let Some(tx_block) = tx.block_number { - let block = fork.db.db.get_full_block(tx_block.to::())?; + let block = fork.db.db.get_full_block(tx_block)?; // we need to subtract 1 here because we want the state before the transaction // was mined - let fork_block = tx_block.to::() - 1; + let fork_block = tx_block - 1; Ok((U64::from(fork_block), block)) } else { let block = fork.db.db.get_full_block(BlockNumberOrTag::Latest)?; @@ -904,7 +904,7 @@ impl Backend { // System transactions such as on L2s don't contain any pricing info so we skip them // otherwise this would cause reverts if is_known_system_sender(tx.from) || - tx.transaction_type.map(|ty| ty.to::()) == Some(SYSTEM_TRANSACTION_TYPE) + tx.transaction_type == Some(SYSTEM_TRANSACTION_TYPE) { trace!(tx=?tx.hash, "skipping system transaction"); continue; diff --git a/crates/evm/core/src/fork/backend.rs b/crates/evm/core/src/fork/backend.rs index b78eec975af4..3fd7706b7b84 100644 --- a/crates/evm/core/src/fork/backend.rs +++ b/crates/evm/core/src/fork/backend.rs @@ -3,7 +3,7 @@ use crate::{ backend::{DatabaseError, DatabaseResult}, fork::{cache::FlushJsonBlockCacheDB, BlockchainDb}, }; -use alloy_primitives::{keccak256, Address, Bytes, B256, U256, U64}; +use alloy_primitives::{keccak256, Address, Bytes, B256, U256}; use alloy_provider::Provider; use alloy_rpc_types::{Block, BlockId, Transaction}; use alloy_transport::Transport; @@ -33,7 +33,7 @@ use std::{ // Various future/request type aliases type AccountFuture = - Pin, Address)> + Send>>; + Pin, Address)> + Send>>; type StorageFuture = Pin, Address, U256)> + Send>>; type BlockHashFuture = Pin, u64)> + Send>>; type FullBlockFuture = @@ -349,7 +349,7 @@ where // update the cache let acc = AccountInfo { - nonce: nonce.to(), + nonce, balance, code: Some(Bytecode::new_raw(code).to_checked()), code_hash, diff --git a/crates/evm/core/src/fork/init.rs b/crates/evm/core/src/fork/init.rs index c43d28955a7b..4bca73c5234c 100644 --- a/crates/evm/core/src/fork/init.rs +++ b/crates/evm/core/src/fork/init.rs @@ -50,7 +50,7 @@ pub async fn environment>( }; let mut cfg = CfgEnv::default(); - cfg.chain_id = override_chain_id.unwrap_or(rpc_chain_id.to::()); + cfg.chain_id = override_chain_id.unwrap_or(rpc_chain_id); cfg.memory_limit = memory_limit; cfg.limit_contract_code_size = Some(usize::MAX); // EIP-3607 rejects transactions from senders with deployed code. @@ -73,8 +73,8 @@ pub async fn environment>( }, tx: TxEnv { caller: origin, - gas_price: gas_price.map(U256::from).unwrap_or(fork_gas_price), - chain_id: Some(override_chain_id.unwrap_or(rpc_chain_id.to::())), + gas_price: gas_price.map(U256::from).unwrap_or(U256::from(fork_gas_price)), + chain_id: Some(override_chain_id.unwrap_or(rpc_chain_id)), gas_limit: block.header.gas_limit.to::(), ..Default::default() }, diff --git a/crates/evm/core/src/opts.rs b/crates/evm/core/src/opts.rs index 92cfdcd9b131..70f72087a752 100644 --- a/crates/evm/core/src/opts.rs +++ b/crates/evm/core/src/opts.rs @@ -205,7 +205,7 @@ impl EvmOpts { .unwrap_or_else(|| panic!("Failed to establish provider to {url}")); if let Ok(id) = RuntimeOrHandle::new().block_on(provider.get_chain_id()) { - return Some(Chain::from(id.to::())); + return Some(Chain::from(id)); } } diff --git a/crates/evm/core/src/utils.rs b/crates/evm/core/src/utils.rs index ad11165267aa..74cbd0a61f13 100644 --- a/crates/evm/core/src/utils.rs +++ b/crates/evm/core/src/utils.rs @@ -68,9 +68,9 @@ pub fn get_function( /// Configures the env for the transaction pub fn configure_tx_env(env: &mut revm::primitives::Env, tx: &Transaction) { env.tx.caller = tx.from; - env.tx.gas_limit = tx.gas.to(); - env.tx.gas_price = tx.gas_price.unwrap_or_default().to(); - env.tx.gas_priority_fee = tx.max_priority_fee_per_gas.map(|g| g.to()); + env.tx.gas_limit = tx.gas as u64; + env.tx.gas_price = U256::from(tx.gas_price.unwrap_or_default()); + env.tx.gas_priority_fee = tx.max_priority_fee_per_gas.map(U256::from); env.tx.nonce = Some(tx.nonce); env.tx.access_list = tx .access_list diff --git a/crates/forge/bin/cmd/create.rs b/crates/forge/bin/cmd/create.rs index a768cc40fedd..af8f6204d479 100644 --- a/crates/forge/bin/cmd/create.rs +++ b/crates/forge/bin/cmd/create.rs @@ -129,7 +129,7 @@ impl CreateArgs { let chain_id = if let Some(chain_id) = self.chain_id() { chain_id } else { - provider.get_chain_id().await?.to() + provider.get_chain_id().await? }; if self.unlocked { // Deploy with unlocked account @@ -230,17 +230,14 @@ impl CreateArgs { deployer.tx.set_from(deployer_address); deployer.tx.set_chain_id(chain); - deployer.tx.set_nonce( - if let Some(nonce) = self.tx.nonce { - Ok(nonce) - } else { - provider.get_transaction_count(deployer_address, None).await - }? - .to(), - ); + deployer.tx.set_nonce(if let Some(nonce) = self.tx.nonce { + Ok(nonce.to()) + } else { + provider.get_transaction_count(deployer_address, None).await + }?); deployer.tx.set_gas_limit(if let Some(gas_limit) = self.tx.gas_limit { - Ok(gas_limit) + Ok(gas_limit.to()) } else { provider.estimate_gas(&deployer.tx, None).await }?); @@ -252,7 +249,7 @@ impl CreateArgs { if is_legacy { let gas_price = if let Some(gas_price) = self.tx.gas_price { - gas_price + gas_price.to() } else { provider.get_gas_price().await? }; @@ -262,12 +259,12 @@ impl CreateArgs { .await .wrap_err("Failed to estimate EIP1559 fees. This chain might not support EIP1559, try adding --legacy to your command.")?; let priority_fee = if let Some(priority_fee) = self.tx.priority_gas_price { - priority_fee + priority_fee.to() } else { estimate.max_priority_fee_per_gas }; let max_fee = if let Some(max_fee) = self.tx.gas_price { - max_fee + max_fee.to() } else { estimate.max_fee_per_gas }; diff --git a/crates/script/src/broadcast.rs b/crates/script/src/broadcast.rs index 7da5725e8109..bd7891eed5e7 100644 --- a/crates/script/src/broadcast.rs +++ b/crates/script/src/broadcast.rs @@ -6,7 +6,7 @@ use crate::{ use alloy_chains::Chain; use alloy_eips::eip2718::Encodable2718; use alloy_network::{EthereumSigner, TransactionBuilder}; -use alloy_primitives::{utils::format_units, Address, TxHash, U256}; +use alloy_primitives::{utils::format_units, Address, TxHash}; use alloy_provider::{utils::Eip1559Estimation, Provider}; use alloy_rpc_types::TransactionRequest; use alloy_transport::Transport; @@ -46,8 +46,8 @@ where tx.set_gas_limit( provider.estimate_gas(tx, None).await.wrap_err("Failed to estimate gas for tx")? * - U256::from(estimate_multiplier) / - U256::from(100), + estimate_multiplier as u128 / + 100, ); Ok(()) } @@ -55,8 +55,7 @@ where pub async fn next_nonce(caller: Address, provider_url: &str) -> eyre::Result { let provider = try_get_http_provider(provider_url) .wrap_err_with(|| format!("bad fork_url provider: {provider_url}"))?; - let res = provider.get_transaction_count(caller, None).await?; - res.try_into().map_err(Into::into) + Ok(provider.get_transaction_count(caller, None).await?) } pub async fn send_transaction( @@ -74,7 +73,7 @@ pub async fn send_transaction( let nonce = provider.get_transaction_count(from, None).await?; let tx_nonce = tx.nonce.expect("no nonce"); - if nonce.to::() != tx_nonce { + if nonce != tx_nonce { bail!("EOA nonce changed unexpectedly while sending transactions. Expected {tx_nonce} got {nonce} from provider.") } } @@ -246,11 +245,14 @@ impl BundledState { self.args.with_gas_price, self.args.priority_gas_price, ) { - (true, Some(gas_price), _) => (Some(gas_price), None), + (true, Some(gas_price), _) => (Some(gas_price.to()), None), (true, None, _) => (Some(provider.get_gas_price().await?), None), (false, Some(max_fee_per_gas), Some(max_priority_fee_per_gas)) => ( None, - Some(Eip1559Estimation { max_fee_per_gas, max_priority_fee_per_gas }), + Some(Eip1559Estimation { + max_fee_per_gas: max_fee_per_gas.to(), + max_priority_fee_per_gas: max_priority_fee_per_gas.to(), + }), ), (false, _, _) => { let mut fees = estimate_eip1559_fees(&provider, Some(sequence.chain)) @@ -258,11 +260,11 @@ impl BundledState { .wrap_err("Failed to estimate EIP1559 fees. This chain might not support EIP1559, try adding --legacy to your command.")?; if let Some(gas_price) = self.args.with_gas_price { - fees.max_fee_per_gas = gas_price; + fees.max_fee_per_gas = gas_price.to(); } if let Some(priority_gas_price) = self.args.priority_gas_price { - fees.max_priority_fee_per_gas = priority_gas_price; + fees.max_priority_fee_per_gas = priority_gas_price.to(); } (None, Some(fees)) diff --git a/crates/script/src/build.rs b/crates/script/src/build.rs index 5f2929c222dd..51fde33adafd 100644 --- a/crates/script/src/build.rs +++ b/crates/script/src/build.rs @@ -289,7 +289,7 @@ impl CompiledState { } else { let fork_url = self.script_config.evm_opts.fork_url.clone().ok_or_eyre("Missing --fork-url field, if you were trying to broadcast a multi-chain sequence, please use --multi flag")?; let provider = Arc::new(try_get_http_provider(fork_url)?); - Some(provider.get_chain_id().await?.to::()) + Some(provider.get_chain_id().await?) }; let sequence = match self.try_load_sequence(chain, false) { diff --git a/crates/script/src/execute.rs b/crates/script/src/execute.rs index 648c49faa3a1..67108c72c7be 100644 --- a/crates/script/src/execute.rs +++ b/crates/script/src/execute.rs @@ -253,8 +253,7 @@ impl RpcData { let chain_ids = self.total_rpcs.iter().map(|rpc| async move { let provider = get_http_provider(rpc); let id = provider.get_chain_id().await.ok()?; - let id_u64: u64 = id.try_into().ok()?; - NamedChain::try_from(id_u64).ok() + NamedChain::try_from(id).ok() }); let chains = join_all(chain_ids).await; diff --git a/crates/script/src/providers.rs b/crates/script/src/providers.rs index 022b0a3aeaea..ab2ee99112f9 100644 --- a/crates/script/src/providers.rs +++ b/crates/script/src/providers.rs @@ -1,4 +1,3 @@ -use alloy_primitives::U256; use alloy_provider::{utils::Eip1559Estimation, Provider}; use eyre::{Result, WrapErr}; use foundry_common::provider::alloy::{get_http_provider, RetryProvider, RpcUrl}; @@ -51,14 +50,14 @@ pub struct ProviderInfo { /// Represents the outcome of a gas price request #[derive(Debug)] pub enum GasPrice { - Legacy(Result), + Legacy(Result), EIP1559(Result), } impl ProviderInfo { pub async fn new(rpc: &str, mut is_legacy: bool) -> Result { let provider = Arc::new(get_http_provider(rpc)); - let chain = provider.get_chain_id().await?.to::(); + let chain = provider.get_chain_id().await?; if let Some(chain) = Chain::from(chain).named() { is_legacy |= chain.is_legacy(); @@ -78,7 +77,7 @@ impl ProviderInfo { } /// Returns the gas price to use - pub fn gas_price(&self) -> Result { + pub fn gas_price(&self) -> Result { let res = match &self.gas_price { GasPrice::Legacy(res) => res.as_ref(), GasPrice::EIP1559(res) => res.as_ref().map(|res| &res.max_fee_per_gas), diff --git a/crates/script/src/simulate.rs b/crates/script/src/simulate.rs index 5ccf7d346f74..c740e59a4735 100644 --- a/crates/script/src/simulate.rs +++ b/crates/script/src/simulate.rs @@ -131,9 +131,8 @@ impl PreSimulationState { } // We inflate the gas used by the user specified percentage None => { - let gas = - U256::from(result.gas_used * self.args.gas_estimate_multiplier / 100); - tx.gas = Some(gas); + let gas = result.gas_used * self.args.gas_estimate_multiplier / 100; + tx.gas = Some(gas as u128); } } let tx = TransactionWithMetadata::new( @@ -265,7 +264,7 @@ impl FilledTransactionsState { eyre::bail!("Multi-chain deployment is not supported with libraries."); } - let mut total_gas_per_rpc: HashMap = HashMap::new(); + let mut total_gas_per_rpc: HashMap = HashMap::new(); // Batches sequence of transactions from different rpcs. let mut new_sequence = VecDeque::new(); @@ -312,7 +311,7 @@ impl FilledTransactionsState { } } - let total_gas = total_gas_per_rpc.entry(tx_rpc.clone()).or_insert(U256::ZERO); + let total_gas = total_gas_per_rpc.entry(tx_rpc.clone()).or_insert(0); *total_gas += tx.gas.expect("gas is set"); } @@ -341,7 +340,7 @@ impl FilledTransactionsState { // We don't store it in the transactions, since we want the most updated value. // Right before broadcasting. let per_gas = if let Some(gas_price) = self.args.with_gas_price { - gas_price + gas_price.to() } else { provider_info.gas_price()? }; diff --git a/crates/test-utils/src/script.rs b/crates/test-utils/src/script.rs index 8eecdd785310..fecbc9f5f07f 100644 --- a/crates/test-utils/src/script.rs +++ b/crates/test-utils/src/script.rs @@ -1,5 +1,5 @@ use crate::{init_tracing, TestCommand}; -use alloy_primitives::{Address, U64}; +use alloy_primitives::Address; use alloy_provider::Provider; use eyre::Result; use foundry_common::provider::alloy::{get_http_provider, RetryProvider}; @@ -13,8 +13,8 @@ pub struct ScriptTester { pub accounts_pub: Vec
, pub accounts_priv: Vec, pub provider: Option, - pub nonces: BTreeMap, - pub address_nonces: BTreeMap, + pub nonces: BTreeMap, + pub address_nonces: BTreeMap, pub cmd: TestCommand, } @@ -175,7 +175,7 @@ impl ScriptTester { assert_eq!( nonce, - (prev_nonce + U64::from(expected_increment)), + (*prev_nonce + expected_increment as u64), "nonce not incremented correctly for {addr}: \ {prev_nonce} + {expected_increment} != {nonce}" ); @@ -198,7 +198,7 @@ impl ScriptTester { .unwrap(); let prev_nonce = self.address_nonces.get(address).unwrap(); - assert_eq!(nonce, (prev_nonce + U64::from(*expected_increment))); + assert_eq!(nonce, *prev_nonce + *expected_increment as u64); } self } From 26bf989f83d925c612670fe6f92c17a62b61200b Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Sun, 7 Apr 2024 07:38:25 +0400 Subject: [PATCH 57/63] AnyNetwork --- Cargo.lock | 43 +++++------ Cargo.toml | 44 +++++------ crates/anvil/core/src/eth/transaction/mod.rs | 70 ++++++++++++----- crates/anvil/src/config.rs | 3 +- crates/anvil/src/eth/api.rs | 20 +++-- crates/anvil/src/eth/backend/fork.rs | 44 +++++++---- crates/anvil/src/eth/backend/mem/mod.rs | 28 +++---- crates/anvil/src/eth/error.rs | 5 ++ crates/anvil/src/eth/otterscan/api.rs | 6 +- crates/anvil/src/eth/otterscan/types.rs | 6 +- crates/anvil/src/tasks/mod.rs | 9 ++- crates/anvil/tests/it/transaction.rs | 2 +- crates/cast/bin/cmd/access_list.rs | 8 +- crates/cast/bin/cmd/call.rs | 4 +- crates/cast/bin/cmd/estimate.rs | 4 +- crates/cast/bin/cmd/send.rs | 7 +- crates/cast/bin/cmd/storage.rs | 5 +- crates/cast/bin/tx.rs | 10 +-- crates/cast/src/lib.rs | 22 +++--- crates/cli/src/utils/abi.rs | 6 +- crates/cli/src/utils/mod.rs | 4 +- crates/common/src/fmt/ui.rs | 80 ++++++++++---------- crates/common/src/provider/alloy.rs | 10 +-- crates/common/src/transactions.rs | 26 ++++--- crates/evm/core/src/backend/mod.rs | 6 +- crates/evm/core/src/fork/backend.rs | 26 ++++--- crates/forge/bin/cmd/create.rs | 20 ++--- crates/script/src/broadcast.rs | 10 +-- crates/script/src/receipts.rs | 22 +++--- crates/script/src/sequence.rs | 8 +- crates/script/src/transaction.rs | 10 +-- 31 files changed, 319 insertions(+), 249 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 38b996997d0d..2277f60a2bd1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -90,7 +90,7 @@ dependencies = [ [[package]] name = "alloy-consensus" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" +source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" dependencies = [ "alloy-eips", "alloy-primitives", @@ -105,7 +105,7 @@ dependencies = [ [[package]] name = "alloy-contract" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" +source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" dependencies = [ "alloy-dyn-abi", "alloy-json-abi", @@ -144,7 +144,7 @@ dependencies = [ [[package]] name = "alloy-eips" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" +source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -158,7 +158,7 @@ dependencies = [ [[package]] name = "alloy-genesis" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" +source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" dependencies = [ "alloy-primitives", "alloy-serde", @@ -180,7 +180,7 @@ dependencies = [ [[package]] name = "alloy-json-rpc" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" +source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" dependencies = [ "alloy-primitives", "serde", @@ -191,7 +191,7 @@ dependencies = [ [[package]] name = "alloy-network" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" +source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" dependencies = [ "alloy-consensus", "alloy-eips", @@ -234,7 +234,7 @@ dependencies = [ [[package]] name = "alloy-provider" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" +source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" dependencies = [ "alloy-json-rpc", "alloy-network", @@ -258,7 +258,7 @@ dependencies = [ [[package]] name = "alloy-pubsub" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" +source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" dependencies = [ "alloy-json-rpc", "alloy-primitives", @@ -298,7 +298,7 @@ dependencies = [ [[package]] name = "alloy-rpc-client" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" +source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" dependencies = [ "alloy-json-rpc", "alloy-primitives", @@ -318,7 +318,7 @@ dependencies = [ [[package]] name = "alloy-rpc-types" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" +source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" dependencies = [ "alloy-consensus", "alloy-eips", @@ -336,7 +336,7 @@ dependencies = [ [[package]] name = "alloy-rpc-types-trace" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" +source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" dependencies = [ "alloy-primitives", "alloy-rpc-types", @@ -348,7 +348,7 @@ dependencies = [ [[package]] name = "alloy-serde" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" +source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" dependencies = [ "alloy-primitives", "serde", @@ -358,7 +358,7 @@ dependencies = [ [[package]] name = "alloy-signer" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" +source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" dependencies = [ "alloy-dyn-abi", "alloy-primitives", @@ -373,7 +373,7 @@ dependencies = [ [[package]] name = "alloy-signer-aws" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" +source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" dependencies = [ "alloy-consensus", "alloy-network", @@ -390,7 +390,7 @@ dependencies = [ [[package]] name = "alloy-signer-ledger" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" +source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" dependencies = [ "alloy-consensus", "alloy-network", @@ -407,7 +407,7 @@ dependencies = [ [[package]] name = "alloy-signer-trezor" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" +source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" dependencies = [ "alloy-consensus", "alloy-network", @@ -423,7 +423,7 @@ dependencies = [ [[package]] name = "alloy-signer-wallet" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" +source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" dependencies = [ "alloy-consensus", "alloy-network", @@ -500,7 +500,7 @@ dependencies = [ [[package]] name = "alloy-transport" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" +source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" dependencies = [ "alloy-json-rpc", "base64 0.22.0", @@ -518,7 +518,7 @@ dependencies = [ [[package]] name = "alloy-transport-http" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" +source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" dependencies = [ "alloy-json-rpc", "alloy-transport", @@ -531,7 +531,7 @@ dependencies = [ [[package]] name = "alloy-transport-ipc" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" +source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" dependencies = [ "alloy-json-rpc", "alloy-pubsub", @@ -549,7 +549,7 @@ dependencies = [ [[package]] name = "alloy-transport-ws" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=17633df#17633df04920e07cd7afbd6ee825fcde677fa1d1" +source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" dependencies = [ "alloy-pubsub", "alloy-transport", @@ -6845,7 +6845,6 @@ dependencies = [ [[package]] name = "revm-inspectors" version = "0.1.0" -source = "git+https://github.com/paradigmxyz/evm-inspectors?rev=c34b770#c34b77089b508bea7221aaa4bfeb33d444a62ea3" dependencies = [ "alloy-primitives", "alloy-rpc-types", diff --git a/Cargo.toml b/Cargo.toml index ea6f420ccdee..427e340be26c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -143,7 +143,7 @@ foundry-compilers = { version = "0.3.14", default-features = false } # no default features to avoid c-kzg revm = { version = "8", default-features = false } revm-primitives = { version = "3", default-features = false } -revm-inspectors = { git = "https://github.com/paradigmxyz/evm-inspectors", rev = "c34b770", features = [ +revm-inspectors = { path = "../evm-inspectors", features = [ "serde", ] } @@ -157,27 +157,27 @@ ethers-signers = { version = "2.0.14", default-features = false } ethers-middleware = { version = "2.0.14", default-features = false } ## alloy -alloy-consensus = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } -alloy-contract = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } -alloy-eips = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } -alloy-genesis = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } -alloy-json-rpc = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } -alloy-network = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } -alloy-node-bindings = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } -alloy-provider = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } -alloy-pubsub = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } -alloy-rpc-client = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } -alloy-rpc-types-trace = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } -alloy-rpc-types = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } -alloy-signer = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } -alloy-signer-wallet = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } -alloy-signer-aws = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } -alloy-signer-ledger = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } -alloy-signer-trezor = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } -alloy-transport = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } -alloy-transport-http = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } -alloy-transport-ipc = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } -alloy-transport-ws = { git = "https://github.com/alloy-rs/alloy", rev = "17633df", default-features = false } +alloy-consensus = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } +alloy-contract = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } +alloy-eips = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } +alloy-genesis = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } +alloy-json-rpc = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } +alloy-network = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } +alloy-node-bindings = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } +alloy-provider = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } +alloy-pubsub = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } +alloy-rpc-client = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } +alloy-rpc-types-trace = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } +alloy-rpc-types = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } +alloy-signer = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } +alloy-signer-wallet = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } +alloy-signer-aws = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } +alloy-signer-ledger = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } +alloy-signer-trezor = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } +alloy-transport = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } +alloy-transport-http = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } +alloy-transport-ipc = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } +alloy-transport-ws = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } alloy-primitives = { version = "0.7.0", features = ["getrandom"] } alloy-dyn-abi = "0.7.0" alloy-json-abi = "0.7.0" diff --git a/crates/anvil/core/src/eth/transaction/mod.rs b/crates/anvil/core/src/eth/transaction/mod.rs index bbe983a3444e..e5b0a3af0cc7 100644 --- a/crates/anvil/core/src/eth/transaction/mod.rs +++ b/crates/anvil/core/src/eth/transaction/mod.rs @@ -5,14 +5,15 @@ use crate::eth::{ utils::eip_to_revm_access_list, }; use alloy_consensus::{ - BlobTransactionSidecar, Receipt, ReceiptEnvelope, ReceiptWithBloom, Signed, TxEip1559, - TxEip2930, TxEip4844, TxEip4844Variant, TxEip4844WithSidecar, TxEnvelope, TxLegacy, TxReceipt, + AnyReceiptEnvelope, BlobTransactionSidecar, Receipt, ReceiptEnvelope, ReceiptWithBloom, Signed, + TxEip1559, TxEip2930, TxEip4844, TxEip4844Variant, TxEip4844WithSidecar, TxEnvelope, TxLegacy, + TxReceipt, }; use alloy_eips::eip2718::Decodable2718; use alloy_primitives::{Address, Bloom, Bytes, Log, Signature, TxHash, TxKind, B256, U256}; use alloy_rlp::{length_of_length, Decodable, Encodable, Header}; use alloy_rpc_types::{ - request::TransactionRequest, AccessList, Signature as RpcSignature, + request::TransactionRequest, AccessList, AnyTransactionReceipt, Signature as RpcSignature, Transaction as RpcTransaction, TransactionReceipt, WithOtherFields, }; use bytes::BufMut; @@ -1229,22 +1230,53 @@ impl Decodable for TypedReceipt { pub type ReceiptResponse = TransactionReceipt>; -pub fn convert_to_anvil_receipt(receipt: TransactionReceipt) -> ReceiptResponse { - TransactionReceipt { - transaction_hash: receipt.transaction_hash, - transaction_index: receipt.transaction_index, - block_hash: receipt.block_hash, - block_number: receipt.block_number, - gas_used: receipt.gas_used, - contract_address: receipt.contract_address, - effective_gas_price: receipt.effective_gas_price, - from: receipt.from, - to: receipt.to, - blob_gas_price: receipt.blob_gas_price, - blob_gas_used: receipt.blob_gas_used, - state_root: receipt.state_root, - inner: receipt.inner.into(), - } +pub fn convert_to_anvil_receipt(receipt: AnyTransactionReceipt) -> Option { + let WithOtherFields { + inner: + TransactionReceipt { + transaction_hash, + transaction_index, + block_hash, + block_number, + gas_used, + contract_address, + effective_gas_price, + from, + to, + blob_gas_price, + blob_gas_used, + state_root, + inner: AnyReceiptEnvelope { inner: receipt_with_bloom, r#type }, + }, + other, + } = receipt; + + Some(TransactionReceipt { + transaction_hash, + transaction_index, + block_hash, + block_number, + gas_used, + contract_address, + effective_gas_price, + from, + to, + blob_gas_price, + blob_gas_used, + state_root, + inner: match r#type { + 0x00 => TypedReceipt::Legacy(receipt_with_bloom), + 0x01 => TypedReceipt::EIP2930(receipt_with_bloom), + 0x02 => TypedReceipt::EIP1559(receipt_with_bloom), + 0x03 => TypedReceipt::EIP4844(receipt_with_bloom), + 0x7E => TypedReceipt::Deposit(DepositReceipt { + inner: receipt_with_bloom, + deposit_nonce: other.get("depositNonce").and_then(|v| v.as_u64()), + deposit_nonce_version: other.get("depositNonceVersion").and_then(|v| v.as_u64()), + }), + _ => return None, + }, + }) } #[cfg(test)] diff --git a/crates/anvil/src/config.rs b/crates/anvil/src/config.rs index dbecd15b86c0..9db1428a7565 100644 --- a/crates/anvil/src/config.rs +++ b/crates/anvil/src/config.rs @@ -16,6 +16,7 @@ use crate::{ FeeManager, Hardfork, }; use alloy_genesis::Genesis; +use alloy_network::AnyNetwork; use alloy_primitives::{hex, utils::Unit, U256}; use alloy_provider::Provider; use alloy_rpc_types::BlockNumberOrTag; @@ -1232,7 +1233,7 @@ pub fn anvil_tmp_dir() -> Option { /// /// This fetches the "latest" block and checks whether the `Block` is fully populated (`hash` field /// is present). This prevents edge cases where anvil forks the "latest" block but `eth_getBlockByNumber` still returns a pending block, -async fn find_latest_fork_block, T: Transport + Clone>( +async fn find_latest_fork_block, T: Transport + Clone>( provider: P, ) -> Result { let mut num = provider.get_block_number().await?; diff --git a/crates/anvil/src/eth/api.rs b/crates/anvil/src/eth/api.rs index bb46019ccd55..d21ed852feee 100644 --- a/crates/anvil/src/eth/api.rs +++ b/crates/anvil/src/eth/api.rs @@ -853,7 +853,7 @@ impl EthApi { if request.gas.is_none() { // estimate if not provided if let Ok(gas) = self.estimate_gas(request.clone(), None, None).await { - request.gas = Some(gas); + request.gas = Some(gas.to()); } } @@ -882,7 +882,7 @@ impl EthApi { if request.gas.is_none() { // estimate if not provided if let Ok(gas) = self.estimate_gas(request.clone(), None, None).await { - request.gas = Some(gas); + request.gas = Some(gas.to()); } } @@ -1056,7 +1056,7 @@ impl EthApi { request: WithOtherFields, block_number: Option, overrides: Option, - ) -> Result { + ) -> Result { node_info!("eth_estimateGas"); self.do_estimate_gas( request, @@ -1064,6 +1064,7 @@ impl EthApi { overrides, ) .await + .map(U256::from) } /// Get transaction by its hash. @@ -1072,7 +1073,10 @@ impl EthApi { /// this will also scan the mempool for a matching pending transaction /// /// Handler for ETH RPC call: `eth_getTransactionByHash` - pub async fn transaction_by_hash(&self, hash: B256) -> Result> { + pub async fn transaction_by_hash( + &self, + hash: B256, + ) -> Result>> { node_info!("eth_getTransactionByHash"); let mut tx = self.pool.get_transaction(hash).map(|pending| { let from = *pending.sender(); @@ -1102,7 +1106,7 @@ impl EthApi { &self, hash: B256, index: Index, - ) -> Result> { + ) -> Result>> { node_info!("eth_getTransactionByBlockHashAndIndex"); self.backend.transaction_by_block_hash_and_index(hash, index).await } @@ -1114,7 +1118,7 @@ impl EthApi { &self, block: BlockNumber, idx: Index, - ) -> Result> { + ) -> Result>> { node_info!("eth_getTransactionByBlockNumberAndIndex"); self.backend.transaction_by_block_number_and_index(block, idx).await } @@ -2056,7 +2060,7 @@ impl EthApi { // we set the from field here explicitly to the set sender of the pending transaction, // in case the transaction is impersonated. tx.from = from; - tx + tx.inner } for pending in self.pool.ready_transactions() { @@ -2377,7 +2381,7 @@ impl EthApi { Some(info), Some(base_fee), ); - block_transactions.push(tx); + block_transactions.push(tx.inner); } Some(partial_block.into_full_block(block_transactions)) diff --git a/crates/anvil/src/eth/backend/fork.rs b/crates/anvil/src/eth/backend/fork.rs index 849baaeabfb2..7e9e04ba2f68 100644 --- a/crates/anvil/src/eth/backend/fork.rs +++ b/crates/anvil/src/eth/backend/fork.rs @@ -168,7 +168,7 @@ impl ClientFork { /// Sends `eth_call` pub async fn call( &self, - request: &TransactionRequest, + request: &WithOtherFields, block: Option, ) -> Result { let block = block.unwrap_or(BlockNumber::Latest); @@ -180,7 +180,7 @@ impl ClientFork { /// Sends `eth_call` pub async fn estimate_gas( &self, - request: &TransactionRequest, + request: &WithOtherFields, block: Option, ) -> Result { let block = block.unwrap_or(BlockNumber::Latest); @@ -257,12 +257,12 @@ impl ClientFork { &self, number: u64, index: usize, - ) -> Result, TransportError> { + ) -> Result>, TransportError> { if let Some(block) = self.block_by_number(number).await? { match block.transactions { BlockTransactions::Full(txs) => { if let Some(tx) = txs.get(index) { - return Ok(Some(tx.clone())); + return Ok(Some(WithOtherFields::new(tx.clone()))); } } BlockTransactions::Hashes(hashes) => { @@ -281,12 +281,12 @@ impl ClientFork { &self, hash: B256, index: usize, - ) -> Result, TransportError> { + ) -> Result>, TransportError> { if let Some(block) = self.block_by_hash(hash).await? { match block.transactions { BlockTransactions::Full(txs) => { if let Some(tx) = txs.get(index) { - return Ok(Some(tx.clone())); + return Ok(Some(WithOtherFields::new(tx.clone()))); } } BlockTransactions::Hashes(hashes) => { @@ -304,7 +304,7 @@ impl ClientFork { pub async fn transaction_by_hash( &self, hash: B256, - ) -> Result, TransportError> { + ) -> Result>, TransportError> { trace!(target: "backend::fork", "transaction_by_hash={:?}", hash); if let tx @ Some(_) = self.storage_read().transactions.get(&hash).cloned() { return Ok(tx); @@ -364,14 +364,14 @@ impl ClientFork { pub async fn transaction_receipt( &self, hash: B256, - ) -> Result, TransportError> { + ) -> Result, BlockchainError> { if let Some(receipt) = self.storage_read().transaction_receipts.get(&hash).cloned() { return Ok(Some(receipt)); } - if let Some(receipt) = - self.provider().get_transaction_receipt(hash).await?.map(convert_to_anvil_receipt) - { + if let Some(receipt) = self.provider().get_transaction_receipt(hash).await? { + let receipt = + convert_to_anvil_receipt(receipt).ok_or(BlockchainError::FailedToDecodeReceipt)?; let mut storage = self.storage_write(); storage.transaction_receipts.insert(hash, receipt.clone()); return Ok(Some(receipt)); @@ -383,7 +383,7 @@ impl ClientFork { pub async fn block_receipts( &self, number: u64, - ) -> Result>, TransportError> { + ) -> Result>, BlockchainError> { if let receipts @ Some(_) = self.storage_read().block_receipts.get(&number).cloned() { return Ok(receipts); } @@ -393,7 +393,16 @@ impl ClientFork { // this is being temporarily implemented in anvil. if self.predates_fork_inclusive(number) { let receipts = self.provider().get_block_receipts(BlockNumber::Number(number)).await?; - let receipts = receipts.map(|r| r.into_iter().map(convert_to_anvil_receipt).collect()); + let receipts = receipts + .map(|r| { + r.into_iter() + .map(|r| { + convert_to_anvil_receipt(r) + .ok_or(BlockchainError::FailedToDecodeReceipt) + }) + .collect::, _>>() + }) + .transpose()?; if let Some(receipts) = receipts.clone() { let mut storage = self.storage_write(); @@ -476,7 +485,9 @@ impl ClientFork { BlockTransactions::Full(txs) => txs, _ => vec![], }; - storage.transactions.extend(block_txs.iter().map(|tx| (tx.hash, tx.clone()))); + storage + .transactions + .extend(block_txs.iter().map(|tx| (tx.hash, WithOtherFields::new(tx.clone())))); storage.hashes.insert(block_number, hash); storage.blocks.insert(hash, block.clone()); return Ok(Some(block)); @@ -546,9 +557,10 @@ impl ClientFork { let mut transactions = Vec::with_capacity(block_txs_len); for tx in block.transactions.hashes() { if let Some(tx) = storage.transactions.get(tx).cloned() { - transactions.push(tx); + transactions.push(tx.inner); } } + // TODO: fix once blocks have generic transactions block.into_full_block(transactions) } } @@ -631,7 +643,7 @@ pub struct ForkedStorage { pub uncles: HashMap>, pub blocks: HashMap, pub hashes: HashMap, - pub transactions: HashMap, + pub transactions: HashMap>, pub transaction_receipts: HashMap, pub transaction_traces: HashMap>, pub logs: HashMap>, diff --git a/crates/anvil/src/eth/backend/mem/mod.rs b/crates/anvil/src/eth/backend/mem/mod.rs index f96f765a3adf..536b09dec98b 100644 --- a/crates/anvil/src/eth/backend/mem/mod.rs +++ b/crates/anvil/src/eth/backend/mem/mod.rs @@ -1387,7 +1387,7 @@ impl Backend { pub(crate) async fn mined_transactions_by_block_number( &self, number: BlockNumber, - ) -> Option> { + ) -> Option>> { if let Some(block) = self.get_block(number) { return self.mined_transactions_in_block(&block); } @@ -1395,7 +1395,10 @@ impl Backend { } /// Returns all transactions given a block - pub(crate) fn mined_transactions_in_block(&self, block: &Block) -> Option> { + pub(crate) fn mined_transactions_in_block( + &self, + block: &Block, + ) -> Option>> { let mut transactions = Vec::with_capacity(block.transactions.len()); let base_fee = block.header.base_fee_per_gas; let storage = self.blockchain.storage.read(); @@ -1501,7 +1504,7 @@ impl Backend { let block = self.get_block(id)?; let transactions = self.mined_transactions_in_block(&block)?; let block = self.convert_block(block); - Some(block.into_full_block(transactions)) + Some(block.into_full_block(transactions.into_iter().map(|t| t.inner).collect())) } /// Takes a block as it's stored internally and returns the eth api conform block format @@ -2029,10 +2032,7 @@ impl Backend { let number = self.convert_block_number(Some(number)); if fork.predates_fork_inclusive(number) { - let receipts = fork - .block_receipts(number) - .await - .map_err(BlockchainError::AlloyForkProvider)?; + let receipts = fork.block_receipts(number).await?; return Ok(receipts); } @@ -2045,7 +2045,7 @@ impl Backend { &self, number: BlockNumber, index: Index, - ) -> Result, BlockchainError> { + ) -> Result>, BlockchainError> { if let Some(hash) = self.mined_block_by_number(number).and_then(|b| b.header.hash) { return Ok(self.mined_transaction_by_block_hash_and_index(hash, index)); } @@ -2064,7 +2064,7 @@ impl Backend { &self, hash: B256, index: Index, - ) -> Result, BlockchainError> { + ) -> Result>, BlockchainError> { if let tx @ Some(_) = self.mined_transaction_by_block_hash_and_index(hash, index) { return Ok(tx); } @@ -2080,7 +2080,7 @@ impl Backend { &self, block_hash: B256, index: Index, - ) -> Option { + ) -> Option> { let (info, block, tx) = { let storage = self.blockchain.storage.read(); let block = storage.blocks.get(&block_hash).cloned()?; @@ -2102,7 +2102,7 @@ impl Backend { pub async fn transaction_by_hash( &self, hash: B256, - ) -> Result, BlockchainError> { + ) -> Result>, BlockchainError> { trace!(target: "backend", "transaction_by_hash={:?}", hash); if let tx @ Some(_) = self.mined_transaction_by_hash(hash) { return Ok(tx); @@ -2115,7 +2115,7 @@ impl Backend { Ok(None) } - fn mined_transaction_by_hash(&self, hash: B256) -> Option { + fn mined_transaction_by_hash(&self, hash: B256) -> Option> { let (info, block) = { let storage = self.blockchain.storage.read(); let MinedTransaction { info, block_hash, .. } = @@ -2370,7 +2370,7 @@ pub fn transaction_build( block: Option<&Block>, info: Option, base_fee: Option, -) -> Transaction { +) -> WithOtherFields { let mut transaction: Transaction = eth_transaction.clone().into(); if info.is_some() && transaction.transaction_type == Some(0x7E) { transaction.nonce = info.as_ref().unwrap().nonce; @@ -2419,7 +2419,7 @@ pub fn transaction_build( } transaction.to = info.as_ref().map_or(eth_transaction.to(), |status| status.to); - transaction + WithOtherFields::new(transaction) } /// Prove a storage key's existence or nonexistence in the account's storage diff --git a/crates/anvil/src/eth/error.rs b/crates/anvil/src/eth/error.rs index 1e35e78e14d4..9bd3d64a4bee 100644 --- a/crates/anvil/src/eth/error.rs +++ b/crates/anvil/src/eth/error.rs @@ -37,6 +37,8 @@ pub enum BlockchainError { FailedToDecodeSignedTransaction, #[error("Failed to decode transaction")] FailedToDecodeTransaction, + #[error("Failed to decode receipt")] + FailedToDecodeReceipt, #[error("Failed to decode state")] FailedToDecodeStateDump, #[error("Prevrandao not in th EVM's environment after merge")] @@ -348,6 +350,9 @@ impl ToRpcResponseResult for Result { BlockchainError::FailedToDecodeTransaction => { RpcError::invalid_params("Failed to decode transaction") } + BlockchainError::FailedToDecodeReceipt => { + RpcError::invalid_params("Failed to decode receipt") + } BlockchainError::FailedToDecodeStateDump => { RpcError::invalid_params("Failed to decode state dump") } diff --git a/crates/anvil/src/eth/otterscan/api.rs b/crates/anvil/src/eth/otterscan/api.rs index 604a5d373e88..636140f13ffe 100644 --- a/crates/anvil/src/eth/otterscan/api.rs +++ b/crates/anvil/src/eth/otterscan/api.rs @@ -8,7 +8,9 @@ use crate::eth::{ EthApi, }; use alloy_primitives::{Address, Bytes, B256, U256}; -use alloy_rpc_types::{Block, BlockId, BlockNumberOrTag as BlockNumber, Transaction}; +use alloy_rpc_types::{ + Block, BlockId, BlockNumberOrTag as BlockNumber, Transaction, WithOtherFields, +}; use alloy_rpc_types_trace::parity::{ Action, CallAction, CreateAction, CreateOutput, RewardAction, TraceOutput, }; @@ -238,7 +240,7 @@ impl EthApi { &self, address: Address, nonce: U256, - ) -> Result> { + ) -> Result>> { node_info!("ots_getTransactionBySenderAndNonce"); let from = self.get_fork().map(|f| f.block_number() + 1).unwrap_or_default(); diff --git a/crates/anvil/src/eth/otterscan/types.rs b/crates/anvil/src/eth/otterscan/types.rs index 13bfab2fd197..bde2d20833f2 100644 --- a/crates/anvil/src/eth/otterscan/types.rs +++ b/crates/anvil/src/eth/otterscan/types.rs @@ -3,7 +3,7 @@ use crate::eth::{ error::{BlockchainError, Result}, }; use alloy_primitives::{Address, Bytes, B256, U256 as rU256, U256}; -use alloy_rpc_types::{Block, BlockTransactions, Transaction}; +use alloy_rpc_types::{Block, BlockTransactions, Transaction, WithOtherFields}; use alloy_rpc_types_trace::parity::{Action, CallType, LocalizedTransactionTrace}; use anvil_core::eth::transaction::ReceiptResponse; use foundry_evm::{revm::interpreter::InstructionResult, traces::CallKind}; @@ -64,7 +64,7 @@ pub struct OtsContractCreator { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct OtsSearchTransactions { - pub txs: Vec, + pub txs: Vec>, pub receipts: Vec, pub first_page: bool, pub last_page: bool, @@ -226,7 +226,7 @@ impl OtsSearchTransactions { ) -> Result { let txs_futs = hashes.iter().map(|hash| async { backend.transaction_by_hash(*hash).await }); - let txs: Vec = join_all(txs_futs) + let txs: Vec<_> = join_all(txs_futs) .await .into_iter() .map(|t| match t { diff --git a/crates/anvil/src/tasks/mod.rs b/crates/anvil/src/tasks/mod.rs index 0d25abccd082..1f03fee9c5ba 100644 --- a/crates/anvil/src/tasks/mod.rs +++ b/crates/anvil/src/tasks/mod.rs @@ -1,6 +1,7 @@ //! Task management support use crate::{shutdown::Shutdown, tasks::block_listener::BlockListener, EthApi}; +use alloy_network::AnyNetwork; use alloy_primitives::B256; use alloy_provider::Provider; use alloy_rpc_types::Block; @@ -66,7 +67,7 @@ impl TaskManager { /// ``` pub fn spawn_reset_on_new_polled_blocks(&self, provider: P, api: EthApi) where - P: Provider + Clone + Unpin + 'static, + P: Provider + Clone + Unpin + 'static, T: Transport + Clone, { self.spawn_block_poll_listener(provider.clone(), move |hash| { @@ -90,7 +91,7 @@ impl TaskManager { /// block hash pub fn spawn_block_poll_listener(&self, provider: P, task_factory: F) where - P: Provider + 'static, + P: Provider + 'static, T: Transport + Clone, F: Fn(B256) -> Fut + Unpin + Send + Sync + 'static, Fut: Future + Send, @@ -126,7 +127,7 @@ impl TaskManager { /// ``` pub fn spawn_reset_on_subscribed_blocks(&self, provider: P, api: EthApi) where - P: Provider + 'static, + P: Provider + 'static, T: Transport + Clone, { self.spawn_block_subscription(provider, move |block| { @@ -147,7 +148,7 @@ impl TaskManager { /// new block hash pub fn spawn_block_subscription(&self, provider: P, task_factory: F) where - P: Provider + 'static, + P: Provider + 'static, T: Transport + Clone, F: Fn(Block) -> Fut + Unpin + Send + Sync + 'static, Fut: Future + Send, diff --git a/crates/anvil/tests/it/transaction.rs b/crates/anvil/tests/it/transaction.rs index 685dc43c82b9..1c85480ced6a 100644 --- a/crates/anvil/tests/it/transaction.rs +++ b/crates/anvil/tests/it/transaction.rs @@ -1007,7 +1007,7 @@ async fn test_estimate_gas() { .expect("Failed to estimate gas with state override"); // Assert the gas estimate meets the expected minimum. - assert!(gas_estimate >= 21000, "Gas estimate is lower than expected minimum"); + assert!(gas_estimate >= rU256::from(21000), "Gas estimate is lower than expected minimum"); } #[tokio::test(flavor = "multi_thread")] diff --git a/crates/cast/bin/cmd/access_list.rs b/crates/cast/bin/cmd/access_list.rs index 780e835bbb42..ed572628de66 100644 --- a/crates/cast/bin/cmd/access_list.rs +++ b/crates/cast/bin/cmd/access_list.rs @@ -1,7 +1,7 @@ -use alloy_network::TransactionBuilder; +use alloy_network::{AnyNetwork, TransactionBuilder}; use alloy_primitives::Address; use alloy_provider::Provider; -use alloy_rpc_types::{BlockId, TransactionRequest}; +use alloy_rpc_types::{BlockId, TransactionRequest, WithOtherFields}; use alloy_transport::Transport; use cast::Cast; use clap::Parser; @@ -91,7 +91,7 @@ impl AccessListArgs { } #[allow(clippy::too_many_arguments)] -async fn access_list, T: Transport + Clone>( +async fn access_list, T: Transport + Clone>( provider: P, etherscan_api_key: Option<&str>, from: Address, @@ -104,7 +104,7 @@ async fn access_list, T: Transport + Clone>( block: Option, to_json: bool, ) -> Result<()> { - let mut req = TransactionRequest::default() + let mut req = WithOtherFields::::default() .with_to(to.into()) .with_from(from) .with_value(tx.value.unwrap_or_default()) diff --git a/crates/cast/bin/cmd/call.rs b/crates/cast/bin/cmd/call.rs index 3ad1cf3a977c..eeb09d5c0442 100644 --- a/crates/cast/bin/cmd/call.rs +++ b/crates/cast/bin/cmd/call.rs @@ -1,6 +1,6 @@ use alloy_network::TransactionBuilder; use alloy_primitives::U256; -use alloy_rpc_types::{BlockId, TransactionRequest}; +use alloy_rpc_types::{BlockId, TransactionRequest, WithOtherFields}; use cast::Cast; use clap::Parser; use eyre::Result; @@ -121,7 +121,7 @@ impl CallArgs { None => None, }; - let mut req = TransactionRequest::default() + let mut req = WithOtherFields::::default() .with_to(to.into()) .with_from(sender) .with_value(tx.value.unwrap_or_default()); diff --git a/crates/cast/bin/cmd/estimate.rs b/crates/cast/bin/cmd/estimate.rs index 545181b264a9..55149937b8a6 100644 --- a/crates/cast/bin/cmd/estimate.rs +++ b/crates/cast/bin/cmd/estimate.rs @@ -1,7 +1,7 @@ use alloy_network::TransactionBuilder; use alloy_primitives::U256; use alloy_provider::Provider; -use alloy_rpc_types::TransactionRequest; +use alloy_rpc_types::{TransactionRequest, WithOtherFields}; use clap::Parser; use eyre::Result; use foundry_cli::{ @@ -93,7 +93,7 @@ impl EstimateArgs { None => None, }; - let mut req = TransactionRequest::default() + let mut req = WithOtherFields::::default() .with_to(to.into()) .with_from(from) .with_value(value.unwrap_or_default()); diff --git a/crates/cast/bin/cmd/send.rs b/crates/cast/bin/cmd/send.rs index 3d40bd0133d9..c1901861b6d6 100644 --- a/crates/cast/bin/cmd/send.rs +++ b/crates/cast/bin/cmd/send.rs @@ -1,5 +1,5 @@ use crate::tx; -use alloy_network::{Ethereum, EthereumSigner}; +use alloy_network::{AnyNetwork, EthereumSigner}; use alloy_primitives::{Address, U64}; use alloy_provider::{Provider, ProviderBuilder}; use alloy_signer::Signer; @@ -177,7 +177,8 @@ impl SendTxArgs { } let signer = EthereumSigner::from(signer); - let provider = ProviderBuilder::<_, Ethereum>::new().signer(signer).provider(provider); + let provider = + ProviderBuilder::<_, AnyNetwork>::default().signer(signer).provider(provider); cast_send( provider, @@ -199,7 +200,7 @@ impl SendTxArgs { } #[allow(clippy::too_many_arguments)] -async fn cast_send, T: Transport + Clone>( +async fn cast_send, T: Transport + Clone>( provider: P, from: Address, to: Option
, diff --git a/crates/cast/bin/cmd/storage.rs b/crates/cast/bin/cmd/storage.rs index bfa1b7228d9c..0bf041b8a9cf 100644 --- a/crates/cast/bin/cmd/storage.rs +++ b/crates/cast/bin/cmd/storage.rs @@ -1,4 +1,5 @@ use crate::opts::parse_slot; +use alloy_network::AnyNetwork; use alloy_primitives::{Address, B256, U256}; use alloy_provider::Provider; use alloy_rpc_types::BlockId; @@ -204,7 +205,7 @@ impl StorageValue { } } -async fn fetch_and_print_storage, T: Transport + Clone>( +async fn fetch_and_print_storage, T: Transport + Clone>( provider: P, address: Address, block: Option, @@ -221,7 +222,7 @@ async fn fetch_and_print_storage, T: Transport + Clone>( } } -async fn fetch_storage_slots, T: Transport + Clone>( +async fn fetch_storage_slots, T: Transport + Clone>( provider: P, address: Address, block: Option, diff --git a/crates/cast/bin/tx.rs b/crates/cast/bin/tx.rs index 57718cc8fc2c..98f7bf67e4c4 100644 --- a/crates/cast/bin/tx.rs +++ b/crates/cast/bin/tx.rs @@ -1,8 +1,8 @@ use alloy_json_abi::Function; -use alloy_network::TransactionBuilder; +use alloy_network::{AnyNetwork, TransactionBuilder}; use alloy_primitives::{Address, U256}; use alloy_provider::Provider; -use alloy_rpc_types::TransactionRequest; +use alloy_rpc_types::{TransactionRequest, WithOtherFields}; use alloy_transport::Transport; use eyre::Result; use foundry_cli::{opts::TransactionOpts, utils::parse_function_args}; @@ -38,7 +38,7 @@ pub fn validate_to_address(code: &Option, to: &Option) -> #[allow(clippy::too_many_arguments)] pub async fn build_tx< - P: Provider, + P: Provider, T: Transport + Clone, F: Into, TO: Into, @@ -52,13 +52,13 @@ pub async fn build_tx< tx: TransactionOpts, chain: impl Into, etherscan_api_key: Option, -) -> Result<(TransactionRequest, Option)> { +) -> Result<(WithOtherFields, Option)> { let chain = chain.into(); let from = from.into().resolve(provider).await?; let to = if let Some(to) = to { Some(to.into().resolve(provider).await?) } else { None }; - let mut req = TransactionRequest::default() + let mut req = WithOtherFields::new(TransactionRequest::default()) .with_to(to.into()) .with_from(from) .with_value(tx.value.unwrap_or_default()) diff --git a/crates/cast/src/lib.rs b/crates/cast/src/lib.rs index c4549f5a683f..d50385701f75 100644 --- a/crates/cast/src/lib.rs +++ b/crates/cast/src/lib.rs @@ -1,19 +1,17 @@ use alloy_consensus::TxEnvelope; use alloy_dyn_abi::{DynSolType, DynSolValue, FunctionExt}; use alloy_json_abi::{ContractObject, Function}; +use alloy_network::AnyNetwork; use alloy_primitives::{ utils::{keccak256, ParseUnits, Unit}, Address, Keccak256, TxHash, B256, I256, U256, }; use alloy_provider::{ - network::{ - eip2718::{Decodable2718, Encodable2718}, - Ethereum, - }, + network::eip2718::{Decodable2718, Encodable2718}, PendingTransactionBuilder, Provider, }; use alloy_rlp::Decodable; -use alloy_rpc_types::{BlockId, BlockNumberOrTag, Filter, TransactionRequest}; +use alloy_rpc_types::{BlockId, BlockNumberOrTag, Filter, TransactionRequest, WithOtherFields}; use alloy_sol_types::sol; use alloy_transport::Transport; use base::{Base, NumberWithBase, ToBase}; @@ -66,7 +64,7 @@ pub struct Cast { impl Cast where T: Transport + Clone, - P: Provider, + P: Provider, { /// Creates a new Cast instance from the provided client /// @@ -115,7 +113,7 @@ where /// ``` pub async fn call<'a>( &self, - req: &TransactionRequest, + req: &WithOtherFields, func: Option<&Function>, block: Option, ) -> Result { @@ -184,7 +182,7 @@ where /// ``` pub async fn access_list( &self, - req: &TransactionRequest, + req: &WithOtherFields, block: Option, to_json: bool, ) -> Result { @@ -243,8 +241,8 @@ where /// ``` pub async fn send( &self, - tx: TransactionRequest, - ) -> Result> { + tx: WithOtherFields, + ) -> Result> { let res = self.provider.send_transaction(tx).await?; Ok(res) @@ -269,7 +267,7 @@ where pub async fn publish( &self, mut raw_tx: String, - ) -> Result> { + ) -> Result> { raw_tx = match raw_tx.strip_prefix("0x") { Some(s) => s.to_string(), None => raw_tx, @@ -608,7 +606,7 @@ where let tx = self.provider.get_transaction_by_hash(tx_hash).await?; Ok(if raw { - format!("0x{}", hex::encode(TxEnvelope::try_from(tx)?.encoded_2718())) + format!("0x{}", hex::encode(TxEnvelope::try_from(tx.inner)?.encoded_2718())) } else if let Some(field) = field { get_pretty_tx_attr(&tx, field.as_str()) .ok_or_else(|| eyre::eyre!("invalid tx field: {}", field.to_string()))? diff --git a/crates/cli/src/utils/abi.rs b/crates/cli/src/utils/abi.rs index 395ea1127e99..634b889ca711 100644 --- a/crates/cli/src/utils/abi.rs +++ b/crates/cli/src/utils/abi.rs @@ -1,7 +1,7 @@ use alloy_chains::Chain; use alloy_json_abi::Function; use alloy_primitives::Address; -use alloy_provider::Provider; +use alloy_provider::{network::AnyNetwork, Provider}; use alloy_transport::Transport; use eyre::{OptionExt, Result}; use foundry_common::{ @@ -10,7 +10,7 @@ use foundry_common::{ }; use futures::future::join_all; -async fn resolve_name_args>( +async fn resolve_name_args>( args: &[String], provider: &P, ) -> Vec { @@ -28,7 +28,7 @@ async fn resolve_name_args>( .await } -pub async fn parse_function_args>( +pub async fn parse_function_args>( sig: &str, args: Vec, to: Option
, diff --git a/crates/cli/src/utils/mod.rs b/crates/cli/src/utils/mod.rs index 08eda672cbb0..015ce2145af6 100644 --- a/crates/cli/src/utils/mod.rs +++ b/crates/cli/src/utils/mod.rs @@ -1,6 +1,6 @@ use alloy_json_abi::JsonAbi; use alloy_primitives::U256; -use alloy_provider::Provider; +use alloy_provider::{network::AnyNetwork, Provider}; use alloy_transport::Transport; use eyre::{ContextCompat, Result}; use foundry_config::{Chain, Config}; @@ -112,7 +112,7 @@ pub fn get_provider_builder( pub async fn get_chain(chain: Option, provider: P) -> Result where - P: Provider, + P: Provider, T: Transport + Clone, { match chain { diff --git a/crates/common/src/fmt/ui.rs b/crates/common/src/fmt/ui.rs index 37e6695df0c4..f6beb7652975 100644 --- a/crates/common/src/fmt/ui.rs +++ b/crates/common/src/fmt/ui.rs @@ -1,10 +1,11 @@ //! Helper trait and functions to format Ethereum types. use crate::TransactionReceiptWithRevertReason; -use alloy_consensus::{Receipt, ReceiptWithBloom, TxType}; +use alloy_consensus::{AnyReceiptEnvelope, Receipt, ReceiptWithBloom, TxType}; use alloy_primitives::*; use alloy_rpc_types::{ - other::OtherFields, Block, BlockTransactions, Log, Transaction, TransactionReceipt, + other::OtherFields, AnyTransactionReceipt, Block, BlockTransactions, Log, Transaction, + TransactionReceipt, }; use serde::Deserialize; @@ -146,37 +147,36 @@ impl UIfmt for [u8] { } } -impl UIfmt for TransactionReceipt { +impl UIfmt for AnyTransactionReceipt { fn pretty(&self) -> String { - let transaction_type = self.transaction_type(); let Self { - transaction_hash, - transaction_index, - block_hash, - block_number, - from, - to, - gas_used, - contract_address, - state_root, - effective_gas_price, - inner, - blob_gas_price, - blob_gas_used, + inner: + TransactionReceipt { + transaction_hash, + transaction_index, + block_hash, + block_number, + from, + to, + gas_used, + contract_address, + state_root, + effective_gas_price, + inner: + AnyReceiptEnvelope { + r#type: transaction_type, + inner: + ReceiptWithBloom { + receipt: Receipt { status, cumulative_gas_used, logs }, + logs_bloom, + }, + }, + blob_gas_price, + blob_gas_used, + }, + other, } = self; - let (logs_bloom, status, cumulative_gas_used, logs) = - if let Some(receipt) = inner.as_receipt_with_bloom() { - let ReceiptWithBloom { - logs_bloom, - receipt: Receipt { status, cumulative_gas_used, logs }, - } = receipt; - - (Some(logs_bloom), Some(status), Some(cumulative_gas_used), Some(logs)) - } else { - Default::default() - }; - let mut pretty = format!( " blockHash {} @@ -208,7 +208,7 @@ blobGasUsed {}", status.pretty(), transaction_hash.pretty(), transaction_index.pretty(), - transaction_type.pretty(), + transaction_type), blob_gas_price.pretty(), blob_gas_used.pretty(), ); @@ -218,9 +218,9 @@ blobGasUsed {}", } // additional captured fields - // for (key, val) in other.iter() { - // pretty.push_str(&format!("\n{} {}", key, val)); - // } + for (key, val) in other.iter() { + pretty.push_str(&format!("\n{} {}", key, val)); + } pretty } @@ -435,23 +435,23 @@ pub fn get_pretty_tx_receipt_attr( "blockNumber" | "block_number" => Some(receipt.receipt.block_number.pretty()), "contractAddress" | "contract_address" => Some(receipt.receipt.contract_address.pretty()), "cumulativeGasUsed" | "cumulative_gas_used" => { - Some(receipt.receipt.inner.as_receipt().map(|r| r.cumulative_gas_used).pretty()) + Some(receipt.receipt.inner.inner.inner.receipt.cumulative_gas_used.pretty()) } "effectiveGasPrice" | "effective_gas_price" => { Some(receipt.receipt.effective_gas_price.to_string()) } "gasUsed" | "gas_used" => receipt.receipt.gas_used.map(|g| g.to_string()), - "logs" => receipt.receipt.inner.as_receipt().map(|r| r.logs.as_slice().pretty()), - "logsBloom" | "logs_bloom" => { - Some(receipt.receipt.inner.as_receipt_with_bloom().map(|r| r.logs_bloom).pretty()) - } + "logs" => Some(receipt.receipt.inner.inner.inner.receipt.logs.as_slice().pretty()), + "logsBloom" | "logs_bloom" => Some(receipt.receipt.inner.inner.inner.logs_bloom.pretty()), "root" | "stateRoot" | "state_root " => Some(receipt.receipt.state_root.pretty()), - "status" | "statusCode" | "status_code" => Some(receipt.receipt.status().pretty()), + "status" | "statusCode" | "status_code" => { + Some(receipt.receipt.inner.inner.inner.receipt.status.pretty()) + } "transactionHash" | "transaction_hash" => Some(receipt.receipt.transaction_hash.pretty()), "transactionIndex" | "transaction_index" => { Some(receipt.receipt.transaction_index.to_string()) } - "type" | "transaction_type" => Some(receipt.receipt.transaction_type().pretty()), + "type" | "transaction_type" => Some(receipt.receipt.inner.inner.r#type.to_string()), "revertReason" | "revert_reason" => Some(receipt.revert_reason.pretty()), _ => None, } diff --git a/crates/common/src/provider/alloy.rs b/crates/common/src/provider/alloy.rs index 39a53fab7f5c..e26fd7a1bdde 100644 --- a/crates/common/src/provider/alloy.rs +++ b/crates/common/src/provider/alloy.rs @@ -4,8 +4,8 @@ use crate::{ provider::runtime_transport::RuntimeTransportBuilder, ALCHEMY_FREE_TIER_CUPS, REQUEST_TIMEOUT, }; use alloy_provider::{ - network::Ethereum, utils::Eip1559Estimation, Provider, ProviderBuilder as AlloyProviderBuilder, - RootProvider, + network::AnyNetwork, utils::Eip1559Estimation, Provider, + ProviderBuilder as AlloyProviderBuilder, RootProvider, }; use alloy_rpc_client::ClientBuilder; use alloy_transport::Transport; @@ -28,7 +28,7 @@ use super::{ }; /// Helper type alias for a retry provider -pub type RetryProvider = RootProvider, N>; +pub type RetryProvider = RootProvider, N>; /// Helper type alias for a rpc url pub type RpcUrl = String; @@ -243,7 +243,7 @@ impl ProviderBuilder { let client = ClientBuilder::default().layer(retry_layer).transport(transport, false); let provider = - AlloyProviderBuilder::<_, Ethereum>::new().provider(RootProvider::new(client)); + AlloyProviderBuilder::<_, AnyNetwork>::default().provider(RootProvider::new(client)); Ok(provider) } @@ -255,7 +255,7 @@ impl ProviderBuilder { /// - polygon /// /// Fallback is the default [`Provider::estimate_eip1559_fees`] implementation -pub async fn estimate_eip1559_fees, T: Transport + Clone>( +pub async fn estimate_eip1559_fees, T: Transport + Clone>( provider: &P, chain: Option, ) -> Result { diff --git a/crates/common/src/transactions.rs b/crates/common/src/transactions.rs index 1eae8421e565..27234bbd5609 100644 --- a/crates/common/src/transactions.rs +++ b/crates/common/src/transactions.rs @@ -1,6 +1,6 @@ //! wrappers for transactions -use alloy_provider::Provider; -use alloy_rpc_types::{BlockId, TransactionReceipt}; +use alloy_provider::{network::AnyNetwork, Provider}; +use alloy_rpc_types::{AnyTransactionReceipt, BlockId, WithOtherFields}; use alloy_transport::Transport; use eyre::Result; use serde::{Deserialize, Serialize}; @@ -10,7 +10,7 @@ use serde::{Deserialize, Serialize}; pub struct TransactionReceiptWithRevertReason { /// The underlying transaction receipt #[serde(flatten)] - pub receipt: TransactionReceipt, + pub receipt: AnyTransactionReceipt, /// The revert reason string if the transaction status is failed #[serde(skip_serializing_if = "Option::is_none", rename = "revertReason")] @@ -20,12 +20,12 @@ pub struct TransactionReceiptWithRevertReason { impl TransactionReceiptWithRevertReason { /// Returns if the status of the transaction is 0 (failure) pub fn is_failure(&self) -> bool { - !self.receipt.status() + self.receipt.inner.inner.inner.receipt.status } /// Updates the revert reason field using `eth_call` and returns an Err variant if the revert /// reason was not successfully updated - pub async fn update_revert_reason>( + pub async fn update_revert_reason>( &mut self, provider: &P, ) -> Result<()> { @@ -33,7 +33,7 @@ impl TransactionReceiptWithRevertReason { Ok(()) } - async fn fetch_revert_reason>( + async fn fetch_revert_reason>( &self, provider: &P, ) -> Result> { @@ -47,7 +47,13 @@ impl TransactionReceiptWithRevertReason { .map_err(|_| eyre::eyre!("unable to fetch transaction"))?; if let Some(block_hash) = self.receipt.block_hash { - match provider.call(&transaction.into(), Some(BlockId::Hash(block_hash.into()))).await { + match provider + .call( + &WithOtherFields::new(transaction.inner.into()), + Some(BlockId::Hash(block_hash.into())), + ) + .await + { Err(e) => return Ok(extract_revert_reason(e.to_string())), Ok(_) => eyre::bail!("no revert reason as transaction succeeded"), } @@ -56,13 +62,13 @@ impl TransactionReceiptWithRevertReason { } } -impl From for TransactionReceiptWithRevertReason { - fn from(receipt: TransactionReceipt) -> Self { +impl From for TransactionReceiptWithRevertReason { + fn from(receipt: AnyTransactionReceipt) -> Self { Self { receipt, revert_reason: None } } } -impl From for TransactionReceipt { +impl From for AnyTransactionReceipt { fn from(receipt_with_reason: TransactionReceiptWithRevertReason) -> Self { receipt_with_reason.receipt } diff --git a/crates/evm/core/src/backend/mod.rs b/crates/evm/core/src/backend/mod.rs index fc5eff27dde2..5124c6f29ade 100644 --- a/crates/evm/core/src/backend/mod.rs +++ b/crates/evm/core/src/backend/mod.rs @@ -8,7 +8,7 @@ use crate::{ }; use alloy_genesis::GenesisAccount; use alloy_primitives::{b256, keccak256, Address, B256, U256, U64}; -use alloy_rpc_types::{Block, BlockNumberOrTag, BlockTransactions, Transaction}; +use alloy_rpc_types::{Block, BlockNumberOrTag, BlockTransactions, Transaction, WithOtherFields}; use eyre::Context; use foundry_common::{is_known_system_sender, SYSTEM_TRANSACTION_TYPE}; use revm::{ @@ -917,7 +917,7 @@ impl Backend { trace!(tx=?tx.hash, "committing transaction"); commit_transaction( - tx, + WithOtherFields::new(tx), env.clone(), journaled_state, fork, @@ -1868,7 +1868,7 @@ fn update_env_block(env: &mut Env, fork_block: U64, block: &Block) { /// Executes the given transaction and commits state changes to the database _and_ the journaled /// state, with an optional inspector fn commit_transaction>( - tx: Transaction, + tx: WithOtherFields, mut env: EnvWithHandlerCfg, journaled_state: &mut JournaledState, fork: &mut Fork, diff --git a/crates/evm/core/src/fork/backend.rs b/crates/evm/core/src/fork/backend.rs index 3fd7706b7b84..f6da76fc5c42 100644 --- a/crates/evm/core/src/fork/backend.rs +++ b/crates/evm/core/src/fork/backend.rs @@ -4,8 +4,8 @@ use crate::{ fork::{cache::FlushJsonBlockCacheDB, BlockchainDb}, }; use alloy_primitives::{keccak256, Address, Bytes, B256, U256}; -use alloy_provider::Provider; -use alloy_rpc_types::{Block, BlockId, Transaction}; +use alloy_provider::{network::AnyNetwork, Provider}; +use alloy_rpc_types::{Block, BlockId, Transaction, WithOtherFields}; use alloy_transport::Transport; use eyre::WrapErr; use foundry_common::NON_ARCHIVE_NODE_WARNING; @@ -38,14 +38,18 @@ type StorageFuture = Pin, Addres type BlockHashFuture = Pin, u64)> + Send>>; type FullBlockFuture = Pin, Err>, BlockId)> + Send>>; -type TransactionFuture = - Pin, B256)> + Send>>; +type TransactionFuture = Pin< + Box< + dyn Future, Err>, B256)> + + Send, + >, +>; type AccountInfoSender = OneshotSender>; type StorageSender = OneshotSender>; type BlockHashSender = OneshotSender>; type FullBlockSender = OneshotSender>; -type TransactionSender = OneshotSender>; +type TransactionSender = OneshotSender>>; /// Request variants that are executed by the provider enum ProviderRequest { @@ -103,7 +107,7 @@ pub struct BackendHandler { impl BackendHandler where T: Transport + Clone, - P: Provider + Clone + Unpin + 'static, + P: Provider + Clone + Unpin + 'static, { fn new( provider: P, @@ -291,7 +295,7 @@ where impl Future for BackendHandler where T: Transport + Clone + Unpin, - P: Provider + Clone + Unpin + 'static, + P: Provider + Clone + Unpin + 'static, { type Output = (); @@ -525,7 +529,7 @@ impl SharedBackend { ) -> Self where T: Transport + Clone + Unpin, - P: Provider + Unpin + 'static + Clone, + P: Provider + Unpin + 'static + Clone, { let (shared, handler) = Self::new(provider, db, pin_block); // spawn the provider handler to a task @@ -543,7 +547,7 @@ impl SharedBackend { ) -> Self where T: Transport + Clone + Unpin, - P: Provider + Unpin + 'static + Clone, + P: Provider + Unpin + 'static + Clone, { let (shared, handler) = Self::new(provider, db, pin_block); @@ -573,7 +577,7 @@ impl SharedBackend { ) -> (Self, BackendHandler) where T: Transport + Clone + Unpin, - P: Provider + Unpin + 'static + Clone, + P: Provider + Unpin + 'static + Clone, { let (backend, backend_rx) = channel(1); let cache = Arc::new(FlushJsonBlockCacheDB(Arc::clone(db.cache()))); @@ -598,7 +602,7 @@ impl SharedBackend { } /// Returns the transaction for the hash - pub fn get_transaction(&self, tx: B256) -> DatabaseResult { + pub fn get_transaction(&self, tx: B256) -> DatabaseResult> { tokio::task::block_in_place(|| { let (sender, rx) = oneshot_channel(); let req = BackendRequest::Transaction(tx, sender); diff --git a/crates/forge/bin/cmd/create.rs b/crates/forge/bin/cmd/create.rs index af8f6204d479..3f42019a63df 100644 --- a/crates/forge/bin/cmd/create.rs +++ b/crates/forge/bin/cmd/create.rs @@ -1,10 +1,10 @@ use alloy_chains::Chain; use alloy_dyn_abi::{DynSolValue, JsonAbiExt, Specifier}; use alloy_json_abi::{Constructor, JsonAbi}; -use alloy_network::{Ethereum, EthereumSigner, TransactionBuilder}; +use alloy_network::{AnyNetwork, EthereumSigner, TransactionBuilder}; use alloy_primitives::{Address, Bytes}; use alloy_provider::{Provider, ProviderBuilder}; -use alloy_rpc_types::{TransactionReceipt, TransactionRequest}; +use alloy_rpc_types::{AnyTransactionReceipt, TransactionRequest, WithOtherFields}; use alloy_signer::Signer; use alloy_transport::{Transport, TransportError}; use clap::{Parser, ValueHint}; @@ -139,7 +139,7 @@ impl CreateArgs { // Deploy with signer let signer = self.eth.wallet.signer().await?; let deployer = signer.address(); - let provider = ProviderBuilder::<_, Ethereum>::default() + let provider = ProviderBuilder::<_, AnyNetwork>::default() .signer(EthereumSigner::new(signer)) .provider(provider); self.deploy(abi, bin, params, provider, chain_id, deployer).await @@ -201,7 +201,7 @@ impl CreateArgs { } /// Deploys the contract - async fn deploy, T: Transport + Clone>( + async fn deploy, T: Transport + Clone>( self, abi: JsonAbi, bin: BytecodeObject, @@ -403,7 +403,7 @@ impl From> for ContractDeploymentTx { #[must_use = "Deployer does nothing unless you `send` it"] pub struct Deployer { /// The deployer's transaction, exposed for overriding the defaults - pub tx: TransactionRequest, + pub tx: WithOtherFields, abi: JsonAbi, client: B, confs: usize, @@ -430,16 +430,16 @@ where impl Deployer where B: Borrow

+ Clone, - P: Provider, + P: Provider, T: Transport + Clone, { /// Broadcasts the contract deployment transaction and after waiting for it to /// be sufficiently confirmed (default: 1), it returns a tuple with /// the [`Contract`](crate::Contract) struct at the deployed contract's address - /// and the corresponding [`TransactionReceipt`]. + /// and the corresponding [`AnyReceipt`]. pub async fn send_with_receipt( self, - ) -> Result<(Address, TransactionReceipt), ContractDeploymentError> { + ) -> Result<(Address, AnyTransactionReceipt), ContractDeploymentError> { let receipt = self .client .borrow() @@ -519,7 +519,7 @@ where impl DeploymentTxFactory where B: Borrow

+ Clone, - P: Provider, + P: Provider, T: Transport + Clone, { /// Creates a factory for deployment of the Contract with bytecode, and the @@ -553,7 +553,7 @@ where }; // create the tx object. Since we're deploying a contract, `to` is `None` - let tx = TransactionRequest::default().input(data.into()).to(None); + let tx = WithOtherFields::new(TransactionRequest::default().input(data.into()).to(None)); Ok(Deployer { client: self.client.clone(), diff --git a/crates/script/src/broadcast.rs b/crates/script/src/broadcast.rs index bd7891eed5e7..d16af14204be 100644 --- a/crates/script/src/broadcast.rs +++ b/crates/script/src/broadcast.rs @@ -5,10 +5,10 @@ use crate::{ }; use alloy_chains::Chain; use alloy_eips::eip2718::Encodable2718; -use alloy_network::{EthereumSigner, TransactionBuilder}; +use alloy_network::{AnyNetwork, EthereumSigner, TransactionBuilder}; use alloy_primitives::{utils::format_units, Address, TxHash}; use alloy_provider::{utils::Eip1559Estimation, Provider}; -use alloy_rpc_types::TransactionRequest; +use alloy_rpc_types::{TransactionRequest, WithOtherFields}; use alloy_transport::Transport; use eyre::{bail, Context, Result}; use forge_verify::provider::VerificationProviderType; @@ -32,12 +32,12 @@ use std::{ }; pub async fn estimate_gas( - tx: &mut TransactionRequest, + tx: &mut WithOtherFields, provider: &P, estimate_multiplier: u64, ) -> Result<()> where - P: Provider, + P: Provider, T: Transport + Clone, { // if already set, some RPC endpoints might simply return the gas value that is already @@ -60,7 +60,7 @@ pub async fn next_nonce(caller: Address, provider_url: &str) -> eyre::Result, - mut tx: TransactionRequest, + mut tx: WithOtherFields, kind: SendTransactionKind<'_>, sequential_broadcast: bool, is_fixed_gas_limit: bool, diff --git a/crates/script/src/receipts.rs b/crates/script/src/receipts.rs index 15106bcef76f..33c99dfcadeb 100644 --- a/crates/script/src/receipts.rs +++ b/crates/script/src/receipts.rs @@ -2,7 +2,7 @@ use super::sequence::ScriptSequence; use alloy_chains::Chain; use alloy_primitives::{utils::format_units, TxHash, U256}; use alloy_provider::{PendingTransactionBuilder, Provider}; -use alloy_rpc_types::TransactionReceipt; +use alloy_rpc_types::AnyTransactionReceipt; use eyre::Result; use foundry_cli::{init_progress, update_progress}; use foundry_common::provider::alloy::RetryProvider; @@ -12,13 +12,13 @@ use std::sync::Arc; /// Convenience enum for internal signalling of transaction status enum TxStatus { Dropped, - Success(TransactionReceipt), - Revert(TransactionReceipt), + Success(AnyTransactionReceipt), + Revert(AnyTransactionReceipt), } -impl From for TxStatus { - fn from(receipt: TransactionReceipt) -> Self { - if !receipt.status() { +impl From for TxStatus { + fn from(receipt: AnyTransactionReceipt) -> Self { + if !receipt.inner.inner.inner.receipt.status { TxStatus::Revert(receipt) } else { TxStatus::Success(receipt) @@ -65,7 +65,7 @@ pub async fn clear_pendings( let mut tasks = futures::stream::iter(futs).buffer_unordered(10); let mut errors: Vec = vec![]; - let mut receipts = Vec::::with_capacity(count); + let mut receipts = Vec::::with_capacity(count); // set up progress bar let mut pos = 0; @@ -151,12 +151,16 @@ async fn check_tx_status( } /// Prints parts of the receipt to stdout -pub fn print_receipt(chain: Chain, receipt: &TransactionReceipt) { +pub fn print_receipt(chain: Chain, receipt: &AnyTransactionReceipt) { let gas_used = receipt.gas_used.unwrap_or_default(); let gas_price = receipt.effective_gas_price; foundry_common::shell::println(format!( "\n##### {chain}\n{status}Hash: {tx_hash:?}{caddr}\nBlock: {bn}\n{gas}\n", - status = if !receipt.status() { "❌ [Failed]" } else { "✅ [Success]" }, + status = if !receipt.inner.inner.inner.receipt.status { + "❌ [Failed]" + } else { + "✅ [Success]" + }, tx_hash = receipt.transaction_hash, caddr = if let Some(addr) = &receipt.contract_address { format!("\nContract Address: {}", addr.to_checksum(None)) diff --git a/crates/script/src/sequence.rs b/crates/script/src/sequence.rs index fb0eae1e1222..2d39c12923db 100644 --- a/crates/script/src/sequence.rs +++ b/crates/script/src/sequence.rs @@ -4,7 +4,7 @@ use crate::{ verify::VerifyBundle, }; use alloy_primitives::{Address, TxHash}; -use alloy_rpc_types::{TransactionReceipt, TransactionRequest}; +use alloy_rpc_types::{AnyTransactionReceipt, TransactionRequest, WithOtherFields}; use eyre::{ContextCompat, Result, WrapErr}; use forge_verify::provider::VerificationProviderType; use foundry_cli::utils::{now, Git}; @@ -87,7 +87,7 @@ pub const DRY_RUN_DIR: &str = "dry-run"; #[derive(Clone, Default, Serialize, Deserialize)] pub struct ScriptSequence { pub transactions: VecDeque, - pub receipts: Vec, + pub receipts: Vec, pub libraries: Vec, pub pending: Vec, #[serde(skip)] @@ -196,7 +196,7 @@ impl ScriptSequence { Ok(()) } - pub fn add_receipt(&mut self, receipt: TransactionReceipt) { + pub fn add_receipt(&mut self, receipt: AnyTransactionReceipt) { self.receipts.push(receipt); } @@ -352,7 +352,7 @@ impl ScriptSequence { } /// Returns the list of the transactions without the metadata. - pub fn transactions(&self) -> impl Iterator { + pub fn transactions(&self) -> impl Iterator> { self.transactions.iter().map(|tx| tx.tx()) } diff --git a/crates/script/src/transaction.rs b/crates/script/src/transaction.rs index 0dc038c05075..e74699e74913 100644 --- a/crates/script/src/transaction.rs +++ b/crates/script/src/transaction.rs @@ -1,7 +1,7 @@ use super::{artifacts::ArtifactInfo, ScriptResult}; use alloy_dyn_abi::JsonAbiExt; use alloy_primitives::{Address, Bytes, B256}; -use alloy_rpc_types::request::TransactionRequest; +use alloy_rpc_types::{request::TransactionRequest, WithOtherFields}; use eyre::{ContextCompat, Result, WrapErr}; use foundry_common::{fmt::format_token_raw, provider::alloy::RpcUrl, SELECTOR_LEN}; use foundry_evm::{constants::DEFAULT_CREATE2_DEPLOYER, traces::CallTraceDecoder}; @@ -35,7 +35,7 @@ pub struct TransactionWithMetadata { pub arguments: Option>, #[serde(skip)] pub rpc: RpcUrl, - pub transaction: TransactionRequest, + pub transaction: WithOtherFields, pub additional_contracts: Vec, pub is_fixed_gas_limit: bool, } @@ -54,7 +54,7 @@ fn default_vec_of_strings() -> Option> { impl TransactionWithMetadata { pub fn from_tx_request(transaction: TransactionRequest) -> Self { - Self { transaction, ..Default::default() } + Self { transaction: WithOtherFields::new(transaction), ..Default::default() } } pub fn new( @@ -208,11 +208,11 @@ impl TransactionWithMetadata { Ok(()) } - pub fn tx(&self) -> &TransactionRequest { + pub fn tx(&self) -> &WithOtherFields { &self.transaction } - pub fn tx_mut(&mut self) -> &mut TransactionRequest { + pub fn tx_mut(&mut self) -> &mut WithOtherFields { &mut self.transaction } From 50b3bc144beef0492acc693f18f44973ca54e9c5 Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Sun, 7 Apr 2024 16:28:44 +0400 Subject: [PATCH 58/63] bump alloy --- Cargo.lock | 43 ++++++++++++++++++------------------ Cargo.toml | 44 ++++++++++++++++++------------------- crates/common/src/fmt/ui.rs | 2 +- 3 files changed, 45 insertions(+), 44 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2277f60a2bd1..6b4704fb7264 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -90,7 +90,7 @@ dependencies = [ [[package]] name = "alloy-consensus" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" +source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" dependencies = [ "alloy-eips", "alloy-primitives", @@ -105,7 +105,7 @@ dependencies = [ [[package]] name = "alloy-contract" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" +source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" dependencies = [ "alloy-dyn-abi", "alloy-json-abi", @@ -144,7 +144,7 @@ dependencies = [ [[package]] name = "alloy-eips" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" +source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -158,7 +158,7 @@ dependencies = [ [[package]] name = "alloy-genesis" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" +source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" dependencies = [ "alloy-primitives", "alloy-serde", @@ -180,7 +180,7 @@ dependencies = [ [[package]] name = "alloy-json-rpc" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" +source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" dependencies = [ "alloy-primitives", "serde", @@ -191,7 +191,7 @@ dependencies = [ [[package]] name = "alloy-network" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" +source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" dependencies = [ "alloy-consensus", "alloy-eips", @@ -234,7 +234,7 @@ dependencies = [ [[package]] name = "alloy-provider" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" +source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" dependencies = [ "alloy-json-rpc", "alloy-network", @@ -258,7 +258,7 @@ dependencies = [ [[package]] name = "alloy-pubsub" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" +source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" dependencies = [ "alloy-json-rpc", "alloy-primitives", @@ -298,7 +298,7 @@ dependencies = [ [[package]] name = "alloy-rpc-client" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" +source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" dependencies = [ "alloy-json-rpc", "alloy-primitives", @@ -318,7 +318,7 @@ dependencies = [ [[package]] name = "alloy-rpc-types" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" +source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" dependencies = [ "alloy-consensus", "alloy-eips", @@ -336,7 +336,7 @@ dependencies = [ [[package]] name = "alloy-rpc-types-trace" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" +source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" dependencies = [ "alloy-primitives", "alloy-rpc-types", @@ -348,7 +348,7 @@ dependencies = [ [[package]] name = "alloy-serde" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" +source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" dependencies = [ "alloy-primitives", "serde", @@ -358,7 +358,7 @@ dependencies = [ [[package]] name = "alloy-signer" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" +source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" dependencies = [ "alloy-dyn-abi", "alloy-primitives", @@ -373,7 +373,7 @@ dependencies = [ [[package]] name = "alloy-signer-aws" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" +source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" dependencies = [ "alloy-consensus", "alloy-network", @@ -390,7 +390,7 @@ dependencies = [ [[package]] name = "alloy-signer-ledger" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" +source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" dependencies = [ "alloy-consensus", "alloy-network", @@ -407,7 +407,7 @@ dependencies = [ [[package]] name = "alloy-signer-trezor" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" +source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" dependencies = [ "alloy-consensus", "alloy-network", @@ -423,7 +423,7 @@ dependencies = [ [[package]] name = "alloy-signer-wallet" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" +source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" dependencies = [ "alloy-consensus", "alloy-network", @@ -500,7 +500,7 @@ dependencies = [ [[package]] name = "alloy-transport" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" +source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" dependencies = [ "alloy-json-rpc", "base64 0.22.0", @@ -518,7 +518,7 @@ dependencies = [ [[package]] name = "alloy-transport-http" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" +source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" dependencies = [ "alloy-json-rpc", "alloy-transport", @@ -531,7 +531,7 @@ dependencies = [ [[package]] name = "alloy-transport-ipc" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" +source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" dependencies = [ "alloy-json-rpc", "alloy-pubsub", @@ -549,7 +549,7 @@ dependencies = [ [[package]] name = "alloy-transport-ws" version = "0.1.0" -source = "git+https://github.com/klkvr/alloy?rev=af2eef3#af2eef360b60c2d97d533e7fe03bf1102d3d4db6" +source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" dependencies = [ "alloy-pubsub", "alloy-transport", @@ -6845,6 +6845,7 @@ dependencies = [ [[package]] name = "revm-inspectors" version = "0.1.0" +source = "git+https://github.com/paradigmxyz/evm-inspectors?rev=37d1fcd#37d1fcd6a5b4a30ab7267ce71fbf9c3bcbe7b01c" dependencies = [ "alloy-primitives", "alloy-rpc-types", diff --git a/Cargo.toml b/Cargo.toml index 427e340be26c..ec194b26260e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -143,7 +143,7 @@ foundry-compilers = { version = "0.3.14", default-features = false } # no default features to avoid c-kzg revm = { version = "8", default-features = false } revm-primitives = { version = "3", default-features = false } -revm-inspectors = { path = "../evm-inspectors", features = [ +revm-inspectors = { git = "https://github.com/paradigmxyz/evm-inspectors", rev = "37d1fcd", features = [ "serde", ] } @@ -157,27 +157,27 @@ ethers-signers = { version = "2.0.14", default-features = false } ethers-middleware = { version = "2.0.14", default-features = false } ## alloy -alloy-consensus = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } -alloy-contract = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } -alloy-eips = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } -alloy-genesis = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } -alloy-json-rpc = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } -alloy-network = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } -alloy-node-bindings = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } -alloy-provider = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } -alloy-pubsub = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } -alloy-rpc-client = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } -alloy-rpc-types-trace = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } -alloy-rpc-types = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } -alloy-signer = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } -alloy-signer-wallet = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } -alloy-signer-aws = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } -alloy-signer-ledger = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } -alloy-signer-trezor = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } -alloy-transport = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } -alloy-transport-http = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } -alloy-transport-ipc = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } -alloy-transport-ws = { git = "https://github.com/klkvr/alloy", rev = "af2eef3", default-features = false } +alloy-consensus = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } +alloy-contract = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } +alloy-eips = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } +alloy-genesis = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } +alloy-json-rpc = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } +alloy-network = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } +alloy-node-bindings = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } +alloy-provider = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } +alloy-pubsub = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } +alloy-rpc-client = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } +alloy-rpc-types-trace = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } +alloy-rpc-types = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } +alloy-signer = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } +alloy-signer-wallet = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } +alloy-signer-aws = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } +alloy-signer-ledger = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } +alloy-signer-trezor = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } +alloy-transport = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } +alloy-transport-http = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } +alloy-transport-ipc = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } +alloy-transport-ws = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } alloy-primitives = { version = "0.7.0", features = ["getrandom"] } alloy-dyn-abi = "0.7.0" alloy-json-abi = "0.7.0" diff --git a/crates/common/src/fmt/ui.rs b/crates/common/src/fmt/ui.rs index f6beb7652975..f8941d7dc2f2 100644 --- a/crates/common/src/fmt/ui.rs +++ b/crates/common/src/fmt/ui.rs @@ -208,7 +208,7 @@ blobGasUsed {}", status.pretty(), transaction_hash.pretty(), transaction_index.pretty(), - transaction_type), + transaction_type, blob_gas_price.pretty(), blob_gas_used.pretty(), ); From 4ae360bc790f3a4e01faea3bf347b18a07c2c1ef Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Sun, 7 Apr 2024 16:32:30 +0400 Subject: [PATCH 59/63] add comment --- clippy.toml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/clippy.toml b/clippy.toml index 07ea6cab0848..09acb653d14a 100644 --- a/clippy.toml +++ b/clippy.toml @@ -1,2 +1,4 @@ msrv = "1.76" +# bytes::Bytes is included by default and alloy_primitives::Bytes is a wrapper around it, +# so it is safe to ignore it as well ignore-interior-mutability = ["bytes::Bytes", "alloy_primitives::Bytes"] From 6900bef23d30be54bb51a1385882101b80a46058 Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Sun, 7 Apr 2024 16:33:13 +0400 Subject: [PATCH 60/63] clippy --- crates/cheatcodes/src/fs.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/cheatcodes/src/fs.rs b/crates/cheatcodes/src/fs.rs index 037c6ec61e79..d53620f43cc0 100644 --- a/crates/cheatcodes/src/fs.rs +++ b/crates/cheatcodes/src/fs.rs @@ -486,7 +486,7 @@ mod tests { use super::*; use crate::CheatsConfig; use alloy_primitives::Bytes; - use std::{path::PathBuf, sync::Arc}; + use std::sync::Arc; fn cheats() -> Cheatcodes { let config = CheatsConfig { From e8ccb7d12e4d9012174ef663f392a859e133b4ff Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Tue, 9 Apr 2024 22:40:24 +0400 Subject: [PATCH 61/63] bump alloy --- Cargo.lock | 46 +++++++------ Cargo.toml | 46 ++++++------- crates/anvil/core/src/eth/block.rs | 40 +++++------ crates/anvil/core/src/eth/transaction/mod.rs | 8 +-- crates/anvil/src/config.rs | 22 +++--- crates/anvil/src/eth/backend/executor.rs | 11 ++- crates/anvil/src/eth/backend/fork.rs | 25 +++---- crates/anvil/src/eth/backend/mem/mod.rs | 71 +++++++++----------- crates/anvil/src/eth/backend/mem/storage.rs | 2 +- crates/anvil/src/eth/fees.rs | 4 +- crates/anvil/src/eth/otterscan/types.rs | 2 +- crates/anvil/src/tasks/mod.rs | 4 +- crates/anvil/tests/it/anvil_api.rs | 10 +-- crates/anvil/tests/it/api.rs | 4 +- crates/anvil/tests/it/fork.rs | 13 ++-- crates/anvil/tests/it/otterscan.rs | 4 +- crates/anvil/tests/it/transaction.rs | 4 +- crates/cast/bin/cmd/run.rs | 6 +- crates/cast/bin/cmd/send.rs | 2 +- crates/cast/src/lib.rs | 6 +- crates/cheatcodes/src/evm/fork.rs | 9 ++- crates/common/src/fmt/ui.rs | 2 +- crates/common/src/provider/alloy.rs | 4 +- crates/common/src/provider/retry.rs | 1 + crates/common/src/transactions.rs | 2 +- crates/evm/core/src/backend/cow.rs | 2 +- crates/evm/core/src/backend/mod.rs | 26 +++---- crates/evm/core/src/fork/init.rs | 14 ++-- crates/evm/core/src/fork/multi.rs | 2 +- crates/evm/core/src/opts.rs | 2 +- crates/evm/core/src/utils.rs | 2 +- crates/forge/bin/cmd/create.rs | 4 +- crates/script/src/broadcast.rs | 4 +- crates/script/src/receipts.rs | 2 +- 34 files changed, 198 insertions(+), 208 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6b4704fb7264..1d4cf80fd409 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -90,7 +90,7 @@ dependencies = [ [[package]] name = "alloy-consensus" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" +source = "git+https://github.com/alloy-rs/alloy?rev=5f74d4e#5f74d4e7a417662489e4165236c1251fee8e6078" dependencies = [ "alloy-eips", "alloy-primitives", @@ -105,7 +105,7 @@ dependencies = [ [[package]] name = "alloy-contract" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" +source = "git+https://github.com/alloy-rs/alloy?rev=5f74d4e#5f74d4e7a417662489e4165236c1251fee8e6078" dependencies = [ "alloy-dyn-abi", "alloy-json-abi", @@ -144,7 +144,7 @@ dependencies = [ [[package]] name = "alloy-eips" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" +source = "git+https://github.com/alloy-rs/alloy?rev=5f74d4e#5f74d4e7a417662489e4165236c1251fee8e6078" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -158,7 +158,7 @@ dependencies = [ [[package]] name = "alloy-genesis" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" +source = "git+https://github.com/alloy-rs/alloy?rev=5f74d4e#5f74d4e7a417662489e4165236c1251fee8e6078" dependencies = [ "alloy-primitives", "alloy-serde", @@ -180,7 +180,7 @@ dependencies = [ [[package]] name = "alloy-json-rpc" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" +source = "git+https://github.com/alloy-rs/alloy?rev=5f74d4e#5f74d4e7a417662489e4165236c1251fee8e6078" dependencies = [ "alloy-primitives", "serde", @@ -191,7 +191,7 @@ dependencies = [ [[package]] name = "alloy-network" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" +source = "git+https://github.com/alloy-rs/alloy?rev=5f74d4e#5f74d4e7a417662489e4165236c1251fee8e6078" dependencies = [ "alloy-consensus", "alloy-eips", @@ -234,8 +234,9 @@ dependencies = [ [[package]] name = "alloy-provider" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" +source = "git+https://github.com/alloy-rs/alloy?rev=5f74d4e#5f74d4e7a417662489e4165236c1251fee8e6078" dependencies = [ + "alloy-eips", "alloy-json-rpc", "alloy-network", "alloy-primitives", @@ -249,6 +250,7 @@ dependencies = [ "auto_impl", "dashmap", "futures", + "futures-utils-wasm", "lru", "serde_json", "tokio", @@ -258,7 +260,7 @@ dependencies = [ [[package]] name = "alloy-pubsub" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" +source = "git+https://github.com/alloy-rs/alloy?rev=5f74d4e#5f74d4e7a417662489e4165236c1251fee8e6078" dependencies = [ "alloy-json-rpc", "alloy-primitives", @@ -298,7 +300,7 @@ dependencies = [ [[package]] name = "alloy-rpc-client" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" +source = "git+https://github.com/alloy-rs/alloy?rev=5f74d4e#5f74d4e7a417662489e4165236c1251fee8e6078" dependencies = [ "alloy-json-rpc", "alloy-primitives", @@ -318,7 +320,7 @@ dependencies = [ [[package]] name = "alloy-rpc-types" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" +source = "git+https://github.com/alloy-rs/alloy?rev=5f74d4e#5f74d4e7a417662489e4165236c1251fee8e6078" dependencies = [ "alloy-consensus", "alloy-eips", @@ -336,7 +338,7 @@ dependencies = [ [[package]] name = "alloy-rpc-types-trace" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" +source = "git+https://github.com/alloy-rs/alloy?rev=5f74d4e#5f74d4e7a417662489e4165236c1251fee8e6078" dependencies = [ "alloy-primitives", "alloy-rpc-types", @@ -348,7 +350,7 @@ dependencies = [ [[package]] name = "alloy-serde" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" +source = "git+https://github.com/alloy-rs/alloy?rev=5f74d4e#5f74d4e7a417662489e4165236c1251fee8e6078" dependencies = [ "alloy-primitives", "serde", @@ -358,7 +360,7 @@ dependencies = [ [[package]] name = "alloy-signer" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" +source = "git+https://github.com/alloy-rs/alloy?rev=5f74d4e#5f74d4e7a417662489e4165236c1251fee8e6078" dependencies = [ "alloy-dyn-abi", "alloy-primitives", @@ -373,7 +375,7 @@ dependencies = [ [[package]] name = "alloy-signer-aws" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" +source = "git+https://github.com/alloy-rs/alloy?rev=5f74d4e#5f74d4e7a417662489e4165236c1251fee8e6078" dependencies = [ "alloy-consensus", "alloy-network", @@ -390,7 +392,7 @@ dependencies = [ [[package]] name = "alloy-signer-ledger" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" +source = "git+https://github.com/alloy-rs/alloy?rev=5f74d4e#5f74d4e7a417662489e4165236c1251fee8e6078" dependencies = [ "alloy-consensus", "alloy-network", @@ -407,7 +409,7 @@ dependencies = [ [[package]] name = "alloy-signer-trezor" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" +source = "git+https://github.com/alloy-rs/alloy?rev=5f74d4e#5f74d4e7a417662489e4165236c1251fee8e6078" dependencies = [ "alloy-consensus", "alloy-network", @@ -423,7 +425,7 @@ dependencies = [ [[package]] name = "alloy-signer-wallet" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" +source = "git+https://github.com/alloy-rs/alloy?rev=5f74d4e#5f74d4e7a417662489e4165236c1251fee8e6078" dependencies = [ "alloy-consensus", "alloy-network", @@ -500,7 +502,7 @@ dependencies = [ [[package]] name = "alloy-transport" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" +source = "git+https://github.com/alloy-rs/alloy?rev=5f74d4e#5f74d4e7a417662489e4165236c1251fee8e6078" dependencies = [ "alloy-json-rpc", "base64 0.22.0", @@ -518,7 +520,7 @@ dependencies = [ [[package]] name = "alloy-transport-http" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" +source = "git+https://github.com/alloy-rs/alloy?rev=5f74d4e#5f74d4e7a417662489e4165236c1251fee8e6078" dependencies = [ "alloy-json-rpc", "alloy-transport", @@ -531,7 +533,7 @@ dependencies = [ [[package]] name = "alloy-transport-ipc" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" +source = "git+https://github.com/alloy-rs/alloy?rev=5f74d4e#5f74d4e7a417662489e4165236c1251fee8e6078" dependencies = [ "alloy-json-rpc", "alloy-pubsub", @@ -549,7 +551,7 @@ dependencies = [ [[package]] name = "alloy-transport-ws" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6aab216#6aab2164b92c3174cdd81fcb403177361338e594" +source = "git+https://github.com/alloy-rs/alloy?rev=5f74d4e#5f74d4e7a417662489e4165236c1251fee8e6078" dependencies = [ "alloy-pubsub", "alloy-transport", @@ -6845,7 +6847,7 @@ dependencies = [ [[package]] name = "revm-inspectors" version = "0.1.0" -source = "git+https://github.com/paradigmxyz/evm-inspectors?rev=37d1fcd#37d1fcd6a5b4a30ab7267ce71fbf9c3bcbe7b01c" +source = "git+https://github.com/paradigmxyz/evm-inspectors?rev=510d4d0#510d4d0d06130d52ee996fa8aebd32cdc8267905" dependencies = [ "alloy-primitives", "alloy-rpc-types", diff --git a/Cargo.toml b/Cargo.toml index ec194b26260e..d48ab2e8cf0f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -143,9 +143,9 @@ foundry-compilers = { version = "0.3.14", default-features = false } # no default features to avoid c-kzg revm = { version = "8", default-features = false } revm-primitives = { version = "3", default-features = false } -revm-inspectors = { git = "https://github.com/paradigmxyz/evm-inspectors", rev = "37d1fcd", features = [ +revm-inspectors = { git = "https://github.com/paradigmxyz/evm-inspectors", rev = "510d4d0", features = [ "serde", -] } +] } ## ethers ethers = { version = "2.0.14", default-features = false } @@ -157,27 +157,27 @@ ethers-signers = { version = "2.0.14", default-features = false } ethers-middleware = { version = "2.0.14", default-features = false } ## alloy -alloy-consensus = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } -alloy-contract = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } -alloy-eips = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } -alloy-genesis = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } -alloy-json-rpc = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } -alloy-network = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } -alloy-node-bindings = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } -alloy-provider = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } -alloy-pubsub = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } -alloy-rpc-client = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } -alloy-rpc-types-trace = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } -alloy-rpc-types = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } -alloy-signer = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } -alloy-signer-wallet = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } -alloy-signer-aws = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } -alloy-signer-ledger = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } -alloy-signer-trezor = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } -alloy-transport = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } -alloy-transport-http = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } -alloy-transport-ipc = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } -alloy-transport-ws = { git = "https://github.com/alloy-rs/alloy", rev = "6aab216", default-features = false } +alloy-consensus = { git = "https://github.com/alloy-rs/alloy", rev = "5f74d4e", default-features = false } +alloy-contract = { git = "https://github.com/alloy-rs/alloy", rev = "5f74d4e", default-features = false } +alloy-eips = { git = "https://github.com/alloy-rs/alloy", rev = "5f74d4e", default-features = false } +alloy-genesis = { git = "https://github.com/alloy-rs/alloy", rev = "5f74d4e", default-features = false } +alloy-json-rpc = { git = "https://github.com/alloy-rs/alloy", rev = "5f74d4e", default-features = false } +alloy-network = { git = "https://github.com/alloy-rs/alloy", rev = "5f74d4e", default-features = false } +alloy-node-bindings = { git = "https://github.com/alloy-rs/alloy", rev = "5f74d4e", default-features = false } +alloy-provider = { git = "https://github.com/alloy-rs/alloy", rev = "5f74d4e", default-features = false } +alloy-pubsub = { git = "https://github.com/alloy-rs/alloy", rev = "5f74d4e", default-features = false } +alloy-rpc-client = { git = "https://github.com/alloy-rs/alloy", rev = "5f74d4e", default-features = false } +alloy-rpc-types-trace = { git = "https://github.com/alloy-rs/alloy", rev = "5f74d4e", default-features = false } +alloy-rpc-types = { git = "https://github.com/alloy-rs/alloy", rev = "5f74d4e", default-features = false } +alloy-signer = { git = "https://github.com/alloy-rs/alloy", rev = "5f74d4e", default-features = false } +alloy-signer-wallet = { git = "https://github.com/alloy-rs/alloy", rev = "5f74d4e", default-features = false } +alloy-signer-aws = { git = "https://github.com/alloy-rs/alloy", rev = "5f74d4e", default-features = false } +alloy-signer-ledger = { git = "https://github.com/alloy-rs/alloy", rev = "5f74d4e", default-features = false } +alloy-signer-trezor = { git = "https://github.com/alloy-rs/alloy", rev = "5f74d4e", default-features = false } +alloy-transport = { git = "https://github.com/alloy-rs/alloy", rev = "5f74d4e", default-features = false } +alloy-transport-http = { git = "https://github.com/alloy-rs/alloy", rev = "5f74d4e", default-features = false } +alloy-transport-ipc = { git = "https://github.com/alloy-rs/alloy", rev = "5f74d4e", default-features = false } +alloy-transport-ws = { git = "https://github.com/alloy-rs/alloy", rev = "5f74d4e", default-features = false } alloy-primitives = { version = "0.7.0", features = ["getrandom"] } alloy-dyn-abi = "0.7.0" alloy-json-abi = "0.7.0" diff --git a/crates/anvil/core/src/eth/block.rs b/crates/anvil/core/src/eth/block.rs index 719bf8d25dca..462d16c8209c 100644 --- a/crates/anvil/core/src/eth/block.rs +++ b/crates/anvil/core/src/eth/block.rs @@ -3,7 +3,7 @@ use super::{ trie, }; use alloy_consensus::Header; -use alloy_primitives::{Address, Bloom, Bytes, B256, U256}; +use alloy_primitives::{Address, Bloom, Bytes, B256, B64, U256}; use alloy_rlp::{RlpDecodable, RlpEncodable}; // Type alias to optionally support impersonated transactions @@ -60,8 +60,8 @@ impl Block { logs_bloom: partial_header.logs_bloom, difficulty: partial_header.difficulty, number: partial_header.number, - gas_limit: partial_header.gas_limit as u64, - gas_used: partial_header.gas_used as u64, + gas_limit: partial_header.gas_limit, + gas_used: partial_header.gas_used, timestamp: partial_header.timestamp, extra_data: partial_header.extra_data, mix_hash: partial_header.mix_hash, @@ -70,7 +70,7 @@ impl Block { excess_blob_gas: None, parent_beacon_block_root: None, nonce: partial_header.nonce, - base_fee_per_gas: partial_header.base_fee.map(|v| v as u64), + base_fee_per_gas: partial_header.base_fee, }, transactions, ommers, @@ -93,7 +93,7 @@ pub struct PartialHeader { pub timestamp: u64, pub extra_data: Bytes, pub mix_hash: B256, - pub nonce: u64, + pub nonce: B64, pub base_fee: Option, } @@ -107,13 +107,13 @@ impl From

for PartialHeader { logs_bloom: value.logs_bloom, difficulty: value.difficulty, number: value.number, - gas_limit: value.gas_limit as u128, - gas_used: value.gas_used as u128, + gas_limit: value.gas_limit, + gas_used: value.gas_used, timestamp: value.timestamp, extra_data: value.extra_data, mix_hash: value.mix_hash, nonce: value.nonce, - base_fee: value.base_fee_per_gas.map(|v| v as u128), + base_fee: value.base_fee_per_gas, } } } @@ -142,11 +142,11 @@ mod tests { difficulty: Default::default(), number: 124u64, gas_limit: Default::default(), - gas_used: 1337u64, + gas_used: 1337u128, timestamp: 0, extra_data: Default::default(), mix_hash: Default::default(), - nonce: 99u64, + nonce: B64::with_last_byte(99), withdrawals_root: Default::default(), blob_gas_used: Default::default(), excess_blob_gas: Default::default(), @@ -158,7 +158,7 @@ mod tests { let decoded: Header = Header::decode(&mut encoded.as_ref()).unwrap(); assert_eq!(header, decoded); - header.base_fee_per_gas = Some(12345u64); + header.base_fee_per_gas = Some(12345u128); let encoded = alloy_rlp::encode(&header); let decoded: Header = Header::decode(&mut encoded.as_ref()).unwrap(); @@ -181,8 +181,8 @@ mod tests { logs_bloom: Bloom::from_hex("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap(), difficulty: U256::from(2222), number: 0xd05u64, - gas_limit: 0x115cu64, - gas_used: 0x15b3u64, + gas_limit: 0x115cu128, + gas_used: 0x15b3u128, timestamp: 0x1a0au64, extra_data: hex::decode("7788").unwrap().into(), mix_hash: B256::from_str("0000000000000000000000000000000000000000000000000000000000000000").unwrap(), @@ -190,7 +190,7 @@ mod tests { blob_gas_used: None, excess_blob_gas: None, parent_beacon_block_root: None, - nonce: 0, + nonce: B64::ZERO, base_fee_per_gas: None, }; @@ -213,12 +213,12 @@ mod tests { logs_bloom: <[u8; 256]>::from_hex("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap().into(), difficulty: U256::from(2222), number: 0xd05u64, - gas_limit: 0x115cu64, - gas_used: 0x15b3u64, + gas_limit: 0x115cu128, + gas_used: 0x15b3u128, timestamp: 0x1a0au64, extra_data: hex::decode("7788").unwrap().into(), mix_hash: B256::from_str("0000000000000000000000000000000000000000000000000000000000000000").unwrap(), - nonce: 0, + nonce: B64::ZERO, withdrawals_root: None, blob_gas_used: None, excess_blob_gas: None, @@ -244,12 +244,12 @@ mod tests { logs_bloom: Bloom::from_hex("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap(), difficulty: U256::from(0x020000), number: 1u64, - gas_limit: U256::from(0x016345785d8a0000u128).to::(), - gas_used: U256::from(0x015534).to::(), + gas_limit: U256::from(0x016345785d8a0000u128).to::(), + gas_used: U256::from(0x015534).to::(), timestamp: 0x079e, extra_data: hex::decode("42").unwrap().into(), mix_hash: B256::from_str("0000000000000000000000000000000000000000000000000000000000000000").unwrap(), - nonce: 0, + nonce: B64::ZERO, base_fee_per_gas: Some(875), withdrawals_root: None, blob_gas_used: None, diff --git a/crates/anvil/core/src/eth/transaction/mod.rs b/crates/anvil/core/src/eth/transaction/mod.rs index e5b0a3af0cc7..84e236f92f8b 100644 --- a/crates/anvil/core/src/eth/transaction/mod.rs +++ b/crates/anvil/core/src/eth/transaction/mod.rs @@ -990,7 +990,7 @@ pub struct TransactionInfo { pub exit: InstructionResult, pub out: Option, pub nonce: u64, - pub gas_used: u64, + pub gas_used: u128, } #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)] @@ -1117,7 +1117,7 @@ impl TypedReceipt { } impl TypedReceipt { - pub fn cumulative_gas_used(&self) -> u64 { + pub fn cumulative_gas_used(&self) -> u128 { self.as_receipt_with_bloom().cumulative_gas_used() } @@ -1412,7 +1412,7 @@ mod tests { let receipt = TypedReceipt::Legacy(ReceiptWithBloom { receipt: Receipt { status: false, - cumulative_gas_used: 0x1u64, + cumulative_gas_used: 0x1u128, logs: vec![Log { address: Address::from_str("0000000000000000000000000000000000000011").unwrap(), data: LogData::new_unchecked( @@ -1447,7 +1447,7 @@ mod tests { let expected = TypedReceipt::Legacy(ReceiptWithBloom { receipt: Receipt { status: false, - cumulative_gas_used: 0x1u64, + cumulative_gas_used: 0x1u128, logs: vec![Log { address: Address::from_str("0000000000000000000000000000000000000011").unwrap(), data: LogData::new_unchecked( diff --git a/crates/anvil/src/config.rs b/crates/anvil/src/config.rs index 9db1428a7565..9380e4d99808 100644 --- a/crates/anvil/src/config.rs +++ b/crates/anvil/src/config.rs @@ -426,7 +426,7 @@ impl NodeConfig { /// Returns the base fee to use pub fn get_base_fee(&self) -> u128 { self.base_fee - .or_else(|| self.genesis.as_ref().and_then(|g| g.base_fee_per_gas.map(|b| b as u128))) + .or_else(|| self.genesis.as_ref().and_then(|g| g.base_fee_per_gas)) .unwrap_or(INITIAL_BASE_FEE) } @@ -1022,19 +1022,19 @@ latest block number: {latest_block}" // we only use the gas limit value of the block if it is non-zero and the block gas // limit is enabled, since there are networks where this is not used and is always // `0x0` which would inevitably result in `OutOfGas` errors as soon as the evm is about to record gas, See also - let gas_limit = if self.disable_block_gas_limit || block.header.gas_limit.is_zero() { - U256::from(u64::MAX) + let gas_limit = if self.disable_block_gas_limit || block.header.gas_limit == 0 { + u128::MAX } else { block.header.gas_limit }; env.block = BlockEnv { number: U256::from(fork_block_number), - timestamp: block.header.timestamp, + timestamp: U256::from(block.header.timestamp), difficulty: block.header.difficulty, // ensures prevrandao is set prevrandao: Some(block.header.mix_hash.unwrap_or_default()), - gas_limit, + gas_limit: U256::from(gas_limit), // Keep previous `coinbase` and `basefee` value coinbase: env.block.coinbase, basefee: env.block.basefee, @@ -1044,14 +1044,14 @@ latest block number: {latest_block}" // if not set explicitly we use the base fee of the latest block if self.base_fee.is_none() { if let Some(base_fee) = block.header.base_fee_per_gas { - self.base_fee = Some(base_fee.to()); - env.block.basefee = base_fee; + self.base_fee = Some(base_fee); + env.block.basefee = U256::from(base_fee); // this is the base fee of the current block, but we need the base fee of // the next block let next_block_base_fee = fees.get_next_block_base_fee_per_gas( - block.header.gas_used.to(), - block.header.gas_limit.to(), - block.header.base_fee_per_gas.unwrap_or_default().to(), + block.header.gas_used, + block.header.gas_limit, + block.header.base_fee_per_gas.unwrap_or_default(), ); // update next base fee fees.set_base_fee(next_block_base_fee); @@ -1109,7 +1109,7 @@ latest block number: {latest_block}" provider, chain_id, override_chain_id, - timestamp: block.header.timestamp.to::(), + timestamp: block.header.timestamp, base_fee: block.header.base_fee_per_gas, timeout: self.fork_request_timeout, retries: self.fork_request_retries, diff --git a/crates/anvil/src/eth/backend/executor.rs b/crates/anvil/src/eth/backend/executor.rs index d4dcec912da7..80a72beedc64 100644 --- a/crates/anvil/src/eth/backend/executor.rs +++ b/crates/anvil/src/eth/backend/executor.rs @@ -51,12 +51,9 @@ impl ExecutedTransaction { // successful return see [Return] let status_code = u8::from(self.exit_reason as u8 <= InstructionResult::SelfDestruct as u8); - let receipt_with_bloom: ReceiptWithBloom = Receipt { - status: status_code == 1, - cumulative_gas_used: *cumulative_gas_used as u64, - logs, - } - .into(); + let receipt_with_bloom: ReceiptWithBloom = + Receipt { status: status_code == 1, cumulative_gas_used: *cumulative_gas_used, logs } + .into(); match &self.transaction.pending_transaction.transaction.transaction { TypedTransaction::Legacy(_) => TypedReceipt::Legacy(receipt_with_bloom), @@ -173,7 +170,7 @@ impl<'a, DB: Db + ?Sized, Validator: TransactionValidator> TransactionExecutor<' _ => None, }, nonce: tx.nonce, - gas_used: tx.gas_used as u64, + gas_used: tx.gas_used, }; transaction_infos.push(info); diff --git a/crates/anvil/src/eth/backend/fork.rs b/crates/anvil/src/eth/backend/fork.rs index 7e9e04ba2f68..3727740cd51a 100644 --- a/crates/anvil/src/eth/backend/fork.rs +++ b/crates/anvil/src/eth/backend/fork.rs @@ -76,11 +76,11 @@ impl ClientFork { let block = provider.get_block(block_number, false).await?.ok_or(BlockchainError::BlockNotFound)?; let block_hash = block.header.hash.ok_or(BlockchainError::BlockNotFound)?; - let timestamp = block.header.timestamp.to::(); + let timestamp = block.header.timestamp; let base_fee = block.header.base_fee_per_gas; let total_difficulty = block.header.total_difficulty.unwrap_or_default(); - let number = block.header.number.ok_or(BlockchainError::BlockNotFound)?.to::(); + let number = block.header.number.ok_or(BlockchainError::BlockNotFound)?; self.config.write().update_block(number, block_hash, timestamp, base_fee, total_difficulty); self.clear_cached_storage(); @@ -117,7 +117,7 @@ impl ClientFork { self.config.read().total_difficulty } - pub fn base_fee(&self) -> Option { + pub fn base_fee(&self) -> Option { self.config.read().base_fee } @@ -478,7 +478,7 @@ impl ClientFork { ) -> Result, TransportError> { if let Some(block) = self.provider().get_block(block_id.into(), true).await? { let hash = block.header.hash.unwrap(); - let block_number = block.header.number.unwrap().to::(); + let block_number = block.header.number.unwrap(); let mut storage = self.storage_write(); // also insert all transactions let block_txs = match block.clone().transactions { @@ -531,14 +531,11 @@ impl ClientFork { let mut uncles = Vec::with_capacity(block.uncles.len()); for (uncle_idx, _) in block.uncles.iter().enumerate() { - let uncle = match self - .provider() - .get_uncle(block_number.to::().into(), U64::from(uncle_idx)) - .await? - { - Some(u) => u, - None => return Ok(None), - }; + let uncle = + match self.provider().get_uncle(block_number.into(), U64::from(uncle_idx)).await? { + Some(u) => u, + None => return Ok(None), + }; uncles.push(uncle); } self.storage_write().uncles.insert(block_hash, uncles.clone()); @@ -580,7 +577,7 @@ pub struct ClientForkConfig { /// The timestamp for the forked block pub timestamp: u64, /// The basefee of the forked block - pub base_fee: Option, + pub base_fee: Option, /// request timeout pub timeout: Duration, /// request retries for spurious networks @@ -623,7 +620,7 @@ impl ClientForkConfig { block_number: u64, block_hash: B256, timestamp: u64, - base_fee: Option, + base_fee: Option, total_difficulty: U256, ) { self.block_number = block_number; diff --git a/crates/anvil/src/eth/backend/mem/mod.rs b/crates/anvil/src/eth/backend/mem/mod.rs index 536b09dec98b..3fc05b5ba9e4 100644 --- a/crates/anvil/src/eth/backend/mem/mod.rs +++ b/crates/anvil/src/eth/backend/mem/mod.rs @@ -30,7 +30,7 @@ use crate::{ NodeConfig, }; use alloy_consensus::{Header, Receipt, ReceiptWithBloom}; -use alloy_primitives::{keccak256, Address, Bytes, TxHash, B256, B64, U256, U64}; +use alloy_primitives::{keccak256, Address, Bytes, TxHash, B256, U256, U64}; use alloy_rlp::Decodable; use alloy_rpc_types::{ request::TransactionRequest, serde_helpers::JsonStorageKey, state::StateOverride, AccessList, @@ -410,8 +410,8 @@ impl Backend { env.block = BlockEnv { number: rU256::from(fork_block_number), - timestamp: fork_block.header.timestamp, - gas_limit: fork_block.header.gas_limit, + timestamp: U256::from(fork_block.header.timestamp), + gas_limit: U256::from(fork_block.header.gas_limit), difficulty: fork_block.header.difficulty, prevrandao: Some(fork_block.header.mix_hash.unwrap_or_default()), // Keep previous `coinbase` and `basefee` value @@ -425,9 +425,9 @@ impl Backend { // this is the base fee of the current block, but we need the base fee of // the next block let next_block_base_fee = self.fees.get_next_block_base_fee_per_gas( - fork_block.header.gas_used.to(), - fork_block.header.gas_limit.to(), - fork_block.header.base_fee_per_gas.unwrap_or_default().to(), + fork_block.header.gas_used, + fork_block.header.gas_limit, + fork_block.header.base_fee_per_gas.unwrap_or_default(), ); self.fees.set_base_fee(next_block_base_fee); @@ -705,17 +705,17 @@ impl Backend { let block = self.block_by_hash(best_block_hash).await?.ok_or(BlockchainError::BlockNotFound)?; - let reset_time = block.header.timestamp.to::(); + let reset_time = block.header.timestamp; self.time.reset(reset_time); let mut env = self.env.write(); env.block = BlockEnv { number: rU256::from(num), - timestamp: block.header.timestamp, + timestamp: U256::from(block.header.timestamp), difficulty: block.header.difficulty, // ensures prevrandao is set prevrandao: Some(block.header.mix_hash.unwrap_or_default()), - gas_limit: block.header.gas_limit, + gas_limit: U256::from(block.header.gas_limit), // Keep previous `coinbase` and `basefee` value coinbase: env.block.coinbase, basefee: env.block.basefee, @@ -1018,9 +1018,9 @@ impl Backend { (outcome, header, block_hash) }; let next_block_base_fee = self.fees.get_next_block_base_fee_per_gas( - header.gas_used as u128, - header.gas_limit as u128, - header.base_fee_per_gas.unwrap_or_default() as u128, + header.gas_used, + header.gas_limit, + header.base_fee_per_gas.unwrap_or_default(), ); // notify all listeners @@ -1406,13 +1406,7 @@ impl Backend { let info = storage.transactions.get(&hash)?.info.clone(); let tx = block.transactions.get(info.transaction_index as usize)?.clone(); - let tx = transaction_build( - Some(hash), - tx, - Some(block), - Some(info), - base_fee.map(|f| f as u128), - ); + let tx = transaction_build(Some(hash), tx, Some(block), Some(info), base_fee); transactions.push(tx); } Some(transactions) @@ -1546,17 +1540,17 @@ impl Backend { state_root, transactions_root, receipts_root, - number: Some(number.to_alloy()), - gas_used: gas_used.to_alloy(), - gas_limit: gas_limit.to_alloy(), + number: Some(number), + gas_used, + gas_limit, extra_data: extra_data.0.into(), logs_bloom, - timestamp: U256::from(timestamp), + timestamp, total_difficulty: Some(self.total_difficulty()), difficulty, mix_hash: Some(mix_hash), - nonce: Some(B64::from(nonce)), - base_fee_per_gas: base_fee_per_gas.map(|f| f.to_alloy()), + nonce: Some(nonce), + base_fee_per_gas, withdrawals_root: None, blob_gas_used: None, excess_blob_gas: None, @@ -1590,8 +1584,7 @@ impl Backend { .ok_or(BlockchainError::BlockNotFound)? .header .number - .ok_or(BlockchainError::BlockNotFound)? - .to::(), + .ok_or(BlockchainError::BlockNotFound)?, BlockId::Number(num) => match num { BlockNumber::Latest | BlockNumber::Pending => self.best_number(), BlockNumber::Earliest => U64::ZERO.to::(), @@ -1636,11 +1629,11 @@ impl Backend { let block = BlockEnv { number: block.header.number.to_alloy(), coinbase: block.header.beneficiary, - timestamp: rU256::from(block.header.timestamp), + timestamp: U256::from(block.header.timestamp), difficulty: block.header.difficulty, prevrandao: Some(block.header.mix_hash), - basefee: block.header.base_fee_per_gas.unwrap_or_default().to_alloy(), - gas_limit: block.header.gas_limit.to_alloy(), + basefee: U256::from(block.header.base_fee_per_gas.unwrap_or_default()), + gas_limit: U256::from(block.header.gas_limit), ..Default::default() }; f(state, block) @@ -1667,8 +1660,8 @@ impl Backend { timestamp: rU256::from(block.header.timestamp), difficulty: block.header.difficulty, prevrandao: Some(block.header.mix_hash), - basefee: block.header.base_fee_per_gas.unwrap_or_default().to_alloy(), - gas_limit: block.header.gas_limit.to_alloy(), + basefee: U256::from(block.header.base_fee_per_gas.unwrap_or_default()), + gas_limit: U256::from(block.header.gas_limit), ..Default::default() }; return Ok(f(Box::new(state), block)); @@ -1688,7 +1681,7 @@ impl Backend { block.number = block_number; block.timestamp = rU256::from(fork.timestamp()); - block.basefee = fork.base_fee().unwrap_or_default(); + block.basefee = rU256::from(fork.base_fee().unwrap_or_default()); return Ok(f(Box::new(&gen_db), block)); } @@ -1952,12 +1945,12 @@ impl Backend { TypedTransaction::EIP1559(t) => block .header .base_fee_per_gas - .map_or(self.base_fee(), |b| b as u128) + .unwrap_or_else(|| self.base_fee()) .saturating_add(t.tx().max_priority_fee_per_gas), TypedTransaction::EIP4844(t) => block .header .base_fee_per_gas - .map_or(self.base_fee(), |b| b as u128) + .unwrap_or_else(|| self.base_fee()) .saturating_add(t.tx().tx().max_priority_fee_per_gas), TypedTransaction::Deposit(_) => 0_u128, }; @@ -2005,9 +1998,9 @@ impl Backend { transaction_hash: info.transaction_hash, transaction_index: info.transaction_index, block_number: Some(block.header.number), - gas_used: Some(info.gas_used), + gas_used: info.gas_used, contract_address: info.contract_address, - effective_gas_price: effective_gas_price as u64, + effective_gas_price, block_hash: Some(block_hash), from: info.from, to: info.to, @@ -2095,7 +2088,7 @@ impl Backend { tx, Some(&block), Some(info), - block.header.base_fee_per_gas.map(|g| g as u128), + block.header.base_fee_per_gas, )) } @@ -2130,7 +2123,7 @@ impl Backend { tx, Some(&block), Some(info), - block.header.base_fee_per_gas.map(|g| g as u128), + block.header.base_fee_per_gas, )) } diff --git a/crates/anvil/src/eth/backend/mem/storage.rs b/crates/anvil/src/eth/backend/mem/storage.rs index 7ef240d2f0a6..9637620992b2 100644 --- a/crates/anvil/src/eth/backend/mem/storage.rs +++ b/crates/anvil/src/eth/backend/mem/storage.rs @@ -415,7 +415,7 @@ impl MinedTransaction { pub fn geth_trace(&self, opts: GethDefaultTracingOptions) -> DefaultFrame { GethTraceBuilder::new(self.info.traces.clone(), TracingInspectorConfig::default_geth()) .geth_traces( - self.receipt.cumulative_gas_used(), + self.receipt.cumulative_gas_used() as u64, self.info.out.clone().unwrap_or_default().0.into(), opts, ) diff --git a/crates/anvil/src/eth/fees.rs b/crates/anvil/src/eth/fees.rs index eef25d543a93..2b070b281d75 100644 --- a/crates/anvil/src/eth/fees.rs +++ b/crates/anvil/src/eth/fees.rs @@ -228,7 +228,7 @@ impl FeeHistoryService { item.gas_used_ratio = gas_used / (gas_target * elasticity); // extract useful tx info (gas_used, effective_reward) - let mut transactions: Vec<(u64, u128)> = receipts + let mut transactions: Vec<(u128, u128)> = receipts .iter() .enumerate() .map(|(i, receipt)| { @@ -266,7 +266,7 @@ impl FeeHistoryService { item.rewards = reward_percentiles .into_iter() .filter_map(|p| { - let target_gas = (p * gas_used / 100f64) as u64; + let target_gas = (p * gas_used / 100f64) as u128; let mut sum_gas = 0; for (gas_used, effective_reward) in transactions.iter().cloned() { sum_gas += gas_used; diff --git a/crates/anvil/src/eth/otterscan/types.rs b/crates/anvil/src/eth/otterscan/types.rs index bde2d20833f2..d7e75c02c7e4 100644 --- a/crates/anvil/src/eth/otterscan/types.rs +++ b/crates/anvil/src/eth/otterscan/types.rs @@ -144,7 +144,7 @@ impl OtsBlockDetails { let total_fees = receipts .iter() - .fold(0, |acc, receipt| acc + receipt.gas_used.unwrap() * receipt.effective_gas_price); + .fold(0, |acc, receipt| acc + receipt.gas_used * receipt.effective_gas_price); Ok(Self { block: block.into(), diff --git a/crates/anvil/src/tasks/mod.rs b/crates/anvil/src/tasks/mod.rs index 1f03fee9c5ba..e42b0437ca68 100644 --- a/crates/anvil/src/tasks/mod.rs +++ b/crates/anvil/src/tasks/mod.rs @@ -78,7 +78,7 @@ impl TaskManager { let _ = api .anvil_reset(Some(Forking { json_rpc_url: None, - block_number: block.header.number.map(|b| b.to()), + block_number: block.header.number, })) .await; } @@ -136,7 +136,7 @@ impl TaskManager { let _ = api .anvil_reset(Some(Forking { json_rpc_url: None, - block_number: block.header.number.map(|b| b.to()), + block_number: block.header.number, })) .await; } diff --git a/crates/anvil/tests/it/anvil_api.rs b/crates/anvil/tests/it/anvil_api.rs index ed933363d34d..d2826b9ed0a7 100644 --- a/crates/anvil/tests/it/anvil_api.rs +++ b/crates/anvil/tests/it/anvil_api.rs @@ -44,7 +44,7 @@ async fn can_set_block_gas_limit() { api.mine_one().await; let latest_block = api.block_by_number(alloy_rpc_types::BlockNumberOrTag::Latest).await.unwrap().unwrap(); - assert_eq!(block_gas_limit.to_alloy(), latest_block.header.gas_limit); + assert_eq!(block_gas_limit.as_u128(), latest_block.header.gas_limit); } // Ref @@ -616,16 +616,16 @@ async fn test_fork_revert_call_latest_block_timestamp() { ); assert_eq!( - multicall.get_current_block_timestamp().await.unwrap(), - latest_block.header.timestamp.to_ethers() + multicall.get_current_block_timestamp().await.unwrap().as_u64(), + latest_block.header.timestamp ); assert_eq!( multicall.get_current_block_difficulty().await.unwrap(), latest_block.header.difficulty.to_ethers() ); assert_eq!( - multicall.get_current_block_gas_limit().await.unwrap(), - latest_block.header.gas_limit.to_ethers() + multicall.get_current_block_gas_limit().await.unwrap().as_u128(), + latest_block.header.gas_limit ); assert_eq!( multicall.get_current_block_coinbase().await.unwrap(), diff --git a/crates/anvil/tests/it/api.rs b/crates/anvil/tests/it/api.rs index d34499a3e782..acf9a0f9834a 100644 --- a/crates/anvil/tests/it/api.rs +++ b/crates/anvil/tests/it/api.rs @@ -213,7 +213,7 @@ async fn can_call_on_pending_block() { .call() .await .unwrap(); - assert_eq!(block.header.timestamp, block_timestamp.to_alloy()); + assert_eq!(block.header.timestamp, block_timestamp.as_u64()); let block_gas_limit = pending_contract .get_current_block_gas_limit() @@ -221,7 +221,7 @@ async fn can_call_on_pending_block() { .call() .await .unwrap(); - assert_eq!(block.header.gas_limit, block_gas_limit.to_alloy()); + assert_eq!(block.header.gas_limit, block_gas_limit.as_u128()); let block_coinbase = pending_contract .get_current_block_coinbase() diff --git a/crates/anvil/tests/it/fork.rs b/crates/anvil/tests/it/fork.rs index 9c402b71de3e..5f94a95aefba 100644 --- a/crates/anvil/tests/it/fork.rs +++ b/crates/anvil/tests/it/fork.rs @@ -812,7 +812,7 @@ async fn test_fork_block_timestamp() { api.anvil_mine(Some(rU256::from(1)), None).await.unwrap(); let latest_block = api.block_by_number(BlockNumberOrTag::Latest).await.unwrap().unwrap(); - assert!(initial_block.header.timestamp.to::() < latest_block.header.timestamp.to::()); + assert!(initial_block.header.timestamp < latest_block.header.timestamp); } #[tokio::test(flavor = "multi_thread")] @@ -823,14 +823,11 @@ async fn test_fork_snapshot_block_timestamp() { api.anvil_mine(Some(rU256::from(1)), None).await.unwrap(); let initial_block = api.block_by_number(BlockNumberOrTag::Latest).await.unwrap().unwrap(); api.evm_revert(snapshot_id).await.unwrap(); - api.evm_set_next_block_timestamp(initial_block.header.timestamp.to::()).unwrap(); + api.evm_set_next_block_timestamp(initial_block.header.timestamp).unwrap(); api.anvil_mine(Some(rU256::from(1)), None).await.unwrap(); let latest_block = api.block_by_number(BlockNumberOrTag::Latest).await.unwrap().unwrap(); - assert_eq!( - initial_block.header.timestamp.to::(), - latest_block.header.timestamp.to::() - ); + assert_eq!(initial_block.header.timestamp, latest_block.header.timestamp); } #[tokio::test(flavor = "multi_thread")] @@ -1094,7 +1091,7 @@ async fn test_fork_reset_basefee() { let latest = api.block_by_number(BlockNumberOrTag::Latest).await.unwrap().unwrap(); // basefee of +1 block: - assert_eq!(latest.header.base_fee_per_gas.unwrap(), rU256::from(59455969592u64)); + assert_eq!(latest.header.base_fee_per_gas.unwrap(), 59455969592u128); // now reset to block 18835000 -1 api.anvil_reset(Some(Forking { json_rpc_url: None, block_number: Some(18835000u64 - 1) })) @@ -1105,7 +1102,7 @@ async fn test_fork_reset_basefee() { let latest = api.block_by_number(BlockNumberOrTag::Latest).await.unwrap().unwrap(); // basefee of the forked block: - assert_eq!(latest.header.base_fee_per_gas.unwrap(), rU256::from(59017001138u64)); + assert_eq!(latest.header.base_fee_per_gas.unwrap(), 59017001138u128); } // diff --git a/crates/anvil/tests/it/otterscan.rs b/crates/anvil/tests/it/otterscan.rs index c40c3653e4ed..4c344264034c 100644 --- a/crates/anvil/tests/it/otterscan.rs +++ b/crates/anvil/tests/it/otterscan.rs @@ -32,8 +32,8 @@ async fn can_call_erigon_get_header_by_number() { let res0 = api.erigon_get_header_by_number(0.into()).await.unwrap().unwrap(); let res1 = api.erigon_get_header_by_number(1.into()).await.unwrap().unwrap(); - assert_eq!(res0.header.number, Some(rU256::from(0))); - assert_eq!(res1.header.number, Some(rU256::from(1))); + assert_eq!(res0.header.number, Some(0)); + assert_eq!(res1.header.number, Some(1)); } #[tokio::test(flavor = "multi_thread")] diff --git a/crates/anvil/tests/it/transaction.rs b/crates/anvil/tests/it/transaction.rs index 1c85480ced6a..46c059374c60 100644 --- a/crates/anvil/tests/it/transaction.rs +++ b/crates/anvil/tests/it/transaction.rs @@ -433,11 +433,11 @@ async fn get_blocktimestamp_works() { api.block_by_number(alloy_rpc_types::BlockNumberOrTag::Latest).await.unwrap().unwrap(); let timestamp = contract.get_current_block_timestamp().call().await.unwrap(); - assert_eq!(timestamp, latest_block.header.timestamp.to_ethers()); + assert_eq!(timestamp.as_u64(), latest_block.header.timestamp); // repeat call same result let timestamp = contract.get_current_block_timestamp().call().await.unwrap(); - assert_eq!(timestamp, latest_block.header.timestamp.to_ethers()); + assert_eq!(timestamp.as_u64(), latest_block.header.timestamp); // mock timestamp let next_timestamp = timestamp.as_u64() + 1337; diff --git a/crates/cast/bin/cmd/run.rs b/crates/cast/bin/cmd/run.rs index a1e01fe23c4a..33c26e2a907b 100644 --- a/crates/cast/bin/cmd/run.rs +++ b/crates/cast/bin/cmd/run.rs @@ -132,12 +132,12 @@ impl RunArgs { env.block.number = U256::from(tx_block_number); if let Some(block) = &block { - env.block.timestamp = block.header.timestamp; + env.block.timestamp = U256::from(block.header.timestamp); env.block.coinbase = block.header.miner; env.block.difficulty = block.header.difficulty; env.block.prevrandao = Some(block.header.mix_hash.unwrap_or_default()); - env.block.basefee = block.header.base_fee_per_gas.unwrap_or_default(); - env.block.gas_limit = block.header.gas_limit; + env.block.basefee = U256::from(block.header.base_fee_per_gas.unwrap_or_default()); + env.block.gas_limit = U256::from(block.header.gas_limit); // TODO: we need a smarter way to map the block to the corresponding evm_version for // commonly used chains diff --git a/crates/cast/bin/cmd/send.rs b/crates/cast/bin/cmd/send.rs index c1901861b6d6..b24de5fba294 100644 --- a/crates/cast/bin/cmd/send.rs +++ b/crates/cast/bin/cmd/send.rs @@ -178,7 +178,7 @@ impl SendTxArgs { let signer = EthereumSigner::from(signer); let provider = - ProviderBuilder::<_, AnyNetwork>::default().signer(signer).provider(provider); + ProviderBuilder::<_, _, AnyNetwork>::default().signer(signer).on_provider(provider); cast_send( provider, diff --git a/crates/cast/src/lib.rs b/crates/cast/src/lib.rs index d50385701f75..338510eb9419 100644 --- a/crates/cast/src/lib.rs +++ b/crates/cast/src/lib.rs @@ -795,9 +795,7 @@ where BlockId::Number(block_number) => Ok(Some(block_number)), BlockId::Hash(hash) => { let block = self.provider.get_block_by_hash(hash.block_hash, false).await?; - Ok(block - .map(|block| block.header.number.unwrap().to::()) - .map(BlockNumberOrTag::from)) + Ok(block.map(|block| block.header.number.unwrap()).map(BlockNumberOrTag::from)) } }, None => Ok(None), @@ -841,7 +839,7 @@ where None }; - let to_block_number = filter.get_to_block().map(U256::from); + let to_block_number = filter.get_to_block(); // If output should be JSON, start with an opening bracket if to_json { diff --git a/crates/cheatcodes/src/evm/fork.rs b/crates/cheatcodes/src/evm/fork.rs index fdf29f8b24b9..d2a8ff4ebbeb 100644 --- a/crates/cheatcodes/src/evm/fork.rs +++ b/crates/cheatcodes/src/evm/fork.rs @@ -64,7 +64,12 @@ impl Cheatcode for createSelectFork_2Call { impl Cheatcode for rollFork_0Call { fn apply_full(&self, ccx: &mut CheatsCtxt) -> Result { let Self { blockNumber } = self; - ccx.ecx.db.roll_fork(None, *blockNumber, &mut ccx.ecx.env, &mut ccx.ecx.journaled_state)?; + ccx.ecx.db.roll_fork( + None, + (*blockNumber).to(), + &mut ccx.ecx.env, + &mut ccx.ecx.journaled_state, + )?; Ok(Default::default()) } } @@ -87,7 +92,7 @@ impl Cheatcode for rollFork_2Call { let Self { forkId, blockNumber } = self; ccx.ecx.db.roll_fork( Some(*forkId), - *blockNumber, + (*blockNumber).to(), &mut ccx.ecx.env, &mut ccx.ecx.journaled_state, )?; diff --git a/crates/common/src/fmt/ui.rs b/crates/common/src/fmt/ui.rs index f8941d7dc2f2..c5bdf6c130e0 100644 --- a/crates/common/src/fmt/ui.rs +++ b/crates/common/src/fmt/ui.rs @@ -440,7 +440,7 @@ pub fn get_pretty_tx_receipt_attr( "effectiveGasPrice" | "effective_gas_price" => { Some(receipt.receipt.effective_gas_price.to_string()) } - "gasUsed" | "gas_used" => receipt.receipt.gas_used.map(|g| g.to_string()), + "gasUsed" | "gas_used" => Some(receipt.receipt.gas_used.to_string()), "logs" => Some(receipt.receipt.inner.inner.inner.receipt.logs.as_slice().pretty()), "logsBloom" | "logs_bloom" => Some(receipt.receipt.inner.inner.inner.logs_bloom.pretty()), "root" | "stateRoot" | "state_root " => Some(receipt.receipt.state_root.pretty()), diff --git a/crates/common/src/provider/alloy.rs b/crates/common/src/provider/alloy.rs index e26fd7a1bdde..e76a898bd814 100644 --- a/crates/common/src/provider/alloy.rs +++ b/crates/common/src/provider/alloy.rs @@ -242,8 +242,8 @@ impl ProviderBuilder { .build(); let client = ClientBuilder::default().layer(retry_layer).transport(transport, false); - let provider = - AlloyProviderBuilder::<_, AnyNetwork>::default().provider(RootProvider::new(client)); + let provider = AlloyProviderBuilder::<_, _, AnyNetwork>::default() + .on_provider(RootProvider::new(client)); Ok(provider) } diff --git a/crates/common/src/provider/retry.rs b/crates/common/src/provider/retry.rs index 92ea0601ed99..b6adfb646be8 100644 --- a/crates/common/src/provider/retry.rs +++ b/crates/common/src/provider/retry.rs @@ -51,6 +51,7 @@ impl RetryPolicy for RateLimitRetryPolicy { TransportError::ErrorResp(err) => should_retry_json_rpc_error(err), TransportError::NullResp => true, TransportError::UnsupportedFeature(_) => false, + TransportError::LocalUsageError(_) => false, } } diff --git a/crates/common/src/transactions.rs b/crates/common/src/transactions.rs index 27234bbd5609..cf3f5a89a75a 100644 --- a/crates/common/src/transactions.rs +++ b/crates/common/src/transactions.rs @@ -20,7 +20,7 @@ pub struct TransactionReceiptWithRevertReason { impl TransactionReceiptWithRevertReason { /// Returns if the status of the transaction is 0 (failure) pub fn is_failure(&self) -> bool { - self.receipt.inner.inner.inner.receipt.status + !self.receipt.inner.inner.inner.receipt.status } /// Updates the revert reason field using `eth_call` and returns an Err variant if the revert diff --git a/crates/evm/core/src/backend/cow.rs b/crates/evm/core/src/backend/cow.rs index f41a1cd43048..59410541a737 100644 --- a/crates/evm/core/src/backend/cow.rs +++ b/crates/evm/core/src/backend/cow.rs @@ -159,7 +159,7 @@ impl<'a> DatabaseExt for CowBackend<'a> { fn roll_fork( &mut self, id: Option, - block_number: U256, + block_number: u64, env: &mut Env, journaled_state: &mut JournaledState, ) -> eyre::Result<()> { diff --git a/crates/evm/core/src/backend/mod.rs b/crates/evm/core/src/backend/mod.rs index 5124c6f29ade..dbd5071eed60 100644 --- a/crates/evm/core/src/backend/mod.rs +++ b/crates/evm/core/src/backend/mod.rs @@ -7,7 +7,7 @@ use crate::{ utils::configure_tx_env, }; use alloy_genesis::GenesisAccount; -use alloy_primitives::{b256, keccak256, Address, B256, U256, U64}; +use alloy_primitives::{b256, keccak256, Address, B256, U256}; use alloy_rpc_types::{Block, BlockNumberOrTag, BlockTransactions, Transaction, WithOtherFields}; use eyre::Context; use foundry_common::{is_known_system_sender, SYSTEM_TRANSACTION_TYPE}; @@ -166,7 +166,7 @@ pub trait DatabaseExt: Database { fn roll_fork( &mut self, id: Option, - block_number: U256, + block_number: u64, env: &mut Env, journaled_state: &mut JournaledState, ) -> eyre::Result<()>; @@ -857,7 +857,7 @@ impl Backend { &self, id: LocalForkId, transaction: B256, - ) -> eyre::Result<(U64, Block)> { + ) -> eyre::Result<(u64, Block)> { let fork = self.inner.get_fork_by_id(id)?; let tx = fork.db.db.get_transaction(transaction)?; @@ -868,7 +868,7 @@ impl Backend { // we need to subtract 1 here because we want the state before the transaction // was mined let fork_block = tx_block - 1; - Ok((U64::from(fork_block), block)) + Ok((fork_block, block)) } else { let block = fork.db.db.get_full_block(BlockNumberOrTag::Latest)?; @@ -877,7 +877,7 @@ impl Backend { .number .ok_or_else(|| DatabaseError::BlockNotFound(BlockNumberOrTag::Latest.into()))?; - Ok((number.to::(), block)) + Ok((number, block)) } } @@ -1147,14 +1147,14 @@ impl DatabaseExt for Backend { fn roll_fork( &mut self, id: Option, - block_number: U256, + block_number: u64, env: &mut Env, journaled_state: &mut JournaledState, ) -> eyre::Result<()> { trace!(?id, ?block_number, "roll fork"); let id = self.ensure_fork(id)?; let (fork_id, backend, fork_env) = - self.forks.roll_fork(self.inner.ensure_fork_id(id).cloned()?, block_number.to())?; + self.forks.roll_fork(self.inner.ensure_fork_id(id).cloned()?, block_number)?; // this will update the local mapping self.inner.roll_fork(id, fork_id, backend)?; @@ -1216,7 +1216,7 @@ impl DatabaseExt for Backend { self.get_block_number_and_block_for_transaction(id, transaction)?; // roll the fork to the transaction's block or latest if it's pending - self.roll_fork(Some(id), fork_block.to(), env, journaled_state)?; + self.roll_fork(Some(id), fork_block, env, journaled_state)?; update_env_block(env, fork_block, &block); @@ -1855,14 +1855,14 @@ fn is_contract_in_state(journaled_state: &JournaledState, acc: Address) -> bool } /// Updates the env's block with the block's data -fn update_env_block(env: &mut Env, fork_block: U64, block: &Block) { - env.block.timestamp = block.header.timestamp; +fn update_env_block(env: &mut Env, fork_block: u64, block: &Block) { + env.block.timestamp = U256::from(block.header.timestamp); env.block.coinbase = block.header.miner; env.block.difficulty = block.header.difficulty; env.block.prevrandao = Some(block.header.mix_hash.unwrap_or_default()); - env.block.basefee = block.header.base_fee_per_gas.unwrap_or_default(); - env.block.gas_limit = block.header.gas_limit; - env.block.number = block.header.number.map(|n| n.to()).unwrap_or(fork_block.to()); + env.block.basefee = U256::from(block.header.base_fee_per_gas.unwrap_or_default()); + env.block.gas_limit = U256::from(block.header.gas_limit); + env.block.number = U256::from(block.header.number.unwrap_or(fork_block)); } /// Executes the given transaction and commits state changes to the database _and_ the journaled diff --git a/crates/evm/core/src/fork/init.rs b/crates/evm/core/src/fork/init.rs index 4bca73c5234c..b69e02aad9db 100644 --- a/crates/evm/core/src/fork/init.rs +++ b/crates/evm/core/src/fork/init.rs @@ -14,7 +14,7 @@ use revm::primitives::{BlockEnv, CfgEnv, Env, TxEnv}; pub async fn environment>( provider: &P, memory_limit: u64, - gas_price: Option, + gas_price: Option, override_chain_id: Option, pin_block: Option, origin: Address, @@ -62,20 +62,20 @@ pub async fn environment>( let mut env = Env { cfg, block: BlockEnv { - number: block.header.number.expect("block number not found"), - timestamp: block.header.timestamp, + number: U256::from(block.header.number.expect("block number not found")), + timestamp: U256::from(block.header.timestamp), coinbase: block.header.miner, difficulty: block.header.difficulty, prevrandao: Some(block.header.mix_hash.unwrap_or_default()), - basefee: block.header.base_fee_per_gas.unwrap_or_default(), - gas_limit: block.header.gas_limit, + basefee: U256::from(block.header.base_fee_per_gas.unwrap_or_default()), + gas_limit: U256::from(block.header.gas_limit), ..Default::default() }, tx: TxEnv { caller: origin, - gas_price: gas_price.map(U256::from).unwrap_or(U256::from(fork_gas_price)), + gas_price: U256::from(gas_price.unwrap_or(fork_gas_price)), chain_id: Some(override_chain_id.unwrap_or(rpc_chain_id)), - gas_limit: block.header.gas_limit.to::(), + gas_limit: block.header.gas_limit as u64, ..Default::default() }, }; diff --git a/crates/evm/core/src/fork/multi.rs b/crates/evm/core/src/fork/multi.rs index 6ed49ca27f72..60096784c60e 100644 --- a/crates/evm/core/src/fork/multi.rs +++ b/crates/evm/core/src/fork/multi.rs @@ -502,7 +502,7 @@ async fn create_fork(mut fork: CreateFork) -> eyre::Result<(ForkId, CreatedFork, // we need to use the block number from the block because the env's number can be different on // some L2s (e.g. Arbitrum). - let number = block.header.number.unwrap_or(meta.block_env.number).to::(); + let number = block.header.number.unwrap_or(meta.block_env.number.to()); // determine the cache path if caching is enabled let cache_path = if fork.enable_caching { diff --git a/crates/evm/core/src/opts.rs b/crates/evm/core/src/opts.rs index 70f72087a752..fcd92dd6adf3 100644 --- a/crates/evm/core/src/opts.rs +++ b/crates/evm/core/src/opts.rs @@ -95,7 +95,7 @@ impl EvmOpts { environment( &provider, self.memory_limit, - self.env.gas_price, + self.env.gas_price.map(|v| v as u128), self.env.chain_id, self.fork_block_number, self.sender, diff --git a/crates/evm/core/src/utils.rs b/crates/evm/core/src/utils.rs index 74cbd0a61f13..ee8a8a4d4758 100644 --- a/crates/evm/core/src/utils.rs +++ b/crates/evm/core/src/utils.rs @@ -25,7 +25,7 @@ pub fn apply_chain_and_block_specific_env_changes(env: &mut revm::primitives::En match chain { NamedChain::Mainnet => { // after merge difficulty is supplanted with prevrandao EIP-4399 - if block_number.to::() >= 15_537_351u64 { + if block_number >= 15_537_351u64 { env.block.difficulty = env.block.prevrandao.unwrap_or_default().into(); } diff --git a/crates/forge/bin/cmd/create.rs b/crates/forge/bin/cmd/create.rs index 3f42019a63df..e42a17057bdb 100644 --- a/crates/forge/bin/cmd/create.rs +++ b/crates/forge/bin/cmd/create.rs @@ -139,9 +139,9 @@ impl CreateArgs { // Deploy with signer let signer = self.eth.wallet.signer().await?; let deployer = signer.address(); - let provider = ProviderBuilder::<_, AnyNetwork>::default() + let provider = ProviderBuilder::<_, _, AnyNetwork>::default() .signer(EthereumSigner::new(signer)) - .provider(provider); + .on_provider(provider); self.deploy(abi, bin, params, provider, chain_id, deployer).await } } diff --git a/crates/script/src/broadcast.rs b/crates/script/src/broadcast.rs index d16af14204be..bf12ec73bc9c 100644 --- a/crates/script/src/broadcast.rs +++ b/crates/script/src/broadcast.rs @@ -375,12 +375,12 @@ impl BundledState { let (total_gas, total_gas_price, total_paid) = sequence.receipts.iter().fold((0, 0, 0), |acc, receipt| { - let gas_used = receipt.gas_used.unwrap_or_default(); + let gas_used = receipt.gas_used; let gas_price = receipt.effective_gas_price; (acc.0 + gas_used, acc.1 + gas_price, acc.2 + gas_used * gas_price) }); let paid = format_units(total_paid, 18).unwrap_or_else(|_| "N/A".to_string()); - let avg_gas_price = format_units(total_gas_price / sequence.receipts.len() as u64, 9) + let avg_gas_price = format_units(total_gas_price / sequence.receipts.len() as u128, 9) .unwrap_or_else(|_| "N/A".to_string()); shell::println(format!( diff --git a/crates/script/src/receipts.rs b/crates/script/src/receipts.rs index 33c99dfcadeb..3bdc228f0575 100644 --- a/crates/script/src/receipts.rs +++ b/crates/script/src/receipts.rs @@ -152,7 +152,7 @@ async fn check_tx_status( /// Prints parts of the receipt to stdout pub fn print_receipt(chain: Chain, receipt: &AnyTransactionReceipt) { - let gas_used = receipt.gas_used.unwrap_or_default(); + let gas_used = receipt.gas_used; let gas_price = receipt.effective_gas_price; foundry_common::shell::println(format!( "\n##### {chain}\n{status}Hash: {tx_hash:?}{caddr}\nBlock: {bn}\n{gas}\n", From abd79cf2c23cb61e5d25677a499ba706c864c10e Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Tue, 9 Apr 2024 22:49:41 +0400 Subject: [PATCH 62/63] fixes --- Cargo.lock | 92 +++++++++++++++++++++++-- Cargo.toml | 2 +- crates/anvil/src/eth/backend/mem/mod.rs | 2 +- crates/cheatcodes/src/inspector.rs | 2 +- 4 files changed, 90 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a9e434286f57..770e28567edd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -555,9 +555,9 @@ dependencies = [ [[package]] name = "alloy-trie" -version = "0.3.0" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b9e1498416f7e7f09af8061970e14936846b6271e153aa5ba539a22a7eb414d" +checksum = "beb28aa4ecd32fdfa1b1bdd111ff7357dd562c6b2372694cf9e613434fcba659" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -2916,9 +2916,11 @@ dependencies = [ "ethers-addressbook", "ethers-contract", "ethers-core", + "ethers-etherscan", "ethers-middleware", "ethers-providers", "ethers-signers", + "ethers-solc", ] [[package]] @@ -2962,11 +2964,13 @@ dependencies = [ "const-hex", "dunce", "ethers-core", + "ethers-etherscan", "eyre", "prettyplease", "proc-macro2", "quote", "regex", + "reqwest 0.11.27", "serde", "serde_json", "syn 2.0.58", @@ -3020,6 +3024,22 @@ dependencies = [ "unicode-xid", ] +[[package]] +name = "ethers-etherscan" +version = "2.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e79e5973c26d4baf0ce55520bd732314328cabe53193286671b47144145b9649" +dependencies = [ + "chrono", + "ethers-core", + "reqwest 0.11.27", + "semver 1.0.22", + "serde", + "serde_json", + "thiserror", + "tracing", +] + [[package]] name = "ethers-middleware" version = "2.0.14" @@ -3104,6 +3124,38 @@ dependencies = [ "tracing", ] +[[package]] +name = "ethers-solc" +version = "2.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66244a771d9163282646dbeffe0e6eca4dda4146b6498644e678ac6089b11edd" +dependencies = [ + "cfg-if", + "const-hex", + "dirs 5.0.1", + "dunce", + "ethers-core", + "glob", + "home", + "md-5", + "num_cpus", + "once_cell", + "path-slash", + "rayon", + "regex", + "semver 1.0.22", + "serde", + "serde_json", + "solang-parser", + "svm-rs 0.3.5", + "thiserror", + "tiny-keccak", + "tokio", + "tracing", + "walkdir", + "yansi 0.5.1", +] + [[package]] name = "event-listener" version = "2.5.3" @@ -3398,7 +3450,7 @@ dependencies = [ "similar", "solang-parser", "strum 0.26.2", - "svm-rs", + "svm-rs 0.4.1", "tempfile", "thiserror", "tikv-jemallocator", @@ -3722,7 +3774,7 @@ dependencies = [ "serde_json", "sha2", "solang-parser", - "svm-rs", + "svm-rs 0.4.1", "svm-rs-builds", "tempfile", "thiserror", @@ -3988,6 +4040,16 @@ dependencies = [ "tracing", ] +[[package]] +name = "fs2" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213" +dependencies = [ + "libc", + "winapi", +] + [[package]] name = "fs4" version = "0.7.0" @@ -7805,6 +7867,26 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "81cdd64d312baedb58e21336b31bc043b77e01cc99033ce76ef539f78e965ebc" +[[package]] +name = "svm-rs" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11297baafe5fa0c99d5722458eac6a5e25c01eb1b8e5cd137f54079093daa7a4" +dependencies = [ + "dirs 5.0.1", + "fs2", + "hex", + "once_cell", + "reqwest 0.11.27", + "semver 1.0.22", + "serde", + "serde_json", + "sha2", + "thiserror", + "url", + "zip", +] + [[package]] name = "svm-rs" version = "0.4.1" @@ -7835,7 +7917,7 @@ dependencies = [ "const-hex", "semver 1.0.22", "serde_json", - "svm-rs", + "svm-rs 0.4.1", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 05a0993b9dc2..1bc2329a5093 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -185,7 +185,7 @@ alloy-json-abi = "0.7.0" alloy-sol-types = "0.7.0" syn-solidity = "0.7.0" alloy-chains = "0.1" -alloy-trie = "0.3" +alloy-trie = "0.3.1" alloy-rlp = "0.3.3" solang-parser = "=0.3.3" diff --git a/crates/anvil/src/eth/backend/mem/mod.rs b/crates/anvil/src/eth/backend/mem/mod.rs index c1d972b01b07..939913b842a8 100644 --- a/crates/anvil/src/eth/backend/mem/mod.rs +++ b/crates/anvil/src/eth/backend/mem/mod.rs @@ -35,7 +35,6 @@ use crate::{ }; use alloy_consensus::{Header, Receipt, ReceiptWithBloom}; use alloy_primitives::{keccak256, Address, Bytes, TxHash, B256, U256, U64}; -use alloy_rlp::Decodable; use alloy_rpc_types::{ request::TransactionRequest, serde_helpers::JsonStorageKey, state::StateOverride, AccessList, Block as AlloyBlock, BlockId, BlockNumberOrTag as BlockNumber, @@ -46,6 +45,7 @@ use alloy_rpc_types_trace::{ geth::{DefaultFrame, GethDebugTracingOptions, GethDefaultTracingOptions, GethTrace}, parity::LocalizedTransactionTrace, }; +use alloy_trie::{HashBuilder, Nibbles}; use anvil_core::{ eth::{ block::{Block, BlockInfo}, diff --git a/crates/cheatcodes/src/inspector.rs b/crates/cheatcodes/src/inspector.rs index 8512a2a41106..cd2d49ba6307 100644 --- a/crates/cheatcodes/src/inspector.rs +++ b/crates/cheatcodes/src/inspector.rs @@ -1047,7 +1047,7 @@ impl Inspector for Cheatcodes { // The gas limit of the call. gasLimit: gas.limit(), // The total gas used. - gasTotalUsed: gas.spend(), + gasTotalUsed: gas.spent(), // The amount of gas used for memory expansion. gasMemoryUsed: gas.memory(), // The amount of gas refunded. From 144dc19271228a8ec04f18c017f9be39a66fb28b Mon Sep 17 00:00:00 2001 From: bernard-wagner Date: Tue, 9 Apr 2024 21:31:09 +0200 Subject: [PATCH 63/63] refactor cast logs to use alloy (#7594) * refactor cast logs to use alloy * fmt * make clippy happy * cleanup * doc nits --------- Co-authored-by: evalir --- crates/cast/bin/cmd/logs.rs | 197 ++++++++++++------------------------ 1 file changed, 64 insertions(+), 133 deletions(-) diff --git a/crates/cast/bin/cmd/logs.rs b/crates/cast/bin/cmd/logs.rs index fbdbecf27825..e97521fe92df 100644 --- a/crates/cast/bin/cmd/logs.rs +++ b/crates/cast/bin/cmd/logs.rs @@ -1,18 +1,14 @@ -use alloy_primitives::Address; -use alloy_rpc_types::{BlockId, BlockNumberOrTag, Filter, FilterBlockOption, FilterSet}; +use alloy_dyn_abi::{DynSolType, DynSolValue, Specifier}; +use alloy_json_abi::Event; +use alloy_primitives::{Address, B256}; +use alloy_rpc_types::{BlockId, BlockNumberOrTag, Filter, FilterBlockOption, FilterSet, Topic}; use cast::Cast; use clap::Parser; -use ethers_core::{ - abi::{ - token::{LenientTokenizer, StrictTokenizer, Tokenizer}, - Event, HumanReadableParser, ParamType, RawTopicFilter, Token, Topic, TopicFilter, - }, - types::{H256, U256}, -}; -use eyre::{Result, WrapErr}; +use eyre::Result; use foundry_cli::{opts::EthereumOpts, utils}; -use foundry_common::{ens::NameOrAddress, types::ToAlloy}; +use foundry_common::ens::NameOrAddress; use foundry_config::Config; +use hex::FromHex; use itertools::Itertools; use std::{io, str::FromStr}; @@ -115,40 +111,29 @@ fn build_filter( topics_or_args: Vec, ) -> Result { let block_option = FilterBlockOption::Range { from_block, to_block }; - let topic_filter = match sig_or_topic { + let filter = match sig_or_topic { // Try and parse the signature as an event signature - Some(sig_or_topic) => match HumanReadableParser::parse_event(sig_or_topic.as_str()) { + Some(sig_or_topic) => match foundry_common::abi::get_event(sig_or_topic.as_str()) { Ok(event) => build_filter_event_sig(event, topics_or_args)?, Err(_) => { let topics = [vec![sig_or_topic], topics_or_args].concat(); build_filter_topics(topics)? } }, - None => TopicFilter::default(), - }; - // Convert from TopicFilter to Filter - let topics = - vec![topic_filter.topic0, topic_filter.topic1, topic_filter.topic2, topic_filter.topic3] - .into_iter() - .map(|topic| match topic { - Topic::Any => vec![], - Topic::This(topic) => vec![topic.to_alloy()], - _ => unreachable!(), - }) - .map(FilterSet::from) - .collect::>(); - - let filter = Filter { - block_option, - address: address.map(|a| vec![a]).unwrap_or_default().into(), - topics: [topics[0].clone(), topics[1].clone(), topics[2].clone(), topics[3].clone()], + None => Filter::default(), }; + let mut filter = filter.select(block_option); + + if let Some(address) = address { + filter = filter.address(address) + } + Ok(filter) } -/// Creates a TopicFilter from the given event signature and arguments. -fn build_filter_event_sig(event: Event, args: Vec) -> Result { +/// Creates a [Filter] from the given event signature and arguments. +fn build_filter_event_sig(event: Event, args: Vec) -> Result { let args = args.iter().map(|arg| arg.as_str()).collect::>(); // Match the args to indexed inputs. Enumerate so that the ordering can be restored @@ -158,128 +143,74 @@ fn build_filter_event_sig(event: Event, args: Vec) -> Result>>()? + .into_iter() .enumerate() .partition(|(_, (_, arg))| !arg.is_empty()); // Only parse the inputs with arguments - let indexed_tokens = parse_params(with_args.iter().map(|(_, p)| *p), true)?; + let indexed_tokens = with_args + .iter() + .map(|(_, (kind, arg))| kind.coerce_str(arg)) + .collect::, _>>()?; // Merge the inputs restoring the original ordering - let mut tokens = with_args + let mut topics = with_args .into_iter() .zip(indexed_tokens) .map(|((i, _), t)| (i, Some(t))) .chain(without_args.into_iter().map(|(i, _)| (i, None))) .sorted_by(|(i1, _), (i2, _)| i1.cmp(i2)) - .map(|(_, token)| token) - .collect::>(); + .map(|(_, token)| { + token + .map(|token| Topic::from(B256::from_slice(token.abi_encode().as_slice()))) + .unwrap_or(Topic::default()) + }) + .collect::>(); - tokens.resize(3, None); + topics.resize(3, Topic::default()); - let raw = RawTopicFilter { - topic0: tokens[0].clone().map_or(Topic::Any, Topic::This), - topic1: tokens[1].clone().map_or(Topic::Any, Topic::This), - topic2: tokens[2].clone().map_or(Topic::Any, Topic::This), - }; + let filter = Filter::new() + .event_signature(event.selector()) + .topic1(topics[0].clone()) + .topic2(topics[1].clone()) + .topic3(topics[2].clone()); - // Let filter do the hardwork of converting arguments to topics - Ok(event.filter(raw)?) + Ok(filter) } -/// Creates a TopicFilter from raw topic hashes. -fn build_filter_topics(topics: Vec) -> Result { +/// Creates a [Filter] from raw topic hashes. +fn build_filter_topics(topics: Vec) -> Result { let mut topics = topics .into_iter() - .map(|topic| if topic.is_empty() { Ok(None) } else { H256::from_str(&topic).map(Some) }) - .collect::, _>>()?; - - topics.resize(4, None); - - Ok(TopicFilter { - topic0: topics[0].map_or(Topic::Any, Topic::This), - topic1: topics[1].map_or(Topic::Any, Topic::This), - topic2: topics[2].map_or(Topic::Any, Topic::This), - topic3: topics[3].map_or(Topic::Any, Topic::This), - }) -} - -fn parse_params<'a, I: IntoIterator>( - params: I, - lenient: bool, -) -> eyre::Result> { - let mut tokens = Vec::new(); - - for (param, value) in params { - let mut token = if lenient { - LenientTokenizer::tokenize(param, value) - } else { - StrictTokenizer::tokenize(param, value) - }; - if token.is_err() && value.starts_with("0x") { - match param { - ParamType::FixedBytes(32) => { - if value.len() < 66 { - let padded_value = [value, &"0".repeat(66 - value.len())].concat(); - token = if lenient { - LenientTokenizer::tokenize(param, &padded_value) - } else { - StrictTokenizer::tokenize(param, &padded_value) - }; - } - } - ParamType::Uint(_) => { - // try again if value is hex - if let Ok(value) = U256::from_str(value).map(|v| v.to_string()) { - token = if lenient { - LenientTokenizer::tokenize(param, &value) - } else { - StrictTokenizer::tokenize(param, &value) - }; - } - } - // TODO: Not sure what to do here. Put the no effect in for now, but that is not - // ideal. We could attempt massage for every value type? - _ => {} + .map(|topic| { + if topic.is_empty() { + Ok(Topic::default()) + } else { + Ok(Topic::from(B256::from_hex(topic.as_str())?)) } - } + }) + .collect::>>>()?; - let token = token.map(sanitize_token).wrap_err_with(|| { - format!("Failed to parse `{value}`, expected value of type: {param}") - })?; - tokens.push(token); - } - Ok(tokens) -} + topics.resize(4, Topic::default()); -pub fn sanitize_token(token: Token) -> Token { - match token { - Token::Array(tokens) => { - let mut sanitized = Vec::with_capacity(tokens.len()); - for token in tokens { - let token = match token { - Token::String(val) => { - let val = match val.as_str() { - // this is supposed to be an empty string - "\"\"" | "''" => String::new(), - _ => val, - }; - Token::String(val) - } - _ => sanitize_token(token), - }; - sanitized.push(token) - } - Token::Array(sanitized) - } - _ => token, - } + let filter = Filter::new() + .event_signature(topics[0].clone()) + .topic1(topics[1].clone()) + .topic2(topics[2].clone()) + .topic3(topics[3].clone()); + + Ok(filter) } #[cfg(test)] mod tests { use super::*; - use alloy_primitives::{B256, U160, U256 as rU256}; + use alloy_primitives::{U160, U256 as rU256}; use alloy_rpc_types::ValueOrArray; const ADDRESS: &str = "0x4D1A2e2bB4F88F0250f26Ffff098B0b30B26BF38"; @@ -452,7 +383,7 @@ mod tests { .unwrap() .to_string(); - assert_eq!(err, "Failed to parse `1234`, expected value of type: address"); + assert_eq!(err, "parser error:\n1234\n^\nInvalid string length"); } #[test] @@ -462,7 +393,7 @@ mod tests { .unwrap() .to_string(); - assert_eq!(err, "Invalid character 's' at position 1"); + assert_eq!(err, "Odd number of digits"); } #[test] @@ -472,7 +403,7 @@ mod tests { .unwrap() .to_string(); - assert_eq!(err, "Invalid input length"); + assert_eq!(err, "Invalid string length"); } #[test] @@ -488,6 +419,6 @@ mod tests { .unwrap() .to_string(); - assert_eq!(err, "Invalid input length"); + assert_eq!(err, "Invalid string length"); } }