From 6797d2d3af849d38c6876618c68afc6cb3055194 Mon Sep 17 00:00:00 2001 From: Enrique Ortiz Date: Tue, 28 Nov 2023 12:17:27 -0400 Subject: [PATCH] chore: fmt, switch to local tx request type in the meanwhile for optimism tests --- crates/anvil/core/src/eth/mod.rs | 226 ++++++++++-------- crates/anvil/core/src/eth/serde_helpers.rs | 8 +- crates/anvil/core/src/eth/state.rs | 2 +- .../core/src/eth/transaction/ethers_compat.rs | 73 ++++-- crates/anvil/core/src/eth/transaction/mod.rs | 4 +- crates/anvil/core/src/types.rs | 2 +- crates/anvil/src/cmd.rs | 4 +- crates/anvil/src/config.rs | 12 +- crates/anvil/src/eth/api.rs | 90 ++++--- crates/anvil/src/eth/backend/genesis.rs | 18 +- crates/anvil/src/eth/backend/mem/mod.rs | 18 +- crates/anvil/src/eth/backend/mem/state.rs | 2 +- crates/anvil/src/eth/fees.rs | 2 +- crates/anvil/src/eth/otterscan/types.rs | 13 +- crates/anvil/src/genesis.rs | 10 +- crates/anvil/src/lib.rs | 18 +- crates/anvil/src/pubsub.rs | 10 +- crates/anvil/tests/it/api.rs | 12 +- crates/anvil/tests/it/gas.rs | 9 +- crates/anvil/tests/it/otterscan.rs | 51 ++-- crates/anvil/tests/it/proof/mod.rs | 16 +- crates/anvil/tests/it/transaction.rs | 8 +- crates/cast/bin/cmd/run.rs | 10 +- crates/cheatcodes/src/evm/fork.rs | 3 +- crates/cheatcodes/src/inspector.rs | 24 +- crates/common/src/lib.rs | 2 +- crates/common/src/provider/alloy.rs | 2 +- crates/common/src/types.rs | 6 +- crates/evm/core/src/backend/mod.rs | 3 +- crates/evm/core/src/fork/init.rs | 2 +- crates/evm/core/src/fork/multi.rs | 4 +- crates/forge/bin/cmd/create.rs | 11 +- crates/forge/bin/cmd/script/broadcast.rs | 17 +- crates/forge/bin/cmd/script/cmd.rs | 4 +- crates/forge/bin/cmd/script/executor.rs | 6 +- crates/forge/bin/cmd/script/mod.rs | 9 +- crates/forge/bin/cmd/script/providers.rs | 3 +- crates/forge/bin/cmd/script/receipts.rs | 6 +- crates/forge/bin/cmd/script/transaction.rs | 7 +- crates/test-utils/src/script.rs | 26 +- 40 files changed, 430 insertions(+), 323 deletions(-) diff --git a/crates/anvil/core/src/eth/mod.rs b/crates/anvil/core/src/eth/mod.rs index bc46f203cf03..4c7a5c987112 100644 --- a/crates/anvil/core/src/eth/mod.rs +++ b/crates/anvil/core/src/eth/mod.rs @@ -13,20 +13,23 @@ use ethers_core::types::{transaction::eip712::TypedData, GethDebugTracingOptions pub mod block; pub mod proof; pub mod receipt; +pub mod state; pub mod subscription; pub mod transaction; pub mod trie; pub mod utils; -pub mod state; #[cfg(feature = "serde")] pub mod serde_helpers; #[cfg(feature = "serde")] use self::serde_helpers::*; +use self::transaction::EthTransactionRequest; #[cfg(feature = "serde")] -use foundry_common::serde_helpers::{deserialize_number, deserialize_number_opt, deserialize_number_seq}; +use foundry_common::serde_helpers::{ + deserialize_number, deserialize_number_opt, deserialize_number_seq, +}; /// Wrapper type that ensures the type is named `params` #[derive(Debug, Clone, PartialEq, Eq)] @@ -88,9 +91,13 @@ pub enum EthRequest { #[cfg_attr(feature = "serde", serde(rename = "eth_getBlockByNumber"))] EthGetBlockByNumber( - #[cfg_attr(feature = "serde", serde(deserialize_with = "lenient_block_number::lenient_block_number"))] - BlockNumber, - bool), + #[cfg_attr( + feature = "serde", + serde(deserialize_with = "lenient_block_number::lenient_block_number") + )] + BlockNumber, + bool, + ), #[cfg_attr(feature = "serde", serde(rename = "eth_getTransactionCount"))] EthGetTransactionCount(Address, Option), @@ -138,7 +145,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"))] @@ -153,7 +160,7 @@ pub enum EthRequest { EthSignTypedDataV4(Address, 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), @@ -191,9 +198,12 @@ pub enum EthRequest { #[cfg_attr(feature = "serde", serde(rename = "eth_getUncleByBlockNumberAndIndex"))] EthGetUncleByBlockNumberAndIndex( - #[cfg_attr(feature = "serde", serde(deserialize_with = "lenient_block_number::lenient_block_number"))] - BlockNumber, - Index + #[cfg_attr( + feature = "serde", + serde(deserialize_with = "lenient_block_number::lenient_block_number") + )] + BlockNumber, + Index, ), #[cfg_attr(feature = "serde", serde(rename = "eth_getLogs", with = "sequence"))] @@ -269,7 +279,10 @@ pub enum EthRequest { /// Trace transaction endpoint for parity's `trace_block` #[cfg_attr( feature = "serde", - serde(rename = "trace_block", deserialize_with = "lenient_block_number::lenient_block_number_seq") + serde( + rename = "trace_block", + deserialize_with = "lenient_block_number::lenient_block_number_seq" + ) )] TraceBlock(BlockNumber), @@ -575,7 +588,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) @@ -606,8 +619,11 @@ pub enum EthRequest { /// Related upstream issue: https://github.com/otterscan/otterscan/issues/1081 #[cfg_attr(feature = "serde", serde(rename = "erigon_getHeaderByNumber"))] ErigonGetHeaderByNumber( - #[cfg_attr(feature = "serde", serde(deserialize_with = "lenient_block_number::lenient_block_number_seq"))] - BlockNumber + #[cfg_attr( + feature = "serde", + serde(deserialize_with = "lenient_block_number::lenient_block_number_seq") + )] + BlockNumber, ), /// Otterscan's `ots_getApiLevel` endpoint @@ -625,9 +641,12 @@ pub enum EthRequest { /// Check if an ETH address contains code at a certain block number. #[cfg_attr(feature = "serde", serde(rename = "ots_hasCode"))] OtsHasCode( - Address, - #[cfg_attr(feature = "serde", serde(deserialize_with = "lenient_block_number::lenient_block_number", default))] - BlockNumber + Address, + #[cfg_attr( + feature = "serde", + serde(deserialize_with = "lenient_block_number::lenient_block_number", default) + )] + BlockNumber, ), /// Otterscan's `ots_traceTransaction` endpoint @@ -646,8 +665,11 @@ pub enum EthRequest { /// logBloom #[cfg_attr(feature = "serde", serde(rename = "ots_getBlockDetails"))] OtsGetBlockDetails( - #[cfg_attr(feature = "serde", serde(deserialize_with = "lenient_block_number::lenient_block_number", default))] - BlockNumber + #[cfg_attr( + feature = "serde", + serde(deserialize_with = "lenient_block_number::lenient_block_number", default) + )] + BlockNumber, ), /// Otterscan's `ots_getBlockDetails` endpoint @@ -791,16 +813,18 @@ mod tests { #[test] fn test_custom_impersonate_account() { let s = r#"{"method": "anvil_impersonateAccount", "params": -["0xd84de507f3fada7df80908082d3239466db55a71"]}"#; let value: serde_json::Value = -serde_json::from_str(s).unwrap(); let _req = -serde_json::from_value::(value).unwrap(); } +["0xd84de507f3fada7df80908082d3239466db55a71"]}"#; + let value: serde_json::Value = serde_json::from_str(s).unwrap(); + let _req = serde_json::from_value::(value).unwrap(); + } #[test] fn test_custom_stop_impersonate_account() { let s = r#"{"method": "anvil_stopImpersonatingAccount", "params": -["0x364d6D0333432C3Ac016Ca832fb8594A8cE43Ca6"]}"#; let value: serde_json::Value = -serde_json::from_str(s).unwrap(); let _req = -serde_json::from_value::(value).unwrap(); } +["0x364d6D0333432C3Ac016Ca832fb8594A8cE43Ca6"]}"#; + let value: serde_json::Value = serde_json::from_str(s).unwrap(); + let _req = serde_json::from_value::(value).unwrap(); + } #[test] fn test_custom_auto_impersonate_account() { @@ -828,11 +852,11 @@ serde_json::from_value::(value).unwrap(); } } _ => unreachable!(), } - let s = - r#"{"method": "anvil_mine", "params": -["0xd84de507f3fada7df80908082d3239466db55a71"]}"#; let value: serde_json::Value = -serde_json::from_str(s).unwrap(); let req = -serde_json::from_value::(value).unwrap(); match req { + let s = r#"{"method": "anvil_mine", "params": +["0xd84de507f3fada7df80908082d3239466db55a71"]}"#; + let value: serde_json::Value = serde_json::from_str(s).unwrap(); + let req = serde_json::from_value::(value).unwrap(); + match req { EthRequest::Mine(num, time) => { assert!(num.is_some()); assert!(time.is_none()); @@ -874,9 +898,10 @@ serde_json::from_value::(value).unwrap(); match req { #[test] fn test_custom_drop_tx() { let s = r#"{"method": "anvil_dropTransaction", "params": -["0x4a3b0fce2cb9707b0baa68640cf2fe858c8bb4121b2a8cb904ff369d38a560ff"]}"#; let value: -serde_json::Value = serde_json::from_str(s).unwrap(); let _req = -serde_json::from_value::(value).unwrap(); } +["0x4a3b0fce2cb9707b0baa68640cf2fe858c8bb4121b2a8cb904ff369d38a560ff"]}"#; + let value: serde_json::Value = serde_json::from_str(s).unwrap(); + let _req = serde_json::from_value::(value).unwrap(); + } #[test] fn test_custom_reset() { @@ -1019,67 +1044,73 @@ serde_json::from_value::(value).unwrap(); } #[test] fn test_custom_set_balance() { let s = r#"{"method": "anvil_setBalance", "params": -["0xd84de507f3fada7df80908082d3239466db55a71", "0x0"]}"#; let value: serde_json::Value = -serde_json::from_str(s).unwrap(); let _req = -serde_json::from_value::(value).unwrap(); +["0xd84de507f3fada7df80908082d3239466db55a71", "0x0"]}"#; + let value: serde_json::Value = serde_json::from_str(s).unwrap(); + let _req = serde_json::from_value::(value).unwrap(); let s = r#"{"method": "anvil_setBalance", "params": -["0xd84de507f3fada7df80908082d3239466db55a71", 1337]}"#; let value: serde_json::Value = -serde_json::from_str(s).unwrap(); let _req = -serde_json::from_value::(value).unwrap(); } +["0xd84de507f3fada7df80908082d3239466db55a71", 1337]}"#; + let value: serde_json::Value = serde_json::from_str(s).unwrap(); + let _req = serde_json::from_value::(value).unwrap(); + } #[test] fn test_custom_set_code() { let s = r#"{"method": "anvil_setCode", "params": -["0xd84de507f3fada7df80908082d3239466db55a71", "0x0123456789abcdef"]}"#; let value: -serde_json::Value = serde_json::from_str(s).unwrap(); let _req = -serde_json::from_value::(value).unwrap(); +["0xd84de507f3fada7df80908082d3239466db55a71", "0x0123456789abcdef"]}"#; + let value: serde_json::Value = serde_json::from_str(s).unwrap(); + let _req = serde_json::from_value::(value).unwrap(); let s = r#"{"method": "anvil_setCode", "params": -["0xd84de507f3fada7df80908082d3239466db55a71", "0x"]}"#; let value: serde_json::Value = -serde_json::from_str(s).unwrap(); let _req = -serde_json::from_value::(value).unwrap(); +["0xd84de507f3fada7df80908082d3239466db55a71", "0x"]}"#; + let value: serde_json::Value = serde_json::from_str(s).unwrap(); + let _req = serde_json::from_value::(value).unwrap(); let s = r#"{"method": "anvil_setCode", "params": -["0xd84de507f3fada7df80908082d3239466db55a71", ""]}"#; let value: serde_json::Value = -serde_json::from_str(s).unwrap(); let _req = -serde_json::from_value::(value).unwrap(); } +["0xd84de507f3fada7df80908082d3239466db55a71", ""]}"#; + let value: serde_json::Value = serde_json::from_str(s).unwrap(); + let _req = serde_json::from_value::(value).unwrap(); + } #[test] fn test_custom_set_nonce() { let s = r#"{"method": "anvil_setNonce", "params": -["0xd84de507f3fada7df80908082d3239466db55a71", "0x0"]}"#; let value: serde_json::Value = -serde_json::from_str(s).unwrap(); let _req = -serde_json::from_value::(value).unwrap(); let s = r#"{"method": +["0xd84de507f3fada7df80908082d3239466db55a71", "0x0"]}"#; + let value: serde_json::Value = serde_json::from_str(s).unwrap(); + let _req = serde_json::from_value::(value).unwrap(); + let s = r#"{"method": "hardhat_setNonce", "params": ["0xd84de507f3fada7df80908082d3239466db55a71", "0x0"]}"#; let value: serde_json::Value = serde_json::from_str(s).unwrap(); let _req = serde_json::from_value::(value).unwrap(); let s = r#"{"method": "evm_setAccountNonce", "params": -["0xd84de507f3fada7df80908082d3239466db55a71", "0x0"]}"#; let value: serde_json::Value = -serde_json::from_str(s).unwrap(); let _req = -serde_json::from_value::(value).unwrap(); } +["0xd84de507f3fada7df80908082d3239466db55a71", "0x0"]}"#; + let value: serde_json::Value = serde_json::from_str(s).unwrap(); + let _req = serde_json::from_value::(value).unwrap(); + } #[test] fn test_serde_custom_set_storage_at() { let s = r#"{"method": "anvil_setStorageAt", "params": ["0x295a70b2de5e3953354a6a8344e616ed314d7251", "0x0", -"0x0000000000000000000000000000000000000000000000000000000000003039"]}"#; let value: -serde_json::Value = serde_json::from_str(s).unwrap(); let _req = -serde_json::from_value::(value).unwrap(); +"0x0000000000000000000000000000000000000000000000000000000000003039"]}"#; + let value: serde_json::Value = serde_json::from_str(s).unwrap(); + let _req = serde_json::from_value::(value).unwrap(); let s = r#"{"method": "hardhat_setStorageAt", "params": ["0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56", "0xa6eef7e35abe7026729641147f7915573c7e97b47efa546f5f6e3230263bcb49", -"0x0000000000000000000000000000000000000000000000000000000000003039"]}"#; let value: -serde_json::Value = serde_json::from_str(s).unwrap(); let _req = -serde_json::from_value::(value).unwrap(); } +"0x0000000000000000000000000000000000000000000000000000000000003039"]}"#; + let value: serde_json::Value = serde_json::from_str(s).unwrap(); + let _req = serde_json::from_value::(value).unwrap(); + } #[test] fn test_serde_custom_coinbase() { let s = r#"{"method": "anvil_setCoinbase", "params": -["0x295a70b2de5e3953354a6a8344e616ed314d7251"]}"#; let value: serde_json::Value = -serde_json::from_str(s).unwrap(); let _req = -serde_json::from_value::(value).unwrap(); } +["0x295a70b2de5e3953354a6a8344e616ed314d7251"]}"#; + let value: serde_json::Value = serde_json::from_str(s).unwrap(); + let _req = serde_json::from_value::(value).unwrap(); + } #[test] fn test_serde_custom_logging() { @@ -1304,23 +1335,23 @@ serde_json::from_value::(value).unwrap(); } #[test] fn test_eth_uncle_count_by_block_hash() { - let s = r#"{"jsonrpc":"2.0","method":"eth_getUncleCountByBlockHash","params":["0x4a3b0fce2cb9707b0baa68640cf2fe858c8bb4121b2a8cb904ff369d38a560ff"]}"#; - let value: serde_json::Value = serde_json::from_str(s).unwrap(); - let _req = serde_json::from_value::(value).unwrap(); + let s = r#"{"jsonrpc":"2.0","method":"eth_getUncleCountByBlockHash","params":["0x4a3b0fce2cb9707b0baa68640cf2fe858c8bb4121b2a8cb904ff369d38a560ff"]}"#; + let value: serde_json::Value = serde_json::from_str(s).unwrap(); + let _req = serde_json::from_value::(value).unwrap(); } #[test] fn test_eth_block_tx_count_by_block_hash() { - let s = r#"{"jsonrpc":"2.0","method":"eth_getBlockTransactionCountByHash","params":["0x4a3b0fce2cb9707b0baa68640cf2fe858c8bb4121b2a8cb904ff369d38a560ff"]}"#; - let value: serde_json::Value = serde_json::from_str(s).unwrap(); - let _req = serde_json::from_value::(value).unwrap(); + let s = r#"{"jsonrpc":"2.0","method":"eth_getBlockTransactionCountByHash","params":["0x4a3b0fce2cb9707b0baa68640cf2fe858c8bb4121b2a8cb904ff369d38a560ff"]}"#; + let value: serde_json::Value = serde_json::from_str(s).unwrap(); + let _req = serde_json::from_value::(value).unwrap(); } #[test] fn test_eth_get_logs() { - let s = r#"{"jsonrpc":"2.0","method":"eth_getLogs","params":[{"topics":["0x000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b"]}],"id":74}"#; - let value: serde_json::Value = serde_json::from_str(s).unwrap(); - let _req = serde_json::from_value::(value).unwrap(); + let s = r#"{"jsonrpc":"2.0","method":"eth_getLogs","params":[{"topics":["0x000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b"]}],"id":74}"#; + let value: serde_json::Value = serde_json::from_str(s).unwrap(); + let _req = serde_json::from_value::(value).unwrap(); } #[test] @@ -1333,9 +1364,10 @@ serde_json::from_value::(value).unwrap(); } #[test] fn test_serde_eth_unsubscribe() { let s = r#"{"id": 1, "method": "eth_unsubscribe", "params": -["0x9cef478923ff08bf67fde6c64013158d"]}"#; let value: serde_json::Value = -serde_json::from_str(s).unwrap(); let _req = -serde_json::from_value::(value).unwrap(); } +["0x9cef478923ff08bf67fde6c64013158d"]}"#; + let value: serde_json::Value = serde_json::from_str(s).unwrap(); + let _req = serde_json::from_value::(value).unwrap(); + } #[test] fn test_serde_eth_subscribe() { @@ -1345,9 +1377,9 @@ serde_json::from_value::(value).unwrap(); } let s = r#"{"id": 1, "method": "eth_subscribe", "params": ["logs", {"address": "0x8320fe7702b96808f7bbc0d4a888ed1468216cfd", "topics": -["0xd78a0cb8bb633d06981248b816e7bd33c2a35a6089241d099fa519e361cab902"]}]}"#; let value: -serde_json::Value = serde_json::from_str(s).unwrap(); let _req = -serde_json::from_value::(value).unwrap(); +["0xd78a0cb8bb633d06981248b816e7bd33c2a35a6089241d099fa519e361cab902"]}]}"#; + let value: serde_json::Value = serde_json::from_str(s).unwrap(); + let _req = serde_json::from_value::(value).unwrap(); let s = r#"{"id": 1, "method": "eth_subscribe", "params": ["newPendingTransactions"]}"#; let value: serde_json::Value = serde_json::from_str(s).unwrap(); @@ -1361,18 +1393,19 @@ serde_json::from_value::(value).unwrap(); #[test] fn test_serde_debug_trace_transaction() { let s = r#"{"method": "debug_traceTransaction", "params": -["0x4a3b0fce2cb9707b0baa68640cf2fe858c8bb4121b2a8cb904ff369d38a560ff"]}"#; let value: -serde_json::Value = serde_json::from_str(s).unwrap(); let _req = -serde_json::from_value::(value).unwrap(); +["0x4a3b0fce2cb9707b0baa68640cf2fe858c8bb4121b2a8cb904ff369d38a560ff"]}"#; + let value: serde_json::Value = serde_json::from_str(s).unwrap(); + let _req = serde_json::from_value::(value).unwrap(); let s = r#"{"method": "debug_traceTransaction", "params": -["0x4a3b0fce2cb9707b0baa68640cf2fe858c8bb4121b2a8cb904ff369d38a560ff", {}]}"#; let value: -serde_json::Value = serde_json::from_str(s).unwrap(); let _req = -serde_json::from_value::(value).unwrap(); +["0x4a3b0fce2cb9707b0baa68640cf2fe858c8bb4121b2a8cb904ff369d38a560ff", {}]}"#; + let value: serde_json::Value = serde_json::from_str(s).unwrap(); + let _req = serde_json::from_value::(value).unwrap(); let s = r#"{"method": "debug_traceTransaction", "params": ["0x4a3b0fce2cb9707b0baa68640cf2fe858c8bb4121b2a8cb904ff369d38a560ff", {"disableStorage": -true}]}"#; let value: serde_json::Value = serde_json::from_str(s).unwrap(); +true}]}"#; + let value: serde_json::Value = serde_json::from_str(s).unwrap(); let _req = serde_json::from_value::(value).unwrap(); } @@ -1402,36 +1435,37 @@ true}]}"#; let value: serde_json::Value = serde_json::from_str(s).unwrap #[test] fn test_serde_eth_storage() { let s = r#"{"method": "eth_getStorageAt", "params": -["0x295a70b2de5e3953354a6a8344e616ed314d7251", "0x0", "latest"]}"#; let value: -serde_json::Value = serde_json::from_str(s).unwrap(); let _req = -serde_json::from_value::(value).unwrap(); } +["0x295a70b2de5e3953354a6a8344e616ed314d7251", "0x0", "latest"]}"#; + let value: serde_json::Value = serde_json::from_str(s).unwrap(); + let _req = serde_json::from_value::(value).unwrap(); + } #[test] fn test_eth_call() { let req = r#"{"data":"0xcfae3217","from":"0xd84de507f3fada7df80908082d3239466db55a71","to":"0xcbe828fdc46e3b1c351ec90b1a5e7d9742c0398d"}"#; -let _req =serde_json::from_str::(req).unwrap(); + let _req = serde_json::from_str::(req).unwrap(); - let s = r#"{"method": "eth_call", "params":[{"data":"0xcfae3217","from":"0xd84de507f3fada7df80908082d3239466db55a71","to":"0xcbe828fdc46e3b1c351ec90b1a5e7d9742c0398d"},"latest"]}"#; + let s = r#"{"method": "eth_call", "params":[{"data":"0xcfae3217","from":"0xd84de507f3fada7df80908082d3239466db55a71","to":"0xcbe828fdc46e3b1c351ec90b1a5e7d9742c0398d"},"latest"]}"#; let _req = serde_json::from_str::(s).unwrap(); let s = r#"{"method": "eth_call", "params":[{"data":"0xcfae3217","from":"0xd84de507f3fada7df80908082d3239466db55a71","to":"0xcbe828fdc46e3b1c351ec90b1a5e7d9742c0398d"}]}"#; let _req = serde_json::from_str::(s).unwrap(); - let s = r#"{"method": "eth_call", "params":[{"data":"0xcfae3217","from":"0xd84de507f3fada7df80908082d3239466db55a71","to":"0xcbe828fdc46e3b1c351ec90b1a5e7d9742c0398d"}, { "blockNumber": "latest" }]}"#; + let s = r#"{"method": "eth_call", "params":[{"data":"0xcfae3217","from":"0xd84de507f3fada7df80908082d3239466db55a71","to":"0xcbe828fdc46e3b1c351ec90b1a5e7d9742c0398d"}, { "blockNumber": "latest" }]}"#; let _req = serde_json::from_str::(s).unwrap(); - let s = r#"{"method": "eth_call", "params":[{"data":"0xcfae3217","from":"0xd84de507f3fada7df80908082d3239466db55a71","to":"0xcbe828fdc46e3b1c351ec90b1a5e7d9742c0398d"}, { "blockNumber": "0x0" }]}"#; + let s = r#"{"method": "eth_call", "params":[{"data":"0xcfae3217","from":"0xd84de507f3fada7df80908082d3239466db55a71","to":"0xcbe828fdc46e3b1c351ec90b1a5e7d9742c0398d"}, { "blockNumber": "0x0" }]}"#; let _req = serde_json::from_str::(s).unwrap(); - let s = r#"{"method": "eth_call", "params":[{"data":"0xcfae3217","from":"0xd84de507f3fada7df80908082d3239466db55a71","to":"0xcbe828fdc46e3b1c351ec90b1a5e7d9742c0398d"}, { "blockHash":"0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3" }]}"#; - let _req = serde_json::from_str::(s).unwrap(); + let s = r#"{"method": "eth_call", "params":[{"data":"0xcfae3217","from":"0xd84de507f3fada7df80908082d3239466db55a71","to":"0xcbe828fdc46e3b1c351ec90b1a5e7d9742c0398d"}, { "blockHash":"0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3" }]}"#; + let _req = serde_json::from_str::(s).unwrap(); } #[test] fn test_serde_eth_balance() { let s = r#"{"method": "eth_getBalance", "params": -["0x295a70b2de5e3953354a6a8344e616ed314d7251", "latest"]}"#; let value: serde_json::Value -= serde_json::from_str(s).unwrap(); +["0x295a70b2de5e3953354a6a8344e616ed314d7251", "latest"]}"#; + let value: serde_json::Value = serde_json::from_str(s).unwrap(); let _req = serde_json::from_value::(value).unwrap(); } diff --git a/crates/anvil/core/src/eth/serde_helpers.rs b/crates/anvil/core/src/eth/serde_helpers.rs index fd52698ee979..f7d5bd46dba2 100644 --- a/crates/anvil/core/src/eth/serde_helpers.rs +++ b/crates/anvil/core/src/eth/serde_helpers.rs @@ -55,7 +55,7 @@ pub mod empty_params { /// A module that deserializes either a BlockNumberOrTag, or a simple number. pub mod lenient_block_number { use alloy_rpc_types::BlockNumberOrTag; - use serde::{Deserializer, Deserialize}; + use serde::{Deserialize, Deserializer}; /// Following the spec the block parameter is either: /// /// > HEX String - an integer block number @@ -69,8 +69,8 @@ pub mod lenient_block_number { /// /// /// - /// EIP-1898 does not all calls that use `BlockNumber` like `eth_getBlockByNumber` and doesn't list - /// raw integers as supported. + /// EIP-1898 does not all calls that use `BlockNumber` like `eth_getBlockByNumber` and doesn't + /// list raw integers as supported. /// /// However, there are dev node implementations that support integers, such as ganache: /// @@ -107,4 +107,4 @@ pub mod lenient_block_number { } } } -} \ No newline at end of file +} diff --git a/crates/anvil/core/src/eth/state.rs b/crates/anvil/core/src/eth/state.rs index 128941f34771..1a1b9da3308a 100644 --- a/crates/anvil/core/src/eth/state.rs +++ b/crates/anvil/core/src/eth/state.rs @@ -13,4 +13,4 @@ pub struct AccountOverride { pub state_diff: Option>, } -pub type StateOverride = HashMap; \ No newline at end of file +pub type StateOverride = HashMap; diff --git a/crates/anvil/core/src/eth/transaction/ethers_compat.rs b/crates/anvil/core/src/eth/transaction/ethers_compat.rs index 5f51136a4950..34f9c0e7f002 100644 --- a/crates/anvil/core/src/eth/transaction/ethers_compat.rs +++ b/crates/anvil/core/src/eth/transaction/ethers_compat.rs @@ -3,21 +3,24 @@ use super::EthTransactionRequest; use crate::eth::{ proof::AccountProof, + state::{AccountOverride, StateOverride as EthStateOverride}, transaction::{ - EIP1559TransactionRequest, EIP2930TransactionRequest, LegacyTransactionRequest, - MaybeImpersonatedTransaction, TypedTransaction, TypedTransactionRequest, - DepositTransactionRequest, - }, state::{StateOverride as EthStateOverride, AccountOverride}, + DepositTransactionRequest, EIP1559TransactionRequest, EIP2930TransactionRequest, + LegacyTransactionRequest, MaybeImpersonatedTransaction, TypedTransaction, + TypedTransactionRequest, + }, }; use alloy_primitives::{U128 as rU128, U256 as rU256, U64 as rU64}; use alloy_rpc_types::{ + state::{AccountOverride as AlloyAccountOverride, StateOverride}, AccessList as AlloyAccessList, CallRequest, Signature, Transaction as AlloyTransaction, - TransactionRequest as AlloyTransactionRequest, state::{StateOverride, AccountOverride as AlloyAccountOverride}, + TransactionRequest as AlloyTransactionRequest, }; use ethers_core::types::{ transaction::{ eip2718::TypedTransaction as EthersTypedTransactionRequest, - eip2930::{AccessList, AccessListItem}, optimism::DepositTransaction, + eip2930::{AccessList, AccessListItem}, + optimism::DepositTransaction, }, Address, BigEndianHash, Eip1559TransactionRequest as EthersEip1559TransactionRequest, Eip2930TransactionRequest as EthersEip2930TransactionRequest, NameOrAddress, StorageProof, @@ -117,24 +120,52 @@ pub fn from_ethers_access_list(access_list: AccessList) -> AlloyAccessList { pub fn to_ethers_state_override(ov: StateOverride) -> EthStateOverride { ov.into_iter() - .map(|(addr, o)| (addr.to_ethers(), AccountOverride { - nonce: o.nonce.map(|n| n.to::()), - balance: o.balance.map(|b| b.to_ethers()), - code: o.code.map(|c| c.0.into()), - state_diff: o.state_diff.map(|s| s.into_iter().map(|(k, v)| (k.to_ethers(), H256::from_uint(&v.to_ethers()))).collect()), - state: o.state.map(|s| s.into_iter().map(|(k, v)| (k.to_ethers(), H256::from_uint(&v.to_ethers()))).collect()), - })).collect() + .map(|(addr, o)| { + ( + addr.to_ethers(), + AccountOverride { + nonce: o.nonce.map(|n| n.to::()), + balance: o.balance.map(|b| b.to_ethers()), + code: o.code.map(|c| c.0.into()), + state_diff: o.state_diff.map(|s| { + s.into_iter() + .map(|(k, v)| (k.to_ethers(), H256::from_uint(&v.to_ethers()))) + .collect() + }), + state: o.state.map(|s| { + s.into_iter() + .map(|(k, v)| (k.to_ethers(), H256::from_uint(&v.to_ethers()))) + .collect() + }), + }, + ) + }) + .collect() } pub fn to_alloy_state_override(ov: EthStateOverride) -> StateOverride { ov.into_iter() - .map(|(addr, o)| (addr.to_alloy(), AlloyAccountOverride { - nonce: o.nonce.map(rU64::from), - balance: o.balance.map(|b| b.to_alloy()), - code: o.code.map(|c| c.0.into()), - state_diff: o.state_diff.map(|s| s.into_iter().map(|(k, v)| (k.to_alloy(), rU256::from_be_bytes(v.to_alloy().0))).collect()), - state: o.state.map(|s| s.into_iter().map(|(k, v)| (k.to_alloy(), rU256::from_be_bytes(v.to_alloy().0))).collect()), - })).collect() + .map(|(addr, o)| { + ( + addr.to_alloy(), + AlloyAccountOverride { + nonce: o.nonce.map(rU64::from), + balance: o.balance.map(|b| b.to_alloy()), + code: o.code.map(|c| c.0.into()), + state_diff: o.state_diff.map(|s| { + s.into_iter() + .map(|(k, v)| (k.to_alloy(), rU256::from_be_bytes(v.to_alloy().0))) + .collect() + }), + state: o.state.map(|s| { + s.into_iter() + .map(|(k, v)| (k.to_alloy(), rU256::from_be_bytes(v.to_alloy().0))) + .collect() + }), + }, + ) + }) + .collect() } impl From for EthersTypedTransactionRequest { @@ -455,7 +486,7 @@ fn to_alloy_transaction_with_hash_and_sender( transaction_type: None, max_fee_per_blob_gas: None, blob_versioned_hashes: vec![], - } + }, } } diff --git a/crates/anvil/core/src/eth/transaction/mod.rs b/crates/anvil/core/src/eth/transaction/mod.rs index b20e31046996..7d7122ecd6b1 100644 --- a/crates/anvil/core/src/eth/transaction/mod.rs +++ b/crates/anvil/core/src/eth/transaction/mod.rs @@ -26,8 +26,8 @@ use std::ops::Deref; mod ethers_compat; pub use ethers_compat::{ - call_to_internal_tx_request, from_ethers_access_list, to_alloy_proof, to_ethers_access_list, - to_internal_tx_request, to_ethers_state_override, to_alloy_state_override + call_to_internal_tx_request, from_ethers_access_list, to_alloy_proof, to_alloy_state_override, + to_ethers_access_list, to_ethers_state_override, to_internal_tx_request, }; /// The signature used to bypass signing via the `eth_sendUnsignedTransaction` cheat RPC diff --git a/crates/anvil/core/src/types.rs b/crates/anvil/core/src/types.rs index 3b0faccbeefb..87ce8418b392 100644 --- a/crates/anvil/core/src/types.rs +++ b/crates/anvil/core/src/types.rs @@ -1,6 +1,6 @@ use alloy_primitives::{TxHash, B256, U256, U64}; -use std::collections::BTreeMap; use revm::primitives::SpecId; +use std::collections::BTreeMap; #[cfg(feature = "serde")] use serde::{de::Error, Deserializer, Serializer}; diff --git a/crates/anvil/src/cmd.rs b/crates/anvil/src/cmd.rs index 210e8803eda6..ca0be1ec6d0f 100644 --- a/crates/anvil/src/cmd.rs +++ b/crates/anvil/src/cmd.rs @@ -4,15 +4,15 @@ use crate::{ genesis::Genesis, AccountGenerator, Hardfork, NodeConfig, CHAIN_ID, }; +use alloy_primitives::U256; use anvil_server::ServerConfig; use clap::Parser; -use foundry_common::types::ToAlloy; use core::fmt; use ethers::{ signers::coins_bip39::{English, Mnemonic}, utils::WEI_IN_ETHER, }; -use alloy_primitives::U256; +use foundry_common::types::ToAlloy; use foundry_config::{Chain, Config}; use futures::FutureExt; use rand::{rngs::StdRng, SeedableRng}; diff --git a/crates/anvil/src/config.rs b/crates/anvil/src/config.rs index ab87ff72fe5b..acaa2ced7b24 100644 --- a/crates/anvil/src/config.rs +++ b/crates/anvil/src/config.rs @@ -30,9 +30,9 @@ use ethers::{ utils::{format_ether, hex, to_checksum, WEI_IN_ETHER}, }; use foundry_common::{ - provider::alloy::ProviderBuilder, types::{ToAlloy, ToEthers}, - ALCHEMY_FREE_TIER_CUPS, NON_ARCHIVE_NODE_WARNING, - REQUEST_TIMEOUT, + provider::alloy::ProviderBuilder, + types::{ToAlloy, ToEthers}, + ALCHEMY_FREE_TIER_CUPS, NON_ARCHIVE_NODE_WARNING, REQUEST_TIMEOUT, }; use foundry_config::Config; use foundry_evm::{ @@ -824,7 +824,11 @@ impl NodeConfig { }, tx: TxEnv { chain_id: self.get_chain_id().into(), ..Default::default() }, }; - let fees = FeeManager::new(env.cfg.spec_id, self.get_base_fee().to_ethers(), self.get_gas_price().to_ethers()); + let fees = FeeManager::new( + env.cfg.spec_id, + self.get_base_fee().to_ethers(), + self.get_gas_price().to_ethers(), + ); let (db, fork): (Arc>>, Option) = if let Some(eth_rpc_url) = self.eth_rpc_url.clone() { diff --git a/crates/anvil/src/eth/api.rs b/crates/anvil/src/eth/api.rs index dc0e2d65fdc3..f1d2f27813da 100644 --- a/crates/anvil/src/eth/api.rs +++ b/crates/anvil/src/eth/api.rs @@ -9,8 +9,7 @@ use crate::{ validate::TransactionValidator, }, error::{ - BlockchainError, FeeHistoryError, InvalidTransactionError, - Result, ToRpcResponseResult, + BlockchainError, FeeHistoryError, InvalidTransactionError, Result, ToRpcResponseResult, }, fees::{FeeDetails, FeeHistoryCache}, macros::node_info, @@ -30,7 +29,6 @@ use crate::{ ClientFork, LoggingManager, Miner, MiningMode, StorageInfo, }; use alloy_primitives::{Address, Bytes, TxHash, B256, B64, U256, U64}; -use alloy_transport::TransportErrorKind; use alloy_rpc_types::{ state::StateOverride, AccessList, @@ -55,6 +53,7 @@ use alloy_rpc_types::{ TxpoolInspectSummary, TxpoolStatus, }; +use alloy_transport::TransportErrorKind; use anvil_core::{ eth::{ block::BlockInfo, @@ -73,15 +72,13 @@ use anvil_core::{ use anvil_rpc::{error::RpcError, response::ResponseResult}; use ethers::{ prelude::DefaultFrame, - types::{ - transaction::eip712::TypedData, - GethDebugTracingOptions, - GethTrace, - Trace, - }, + types::{transaction::eip712::TypedData, GethDebugTracingOptions, GethTrace, Trace}, utils::rlp, }; -use foundry_common::provider::alloy::ProviderBuilder; +use foundry_common::{ + provider::alloy::ProviderBuilder, + types::{ToAlloy, ToEthers}, +}; use foundry_evm::{ backend::DatabaseError, revm::{ @@ -90,7 +87,6 @@ use foundry_evm::{ primitives::BlockEnv, }, }; -use foundry_common::types::{ToAlloy, ToEthers}; use futures::channel::{mpsc::Receiver, oneshot}; use parking_lot::RwLock; use std::{collections::HashSet, future::Future, sync::Arc, time::Duration}; @@ -300,10 +296,9 @@ impl EthApi { self.anvil_auto_impersonate_account(enable).await.to_rpc_result() } EthRequest::GetAutoMine(()) => self.anvil_get_auto_mine().to_rpc_result(), - EthRequest::Mine(blocks, interval) => self - .anvil_mine(blocks, interval) - .await - .to_rpc_result(), + EthRequest::Mine(blocks, interval) => { + self.anvil_mine(blocks, interval).await.to_rpc_result() + } EthRequest::SetAutomine(enabled) => { self.anvil_set_auto_mine(enabled).await.to_rpc_result() } @@ -343,19 +338,21 @@ impl EthApi { EthRequest::AnvilMetadata(_) => self.anvil_metadata().await.to_rpc_result(), EthRequest::EvmSnapshot(_) => self.evm_snapshot().await.to_rpc_result(), EthRequest::EvmRevert(id) => self.evm_revert(id).await.to_rpc_result(), - EthRequest::EvmIncreaseTime(time) => { - self.evm_increase_time(time).await.to_rpc_result() - } + EthRequest::EvmIncreaseTime(time) => self.evm_increase_time(time).await.to_rpc_result(), EthRequest::EvmSetNextBlockTimeStamp(time) => { if time >= U256::from(u64::MAX) { - return ResponseResult::Error(RpcError::invalid_params("The timestamp is too big")) + return ResponseResult::Error(RpcError::invalid_params( + "The timestamp is too big", + )) } let time = time.to::(); self.evm_set_next_block_timestamp(time).to_rpc_result() } EthRequest::EvmSetTime(timestamp) => { if timestamp >= U256::from(u64::MAX) { - return ResponseResult::Error(RpcError::invalid_params("The timestamp is too big")) + return ResponseResult::Error(RpcError::invalid_params( + "The timestamp is too big", + )) } let time = timestamp.to::(); self.evm_set_time(time).to_rpc_result() @@ -420,10 +417,9 @@ impl EthApi { EthRequest::OtsSearchTransactionsAfter(address, num, page_size) => { self.ots_search_transactions_after(address, num, page_size).await.to_rpc_result() } - EthRequest::OtsGetTransactionBySenderAndNonce(address, nonce) => self - .ots_get_transaction_by_sender_and_nonce(address, nonce) - .await - .to_rpc_result(), + EthRequest::OtsGetTransactionBySenderAndNonce(address, nonce) => { + self.ots_get_transaction_by_sender_and_nonce(address, nonce).await.to_rpc_result() + } EthRequest::OtsGetContractCreator(address) => { self.ots_get_contract_creator(address).await.to_rpc_result() } @@ -437,14 +433,18 @@ impl EthApi { ) -> Result { match request { TypedTransactionRequest::Deposit(_) => { - const NIL_SIGNATURE: ethers::types::Signature = - ethers::types::Signature { r: ethers::types::U256::zero(), s: ethers::types::U256::zero(), v: 0 }; + const NIL_SIGNATURE: ethers::types::Signature = ethers::types::Signature { + r: ethers::types::U256::zero(), + s: ethers::types::U256::zero(), + v: 0, + }; return build_typed_transaction(request, NIL_SIGNATURE) } _ => { for signer in self.signers.iter() { if signer.accounts().contains(&from.to_ethers()) { - let signature = signer.sign_transaction(request.clone(), &from.to_ethers())?; + let signature = + signer.sign_transaction(request.clone(), &from.to_ethers())?; return build_typed_transaction(request, signature) } } @@ -864,16 +864,15 @@ impl EthApi { /// Signs a transaction /// /// Handler for ETH RPC call: `eth_signTransaction` - pub async fn sign_transaction(&self, request: AlloyTransactionRequest) -> Result { + pub async fn sign_transaction(&self, request: EthTransactionRequest) -> Result { node_info!("eth_signTransaction"); let from = request.from.map(Ok).unwrap_or_else(|| { - self.accounts()?.first().cloned().ok_or(BlockchainError::NoSignerAvailable) - })?; + self.accounts()?.first().cloned().ok_or(BlockchainError::NoSignerAvailable).map(|a| a.to_ethers()) + })?.to_alloy(); let (nonce, _) = self.request_nonce(&request, from).await?; - let request = to_internal_tx_request(&request); let request = self.build_typed_tx_request(request, nonce)?; let signer = self.get_signer(from).ok_or(BlockchainError::NoSignerAvailable)?; @@ -884,15 +883,14 @@ impl EthApi { /// Sends a transaction /// /// Handler for ETH RPC call: `eth_sendTransaction` - pub async fn send_transaction(&self, request: AlloyTransactionRequest) -> Result { + pub async fn send_transaction(&self, request: EthTransactionRequest) -> Result { node_info!("eth_sendTransaction"); let from = request.from.map(Ok).unwrap_or_else(|| { - self.accounts()?.first().cloned().ok_or(BlockchainError::NoSignerAvailable) - })?; + self.accounts()?.first().cloned().ok_or(BlockchainError::NoSignerAvailable).map(|a| a.to_ethers()) + })?.to_alloy(); let (nonce, on_chain_nonce) = self.request_nonce(&request, from).await?; - let request = to_internal_tx_request(&request); let request = self.build_typed_tx_request(request, nonce)?; // if the sender is currently impersonated we need to "bypass" signing let pending_transaction = if self.is_impersonated(from) { @@ -1275,11 +1273,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, BlockNumber::Number(number), &reward_percentiles) .await .map_err(|_| BlockchainError::DataUnavailable); } @@ -1964,7 +1958,11 @@ impl EthApi { // let interval = config.provider.get_interval(); let new_provider = Arc::new( ProviderBuilder::new(&url).max_retry(10).initial_backoff(1000).build().map_err( - |_| TransportErrorKind::custom_str(format!("Failed to parse invalid url {url}").as_str()), + |_| { + TransportErrorKind::custom_str( + format!("Failed to parse invalid url {url}").as_str(), + ) + }, // TODO: Add interval )?, // .interval(interval), ); @@ -1989,16 +1987,14 @@ impl EthApi { /// Handler for ETH RPC call: `eth_sendUnsignedTransaction` pub async fn eth_send_unsigned_transaction( &self, - request: AlloyTransactionRequest, + request: EthTransactionRequest, ) -> Result { node_info!("eth_sendUnsignedTransaction"); // either use the impersonated account of the request's `from` field - let from = request.from.ok_or(BlockchainError::NoSignerAvailable)?; + let from = request.from.ok_or(BlockchainError::NoSignerAvailable)?.to_alloy(); let (nonce, on_chain_nonce) = self.request_nonce(&request, from).await?; - let request = to_internal_tx_request(&request); - let request = self.build_typed_tx_request(request, nonce)?; let bypass_signature = self.backend.cheats().bypass_signature(); @@ -2574,12 +2570,12 @@ impl EthApi { /// This will also check the tx pool for pending transactions from the sender. async fn request_nonce( &self, - request: &AlloyTransactionRequest, + request: &EthTransactionRequest, from: Address, ) -> Result<(U256, U256)> { 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.map(|n| n.to_alloy()).unwrap_or(highest_nonce); Ok((nonce, highest_nonce)) } diff --git a/crates/anvil/src/eth/backend/genesis.rs b/crates/anvil/src/eth/backend/genesis.rs index 1b9c68bcf935..816659fdadaf 100644 --- a/crates/anvil/src/eth/backend/genesis.rs +++ b/crates/anvil/src/eth/backend/genesis.rs @@ -63,11 +63,7 @@ impl GenesisConfig { db.insert_account(addr, acc.into()); // insert all storage values for (k, v) in storage.iter() { - db.set_storage_at( - addr, - U256::from_be_bytes(k.0), - U256::from_be_bytes(v.0), - )?; + db.set_storage_at(addr, U256::from_be_bytes(k.0), U256::from_be_bytes(v.0))?; } } } @@ -117,16 +113,10 @@ impl<'a> DatabaseRef for AtGenesisStateDb<'a> { } fn storage_ref(&self, address: Address, index: U256) -> DatabaseResult { - if let Some(acc) = self - .genesis - .as_ref() - .and_then(|genesis| genesis.alloc.accounts.get(&(address))) + if let Some(acc) = + self.genesis.as_ref().and_then(|genesis| genesis.alloc.accounts.get(&(address))) { - let value = acc - .storage - .get(&B256::from(index)) - .copied() - .unwrap_or_default(); + let value = acc.storage.get(&B256::from(index)).copied().unwrap_or_default(); return Ok(U256::from_be_bytes(value.0)) } self.db.storage_ref(address, index) diff --git a/crates/anvil/src/eth/backend/mem/mod.rs b/crates/anvil/src/eth/backend/mem/mod.rs index 91ca19ebe1cc..204b1f7a8ef7 100644 --- a/crates/anvil/src/eth/backend/mem/mod.rs +++ b/crates/anvil/src/eth/backend/mem/mod.rs @@ -1377,10 +1377,7 @@ impl Backend { } if let Some(fork) = self.get_fork() { - return fork - .block_by_hash(hash) - .await - .map_err(|_| BlockchainError::DataUnavailable); + return fork.block_by_hash(hash).await.map_err(|_| BlockchainError::DataUnavailable); } Ok(None) @@ -1506,8 +1503,8 @@ impl Backend { BlockNumber::Finalized => { if storage.best_number.to_ethers() > (slots_in_an_epoch.to_ethers() * 2) { *storage.hashes.get( - &(storage.best_number.to_ethers() - - (slots_in_an_epoch.to_ethers() * 2)) + &(storage.best_number.to_ethers() - + (slots_in_an_epoch.to_ethers() * 2)) .to_alloy(), )? } else { @@ -2303,8 +2300,8 @@ impl TransactionValidator for Backend { if chain_id.to::() != tx_chain_id { if let Some(legacy) = tx.as_legacy() { // - if env.cfg.spec_id >= SpecId::SPURIOUS_DRAGON - && !legacy.meets_eip155(chain_id.to::()) + if env.cfg.spec_id >= SpecId::SPURIOUS_DRAGON && + !legacy.meets_eip155(chain_id.to::()) { warn!(target: "backend", ?chain_id, ?tx_chain_id, "incompatible EIP155-based V"); return Err(InvalidTransactionError::IncompatibleEIP155); @@ -2410,10 +2407,7 @@ pub fn transaction_build( 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::(), + base_fee.checked_add(max_priority_fee_per_gas).unwrap_or(U256::MAX).to::(), ); } } else { diff --git a/crates/anvil/src/eth/backend/mem/state.rs b/crates/anvil/src/eth/backend/mem/state.rs index a7b2a5d6f53b..d5a2d40a7a8b 100644 --- a/crates/anvil/src/eth/backend/mem/state.rs +++ b/crates/anvil/src/eth/backend/mem/state.rs @@ -5,6 +5,7 @@ use alloy_primitives::{Address, Bytes, B256, U256 as rU256}; use alloy_rpc_types::state::StateOverride; use anvil_core::eth::trie::RefSecTrieDBMut; use ethers::utils::{rlp, rlp::RlpStream}; +use foundry_common::types::ToEthers; use foundry_evm::{ backend::DatabaseError, hashbrown::HashMap as Map, @@ -13,7 +14,6 @@ use foundry_evm::{ primitives::{AccountInfo, Bytecode, Log}, }, }; -use foundry_common::types::ToEthers; use memory_db::HashKey; use trie_db::TrieMut; diff --git a/crates/anvil/src/eth/fees.rs b/crates/anvil/src/eth/fees.rs index a79bd2fbcfa5..89bc0b101d6b 100644 --- a/crates/anvil/src/eth/fees.rs +++ b/crates/anvil/src/eth/fees.rs @@ -4,8 +4,8 @@ use crate::eth::{ }; use anvil_core::eth::transaction::TypedTransaction; use ethers::types::{H256, U256}; -use foundry_evm::revm::primitives::SpecId; use foundry_common::types::ToAlloy; +use foundry_evm::revm::primitives::SpecId; use futures::StreamExt; use parking_lot::{Mutex, RwLock}; use std::{ diff --git a/crates/anvil/src/eth/otterscan/types.rs b/crates/anvil/src/eth/otterscan/types.rs index dcbfb220da30..df6cbef13290 100644 --- a/crates/anvil/src/eth/otterscan/types.rs +++ b/crates/anvil/src/eth/otterscan/types.rs @@ -5,8 +5,8 @@ use crate::eth::{ use alloy_primitives::{Address, Bytes, B256, U256 as rU256, U256}; use alloy_rpc_types::{Block, BlockTransactions, Transaction, TransactionReceipt}; use ethers::types::{Action, CallType, Trace}; -use foundry_evm::{revm::interpreter::InstructionResult, utils::CallKind}; use foundry_common::types::ToAlloy; +use foundry_evm::{revm::interpreter::InstructionResult, utils::CallKind}; use futures::future::join_all; use serde::Serialize; use serde_repr::Serialize_repr; @@ -183,11 +183,16 @@ impl OtsBlockTransactions { BlockTransactions::Uncle => return Err(BlockchainError::DataUnavailable), }; - let block_txs = block_txs.into_iter().skip(page * page_size).take(page_size).collect::>(); + let block_txs = + block_txs.into_iter().skip(page * page_size).take(page_size).collect::>(); block.transactions = match block.transactions { - BlockTransactions::Full(txs) => BlockTransactions::Full(txs.into_iter().skip(page * page_size).take(page_size).collect()), - BlockTransactions::Hashes(txs) => BlockTransactions::Hashes(txs.into_iter().skip(page * page_size).take(page_size).collect()), + BlockTransactions::Full(txs) => BlockTransactions::Full( + txs.into_iter().skip(page * page_size).take(page_size).collect(), + ), + BlockTransactions::Hashes(txs) => BlockTransactions::Hashes( + txs.into_iter().skip(page * page_size).take(page_size).collect(), + ), BlockTransactions::Uncle => return Err(BlockchainError::DataUnavailable), }; diff --git a/crates/anvil/src/genesis.rs b/crates/anvil/src/genesis.rs index a737ae223c0a..6e2d3bf92b6a 100644 --- a/crates/anvil/src/genesis.rs +++ b/crates/anvil/src/genesis.rs @@ -1,10 +1,7 @@ //! Bindings for geth's `genesis.json` format use crate::revm::primitives::AccountInfo; -use ethers::{ - signers::LocalWallet, - types::serde_helpers::*, -}; use alloy_primitives::{Address, Bytes, B256, U256}; +use ethers::{signers::LocalWallet, types::serde_helpers::*}; use foundry_common::errors::FsPathError; use foundry_evm::revm::primitives::{Bytecode, Env, KECCAK_EMPTY, U256 as rU256}; use serde::{Deserialize, Serialize}; @@ -58,10 +55,7 @@ pub struct Genesis { pub gas_used: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub parent_hash: Option, - #[serde( - default, - skip_serializing_if = "Option::is_none" - )] + #[serde(default, skip_serializing_if = "Option::is_none")] pub base_fee_per_gas: Option, } diff --git a/crates/anvil/src/lib.rs b/crates/anvil/src/lib.rs index 2a8abfbb3be9..fe4b72d26dd4 100644 --- a/crates/anvil/src/lib.rs +++ b/crates/anvil/src/lib.rs @@ -23,10 +23,14 @@ use ethers::{ signers::Signer, types::{Address, U256}, }; -use foundry_common::provider::alloy::{ProviderBuilder, RetryProvider}; -use foundry_common::provider::ethers::{ProviderBuilder as EthersProviderBuilder, RetryProvider as EthersRetryProvider}; +use foundry_common::{ + provider::{ + alloy::{ProviderBuilder, RetryProvider}, + ethers::{ProviderBuilder as EthersProviderBuilder, RetryProvider as EthersRetryProvider}, + }, + types::ToEthers, +}; use foundry_evm::revm; -use foundry_common::types::ToEthers; use futures::{FutureExt, TryFutureExt}; use parking_lot::Mutex; use std::{ @@ -277,7 +281,9 @@ impl NodeHandle { } pub fn ethers_http_provider(&self) -> EthersRetryProvider { - EthersProviderBuilder::new(&self.http_endpoint()).build().expect("failed to build ethers HTTP provider") + EthersProviderBuilder::new(&self.http_endpoint()) + .build() + .expect("failed to build ethers HTTP provider") } /// Constructs a [`RetryProvider`] for this handle's WS endpoint. @@ -286,7 +292,9 @@ impl NodeHandle { } pub fn ethers_ws_provider(&self) -> EthersRetryProvider { - EthersProviderBuilder::new(&self.ws_endpoint()).build().expect("failed to build ethers WS provider") + EthersProviderBuilder::new(&self.ws_endpoint()) + .build() + .expect("failed to build ethers WS provider") } /// Constructs a [`RetryProvider`] for this handle's IPC endpoint, if any. diff --git a/crates/anvil/src/pubsub.rs b/crates/anvil/src/pubsub.rs index 47686ca4f57a..6ae1d0682bb7 100644 --- a/crates/anvil/src/pubsub.rs +++ b/crates/anvil/src/pubsub.rs @@ -168,10 +168,10 @@ pub fn filter_logs( }; if params.filter.is_some() { let block_number = block.header.number.as_u64(); - if !params.filter_block_range(block_number) - || !params.filter_block_hash(block_hash) - || !params.filter_address(&log) - || !params.filter_topics(&log) + if !params.filter_block_range(block_number) || + !params.filter_block_hash(block_hash) || + !params.filter_address(&log) || + !params.filter_topics(&log) { return false; } @@ -190,7 +190,7 @@ pub fn filter_logs( } else { None }; - for log in receipt_logs.into_iter() { + for log in receipt_logs.into_iter() { if add_log(block_hash.to_alloy(), &log, &block, filter) { logs.push(AlloyLog { address: log.address.to_alloy(), diff --git a/crates/anvil/tests/it/api.rs b/crates/anvil/tests/it/api.rs index 8803687cb9ad..7a6a64ae379a 100644 --- a/crates/anvil/tests/it/api.rs +++ b/crates/anvil/tests/it/api.rs @@ -1,7 +1,8 @@ //! general eth api tests use crate::abi::{MulticallContract, SimpleStorage}; -use alloy_rpc_types::{CallRequest, CallInput}; +use alloy_primitives::U256 as rU256; +use alloy_rpc_types::{CallInput, CallRequest}; use anvil::{ eth::{api::CLIENT_VERSION, EthApi}, spawn, NodeConfig, CHAIN_ID, @@ -14,7 +15,6 @@ use ethers::{ types::{Block, BlockNumber, Chain, Transaction, TransactionRequest, H256, U256}, utils::get_contract_address, }; -use alloy_primitives::U256 as rU256; use foundry_common::types::ToAlloy; use std::{collections::HashMap, sync::Arc, time::Duration}; @@ -213,8 +213,12 @@ async fn can_call_on_pending_block() { .unwrap(); assert_eq!(block.header.gas_limit, block_gas_limit.to_alloy()); - let block_coinbase = - pending_contract.get_current_block_coinbase().block(block_number_ethers).call().await.unwrap(); + let block_coinbase = pending_contract + .get_current_block_coinbase() + .block(block_number_ethers) + .call() + .await + .unwrap(); assert_eq!(block.header.miner, block_coinbase.to_alloy()); } } diff --git a/crates/anvil/tests/it/gas.rs b/crates/anvil/tests/it/gas.rs index 24a8385b86bd..bf1c91c685ce 100644 --- a/crates/anvil/tests/it/gas.rs +++ b/crates/anvil/tests/it/gas.rs @@ -1,5 +1,6 @@ //! Gas related tests +use alloy_primitives::U256; use anvil::{eth::fees::INITIAL_BASE_FEE, spawn, NodeConfig}; use ethers::{ prelude::Middleware, @@ -8,7 +9,6 @@ use ethers::{ TransactionRequest, }, }; -use alloy_primitives::U256; use foundry_common::types::ToAlloy; const GAS_TRANSFER: u64 = 21_000u64; @@ -16,7 +16,9 @@ const GAS_TRANSFER: u64 = 21_000u64; #[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.to_alloy())) + .with_gas_limit(Some(GAS_TRANSFER.to_alloy())), ) .await; let provider = handle.ethers_http_provider(); @@ -55,7 +57,8 @@ async fn test_basefee_half_block() { } #[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.to_alloy()))).await; let provider = handle.ethers_http_provider(); let tx = TransactionRequest::new().to(Address::random()).value(1337u64); diff --git a/crates/anvil/tests/it/otterscan.rs b/crates/anvil/tests/it/otterscan.rs index 7c923f2f2204..ef4cfaf69c81 100644 --- a/crates/anvil/tests/it/otterscan.rs +++ b/crates/anvil/tests/it/otterscan.rs @@ -1,5 +1,7 @@ //! tests for otterscan endpoints use crate::abi::MulticallContract; +use alloy_primitives::U256 as rU256; +use alloy_rpc_types::{BlockNumberOrTag, BlockTransactions}; use anvil::{ eth::otterscan::types::{ OtsInternalOperation, OtsInternalOperationType, OtsTrace, OtsTraceType, @@ -13,10 +15,8 @@ use ethers::{ types::{Bytes, TransactionRequest, U256}, utils::get_contract_address, }; -use alloy_primitives::U256 as rU256; -use alloy_rpc_types::{BlockNumberOrTag, BlockTransactions}; -use foundry_common::types::{ToAlloy, ToEthers}; use ethers_solc::{project_util::TempProject, Artifact}; +use foundry_common::types::{ToAlloy, ToEthers}; use std::{collections::VecDeque, str::FromStr, sync::Arc}; #[tokio::test(flavor = "multi_thread")] @@ -148,7 +148,9 @@ contract Contract { res[0], OtsInternalOperation { r#type: OtsInternalOperationType::Create2, - from: Address::from_str("0x4e59b44847b379578588920cA78FbF26c0B4956C").unwrap().to_alloy(), + from: Address::from_str("0x4e59b44847b379578588920cA78FbF26c0B4956C") + .unwrap() + .to_alloy(), to: Address::from_str("0x347bcdad821abc09b8c275881b368de36476b62c").unwrap().to_alloy(), value: rU256::from(0) } @@ -240,11 +242,17 @@ async fn can_call_ots_has_code() { assert_eq!(num, receipt.block_number.unwrap()); // code is detected after deploying - assert!(api.ots_has_code(pending_contract_address.to_alloy(), BlockNumberOrTag::Number(num.as_u64())).await.unwrap()); + assert!(api + .ots_has_code(pending_contract_address.to_alloy(), BlockNumberOrTag::Number(num.as_u64())) + .await + .unwrap()); // code is not detected for the previous block assert!(!api - .ots_has_code(pending_contract_address.to_alloy(), BlockNumberOrTag::Number(num.as_u64() - 1)) + .ots_has_code( + pending_contract_address.to_alloy(), + BlockNumberOrTag::Number(num.as_u64() - 1) + ) .await .unwrap()); } @@ -389,7 +397,8 @@ contract Contract { let call = contract.method::<_, ()>("trigger_revert", ()).unwrap().gas(150_000u64); let receipt = call.send().await.unwrap().await.unwrap().unwrap(); - let res = api.ots_get_transaction_error(receipt.transaction_hash.to_alloy()).await.unwrap().unwrap(); + let res = + api.ots_get_transaction_error(receipt.transaction_hash.to_alloy()).await.unwrap().unwrap(); let res: Bytes = res.0.into(); assert_eq!(res, Bytes::from_str("0x8d6ea8be00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000012526576657274537472696e67466f6f4261720000000000000000000000000000").unwrap()); } @@ -411,7 +420,7 @@ async fn can_call_ots_get_block_details() { let hash = match result.block.block.transactions { BlockTransactions::Full(txs) => txs[0].hash, BlockTransactions::Hashes(hashes) => hashes[0], - BlockTransactions::Uncle => unreachable!() + BlockTransactions::Uncle => unreachable!(), }; assert_eq!(hash, receipt.transaction_hash.to_alloy()); } @@ -434,7 +443,7 @@ async fn can_call_ots_get_block_details_by_hash() { let hash = match result.block.block.transactions { BlockTransactions::Full(txs) => txs[0].hash, BlockTransactions::Hashes(hashes) => hashes[0], - BlockTransactions::Uncle => unreachable!() + BlockTransactions::Uncle => unreachable!(), }; assert_eq!(hash.to_ethers(), receipt.transaction_hash); } @@ -471,7 +480,10 @@ async fn can_call_ots_get_block_transactions() { result.receipts.iter().enumerate().for_each(|(i, receipt)| { let expected = hashes.pop_front(); assert_eq!(Some(expected), Some(receipt.transaction_hash.map(|h| h.to_ethers()))); - assert_eq!(Some(expected.map(|h| h.to_alloy())), Some(result.clone().fullblock.block.clone().transactions.iter().nth(i))); + assert_eq!( + Some(expected.map(|h| h.to_alloy())), + Some(result.clone().fullblock.block.clone().transactions.iter().nth(i)) + ); }); } @@ -498,7 +510,8 @@ async fn can_call_ots_search_transactions_before() { let page_size = 2; let mut block = 0; for _ in 0..4 { - let result = api.ots_search_transactions_before(sender.to_alloy(), block, page_size).await.unwrap(); + let result = + api.ots_search_transactions_before(sender.to_alloy(), block, page_size).await.unwrap(); assert!(result.txs.len() <= page_size); @@ -533,7 +546,8 @@ async fn can_call_ots_search_transactions_after() { let page_size = 2; let mut block = 0; for _ in 0..4 { - let result = api.ots_search_transactions_after(sender.to_alloy(), block, page_size).await.unwrap(); + let result = + api.ots_search_transactions_after(sender.to_alloy(), block, page_size).await.unwrap(); assert!(result.txs.len() <= page_size); @@ -564,8 +578,14 @@ async fn can_call_ots_get_transaction_by_sender_and_nonce() { let receipt1 = client.send_transaction(tx1, None).await.unwrap().await.unwrap().unwrap(); let receipt2 = client.send_transaction(tx2, None).await.unwrap().await.unwrap().unwrap(); - let result1 = api.ots_get_transaction_by_sender_and_nonce(sender.to_alloy(), rU256::from(0)).await.unwrap(); - let result2 = api.ots_get_transaction_by_sender_and_nonce(sender.to_alloy(), rU256::from(1)).await.unwrap(); + let result1 = api + .ots_get_transaction_by_sender_and_nonce(sender.to_alloy(), rU256::from(0)) + .await + .unwrap(); + let result2 = api + .ots_get_transaction_by_sender_and_nonce(sender.to_alloy(), rU256::from(1)) + .await + .unwrap(); assert_eq!(result1.unwrap().hash, receipt1.transaction_hash.to_alloy()); assert_eq!(result2.unwrap().hash, receipt2.transaction_hash.to_alloy()); @@ -588,7 +608,8 @@ async fn can_call_ots_get_contract_creator() { let receipt = client.send_transaction(deploy_tx, None).await.unwrap().await.unwrap().unwrap(); - let creator = api.ots_get_contract_creator(pending_contract_address.to_alloy()).await.unwrap().unwrap(); + let creator = + api.ots_get_contract_creator(pending_contract_address.to_alloy()).await.unwrap().unwrap(); assert_eq!(creator.creator, sender.to_alloy()); assert_eq!(creator.hash, receipt.transaction_hash.to_alloy()); diff --git a/crates/anvil/tests/it/proof/mod.rs b/crates/anvil/tests/it/proof/mod.rs index 1ed7e1c518d2..cbe803fb2817 100644 --- a/crates/anvil/tests/it/proof/mod.rs +++ b/crates/anvil/tests/it/proof/mod.rs @@ -3,17 +3,14 @@ use crate::proof::eip1186::verify_proof; use alloy_rpc_types::EIP1186AccountProofResponse; use anvil::{spawn, NodeConfig}; -use anvil_core::eth::{ - proof::BasicAccount, - trie::ExtensionLayout, -}; +use anvil_core::eth::{proof::BasicAccount, trie::ExtensionLayout}; use ethers::{ abi::ethereum_types::BigEndianHash, types::{Address, H256, U256}, utils::{keccak256, rlp}, }; +use foundry_common::types::{ToAlloy, ToEthers}; use foundry_evm::revm::primitives::KECCAK_EMPTY; -use foundry_common::types::{ToEthers, ToAlloy}; mod eip1186; @@ -26,9 +23,12 @@ async fn can_get_proof() { let key = U256::zero(); let value = U256::one(); - api.anvil_set_storage_at(acc.to_alloy(), key.to_alloy(), H256::from_uint(&value).to_alloy()).await.unwrap(); + api.anvil_set_storage_at(acc.to_alloy(), key.to_alloy(), H256::from_uint(&value).to_alloy()) + .await + .unwrap(); - let proof: EIP1186AccountProofResponse = api.get_proof(acc.to_alloy(), vec![H256::from_uint(&key).to_alloy()], None).await.unwrap(); + let proof: EIP1186AccountProofResponse = + api.get_proof(acc.to_alloy(), vec![H256::from_uint(&key).to_alloy()], None).await.unwrap(); let account = BasicAccount { nonce: 0.into(), @@ -59,7 +59,7 @@ async fn can_get_proof() { let proof = proof.storage_proof[0].clone(); let storage_proof: Vec> = proof.proof.into_iter().map(|node| rlp::decode::>(&node).unwrap()).collect(); - let key = H256::from(keccak256(proof.key.0.0)); + let key = H256::from(keccak256(proof.key.0 .0)); verify_proof::( &account.storage_root.0, &storage_proof, diff --git a/crates/anvil/tests/it/transaction.rs b/crates/anvil/tests/it/transaction.rs index 73c09cb9bd92..b93286debd6f 100644 --- a/crates/anvil/tests/it/transaction.rs +++ b/crates/anvil/tests/it/transaction.rs @@ -11,7 +11,7 @@ use ethers::{ Address, BlockNumber, Transaction, TransactionReceipt, H256, U256, }, }; -use foundry_common::types::{ToAlloy, ToEthers, to_call_request_from_tx_request}; +use foundry_common::types::{to_call_request_from_tx_request, ToAlloy, ToEthers}; use futures::{future::join_all, FutureExt, StreamExt}; use std::{collections::HashSet, sync::Arc, time::Duration}; use tokio::time::timeout; @@ -182,7 +182,8 @@ async fn can_reject_too_high_gas_limits() { pending.unwrap(); // send transaction with higher gas limit - let pending = provider.send_transaction(tx.clone().gas(gas_limit.to_ethers() + 1u64), None).await; + let pending = + provider.send_transaction(tx.clone().gas(gas_limit.to_ethers() + 1u64), None).await; assert!(pending.is_err()); let err = pending.unwrap_err(); @@ -414,7 +415,8 @@ async fn get_blocktimestamp_works() { assert!(timestamp > U256::one()); - let latest_block = api.block_by_number(alloy_rpc_types::BlockNumberOrTag::Latest).await.unwrap().unwrap(); + let latest_block = + 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()); diff --git a/crates/cast/bin/cmd/run.rs b/crates/cast/bin/cmd/run.rs index 9f82640c062f..676a19ee3ca1 100644 --- a/crates/cast/bin/cmd/run.rs +++ b/crates/cast/bin/cmd/run.rs @@ -98,8 +98,8 @@ impl RunArgs { .ok_or_else(|| eyre::eyre!("tx not found: {:?}", tx_hash))?; // check if the tx is a system transaction - if is_known_system_sender(tx.from.to_alloy()) - || tx.transaction_type.map(|ty| ty.as_u64()) == Some(SYSTEM_TRANSACTION_TYPE) + if is_known_system_sender(tx.from.to_alloy()) || + tx.transaction_type.map(|ty| ty.as_u64()) == Some(SYSTEM_TRANSACTION_TYPE) { return Err(eyre::eyre!( "{:?} is a system transaction.\nReplaying system transactions is currently not supported.", @@ -143,9 +143,9 @@ impl RunArgs { for (index, tx) in block.transactions.into_iter().enumerate() { // 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.to_alloy()) - || tx.transaction_type.map(|ty| ty.as_u64()) - == Some(SYSTEM_TRANSACTION_TYPE) + if is_known_system_sender(tx.from.to_alloy()) || + tx.transaction_type.map(|ty| ty.as_u64()) == + Some(SYSTEM_TRANSACTION_TYPE) { update_progress!(pb, index); continue; diff --git a/crates/cheatcodes/src/evm/fork.rs b/crates/cheatcodes/src/evm/fork.rs index c0cc125aca97..6dd373163b56 100644 --- a/crates/cheatcodes/src/evm/fork.rs +++ b/crates/cheatcodes/src/evm/fork.rs @@ -4,10 +4,9 @@ use alloy_providers::provider::TempProvider; use alloy_rpc_types::Filter; use alloy_sol_types::SolValue; use eyre::WrapErr; -use foundry_common::provider::alloy::ProviderBuilder; +use foundry_common::{provider::alloy::ProviderBuilder, types::ToEthers}; use foundry_compilers::utils::RuntimeOrHandle; use foundry_evm_core::fork::CreateFork; -use foundry_common::types::ToEthers; impl Cheatcode for activeForkCall { fn apply_full(&self, ccx: &mut CheatsCtxt) -> Result { diff --git a/crates/cheatcodes/src/inspector.rs b/crates/cheatcodes/src/inspector.rs index 1771d9d139d7..73a8002f7017 100644 --- a/crates/cheatcodes/src/inspector.rs +++ b/crates/cheatcodes/src/inspector.rs @@ -19,7 +19,7 @@ use ethers_core::types::{ transaction::eip2718::TypedTransaction, NameOrAddress, TransactionRequest, }; use ethers_signers::LocalWallet; -use foundry_common::{evm::Breakpoints, provider::alloy::RpcUrl, types::{ToEthers}}; +use foundry_common::{evm::Breakpoints, provider::alloy::RpcUrl, types::ToEthers}; use foundry_evm_core::{ backend::{DatabaseError, DatabaseExt, RevertDiagnostic}, constants::{CHEATCODE_ADDRESS, DEFAULT_CREATE2_DEPLOYER, HARDHAT_CONSOLE_ADDRESS, MAGIC_SKIP}, @@ -710,8 +710,8 @@ impl Inspector for Cheatcodes { mocks .iter() .find(|(mock, _)| { - call.input.get(..mock.calldata.len()) == Some(&mock.calldata[..]) - && mock.value.map_or(true, |value| value == call.transfer.value) + call.input.get(..mock.calldata.len()) == Some(&mock.calldata[..]) && + mock.value.map_or(true, |value| value == call.transfer.value) }) .map(|(_, v)| v) }) { @@ -721,8 +721,8 @@ impl Inspector for Cheatcodes { // Apply our prank if let Some(prank) = &self.prank { - if data.journaled_state.depth() >= prank.depth - && call.context.caller == prank.prank_caller + if data.journaled_state.depth() >= prank.depth && + call.context.caller == prank.prank_caller { let mut prank_applied = false; @@ -754,8 +754,8 @@ impl Inspector for Cheatcodes { // // We do this because any subsequent contract calls *must* exist on chain and // we only want to grab *this* call, not internal ones - if data.journaled_state.depth() == broadcast.depth - && call.context.caller == broadcast.original_caller + if data.journaled_state.depth() == broadcast.depth && + call.context.caller == broadcast.original_caller { // At the target depth we set `msg.sender` & tx.origin. // We are simulating the caller as being an EOA, so *both* must be set to the @@ -1011,9 +1011,9 @@ impl Inspector for Cheatcodes { if let TransactTo::Call(test_contract) = data.env.tx.transact_to { // if a call to a different contract than the original test contract returned with // `Stop` we check if the contract actually exists on the active fork - if data.db.is_forked_mode() - && status == InstructionResult::Stop - && call.contract != test_contract + if data.db.is_forked_mode() && + status == InstructionResult::Stop && + call.contract != test_contract { self.fork_revert_diagnostic = data.db.diagnose_revert(call.contract, &data.journaled_state); @@ -1122,8 +1122,8 @@ impl Inspector for Cheatcodes { // Apply our broadcast if let Some(broadcast) = &self.broadcast { - if data.journaled_state.depth() >= broadcast.depth - && call.caller == broadcast.original_caller + if data.journaled_state.depth() >= broadcast.depth && + call.caller == broadcast.original_caller { if let Err(err) = data.journaled_state.load_account(broadcast.new_origin, data.db) { return (InstructionResult::Revert, None, gas, Error::encode(err)); diff --git a/crates/common/src/lib.rs b/crates/common/src/lib.rs index 21136720761d..ef8eb88528c0 100644 --- a/crates/common/src/lib.rs +++ b/crates/common/src/lib.rs @@ -23,13 +23,13 @@ pub mod retry; pub mod rpc; pub mod runtime_client; pub mod selectors; +pub mod serde_helpers; pub mod shell; pub mod term; pub mod traits; pub mod transactions; pub mod types; pub mod units; -pub mod serde_helpers; pub use constants::*; pub use contracts::*; diff --git a/crates/common/src/provider/alloy.rs b/crates/common/src/provider/alloy.rs index 9d1a720c8397..4289f07cea59 100644 --- a/crates/common/src/provider/alloy.rs +++ b/crates/common/src/provider/alloy.rs @@ -8,8 +8,8 @@ use alloy_transport_http::Http; use ethers_middleware::gas_oracle::{GasCategory, GasOracle, Polygon}; use ethers_providers::{JwtAuth, JwtKey}; use eyre::{Result, WrapErr}; -use foundry_config::NamedChain; use foundry_common::types::ToAlloy; +use foundry_config::NamedChain; use reqwest::{header::HeaderValue, Url}; use std::{ path::{Path, PathBuf}, diff --git a/crates/common/src/types.rs b/crates/common/src/types.rs index 20d6e5f955d7..80ee952d844c 100644 --- a/crates/common/src/types.rs +++ b/crates/common/src/types.rs @@ -1,7 +1,7 @@ //! Temporary utility conversion traits between ethers-rs and alloy types. use alloy_json_abi::{Event, EventParam, Function, InternalType, Param, StateMutability}; -use alloy_primitives::{Address, B256, I256, U128, U256, U64, B64, Bloom, Bytes}; +use alloy_primitives::{Address, Bloom, Bytes, B256, B64, I256, U128, U256, U64}; use alloy_rpc_types::{AccessList, AccessListItem, CallInput, CallRequest, Signature, Transaction}; use ethers_core::{ abi as ethabi, @@ -9,8 +9,8 @@ use ethers_core::{ transaction::eip2930::{ AccessList as EthersAccessList, AccessListItem as EthersAccessListItem, }, - TransactionRequest, H160, H256, I256 as EthersI256, U256 as EthersU256, U64 as EthersU64, - Bloom as EthersBloom, Bytes as EthersBytes, H64, + Bloom as EthersBloom, Bytes as EthersBytes, TransactionRequest, H160, H256, H64, + I256 as EthersI256, U256 as EthersU256, U64 as EthersU64, }, }; diff --git a/crates/evm/core/src/backend/mod.rs b/crates/evm/core/src/backend/mod.rs index adbba2a38fb8..8394410dea53 100644 --- a/crates/evm/core/src/backend/mod.rs +++ b/crates/evm/core/src/backend/mod.rs @@ -9,8 +9,7 @@ use crate::{ use alloy_primitives::{b256, keccak256, Address, B256, U256, U64}; use alloy_rpc_types::{Block, BlockNumberOrTag, BlockTransactions, Transaction}; use ethers::utils::GenesisAccount; -use foundry_common::{is_known_system_sender, SYSTEM_TRANSACTION_TYPE}; -use foundry_common::types::ToAlloy; +use foundry_common::{is_known_system_sender, types::ToAlloy, SYSTEM_TRANSACTION_TYPE}; use revm::{ db::{CacheDB, DatabaseRef}, inspectors::NoOpInspector, diff --git a/crates/evm/core/src/fork/init.rs b/crates/evm/core/src/fork/init.rs index 46d029ab8201..b235741bef15 100644 --- a/crates/evm/core/src/fork/init.rs +++ b/crates/evm/core/src/fork/init.rs @@ -3,7 +3,7 @@ use alloy_primitives::{Address, U256}; use alloy_providers::provider::TempProvider; use alloy_rpc_types::{Block, BlockNumberOrTag}; use eyre::WrapErr; -use foundry_common::{NON_ARCHIVE_NODE_WARNING}; +use foundry_common::NON_ARCHIVE_NODE_WARNING; use revm::primitives::{BlockEnv, CfgEnv, Env, TxEnv}; diff --git a/crates/evm/core/src/fork/multi.rs b/crates/evm/core/src/fork/multi.rs index de42d6cf0865..d376990e7d8c 100644 --- a/crates/evm/core/src/fork/multi.rs +++ b/crates/evm/core/src/fork/multi.rs @@ -375,8 +375,8 @@ impl Future for MultiForkHandler { .flush_cache_interval .as_mut() .map(|interval| interval.poll_tick(cx).is_ready()) - .unwrap_or_default() - && !pin.forks.is_empty() + .unwrap_or_default() && + !pin.forks.is_empty() { trace!(target: "fork::multi", "tick flushing caches"); let forks = pin.forks.values().map(|f| f.backend.clone()).collect::>(); diff --git a/crates/forge/bin/cmd/create.rs b/crates/forge/bin/cmd/create.rs index 28c5eb79227b..44ca6ae15c45 100644 --- a/crates/forge/bin/cmd/create.rs +++ b/crates/forge/bin/cmd/create.rs @@ -18,7 +18,12 @@ use foundry_cli::{ opts::{CoreBuildArgs, EthereumOpts, EtherscanOpts, TransactionOpts}, utils::{self, read_constructor_args_file, remove_contract, LoadConfig}, }; -use foundry_common::{compile, fmt::parse_tokens, provider::ethers::estimate_eip1559_fees, types::{ToAlloy, ToEthers}}; +use foundry_common::{ + compile, + fmt::parse_tokens, + provider::ethers::estimate_eip1559_fees, + types::{ToAlloy, ToEthers}, +}; use foundry_compilers::{artifacts::BytecodeObject, info::ContractInfo, utils::canonicalized}; use serde_json::json; use std::{borrow::Borrow, marker::PhantomData, path::PathBuf, sync::Arc}; @@ -211,8 +216,8 @@ impl CreateArgs { e } })?; - let is_legacy = self.tx.legacy - || Chain::try_from(chain).map(|x| Chain::is_legacy(&x)).unwrap_or_default(); + 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 }; // set tx value if specified diff --git a/crates/forge/bin/cmd/script/broadcast.rs b/crates/forge/bin/cmd/script/broadcast.rs index aedb896ee4b0..601ba5e2748c 100644 --- a/crates/forge/bin/cmd/script/broadcast.rs +++ b/crates/forge/bin/cmd/script/broadcast.rs @@ -13,8 +13,9 @@ use foundry_cli::{ utils::{has_batch_support, has_different_gas_calc}, }; use foundry_common::{ - provider::ethers::estimate_eip1559_fees, provider::ethers::try_get_http_provider, - provider::ethers::RetryProvider, shell, types::{ToAlloy, ToEthers}, + provider::ethers::{estimate_eip1559_fees, try_get_http_provider, RetryProvider}, + shell, + types::{ToAlloy, ToEthers}, }; use futures::StreamExt; use std::{cmp::min, collections::HashSet, ops::Mul, sync::Arc}; @@ -248,9 +249,9 @@ impl ScriptArgs { // Chains which use `eth_estimateGas` are being sent sequentially and require their // gas to be re-estimated right before broadcasting. - if !is_fixed_gas_limit - && (has_different_gas_calc(provider.get_chainid().await?.as_u64()) - || self.skip_simulation) + if !is_fixed_gas_limit && + (has_different_gas_calc(provider.get_chainid().await?.as_u64()) || + self.skip_simulation) { self.estimate_gas(&mut tx, &provider).await?; } @@ -612,9 +613,9 @@ impl ScriptArgs { provider .estimate_gas(tx, None) .await - .wrap_err_with(|| format!("Failed to estimate gas for tx: {:?}", tx.sighash()))? - * self.gas_estimate_multiplier - / 100, + .wrap_err_with(|| format!("Failed to estimate gas for tx: {:?}", tx.sighash()))? * + self.gas_estimate_multiplier / + 100, ); Ok(()) } diff --git a/crates/forge/bin/cmd/script/cmd.rs b/crates/forge/bin/cmd/script/cmd.rs index e4ce35084a6c..d2f915f04872 100644 --- a/crates/forge/bin/cmd/script/cmd.rs +++ b/crates/forge/bin/cmd/script/cmd.rs @@ -5,7 +5,9 @@ use ethers_providers::Middleware; use ethers_signers::Signer; use eyre::Result; use foundry_cli::utils::LoadConfig; -use foundry_common::{contracts::flatten_contracts, provider::ethers::try_get_http_provider, types::ToAlloy}; +use foundry_common::{ + contracts::flatten_contracts, provider::ethers::try_get_http_provider, types::ToAlloy, +}; use foundry_debugger::DebuggerArgs; use std::sync::Arc; diff --git a/crates/forge/bin/cmd/script/executor.rs b/crates/forge/bin/cmd/script/executor.rs index a3fbadcde48c..a5753fdce4c2 100644 --- a/crates/forge/bin/cmd/script/executor.rs +++ b/crates/forge/bin/cmd/script/executor.rs @@ -15,7 +15,11 @@ use forge::{ utils::CallKind, }; use foundry_cli::utils::{ensure_clean_constructor, needs_setup}; -use foundry_common::{provider::ethers::RpcUrl, shell, types::{ToAlloy, ToEthers}}; +use foundry_common::{ + provider::ethers::RpcUrl, + shell, + types::{ToAlloy, ToEthers}, +}; use foundry_compilers::artifacts::CompactContractBytecode; use futures::future::join_all; use parking_lot::RwLock; diff --git a/crates/forge/bin/cmd/script/mod.rs b/crates/forge/bin/cmd/script/mod.rs index 60ef1fea225e..5339973d283b 100644 --- a/crates/forge/bin/cmd/script/mod.rs +++ b/crates/forge/bin/cmd/script/mod.rs @@ -30,8 +30,9 @@ use foundry_common::{ evm::{Breakpoints, EvmArgs}, fmt::{format_token, format_token_raw}, provider::ethers::RpcUrl, - shell, ContractsByArtifact, CONTRACT_MAX_SIZE, SELECTOR_LEN, + shell, types::{ToAlloy, ToEthers}, + ContractsByArtifact, CONTRACT_MAX_SIZE, SELECTOR_LEN, }; use foundry_compilers::{ artifacts::{ContractBytecodeSome, Libraries}, @@ -570,9 +571,9 @@ impl ScriptArgs { } // Only prompt if we're broadcasting and we've not disabled interactivity. - if prompt_user - && !self.non_interactive - && !Confirm::new().with_prompt("Do you wish to continue?".to_string()).interact()? + if prompt_user && + !self.non_interactive && + !Confirm::new().with_prompt("Do you wish to continue?".to_string()).interact()? { eyre::bail!("User canceled the script."); } diff --git a/crates/forge/bin/cmd/script/providers.rs b/crates/forge/bin/cmd/script/providers.rs index 5a6d588be044..f29a72629320 100644 --- a/crates/forge/bin/cmd/script/providers.rs +++ b/crates/forge/bin/cmd/script/providers.rs @@ -2,7 +2,8 @@ use alloy_primitives::U256; use ethers_providers::{Middleware, Provider}; use eyre::{Result, WrapErr}; use foundry_common::{ - provider::ethers::get_http_provider, provider::ethers::RpcUrl, runtime_client::RuntimeClient, + provider::ethers::{get_http_provider, RpcUrl}, + runtime_client::RuntimeClient, types::ToAlloy, }; use foundry_config::Chain; diff --git a/crates/forge/bin/cmd/script/receipts.rs b/crates/forge/bin/cmd/script/receipts.rs index 29e18507b9db..29848aad3564 100644 --- a/crates/forge/bin/cmd/script/receipts.rs +++ b/crates/forge/bin/cmd/script/receipts.rs @@ -4,8 +4,10 @@ use ethers_core::types::TransactionReceipt; use ethers_providers::{Middleware, PendingTransaction}; use eyre::Result; use foundry_cli::{init_progress, update_progress, utils::print_receipt}; -use foundry_common::provider::ethers::RetryProvider; -use foundry_common::types::{ToAlloy, ToEthers}; +use foundry_common::{ + provider::ethers::RetryProvider, + types::{ToAlloy, ToEthers}, +}; use futures::StreamExt; use std::sync::Arc; diff --git a/crates/forge/bin/cmd/script/transaction.rs b/crates/forge/bin/cmd/script/transaction.rs index f36920c96f0e..a31c9e80a607 100644 --- a/crates/forge/bin/cmd/script/transaction.rs +++ b/crates/forge/bin/cmd/script/transaction.rs @@ -4,7 +4,12 @@ use alloy_json_abi::Function; use alloy_primitives::{Address, Bytes, B256}; use ethers_core::types::{transaction::eip2718::TypedTransaction, NameOrAddress}; use eyre::{ContextCompat, Result, WrapErr}; -use foundry_common::{fmt::format_token_raw, provider::ethers::RpcUrl, SELECTOR_LEN, types::{ToAlloy, ToEthers}}; +use foundry_common::{ + fmt::format_token_raw, + provider::ethers::RpcUrl, + types::{ToAlloy, ToEthers}, + SELECTOR_LEN, +}; use foundry_evm::{constants::DEFAULT_CREATE2_DEPLOYER, traces::CallTraceDecoder, utils::CallKind}; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; diff --git a/crates/test-utils/src/script.rs b/crates/test-utils/src/script.rs index 24dba8b9c0eb..f4449a7694a8 100644 --- a/crates/test-utils/src/script.rs +++ b/crates/test-utils/src/script.rs @@ -3,8 +3,10 @@ use alloy_primitives::{Address, U256}; use ethers_core::types::NameOrAddress; use ethers_providers::Middleware; use eyre::Result; -use foundry_common::provider::ethers::{get_http_provider, RetryProvider}; -use foundry_common::types::{ToAlloy, ToEthers}; +use foundry_common::{ + provider::ethers::{get_http_provider, RetryProvider}, + types::{ToAlloy, ToEthers}, +}; use std::{collections::BTreeMap, fs, path::Path, str::FromStr}; const BROADCAST_TEST_PATH: &str = "src/Broadcast.t.sol"; @@ -276,16 +278,16 @@ impl ScriptOutcome { pub fn is_err(&self) -> bool { match self { - ScriptOutcome::OkNoEndpoint - | ScriptOutcome::OkSimulation - | ScriptOutcome::OkBroadcast - | ScriptOutcome::WarnSpecifyDeployer => false, - ScriptOutcome::MissingSender - | ScriptOutcome::MissingWallet - | ScriptOutcome::StaticCallNotAllowed - | ScriptOutcome::UnsupportedLibraries - | ScriptOutcome::ErrorSelectForkOnBroadcast - | ScriptOutcome::ScriptFailed => true, + ScriptOutcome::OkNoEndpoint | + ScriptOutcome::OkSimulation | + ScriptOutcome::OkBroadcast | + ScriptOutcome::WarnSpecifyDeployer => false, + ScriptOutcome::MissingSender | + ScriptOutcome::MissingWallet | + ScriptOutcome::StaticCallNotAllowed | + ScriptOutcome::UnsupportedLibraries | + ScriptOutcome::ErrorSelectForkOnBroadcast | + ScriptOutcome::ScriptFailed => true, } } }