From 5c63c12525512f37bb52563814a2321af3032f4f Mon Sep 17 00:00:00 2001 From: taikoonwang Date: Fri, 21 Mar 2025 13:29:00 +0800 Subject: [PATCH 1/8] explicit_into_iter_loop --- Cargo.toml | 1 + crates/anvil/src/eth/backend/db.rs | 4 ++-- crates/anvil/src/eth/backend/executor.rs | 2 +- crates/chisel/src/executor.rs | 2 +- crates/config/src/error.rs | 2 +- crates/config/src/etherscan.rs | 2 +- crates/evm/core/src/backend/mod.rs | 2 +- crates/forge/src/cmd/snapshot.rs | 2 +- crates/script-sequence/src/reader.rs | 4 ++-- 9 files changed, 11 insertions(+), 10 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 1aaa3305ac812..807d0afa87b24 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -39,6 +39,7 @@ exclude = ["benches/", "tests/", "test-data/", "testdata/"] [workspace.lints.clippy] dbg-macro = "warn" +explicit_into_iter_loop = "warn" explicit_iter_loop = "warn" manual-string-new = "warn" uninlined-format-args = "warn" diff --git a/crates/anvil/src/eth/backend/db.rs b/crates/anvil/src/eth/backend/db.rs index ecf1759e63a52..2808a01fa87e0 100644 --- a/crates/anvil/src/eth/backend/db.rs +++ b/crates/anvil/src/eth/backend/db.rs @@ -147,7 +147,7 @@ pub trait Db: /// Deserialize and add all chain data to the backend storage fn load_state(&mut self, state: SerializableState) -> DatabaseResult { - for (addr, account) in state.accounts.into_iter() { + for (addr, account) in state.accounts { let old_account_nonce = DatabaseRef::basic_ref(self, addr) .ok() .and_then(|acc| acc.map(|acc| acc.nonce)) @@ -170,7 +170,7 @@ pub trait Db: }, ); - for (k, v) in account.storage.into_iter() { + for (k, v) in account.storage { self.set_storage_at(addr, k, v)?; } } diff --git a/crates/anvil/src/eth/backend/executor.rs b/crates/anvil/src/eth/backend/executor.rs index c07bfab785e24..281692fa7d374 100644 --- a/crates/anvil/src/eth/backend/executor.rs +++ b/crates/anvil/src/eth/backend/executor.rs @@ -140,7 +140,7 @@ impl TransactionExecutor<'_, DB, V> { let excess_blob_gas = if is_cancun { self.block_env.get_blob_excess_gas() } else { None }; let mut cumulative_blob_gas_used = if is_cancun { Some(0u64) } else { None }; - for tx in self.into_iter() { + for tx in &mut self { let tx = match tx { TransactionExecutionOutcome::Executed(tx) => { included.push(tx.transaction.clone()); diff --git a/crates/chisel/src/executor.rs b/crates/chisel/src/executor.rs index 1315cb779ba09..debabac2e5de1 100644 --- a/crates/chisel/src/executor.rs +++ b/crates/chisel/src/executor.rs @@ -1788,7 +1788,7 @@ mod tests { T: AsRef + std::fmt::Display + 'a, I: IntoIterator + 'a, { - for (input, expected) in input.into_iter() { + for (input, expected) in input { let input = input.as_ref(); let ty = get_type_ethabi(s, input, true); assert_eq!(ty.as_ref(), Some(expected), "\n{input}"); diff --git a/crates/config/src/error.rs b/crates/config/src/error.rs index eba84a57da0dc..81c83ed793b0f 100644 --- a/crates/config/src/error.rs +++ b/crates/config/src/error.rs @@ -22,7 +22,7 @@ impl fmt::Display for ExtractConfigError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut unique_errors = Vec::with_capacity(self.error.count()); let mut unique = HashSet::with_capacity(self.error.count()); - for err in self.error.clone().into_iter() { + for err in self.error.clone() { let err = if err .metadata .as_ref() diff --git a/crates/config/src/etherscan.rs b/crates/config/src/etherscan.rs index 9dde4b733a543..2771d45eb7cc0 100644 --- a/crates/config/src/etherscan.rs +++ b/crates/config/src/etherscan.rs @@ -134,7 +134,7 @@ impl ResolvedEtherscanConfigs { self, chain: Chain, ) -> Option> { - for (_, config) in self.configs.into_iter() { + for (_, config) in self.configs { match config { Ok(c) if c.chain == Some(chain) => return Some(Ok(c)), Err(e) => return Some(Err(e)), diff --git a/crates/evm/core/src/backend/mod.rs b/crates/evm/core/src/backend/mod.rs index 299e747231e16..06eea40e6e8ef 100644 --- a/crates/evm/core/src/backend/mod.rs +++ b/crates/evm/core/src/backend/mod.rs @@ -1835,7 +1835,7 @@ pub(crate) fn merge_account_data( active_journaled_state: &mut JournaledState, target_fork: &mut Fork, ) { - for addr in accounts.into_iter() { + for addr in accounts { merge_db_account_data(addr, active, &mut target_fork.db); merge_journaled_state_data(addr, active_journaled_state, &mut target_fork.journaled_state); } diff --git a/crates/forge/src/cmd/snapshot.rs b/crates/forge/src/cmd/snapshot.rs index da642bd1241be..88c705aca03dd 100644 --- a/crates/forge/src/cmd/snapshot.rs +++ b/crates/forge/src/cmd/snapshot.rs @@ -358,7 +358,7 @@ fn diff(tests: Vec, snaps: Vec) -> Result<()> .map(|s| ((s.contract_name, s.signature), s.gas_used)) .collect::>(); let mut diffs = Vec::with_capacity(tests.len()); - for test in tests.into_iter() { + for test in tests { if let Some(target_gas_used) = snaps.get(&(test.contract_name().to_string(), test.signature.clone())).cloned() { diff --git a/crates/script-sequence/src/reader.rs b/crates/script-sequence/src/reader.rs index 9592795e9a203..500b6aa5a2770 100644 --- a/crates/script-sequence/src/reader.rs +++ b/crates/script-sequence/src/reader.rs @@ -52,7 +52,7 @@ impl BroadcastReader { pub fn read(&self) -> eyre::Result> { // 1. Recursively read all .json files in the broadcast directory let mut broadcasts = vec![]; - for entry in walkdir::WalkDir::new(&self.broadcast_path).into_iter() { + for entry in walkdir::WalkDir::new(&self.broadcast_path) { let entry = entry?; let path = entry.path(); @@ -158,7 +158,7 @@ impl BroadcastReader { .collect::>(); let mut targets = Vec::new(); - for tx in txs.into_iter() { + for tx in txs { let maybe_receipt = broadcast .receipts .iter() From f0acca6f500711f9bb6068eb870e579557019be8 Mon Sep 17 00:00:00 2001 From: taikoonwang Date: Fri, 21 Mar 2025 13:34:01 +0800 Subject: [PATCH 2/8] from_iter_instead_of_collect --- Cargo.toml | 1 + crates/doc/src/parser/comment.rs | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 807d0afa87b24..5eaf2a027e743 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -41,6 +41,7 @@ exclude = ["benches/", "tests/", "test-data/", "testdata/"] dbg-macro = "warn" explicit_into_iter_loop = "warn" explicit_iter_loop = "warn" +from_iter_instead_of_collect = "warn" manual-string-new = "warn" uninlined-format-args = "warn" use-self = "warn" diff --git a/crates/doc/src/parser/comment.rs b/crates/doc/src/parser/comment.rs index bf2b0ad7b4f0d..a5f032c9cd18b 100644 --- a/crates/doc/src/parser/comment.rs +++ b/crates/doc/src/parser/comment.rs @@ -134,7 +134,7 @@ impl Comments { ident: &str, inheritdocs: Option>, ) -> Self { - let mut result = Self(Vec::from_iter(self.iter().cloned())); + let mut result = Self(self.iter().cloned().collect::>()); if let (Some(inheritdocs), Some(base)) = (inheritdocs, self.find_inheritdoc_base()) { let key = format!("{base}.{ident}"); From dafc55307b39cbcb1155c3ea72ddf9cb2b1aa838 Mon Sep 17 00:00:00 2001 From: taikoonwang Date: Sat, 22 Mar 2025 16:55:10 +0800 Subject: [PATCH 3/8] save --- Cargo.toml | 15 +++++++++++- crates/anvil/core/src/eth/transaction/mod.rs | 6 ++--- crates/anvil/src/eth/api.rs | 8 +++---- crates/anvil/src/eth/backend/mem/mod.rs | 8 +++---- crates/anvil/src/eth/fees.rs | 2 +- crates/anvil/src/eth/otterscan/api.rs | 2 +- crates/anvil/src/eth/pool/transactions.rs | 2 +- crates/anvil/src/eth/sign.rs | 2 +- crates/cast/src/args.rs | 6 ++--- crates/cheatcodes/src/env.rs | 2 +- crates/cheatcodes/src/inspector.rs | 6 ++--- crates/cheatcodes/src/json.rs | 6 ++--- crates/cheatcodes/src/script.rs | 4 ++-- crates/cheatcodes/src/test/assert.rs | 12 +++++----- crates/chisel/src/session_source.rs | 4 ++-- crates/common/fmt/src/console.rs | 24 +++++++++---------- crates/common/fmt/src/ui.rs | 6 ++--- crates/common/src/compile.rs | 8 +++---- crates/common/src/contracts.rs | 2 +- crates/common/src/fs.rs | 2 +- crates/common/src/io/shell.rs | 6 ++--- crates/config/src/lib.rs | 2 +- crates/config/src/soldeer.rs | 4 ++-- crates/debugger/src/tui/context.rs | 6 ++--- crates/debugger/src/tui/draw.rs | 6 ++--- crates/doc/src/parser/comment.rs | 12 +++++----- crates/doc/src/parser/item.rs | 16 ++++++------- crates/doc/src/writer/as_doc.rs | 4 ++-- crates/evm/core/src/buffer.rs | 2 +- crates/evm/fuzz/src/invariant/mod.rs | 6 ++--- crates/evm/fuzz/src/strategies/invariants.rs | 6 ++--- crates/evm/fuzz/src/strategies/param.rs | 6 ++--- .../evm/traces/src/identifier/signatures.rs | 2 +- crates/fmt/src/formatter.rs | 2 +- crates/fmt/src/solang_ext/ast_eq.rs | 6 ++--- crates/forge/src/cmd/bind.rs | 8 +++---- crates/forge/src/cmd/bind_json.rs | 8 +++---- crates/forge/src/cmd/cache.rs | 2 +- crates/forge/src/cmd/clone.rs | 2 +- crates/forge/src/cmd/create.rs | 16 ++++++------- crates/forge/src/cmd/fmt.rs | 2 +- crates/forge/src/cmd/inspect.rs | 6 ++--- crates/forge/src/cmd/test/mod.rs | 6 ++--- crates/forge/src/runner.rs | 6 ++--- crates/script-sequence/src/sequence.rs | 4 ++-- crates/script/src/build.rs | 14 +++++------ crates/script/src/execute.rs | 12 +++++----- crates/script/src/multi_sequence.rs | 4 ++-- crates/script/src/receipts.rs | 6 ++--- crates/script/src/runner.rs | 8 +++---- crates/script/src/simulate.rs | 22 ++++++++--------- crates/sol-macro-gen/src/sol_macro_gen.rs | 12 +++++----- crates/test-utils/src/util.rs | 3 +-- crates/verify/src/bytecode.rs | 8 +++---- crates/verify/src/etherscan/flatten.rs | 6 ++--- crates/verify/src/etherscan/mod.rs | 14 +++++------ crates/verify/src/utils.rs | 12 +++++----- crates/wallets/src/multi_wallet.rs | 6 ++--- crates/wallets/src/utils.rs | 6 ++--- 59 files changed, 208 insertions(+), 198 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 5eaf2a027e743..602e0ebee40a5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -38,10 +38,23 @@ repository = "https://github.com/foundry-rs/foundry" exclude = ["benches/", "tests/", "test-data/", "testdata/"] [workspace.lints.clippy] -dbg-macro = "warn" +clear_with_drain = "warn" +cloned_instead_of_copied = "warn" +dbg_macro = "warn" +derive_partial_eq_without_eq = "warn" explicit_into_iter_loop = "warn" explicit_iter_loop = "warn" +flat_map_option = "warn" from_iter_instead_of_collect = "warn" +if_not_else = "warn" +if_then_some_else_none = "warn" +implicit_clone = "warn" +imprecise_flops = "warn" +iter_on_empty_collections = "warn" +iter_on_single_items = "warn" +iter_with_drain = "warn" +iter_without_into_iter = "warn" +large_stack_frames = "warn" manual-string-new = "warn" uninlined-format-args = "warn" use-self = "warn" diff --git a/crates/anvil/core/src/eth/transaction/mod.rs b/crates/anvil/core/src/eth/transaction/mod.rs index f28a9899f43b5..1d03e09a97165 100644 --- a/crates/anvil/core/src/eth/transaction/mod.rs +++ b/crates/anvil/core/src/eth/transaction/mod.rs @@ -999,10 +999,10 @@ impl Decodable for TypedTransaction { // 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 { + if ty == 0x7E { Ok(Self::Deposit(DepositTransaction::decode_2718(buf)?)) + } else { + Ok(TxEnvelope::decode(buf)?.into()) } } } diff --git a/crates/anvil/src/eth/api.rs b/crates/anvil/src/eth/api.rs index 6e785db5b92a7..27df12868616a 100644 --- a/crates/anvil/src/eth/api.rs +++ b/crates/anvil/src/eth/api.rs @@ -958,7 +958,7 @@ impl EthApi { node_info!("eth_signTransaction"); let from = request.from.map(Ok).unwrap_or_else(|| { - self.accounts()?.first().cloned().ok_or(BlockchainError::NoSignerAvailable) + self.accounts()?.first().copied().ok_or(BlockchainError::NoSignerAvailable) })?; let (nonce, _) = self.request_nonce(&request, from).await?; @@ -986,7 +986,7 @@ impl EthApi { node_info!("eth_sendTransaction"); let from = request.from.map(Ok).unwrap_or_else(|| { - self.accounts()?.first().cloned().ok_or(BlockchainError::NoSignerAvailable) + self.accounts()?.first().copied().ok_or(BlockchainError::NoSignerAvailable) })?; let (nonce, on_chain_nonce) = self.request_nonce(&request, from).await?; @@ -2037,7 +2037,7 @@ impl EthApi { }; let from = tx_req.from.map(Ok).unwrap_or_else(|| { - self.accounts()?.first().cloned().ok_or(BlockchainError::NoSignerAvailable) + self.accounts()?.first().copied().ok_or(BlockchainError::NoSignerAvailable) })?; // Get the nonce at the common block @@ -2253,7 +2253,7 @@ impl EthApi { } } } - block.transactions = BlockTransactions::Full(block_txs.to_vec()); + block.transactions = BlockTransactions::Full(block_txs.clone()); blocks.push(block); } } diff --git a/crates/anvil/src/eth/backend/mem/mod.rs b/crates/anvil/src/eth/backend/mem/mod.rs index 1404ce5616f2a..09a8a8812f8e9 100644 --- a/crates/anvil/src/eth/backend/mem/mod.rs +++ b/crates/anvil/src/eth/backend/mem/mod.rs @@ -1413,10 +1413,10 @@ impl Backend { gas_priority_fee: max_priority_fee_per_gas.map(U256::from), max_fee_per_blob_gas: max_fee_per_blob_gas .or_else(|| { - if !blob_hashes.is_empty() { - env.block.get_blob_gasprice() - } else { + if blob_hashes.is_empty() { None + } else { + env.block.get_blob_gasprice() } }) .map(U256::from), @@ -2594,7 +2594,7 @@ impl Backend { .zip(storage_proofs) .map(|(key, proof)| { let storage_key: U256 = key.into(); - let value = account.storage.get(&storage_key).cloned().unwrap_or_default(); + let value = account.storage.get(&storage_key).copied().unwrap_or_default(); StorageProof { key: JsonStorageKey::Hash(key), value, proof } }) .collect(), diff --git a/crates/anvil/src/eth/fees.rs b/crates/anvil/src/eth/fees.rs index bb405f62d1ef1..fc1f5980b0b1c 100644 --- a/crates/anvil/src/eth/fees.rs +++ b/crates/anvil/src/eth/fees.rs @@ -315,7 +315,7 @@ impl FeeHistoryService { .filter_map(|p| { let target_gas = (p * gas_used / 100f64) as u64; let mut sum_gas = 0; - for (gas_used, effective_reward) in transactions.iter().cloned() { + for (gas_used, effective_reward) in transactions.iter().copied() { sum_gas += gas_used; if target_gas <= sum_gas { return Some(effective_reward) diff --git a/crates/anvil/src/eth/otterscan/api.rs b/crates/anvil/src/eth/otterscan/api.rs index 24df9f330d31b..b09b029066191 100644 --- a/crates/anvil/src/eth/otterscan/api.rs +++ b/crates/anvil/src/eth/otterscan/api.rs @@ -418,7 +418,7 @@ impl EthApi { txs.iter().skip(page * page_size).take(page_size).cloned().collect(), ), BlockTransactions::Hashes(txs) => BlockTransactions::Hashes( - txs.iter().skip(page * page_size).take(page_size).cloned().collect(), + txs.iter().skip(page * page_size).take(page_size).copied().collect(), ), BlockTransactions::Uncle => unreachable!(), }; diff --git a/crates/anvil/src/eth/pool/transactions.rs b/crates/anvil/src/eth/pool/transactions.rs index 36e421d7a50e1..69f101d7729ea 100644 --- a/crates/anvil/src/eth/pool/transactions.rs +++ b/crates/anvil/src/eth/pool/transactions.rs @@ -516,7 +516,7 @@ impl ReadyTransactions { } } - unlocked_tx.extend(to_remove.unlocks.iter().cloned()) + unlocked_tx.extend(to_remove.unlocks.iter().copied()) } } diff --git a/crates/anvil/src/eth/sign.rs b/crates/anvil/src/eth/sign.rs index e2ea036a0cafb..168cbb38dfaa4 100644 --- a/crates/anvil/src/eth/sign.rs +++ b/crates/anvil/src/eth/sign.rs @@ -52,7 +52,7 @@ pub struct DevSigner { impl DevSigner { pub fn new(accounts: Vec) -> Self { let addresses = accounts.iter().map(|wallet| wallet.address()).collect::>(); - let accounts = addresses.iter().cloned().zip(accounts).collect(); + let accounts = addresses.iter().copied().zip(accounts).collect(); Self { addresses, accounts } } } diff --git a/crates/cast/src/args.rs b/crates/cast/src/args.rs index 05236613fbaa1..9dc9f55f6f315 100644 --- a/crates/cast/src/args.rs +++ b/crates/cast/src/args.rs @@ -184,10 +184,10 @@ pub async fn run_command(args: CastArgs) -> Result<()> { print_tokens(&tokens); } CastSubcommand::AbiEncode { sig, packed, args } => { - if !packed { - sh_println!("{}", SimpleCast::abi_encode(&sig, &args)?)? - } else { + if packed { sh_println!("{}", SimpleCast::abi_encode_packed(&sig, &args)?)? + } else { + sh_println!("{}", SimpleCast::abi_encode(&sig, &args)?)? } } CastSubcommand::DecodeCalldata { sig, calldata } => { diff --git a/crates/cheatcodes/src/env.rs b/crates/cheatcodes/src/env.rs index bba8069fb0ac5..d7c55f107d19c 100644 --- a/crates/cheatcodes/src/env.rs +++ b/crates/cheatcodes/src/env.rs @@ -239,7 +239,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.to_vec(); + let default = defaultValue.clone(); env_array_default(name, delim, &default, &DynSolType::Bytes) } } diff --git a/crates/cheatcodes/src/inspector.rs b/crates/cheatcodes/src/inspector.rs index a7860f353f322..151c998f42e2e 100644 --- a/crates/cheatcodes/src/inspector.rs +++ b/crates/cheatcodes/src/inspector.rs @@ -1555,10 +1555,10 @@ impl Inspector<&mut dyn DatabaseExt> for Cheatcodes { }, }; - if count != expected.count { - Some((expected, count)) - } else { + if count == expected.count { None + } else { + Some((expected, count)) } }) .collect::>(); diff --git a/crates/cheatcodes/src/json.rs b/crates/cheatcodes/src/json.rs index 6ad36e4742901..06e887b8235c8 100644 --- a/crates/cheatcodes/src/json.rs +++ b/crates/cheatcodes/src/json.rs @@ -493,10 +493,10 @@ fn encode(values: Vec) -> Vec { /// Canonicalize a json path key to always start from the root of the document. /// Read more about json path syntax: pub(super) fn canonicalize_json_path(path: &str) -> Cow<'_, str> { - if !path.starts_with('$') { - format!("${path}").into() - } else { + if path.starts_with('$') { path.into() + } else { + format!("${path}").into() } } diff --git a/crates/cheatcodes/src/script.rs b/crates/cheatcodes/src/script.rs index fbed5f490ad6a..f8588a8ab28f4 100644 --- a/crates/cheatcodes/src/script.rs +++ b/crates/cheatcodes/src/script.rs @@ -223,7 +223,7 @@ impl Wallets { /// Locks inner Mutex and returns all signer addresses in the [MultiWallet]. pub fn signers(&self) -> Result> { - Ok(self.inner.lock().multi_wallet.signers()?.keys().cloned().collect()) + Ok(self.inner.lock().multi_wallet.signers()?.keys().copied().collect()) } /// Number of signers in the [MultiWallet]. @@ -251,7 +251,7 @@ fn broadcast(ccx: &mut CheatsCtxt, new_origin: Option<&Address>, single_call: bo ); ensure!(ccx.state.broadcast.is_none(), "a broadcast is active already"); - let mut new_origin = new_origin.cloned(); + let mut new_origin = new_origin.copied(); if new_origin.is_none() { let mut wallets = ccx.state.wallets().inner.lock(); diff --git a/crates/cheatcodes/src/test/assert.rs b/crates/cheatcodes/src/test/assert.rs index a61cc4b2a2ece..87c71fbe9a67b 100644 --- a/crates/cheatcodes/src/test/assert.rs +++ b/crates/cheatcodes/src/test/assert.rs @@ -456,10 +456,10 @@ fn assert_true(condition: bool) -> Result, SimpleAssertionError> { } fn assert_false(condition: bool) -> Result, SimpleAssertionError> { - if !condition { - Ok(Default::default()) - } else { + if condition { Err(SimpleAssertionError) + } else { + Ok(Default::default()) } } @@ -472,10 +472,10 @@ fn assert_eq<'a, T: PartialEq>(left: &'a T, right: &'a T) -> ComparisonResult<'a } fn assert_not_eq<'a, T: PartialEq>(left: &'a T, right: &'a T) -> ComparisonResult<'a, T> { - if left != right { - Ok(Default::default()) - } else { + if left == right { Err(ComparisonAssertionError::Ne { left, right }) + } else { + Ok(Default::default()) } } diff --git a/crates/chisel/src/session_source.rs b/crates/chisel/src/session_source.rs index f6e36395c507e..e6f68e31dadae 100644 --- a/crates/chisel/src/session_source.rs +++ b/crates/chisel/src/session_source.rs @@ -59,7 +59,7 @@ pub struct IntermediateContract { type IntermediateContracts = HashMap; /// Full compilation output for the [SessionSource] -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct GeneratedOutput { /// The [IntermediateOutput] component pub intermediate: IntermediateOutput, @@ -438,7 +438,7 @@ impl SessionSource { let Self { contract_name, global_code, top_level_code, run_code, config, .. } = self; let script_import = - if !config.no_vm { "import {Script} from \"forge-std/Script.sol\";\n" } else { "" }; + if config.no_vm { "" } else { "import {Script} from \"forge-std/Script.sol\";\n" }; format!( r#" diff --git a/crates/common/fmt/src/console.rs b/crates/common/fmt/src/console.rs index 3eda32fc2cd8b..d8197f2d388b9 100644 --- a/crates/common/fmt/src/console.rs +++ b/crates/common/fmt/src/console.rs @@ -222,10 +222,10 @@ impl ConsoleFmt for U256 { let integer = amount / exp10; let decimal = (amount % exp10).to_string(); let decimal = format!("{decimal:0>log$}").trim_end_matches('0').to_string(); - if !decimal.is_empty() { - format!("{integer}.{decimal}e{log}") - } else { + if decimal.is_empty() { format!("{integer}e{log}") + } else { + format!("{integer}.{decimal}e{log}") } } FormatSpec::Exponential(Some(precision)) => { @@ -234,10 +234,10 @@ impl ConsoleFmt for U256 { let integer = amount / exp10; let decimal = (amount % exp10).to_string(); let decimal = format!("{decimal:0>precision$}").trim_end_matches('0').to_string(); - if !decimal.is_empty() { - format!("{integer}.{decimal}") - } else { + if decimal.is_empty() { format!("{integer}") + } else { + format!("{integer}.{decimal}") } } } @@ -266,10 +266,10 @@ impl ConsoleFmt for I256 { let integer = (amount / exp10).twos_complement(); let decimal = (amount % exp10).twos_complement().to_string(); let decimal = format!("{decimal:0>log$}").trim_end_matches('0').to_string(); - if !decimal.is_empty() { - format!("{sign}{integer}.{decimal}e{log}") - } else { + if decimal.is_empty() { format!("{sign}{integer}e{log}") + } else { + format!("{sign}{integer}.{decimal}e{log}") } } FormatSpec::Exponential(Some(precision)) => { @@ -279,10 +279,10 @@ impl ConsoleFmt for I256 { let integer = (amount / exp10).twos_complement(); let decimal = (amount % exp10).twos_complement().to_string(); let decimal = format!("{decimal:0>precision$}").trim_end_matches('0').to_string(); - if !decimal.is_empty() { - format!("{sign}{integer}.{decimal}") - } else { + if decimal.is_empty() { format!("{sign}{integer}") + } else { + format!("{sign}{integer}.{decimal}") } } } diff --git a/crates/common/fmt/src/ui.rs b/crates/common/fmt/src/ui.rs index 64e342c497b01..ca896a25e8207 100644 --- a/crates/common/fmt/src/ui.rs +++ b/crates/common/fmt/src/ui.rs @@ -50,7 +50,9 @@ impl UIfmt for Option { impl UIfmt for [T] { fn pretty(&self) -> String { - if !self.is_empty() { + if self.is_empty() { + "[]".to_string() + } else { let mut s = String::with_capacity(self.len() * 64); s.push_str("[\n"); for item in self { @@ -62,8 +64,6 @@ impl UIfmt for [T] { } s.push(']'); s - } else { - "[]".to_string() } } } diff --git a/crates/common/src/compile.rs b/crates/common/src/compile.rs index a9c845c6fee1d..6a65678a3af6f 100644 --- a/crates/common/src/compile.rs +++ b/crates/common/src/compile.rs @@ -151,10 +151,10 @@ impl ProjectCompiler { // Taking is fine since we don't need these in `compile_with`. let files = std::mem::take(&mut self.files); self.compile_with(|| { - let sources = if !files.is_empty() { - Source::read_all(files)? - } else { + let sources = if files.is_empty() { project.paths.read_input_files()? + } else { + Source::read_all(files)? }; foundry_compilers::project::ProjectCompiler::with_sources(project, sources)? @@ -580,7 +580,7 @@ impl PathOrContractInfo { /// Returns the path to the contract file if provided. pub fn path(&self) -> Option { match self { - Self::Path(path) => Some(path.to_path_buf()), + Self::Path(path) => Some(path.clone()), Self::ContractInfo(info) => info.path.as_ref().map(PathBuf::from), } } diff --git a/crates/common/src/contracts.rs b/crates/common/src/contracts.rs index 0d3170f7c39cb..549c42c2527e6 100644 --- a/crates/common/src/contracts.rs +++ b/crates/common/src/contracts.rs @@ -264,7 +264,7 @@ impl ContractsByArtifact { eyre::bail!("{id} has more than one implementation."); } - Ok(contracts.first().cloned()) + Ok(contracts.first().copied()) } /// Finds abi for contract which has the same contract name or identifier as `id`. diff --git a/crates/common/src/fs.rs b/crates/common/src/fs.rs index 3d061759c50cf..19675e425a4ce 100644 --- a/crates/common/src/fs.rs +++ b/crates/common/src/fs.rs @@ -118,7 +118,7 @@ pub fn open(path: impl AsRef) -> Result { /// ref: pub fn normalize_path(path: &Path) -> PathBuf { let mut components = path.components().peekable(); - let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() { + let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().copied() { components.next(); PathBuf::from(c.as_os_str()) } else { diff --git a/crates/common/src/io/shell.rs b/crates/common/src/io/shell.rs index 19b3ae07e7900..bdd434ec13145 100644 --- a/crates/common/src/io/shell.rs +++ b/crates/common/src/io/shell.rs @@ -79,7 +79,7 @@ impl TtyWidth { } } -#[derive(Debug, Default, Clone, Copy, PartialEq)] +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] /// The requested output mode. pub enum OutputMode { /// Default output @@ -104,7 +104,7 @@ impl OutputMode { } /// The requested output format. -#[derive(Debug, Default, Clone, Copy, PartialEq)] +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] pub enum OutputFormat { /// Plain text output. #[default] @@ -178,7 +178,7 @@ enum ShellOut { } /// Whether messages should use color output. -#[derive(Debug, Default, PartialEq, Clone, Copy, Serialize, Deserialize, ValueEnum)] +#[derive(Debug, Default, PartialEq, Eq, Clone, Copy, Serialize, Deserialize, ValueEnum)] pub enum ColorChoice { /// Intelligently guess whether to use color output (default). #[default] diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs index f58b49ff1c338..23edf19f3f926 100644 --- a/crates/config/src/lib.rs +++ b/crates/config/src/lib.rs @@ -1474,7 +1474,7 @@ impl Config { extra_output.push(ContractOutputSelection::Metadata); } - ConfigurableArtifacts::new(extra_output, self.extra_output_files.iter().cloned()) + ConfigurableArtifacts::new(extra_output, self.extra_output_files.iter().copied()) } /// Parses all libraries in the form of diff --git a/crates/config/src/soldeer.rs b/crates/config/src/soldeer.rs index 75ee96c2c0fee..59a465367c1f6 100644 --- a/crates/config/src/soldeer.rs +++ b/crates/config/src/soldeer.rs @@ -41,7 +41,7 @@ pub enum SoldeerDependencyValue { } /// Location where to store the remappings, either in `remappings.txt` or in the `foundry.toml` -#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Default)] +#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Default)] #[serde(rename_all = "lowercase")] pub enum RemappingsLocation { #[default] @@ -54,7 +54,7 @@ fn default_true() -> bool { } /// Type for Soldeer configs, under soldeer tag in the foundry.toml -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct SoldeerConfig { #[serde(default = "default_true")] pub remappings_generate: bool, diff --git a/crates/debugger/src/tui/context.rs b/crates/debugger/src/tui/context.rs index 0c61a1fcd41c4..828adf387eccc 100644 --- a/crates/debugger/src/tui/context.rs +++ b/crates/debugger/src/tui/context.rs @@ -346,9 +346,9 @@ fn is_jump(step: &CallTraceStep, prev: &CallTraceStep) -> bool { let immediate_len = prev.immediate_bytes.as_ref().map_or(0, |b| b.len()); - if step.pc != prev.pc + 1 + immediate_len { - true - } else { + if step.pc == prev.pc + 1 + immediate_len { step.code_section_idx != prev.code_section_idx + } else { + true } } diff --git a/crates/debugger/src/tui/draw.rs b/crates/debugger/src/tui/draw.rs index a918bc89ea733..5a3bfd4ec1d29 100644 --- a/crates/debugger/src/tui/draw.rs +++ b/crates/debugger/src/tui/draw.rs @@ -292,11 +292,11 @@ impl TUIContext<'_> { lines.push(u_num, line, u_text); } - let first = if !last_has_nl { + let first = if last_has_nl { + 0 + } else { lines.push_raw(h_num, &[Span::raw(last), Span::styled(actual[0], h_text)]); 1 - } else { - 0 }; // Skip the first line if it has already been handled above. diff --git a/crates/doc/src/parser/comment.rs b/crates/doc/src/parser/comment.rs index a5f032c9cd18b..322c8f23812bf 100644 --- a/crates/doc/src/parser/comment.rs +++ b/crates/doc/src/parser/comment.rs @@ -104,7 +104,7 @@ impl Comment { } /// The collection of natspec [Comment] items. -#[derive(Clone, Debug, Default, PartialEq, Deref, DerefMut)] +#[derive(Clone, Debug, Default, PartialEq, Eq, Deref, DerefMut)] pub struct Comments(Vec); /// Forward the [Comments] function implementation to the [CommentsRef] @@ -153,12 +153,12 @@ impl Comments { impl From> for Comments { fn from(value: Vec) -> Self { - Self(value.into_iter().flat_map(Comment::from_doc_comment).collect()) + Self(value.into_iter().filter_map(Comment::from_doc_comment).collect()) } } /// The collection of references to natspec [Comment] items. -#[derive(Debug, Default, PartialEq, Deref)] +#[derive(Debug, Default, PartialEq, Eq, Deref)] pub struct CommentsRef<'a>(Vec<&'a Comment>); impl<'a> CommentsRef<'a> { @@ -170,13 +170,13 @@ impl<'a> CommentsRef<'a> { /// Filter a collection of comments and return only those that match provided tags. pub fn include_tags(&self, tags: &[CommentTag]) -> Self { // Cloning only references here - CommentsRef(self.iter().cloned().filter(|c| tags.contains(&c.tag)).collect()) + CommentsRef(self.iter().copied().filter(|c| tags.contains(&c.tag)).collect()) } /// Filter a collection of comments and return only those that do not match provided tags. pub fn exclude_tags(&self, tags: &[CommentTag]) -> Self { // Cloning only references here - CommentsRef(self.iter().cloned().filter(|c| !tags.contains(&c.tag)).collect()) + CommentsRef(self.iter().copied().filter(|c| !tags.contains(&c.tag)).collect()) } /// Check if the collection contains a target comment. @@ -200,7 +200,7 @@ impl<'a> CommentsRef<'a> { /// Filter a collection of comments and only return the custom tags. pub fn get_custom_tags(&self) -> Self { - CommentsRef(self.iter().cloned().filter(|c| c.is_custom()).collect()) + CommentsRef(self.iter().copied().filter(|c| c.is_custom()).collect()) } } diff --git a/crates/doc/src/parser/item.rs b/crates/doc/src/parser/item.rs index 5cc39f3e9aec6..1b22a7ef832d5 100644 --- a/crates/doc/src/parser/item.rs +++ b/crates/doc/src/parser/item.rs @@ -172,16 +172,16 @@ impl ParseSource { /// Get the identity of the source pub fn ident(&self) -> String { match self { - Self::Contract(contract) => contract.name.safe_unwrap().name.to_owned(), - Self::Variable(var) => var.name.safe_unwrap().name.to_owned(), - Self::Event(event) => event.name.safe_unwrap().name.to_owned(), - Self::Error(error) => error.name.safe_unwrap().name.to_owned(), - Self::Struct(structure) => structure.name.safe_unwrap().name.to_owned(), - Self::Enum(enumerable) => enumerable.name.safe_unwrap().name.to_owned(), + Self::Contract(contract) => contract.name.safe_unwrap().name.clone(), + Self::Variable(var) => var.name.safe_unwrap().name.clone(), + Self::Event(event) => event.name.safe_unwrap().name.clone(), + Self::Error(error) => error.name.safe_unwrap().name.clone(), + Self::Struct(structure) => structure.name.safe_unwrap().name.clone(), + Self::Enum(enumerable) => enumerable.name.safe_unwrap().name.clone(), Self::Function(func) => { - func.name.as_ref().map_or(func.ty.to_string(), |n| n.name.to_owned()) + func.name.as_ref().map_or(func.ty.to_string(), |n| n.name.clone()) } - Self::Type(ty) => ty.name.name.to_owned(), + Self::Type(ty) => ty.name.name.clone(), } } } diff --git a/crates/doc/src/writer/as_doc.rs b/crates/doc/src/writer/as_doc.rs index efdf45af25a83..61758c253ddab 100644 --- a/crates/doc/src/writer/as_doc.rs +++ b/crates/doc/src/writer/as_doc.rs @@ -79,7 +79,7 @@ impl AsDoc for CommentsRef<'_> { impl AsDoc for Base { fn as_doc(&self) -> AsDocResult { - Ok(self.name.identifiers.iter().map(|ident| ident.name.to_owned()).join(".")) + Ok(self.name.identifiers.iter().map(|ident| ident.name.clone()).join(".")) } } @@ -299,7 +299,7 @@ impl Document { comments: &Comments, code: &str, ) -> Result<(), std::fmt::Error> { - let func_name = func.name.as_ref().map_or(func.ty.to_string(), |n| n.name.to_owned()); + let func_name = func.name.as_ref().map_or(func.ty.to_string(), |n| n.name.clone()); let comments = comments.merge_inheritdoc(&func_name, read_context!(self, INHERITDOC_ID, Inheritdoc)); diff --git a/crates/evm/core/src/buffer.rs b/crates/evm/core/src/buffer.rs index 1db7420d78736..44ba84d1fab93 100644 --- a/crates/evm/core/src/buffer.rs +++ b/crates/evm/core/src/buffer.rs @@ -2,7 +2,7 @@ use alloy_primitives::U256; use revm::interpreter::opcode; /// Used to keep track of which buffer is currently active to be drawn by the debugger. -#[derive(Debug, PartialEq)] +#[derive(Debug, PartialEq, Eq)] pub enum BufferKind { Memory, Calldata, diff --git a/crates/evm/fuzz/src/invariant/mod.rs b/crates/evm/fuzz/src/invariant/mod.rs index c681512de1e60..22481da37cc21 100644 --- a/crates/evm/fuzz/src/invariant/mod.rs +++ b/crates/evm/fuzz/src/invariant/mod.rs @@ -176,15 +176,15 @@ impl TargetedContract { /// Returns specified targeted functions if any, else mutable abi functions that are not /// marked as excluded. pub fn abi_fuzzed_functions(&self) -> impl Iterator { - if !self.targeted_functions.is_empty() { - Either::Left(self.targeted_functions.iter()) - } else { + if self.targeted_functions.is_empty() { Either::Right(self.abi.functions().filter(|&func| { !matches!( func.state_mutability, alloy_json_abi::StateMutability::Pure | alloy_json_abi::StateMutability::View ) && !self.excluded_functions.contains(func) })) + } else { + Either::Left(self.targeted_functions.iter()) } } diff --git a/crates/evm/fuzz/src/strategies/invariants.rs b/crates/evm/fuzz/src/strategies/invariants.rs index 37c0b157c3cc2..dd08edb9fd098 100644 --- a/crates/evm/fuzz/src/strategies/invariants.rs +++ b/crates/evm/fuzz/src/strategies/invariants.rs @@ -89,9 +89,7 @@ fn select_random_sender( senders: Rc, dictionary_weight: u32, ) -> impl Strategy { - if !senders.targeted.is_empty() { - any::().prop_map(move |index| *index.get(&senders.targeted)).boxed() - } else { + if senders.targeted.is_empty() { assert!(dictionary_weight <= 100, "dictionary_weight must be <= 100"); proptest::prop_oneof![ 100 - dictionary_weight => fuzz_param(&alloy_dyn_abi::DynSolType::Address), @@ -101,6 +99,8 @@ fn select_random_sender( // Too many exclusions can slow down testing. .prop_filter("excluded sender", move |addr| !senders.excluded.contains(addr)) .boxed() + } else { + any::().prop_map(move |index| *index.get(&senders.targeted)).boxed() } } diff --git a/crates/evm/fuzz/src/strategies/param.rs b/crates/evm/fuzz/src/strategies/param.rs index 43dcdae7b00f3..fd8b79d441c36 100644 --- a/crates/evm/fuzz/src/strategies/param.rs +++ b/crates/evm/fuzz/src/strategies/param.rs @@ -135,9 +135,7 @@ pub fn fuzz_param_from_state( value() .prop_map(move |value| { let mut fuzzed_addr = Address::from_word(value); - if !deployed_libs.contains(&fuzzed_addr) { - DynSolValue::Address(fuzzed_addr) - } else { + if deployed_libs.contains(&fuzzed_addr) { let mut rng = StdRng::seed_from_u64(0x1337); // use deterministic rng // Do not use addresses of deployed libraries as fuzz input, instead return @@ -152,6 +150,8 @@ pub fn fuzz_param_from_state( } } + DynSolValue::Address(fuzzed_addr) + } else { DynSolValue::Address(fuzzed_addr) } }) diff --git a/crates/evm/traces/src/identifier/signatures.rs b/crates/evm/traces/src/identifier/signatures.rs index d1c6f61aa3571..1399bc9de4e05 100644 --- a/crates/evm/traces/src/identifier/signatures.rs +++ b/crates/evm/traces/src/identifier/signatures.rs @@ -56,7 +56,7 @@ impl SignaturesIdentifier { cache_path: Option, offline: bool, ) -> eyre::Result { - let client = if !offline { Some(OpenChainClient::new()?) } else { None }; + let client = if offline { None } else { Some(OpenChainClient::new()?) }; let identifier = if let Some(cache_path) = cache_path { let path = cache_path.join("signatures"); diff --git a/crates/fmt/src/formatter.rs b/crates/fmt/src/formatter.rs index aee9eee91db12..2d421a6fd7c96 100644 --- a/crates/fmt/src/formatter.rs +++ b/crates/fmt/src/formatter.rs @@ -1171,7 +1171,7 @@ impl<'a, W: Write> Formatter<'a, W> { T: Visitable + CodeLocation, { write_chunk!(self, "{}", prefix)?; - let whitespace = if !prefix.is_empty() { " " } else { "" }; + let whitespace = if prefix.is_empty() { "" } else { " " }; let next_after_start_offset = items.first().map(|item| item.loc().start()); let first_surrounding = SurroundingChunk::new("", start_offset, next_after_start_offset); let last_surronding = SurroundingChunk::new(")", None, end_offset); diff --git a/crates/fmt/src/solang_ext/ast_eq.rs b/crates/fmt/src/solang_ext/ast_eq.rs index 3c796a0d00128..1833e529db167 100644 --- a/crates/fmt/src/solang_ext/ast_eq.rs +++ b/crates/fmt/src/solang_ext/ast_eq.rs @@ -100,10 +100,10 @@ where T: AstEq, { fn ast_eq(&self, other: &Self) -> bool { - if self.len() != other.len() { - false - } else { + if self.len() == other.len() { self.iter().zip(other.iter()).all(|(left, right)| left.ast_eq(right)) + } else { + false } } } diff --git a/crates/forge/src/cmd/bind.rs b/crates/forge/src/cmd/bind.rs index 1198a89af5199..7969e91997941 100644 --- a/crates/forge/src/cmd/bind.rs +++ b/crates/forge/src/cmd/bind.rs @@ -227,7 +227,10 @@ impl BindArgs { let mut solmacrogen = self.get_solmacrogen(artifacts)?; sh_println!("Generating bindings for {} contracts", solmacrogen.instances.len())?; - if !self.module { + if self.module { + trace!(single_file = self.single_file, "generating module"); + solmacrogen.write_to_module(bindings_root, self.single_file)?; + } else { trace!(single_file = self.single_file, "generating crate"); solmacrogen.write_to_crate( &self.crate_name, @@ -237,9 +240,6 @@ impl BindArgs { self.alloy_version.clone(), self.alloy_rev.clone(), )?; - } else { - trace!(single_file = self.single_file, "generating module"); - solmacrogen.write_to_module(bindings_root, self.single_file)?; } Ok(()) diff --git a/crates/forge/src/cmd/bind_json.rs b/crates/forge/src/cmd/bind_json.rs index 7c6bfaa52ad74..39eb3575ccda2 100644 --- a/crates/forge/src/cmd/bind_json.rs +++ b/crates/forge/src/cmd/bind_json.rs @@ -331,15 +331,13 @@ impl CompiledState { // those. let Some(schema) = resolver.resolve_struct_eip712(id)? else { continue }; - if !include.is_empty() { - if !include.iter().any(|matcher| matcher.is_match(path)) { - continue; - } - } else { + if include.is_empty() { // Exclude library files by default if project.paths.has_library_ancestor(path) { continue; } + } else if !include.iter().any(|matcher| matcher.is_match(path)) { + continue; } if exclude.iter().any(|matcher| matcher.is_match(path)) { diff --git a/crates/forge/src/cmd/cache.rs b/crates/forge/src/cmd/cache.rs index efbdde5cb6981..72a878b0219d5 100644 --- a/crates/forge/src/cmd/cache.rs +++ b/crates/forge/src/cmd/cache.rs @@ -60,7 +60,7 @@ impl CleanArgs { for chain_or_all in chains { match chain_or_all { ChainOrAll::NamedChain(chain) => { - clean_chain_cache(chain, blocks.to_vec(), etherscan)? + clean_chain_cache(chain, blocks.clone(), etherscan)? } ChainOrAll::All => { if etherscan { diff --git a/crates/forge/src/cmd/clone.rs b/crates/forge/src/cmd/clone.rs index aaf157637c9e7..c08f267fd5416 100644 --- a/crates/forge/src/cmd/clone.rs +++ b/crates/forge/src/cmd/clone.rs @@ -195,7 +195,7 @@ impl CloneArgs { let (main_file, main_artifact) = find_main_contract(&compile_output, &meta.contract_name)?; let main_file = main_file.strip_prefix(root)?.to_path_buf(); let storage_layout = - main_artifact.storage_layout.to_owned().expect("storage layout not found"); + main_artifact.storage_layout.clone().expect("storage layout not found"); // dump the metadata to the root directory let creation_tx = client.contract_creation_data(address).await?; diff --git a/crates/forge/src/cmd/create.rs b/crates/forge/src/cmd/create.rs index 42b8ad758423c..356b132de5db0 100644 --- a/crates/forge/src/cmd/create.rs +++ b/crates/forge/src/cmd/create.rs @@ -351,7 +351,14 @@ impl CreateArgs { } if dry_run { - if !shell::is_json() { + if shell::is_json() { + let output = json!({ + "contract": self.contract.name, + "transaction": &deployer.tx, + "abi":&abi + }); + sh_println!("{}", serde_json::to_string_pretty(&output)?)?; + } else { sh_warn!("Dry run enabled, not broadcasting transaction\n")?; sh_println!("Contract: {}", self.contract.name)?; @@ -362,13 +369,6 @@ impl CreateArgs { sh_println!("ABI: {}\n", serde_json::to_string_pretty(&abi)?)?; sh_warn!("To broadcast this transaction, add --broadcast to the previous command. See forge create --help for more.")?; - } else { - let output = json!({ - "contract": self.contract.name, - "transaction": &deployer.tx, - "abi":&abi - }); - sh_println!("{}", serde_json::to_string_pretty(&output)?)?; } return Ok(()); diff --git a/crates/forge/src/cmd/fmt.rs b/crates/forge/src/cmd/fmt.rs index 26f601d7bbac1..ddc4aed8a1702 100644 --- a/crates/forge/src/cmd/fmt.rs +++ b/crates/forge/src/cmd/fmt.rs @@ -89,7 +89,7 @@ impl FmtArgs { SOLC_EXTENSIONS, )); } else if path.is_sol() { - inputs.push(path.to_path_buf()); + inputs.push(path.clone()); } else { warn!("Cannot process path {}", path.display()); } diff --git a/crates/forge/src/cmd/inspect.rs b/crates/forge/src/cmd/inspect.rs index 32daac06f6172..817e553f190c1 100644 --- a/crates/forge/src/cmd/inspect.rs +++ b/crates/forge/src/cmd/inspect.rs @@ -206,15 +206,15 @@ fn print_abi(abi: &JsonAbi) -> Result<()> { for func in abi.functions.iter().flat_map(|(_, f)| f) { let selector = func.selector().to_string(); let state_mut = func.state_mutability.as_json_str(); - let func_sig = if !func.outputs.is_empty() { + let func_sig = if func.outputs.is_empty() { + format!("{}({}) {state_mut}", func.name, get_ty_sig(&func.inputs)) + } else { format!( "{}({}) {state_mut} returns ({})", func.name, get_ty_sig(&func.inputs), get_ty_sig(&func.outputs) ) - } else { - format!("{}({}) {state_mut}", func.name, get_ty_sig(&func.inputs)) }; table.add_row(["function", &func_sig, &selector]); } diff --git a/crates/forge/src/cmd/test/mod.rs b/crates/forge/src/cmd/test/mod.rs index 4fc3ef2a8e7d9..e99ff09a25e8c 100644 --- a/crates/forge/src/cmd/test/mod.rs +++ b/crates/forge/src/cmd/test/mod.rs @@ -704,13 +704,13 @@ impl TestArgs { .iter() .filter_map(|(k, v)| { previous_snapshots.get(k).and_then(|previous_snapshot| { - if previous_snapshot != v { + if previous_snapshot == v { + None + } else { Some(( k.clone(), (previous_snapshot.clone(), v.clone()), )) - } else { - None } }) }) diff --git a/crates/forge/src/runner.rs b/crates/forge/src/runner.rs index 3701b8d7e8926..6cb3b058015e6 100644 --- a/crates/forge/src/runner.rs +++ b/crates/forge/src/runner.rs @@ -352,10 +352,10 @@ impl<'a> ContractRunner<'a> { if setup.reason.is_some() { // The setup failed, so we return a single test result for `setUp` - let fail_msg = if !setup.deployment_failure { - "setUp()".to_string() - } else { + let fail_msg = if setup.deployment_failure { "constructor()".to_string() + } else { + "setUp()".to_string() }; return SuiteResult::new( start.elapsed(), diff --git a/crates/script-sequence/src/sequence.rs b/crates/script-sequence/src/sequence.rs index 4b2b434e11793..41e4cdc67cbf3 100644 --- a/crates/script-sequence/src/sequence.rs +++ b/crates/script-sequence/src/sequence.rs @@ -175,8 +175,8 @@ impl ScriptSequence { chain_id: u64, dry_run: bool, ) -> Result<(PathBuf, PathBuf)> { - let mut broadcast = config.broadcast.to_path_buf(); - let mut cache = config.cache_path.to_path_buf(); + let mut broadcast = config.broadcast.clone(); + let mut cache = config.cache_path.clone(); let mut common = PathBuf::new(); let target_fname = target.source.file_name().wrap_err("No filename.")?; diff --git a/crates/script/src/build.rs b/crates/script/src/build.rs index d3802d60c38bc..8211745d6fcfd 100644 --- a/crates/script/src/build.rs +++ b/crates/script/src/build.rs @@ -187,7 +187,7 @@ impl PreprocessedState { project.paths.sources.as_path(), MultiCompilerLanguage::FILE_EXTENSIONS, ) - .chain([target_path.to_path_buf()]); + .chain([target_path.clone()]); let output = ProjectCompiler::new().files(sources_to_compile).compile(&project)?; @@ -282,7 +282,9 @@ impl CompiledState { } }; - let (args, build_data, script_wallets, script_config) = if !self.args.unlocked { + let (args, build_data, script_wallets, script_config) = if self.args.unlocked { + (self.args, self.build_data, self.script_wallets, self.script_config) + } else { let mut froms = sequence.sequences().iter().flat_map(|s| { s.transactions .iter() @@ -295,7 +297,9 @@ impl CompiledState { .signers() .map_err(|e| eyre::eyre!("Failed to get available signers: {}", e))?; - if !froms.all(|from| available_signers.contains(&from)) { + if froms.all(|from| available_signers.contains(&from)) { + (self.args, self.build_data, self.script_wallets, self.script_config) + } else { // IF we are missing required signers, execute script as we might need to collect // private keys from the execution. let executed = self.link().await?.prepare_execution().await?.execute().await?; @@ -305,11 +309,7 @@ impl CompiledState { executed.script_wallets, executed.script_config, ) - } else { - (self.args, self.build_data, self.script_wallets, self.script_config) } - } else { - (self.args, self.build_data, self.script_wallets, self.script_config) }; // Collect libraries from sequence and link contracts with them. diff --git a/crates/script/src/execute.rs b/crates/script/src/execute.rs index 1073f7cc6bd95..82dea4ee44816 100644 --- a/crates/script/src/execute.rs +++ b/crates/script/src/execute.rs @@ -361,10 +361,10 @@ impl ExecutedState { ty: "unknown".to_string(), }); - let label = if !output.name.is_empty() { - output.name.to_string() - } else { + let label = if output.name.is_empty() { index.to_string() + } else { + output.name.to_string() }; returns.insert( @@ -454,10 +454,10 @@ impl PreSimulationState { ty: "unknown".to_string(), }); - let label = if !output.name.is_empty() { - output.name.to_string() - } else { + let label = if output.name.is_empty() { index.to_string() + } else { + output.name.to_string() }; sh_println!( "{label}: {internal_type} {value}", diff --git a/crates/script/src/multi_sequence.rs b/crates/script/src/multi_sequence.rs index e0fd4d1bc7e68..27dc10ebdcaa4 100644 --- a/crates/script/src/multi_sequence.rs +++ b/crates/script/src/multi_sequence.rs @@ -58,8 +58,8 @@ impl MultiChainSequence { target: &ArtifactId, dry_run: bool, ) -> Result<(PathBuf, PathBuf)> { - let mut broadcast = config.broadcast.to_path_buf(); - let mut cache = config.cache_path.to_path_buf(); + let mut broadcast = config.broadcast.clone(); + let mut cache = config.cache_path.clone(); let mut common = PathBuf::new(); common.push("multi"); diff --git a/crates/script/src/receipts.rs b/crates/script/src/receipts.rs index 605cdf9ddb0de..995254b8f07af 100644 --- a/crates/script/src/receipts.rs +++ b/crates/script/src/receipts.rs @@ -15,10 +15,10 @@ pub enum TxStatus { impl From for TxStatus { fn from(receipt: AnyTransactionReceipt) -> Self { - if !receipt.inner.inner.inner.receipt.status.coerce_status() { - Self::Revert(receipt) - } else { + if receipt.inner.inner.inner.receipt.status.coerce_status() { Self::Success(receipt) + } else { + Self::Revert(receipt) } } } diff --git a/crates/script/src/runner.rs b/crates/script/src/runner.rs index 2d58e381f6356..11915ebf21cbe 100644 --- a/crates/script/src/runner.rs +++ b/crates/script/src/runner.rs @@ -160,10 +160,7 @@ impl ScriptRunner { traces.extend(constructor_traces.map(|traces| (TraceKind::Deployment, traces))); // Optionally call the `setUp` function - let (success, gas_used, labeled_addresses, transactions) = if !setup { - self.executor.backend_mut().set_test_contract(address); - (true, 0, Default::default(), Some(library_transactions)) - } else { + let (success, gas_used, labeled_addresses, transactions) = if setup { match self.executor.setup(Some(self.evm_opts.sender), address, None) { Ok(RawCallResult { reverted, @@ -204,6 +201,9 @@ impl ScriptRunner { } Err(e) => return Err(e.into()), } + } else { + self.executor.backend_mut().set_test_contract(address); + (true, 0, Default::default(), Some(library_transactions)) }; Ok(( diff --git a/crates/script/src/simulate.rs b/crates/script/src/simulate.rs index a58b1058ebc2e..222eba1f6044e 100644 --- a/crates/script/src/simulate.rs +++ b/crates/script/src/simulate.rs @@ -227,7 +227,7 @@ impl PreSimulationState { if !shell::is_json() { let n = rpcs.len(); - let s = if n != 1 { "s" } else { "" }; + let s = if n == 1 { "" } else { "s" }; sh_println!("\n## Setting up {n} EVM{s}.")?; } @@ -278,7 +278,7 @@ impl FilledTransactionsState { let mut txes_iter = self.transactions.clone().into_iter().peekable(); while let Some(mut tx) = txes_iter.next() { - let tx_rpc = tx.rpc.to_owned(); + let tx_rpc = tx.rpc.clone(); let provider_info = manager.get_or_init_provider(&tx.rpc, self.args.legacy).await?; if let Some(tx) = tx.tx_mut().as_unsigned_mut() { @@ -370,15 +370,7 @@ impl FilledTransactionsState { .unwrap_or_else(|_| "[Could not calculate]".to_string()); let estimated_amount = estimated_amount_raw.trim_end_matches('0'); - if !shell::is_json() { - sh_println!("\n==========================")?; - sh_println!("\nChain {}", provider_info.chain)?; - - sh_println!("\nEstimated gas price: {} gwei", estimated_gas_price)?; - sh_println!("\nEstimated total gas used for script: {total_gas}")?; - sh_println!("\nEstimated amount required: {estimated_amount} {token_symbol}")?; - sh_println!("\n==========================")?; - } else { + if shell::is_json() { sh_println!( "{}", serde_json::json!({ @@ -389,6 +381,14 @@ impl FilledTransactionsState { "token_symbol": token_symbol, }) )?; + } else { + sh_println!("\n==========================")?; + sh_println!("\nChain {}", provider_info.chain)?; + + sh_println!("\nEstimated gas price: {} gwei", estimated_gas_price)?; + sh_println!("\nEstimated total gas used for script: {total_gas}")?; + sh_println!("\nEstimated amount required: {estimated_amount} {token_symbol}")?; + sh_println!("\n==========================")?; } } } diff --git a/crates/sol-macro-gen/src/sol_macro_gen.rs b/crates/sol-macro-gen/src/sol_macro_gen.rs index 62cdebfd54386..ffe33d76be65c 100644 --- a/crates/sol-macro-gen/src/sol_macro_gen.rs +++ b/crates/sol-macro-gen/src/sol_macro_gen.rs @@ -187,7 +187,12 @@ edition = "2021" for instance in &self.instances { let name = instance.name.to_lowercase(); - if !single_file { + if single_file { + // Single File + let mut contents = String::new(); + write!(contents, "{}\n\n", instance.expansion.as_ref().unwrap())?; + write!(mod_contents, "{contents}")?; + } else { // Module write_mod_name(&mut mod_contents, &name)?; let mut contents = String::new(); @@ -198,11 +203,6 @@ edition = "2021" let contents = prettyplease::unparse(&file); fs::write(bindings_path.join(format!("{name}.rs")), contents) .wrap_err("Failed to write file")?; - } else { - // Single File - let mut contents = String::new(); - write!(contents, "{}\n\n", instance.expansion.as_ref().unwrap())?; - write!(mod_contents, "{contents}")?; } } diff --git a/crates/test-utils/src/util.rs b/crates/test-utils/src/util.rs index 17d6036ac5bcd..cb430593e1b2d 100644 --- a/crates/test-utils/src/util.rs +++ b/crates/test-utils/src/util.rs @@ -248,8 +248,7 @@ pub fn initialize(target: &Path) { // but `TempProject` does not currently allow this: https://github.com/foundry-rs/compilers/issues/22 // Release the read lock and acquire a write lock, initializing the lock file. - _read = None; - + drop(_read); let mut write = lock.write().unwrap(); let mut data = String::new(); diff --git a/crates/verify/src/bytecode.rs b/crates/verify/src/bytecode.rs index c3ddd3c4df867..fe77408a02f07 100644 --- a/crates/verify/src/bytecode.rs +++ b/crates/verify/src/bytecode.rs @@ -172,7 +172,7 @@ impl VerifyBytecodeArgs { let source_code = etherscan.contract_source_code(self.address).await?; // Check if the contract name matches. - let name = source_code.items.first().map(|item| item.contract_name.to_owned()); + let name = source_code.items.first().map(|item| item.contract_name.clone()); if name.as_ref() != Some(&self.contract.name) { eyre::bail!("Contract name mismatch"); } @@ -198,15 +198,15 @@ impl VerifyBytecodeArgs { .ok_or_eyre("Unlinked bytecode is not supported for verification")?; // Get and encode user provided constructor args - let provided_constructor_args = if let Some(path) = self.constructor_args_path.to_owned() { + let provided_constructor_args = if let Some(path) = self.constructor_args_path.clone() { // Read from file Some(read_constructor_args_file(path)?) } else { - self.constructor_args.to_owned() + self.constructor_args.clone() } .map(|args| check_and_encode_args(&artifact, args)) .transpose()? - .or(self.encoded_constructor_args.to_owned().map(hex::decode).transpose()?); + .or(self.encoded_constructor_args.clone().map(hex::decode).transpose()?); let mut constructor_args = if let Some(provided) = provided_constructor_args { provided.into() diff --git a/crates/verify/src/etherscan/flatten.rs b/crates/verify/src/etherscan/flatten.rs index a0b3defd7f90e..bfdc6e51870e9 100644 --- a/crates/verify/src/etherscan/flatten.rs +++ b/crates/verify/src/etherscan/flatten.rs @@ -113,9 +113,9 @@ Diagnostics: {diags}", /// sanitized variant of the specific version so that it can be installed. This is merely /// intended to ensure the flattened code can be compiled without errors. fn strip_build_meta(version: Version) -> Version { - if version.build != BuildMetadata::EMPTY { - Version::new(version.major, version.minor, version.patch) - } else { + if version.build == BuildMetadata::EMPTY { version + } else { + Version::new(version.major, version.minor, version.patch) } } diff --git a/crates/verify/src/etherscan/mod.rs b/crates/verify/src/etherscan/mod.rs index aad51093886d7..098cc1af89e96 100644 --- a/crates/verify/src/etherscan/mod.rs +++ b/crates/verify/src/etherscan/mod.rs @@ -283,11 +283,11 @@ impl EtherscanVerificationProvider { // API key passed. let is_etherscan = verifier_type.is_etherscan() || (verifier_type.is_sourcify() && etherscan_key.is_some()); - let base_url = if !is_etherscan { + let base_url = if is_etherscan { + base_url.unwrap_or(api_url) + } else { // If verifier is not Etherscan then set base url as api url without /api suffix. api_url.strip_prefix("/api").unwrap_or(api_url) - } else { - base_url.unwrap_or(api_url) }; builder.with_chain_id(chain).with_api_url(api_url)?.with_url(base_url)? } else { @@ -370,7 +370,7 @@ impl EtherscanVerificationProvider { }; let encoded_args = encode_function_args( &func, - read_constructor_args_file(constructor_args_path.to_path_buf())?, + read_constructor_args_file(constructor_args_path.clone())?, )?; let encoded_args = hex::encode(encoded_args); return Ok(Some(encoded_args[8..].into())) @@ -455,10 +455,10 @@ impl EtherscanVerificationProvider { /// assert_ne!(version.build, BuildMetadata::EMPTY); /// ``` async fn ensure_solc_build_metadata(version: Version) -> Result { - if version.build != BuildMetadata::EMPTY { - Ok(version) - } else { + if version.build == BuildMetadata::EMPTY { Ok(lookup_compiler_version(&version).await?) + } else { + Ok(version) } } diff --git a/crates/verify/src/utils.rs b/crates/verify/src/utils.rs index 132f0218f8d79..c4e563c74c0cd 100644 --- a/crates/verify/src/utils.rs +++ b/crates/verify/src/utils.rs @@ -103,8 +103,8 @@ pub fn build_using_cache( let cached_artifacts = cache.read_artifacts::()?; for (key, value) in cached_artifacts { - let name = args.contract.name.to_owned() + ".sol"; - let version = etherscan_settings.compiler_version.to_owned(); + let name = args.contract.name.clone() + ".sol"; + let version = etherscan_settings.compiler_version.clone(); // Ignores vyper if version.starts_with("vyper:") { eyre::bail!("Vyper contracts are not supported") @@ -147,15 +147,15 @@ pub fn print_result( config: &Config, ) { if let Some(res) = res { - if !shell::is_json() { + if shell::is_json() { + let json_res = JsonResult { bytecode_type, match_type: Some(res), message: None }; + json_results.push(json_res); + } else { let _ = sh_println!( "{} with status {}", format!("{bytecode_type:?} code matched").green().bold(), res.green().bold() ); - } else { - let json_res = JsonResult { bytecode_type, match_type: Some(res), message: None }; - json_results.push(json_res); } } else if !shell::is_json() { let _ = sh_err!( diff --git a/crates/wallets/src/multi_wallet.rs b/crates/wallets/src/multi_wallet.rs index 19dbd978691ea..8f869440f3a19 100644 --- a/crates/wallets/src/multi_wallet.rs +++ b/crates/wallets/src/multi_wallet.rs @@ -268,14 +268,14 @@ impl MultiWalletOpts { pks.push(pk); } } - if !pks.is_empty() { + if pks.is_empty() { + Ok(None) + } else { let wallets = pks .into_iter() .map(|pk| utils::create_private_key_signer(pk)) .collect::>>()?; Ok(Some(wallets)) - } else { - Ok(None) } } diff --git a/crates/wallets/src/utils.rs b/crates/wallets/src/utils.rs index ab1871d6b90b0..f83fd284dc87b 100644 --- a/crates/wallets/src/utils.rs +++ b/crates/wallets/src/utils.rs @@ -123,9 +123,7 @@ pub fn create_keystore_signer( (Some(password), _) => Ok(Some(password.to_string())), (_, Some(password_file)) => { let password_file = Path::new(password_file); - if !password_file.is_file() { - Err(eyre::eyre!("Keystore password file `{password_file:?}` does not exist")) - } else { + if password_file.is_file() { Ok(Some( fs::read_to_string(password_file) .wrap_err_with(|| { @@ -134,6 +132,8 @@ pub fn create_keystore_signer( .trim_end() .to_string(), )) + } else { + Err(eyre::eyre!("Keystore password file `{password_file:?}` does not exist")) } } (None, None) => Ok(None), From 2d5c472b6daa0bd0704fa1804caacd27798e5b78 Mon Sep 17 00:00:00 2001 From: taikoonwang Date: Sat, 22 Mar 2025 17:50:13 +0800 Subject: [PATCH 4/8] save --- Cargo.toml | 14 +++++++++----- crates/anvil/tests/it/fork.rs | 8 ++++---- crates/cheatcodes/src/evm.rs | 2 +- crates/cheatcodes/src/inspector.rs | 2 +- crates/cli/src/opts/dependency.rs | 20 ++++++++------------ crates/cli/src/utils/cmd.rs | 4 ++-- crates/common/fmt/src/console.rs | 6 +++--- crates/doc/src/parser/mod.rs | 6 +++--- crates/evm/traces/src/folded_stack_trace.rs | 2 +- crates/fmt/src/comments.rs | 2 +- crates/fmt/src/formatter.rs | 2 +- crates/forge/src/cmd/clone.rs | 4 ++-- crates/forge/src/cmd/test/mod.rs | 4 ++-- crates/forge/src/multi_runner.rs | 4 ++-- crates/forge/src/progress.rs | 4 ++-- crates/forge/src/runner.rs | 2 +- crates/script/src/progress.rs | 2 +- crates/verify/src/etherscan/mod.rs | 2 +- 18 files changed, 45 insertions(+), 45 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 602e0ebee40a5..a383f3f7816a2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -46,23 +46,27 @@ explicit_into_iter_loop = "warn" explicit_iter_loop = "warn" flat_map_option = "warn" from_iter_instead_of_collect = "warn" -if_not_else = "warn" -if_then_some_else_none = "warn" implicit_clone = "warn" imprecise_flops = "warn" iter_on_empty_collections = "warn" -iter_on_single_items = "warn" iter_with_drain = "warn" iter_without_into_iter = "warn" large_stack_frames = "warn" manual-string-new = "warn" +naive_bytecount = "warn" +needless_bitwise_bool = "warn" +needless_continue = "warn" +needless_for_each = "warn" +needless_pass_by_ref_mut = "warn" +nonstandard_macro_braces = "warn" uninlined-format-args = "warn" use-self = "warn" -redundant-clone = "warn" +read_zero_byte_vec = "warn" +result_large_err = "allow" +redundant_clone = "warn" octal-escapes = "allow" # until is fixed literal-string-with-formatting-args = "allow" -result_large_err = "allow" [workspace.lints.rust] rust-2018-idioms = "warn" diff --git a/crates/anvil/tests/it/fork.rs b/crates/anvil/tests/it/fork.rs index 4a4d28b164cea..f2fdb9e3e07da 100644 --- a/crates/anvil/tests/it/fork.rs +++ b/crates/anvil/tests/it/fork.rs @@ -1466,12 +1466,12 @@ async fn test_reset_dev_account_nonce() { async fn test_reset_updates_cache_path_when_rpc_url_not_provided() { let config: NodeConfig = fork_config(); - let (mut api, _handle) = spawn(config).await; + let (api, _handle) = spawn(config).await; let info = api.anvil_node_info().await.unwrap(); let number = info.fork_config.fork_block_number.unwrap(); assert_eq!(number, BLOCK_NUMBER); - async fn get_block_from_cache_path(api: &mut EthApi) -> u64 { + async fn get_block_from_cache_path(api: &EthApi) -> u64 { let db = api.backend.get_db().read().await; let cache_path = db.maybe_inner().unwrap().cache().cache_path().unwrap(); cache_path @@ -1485,7 +1485,7 @@ async fn test_reset_updates_cache_path_when_rpc_url_not_provided() { .expect("must be valid number") } - assert_eq!(BLOCK_NUMBER, get_block_from_cache_path(&mut api).await); + assert_eq!(BLOCK_NUMBER, get_block_from_cache_path(&api).await); // Reset to older block without specifying a new rpc url api.anvil_reset(Some(Forking { @@ -1495,7 +1495,7 @@ async fn test_reset_updates_cache_path_when_rpc_url_not_provided() { .await .unwrap(); - assert_eq!(BLOCK_NUMBER - 1_000_000, get_block_from_cache_path(&mut api).await); + assert_eq!(BLOCK_NUMBER - 1_000_000, get_block_from_cache_path(&api).await); } #[tokio::test(flavor = "multi_thread")] diff --git a/crates/cheatcodes/src/evm.rs b/crates/cheatcodes/src/evm.rs index 52d246958436b..64d82dd0ea0be 100644 --- a/crates/cheatcodes/src/evm.rs +++ b/crates/cheatcodes/src/evm.rs @@ -1180,7 +1180,7 @@ fn genesis_account(account: &Account) -> GenesisAccount { } /// Helper function to returns state diffs recorded for each changed account. -fn get_recorded_state_diffs(state: &mut Cheatcodes) -> BTreeMap { +fn get_recorded_state_diffs(state: &Cheatcodes) -> BTreeMap { let mut state_diffs: BTreeMap = BTreeMap::default(); if let Some(records) = &state.recorded_account_diffs_stack { records diff --git a/crates/cheatcodes/src/inspector.rs b/crates/cheatcodes/src/inspector.rs index 151c998f42e2e..76f8807f45525 100644 --- a/crates/cheatcodes/src/inspector.rs +++ b/crates/cheatcodes/src/inspector.rs @@ -1777,7 +1777,7 @@ impl Cheatcodes { } #[cold] - fn meter_gas_record(&mut self, interpreter: &mut Interpreter, ecx: Ecx) { + fn meter_gas_record(&mut self, interpreter: &Interpreter, ecx: Ecx) { if matches!(interpreter.instruction_result, InstructionResult::Continue) { self.gas_metering.gas_records.iter_mut().for_each(|record| { if ecx.journaled_state.depth() == record.depth { diff --git a/crates/cli/src/opts/dependency.rs b/crates/cli/src/opts/dependency.rs index b0e9eeadbb8e9..6f6442e6f33ba 100644 --- a/crates/cli/src/opts/dependency.rs +++ b/crates/cli/src/opts/dependency.rs @@ -160,7 +160,7 @@ mod tests { #[test] fn parses_dependencies() { - [ + for (input, expected_path, expected_tag, expected_alias) in &[ ("gakonst/lootloose", "https://github.com/gakonst/lootloose", None, None), ("github.com/gakonst/lootloose", "https://github.com/gakonst/lootloose", None, None), ( @@ -242,15 +242,13 @@ mod tests { Some("v1"), Some("loot"), ), - ] - .iter() - .for_each(|(input, expected_path, expected_tag, expected_alias)| { + ] { let dep = Dependency::from_str(input).unwrap(); assert_eq!(dep.url, Some(expected_path.to_string())); assert_eq!(dep.tag, expected_tag.map(ToString::to_string)); assert_eq!(dep.name, "lootloose"); assert_eq!(dep.alias, expected_alias.map(ToString::to_string)); - }); + } } #[test] @@ -270,28 +268,26 @@ mod tests { #[test] fn parses_contract_info() { - [ + for (input, expected_path, expected_name) in &[ ( "src/contracts/Contracts.sol:Contract", Some("src/contracts/Contracts.sol"), "Contract", ), ("Contract", None, "Contract"), - ] - .iter() - .for_each(|(input, expected_path, expected_name)| { + ] { let contract = ContractInfo::from_str(input).unwrap(); assert_eq!(contract.path, expected_path.map(ToString::to_string)); assert_eq!(contract.name, expected_name.to_string()); - }); + } } #[test] fn contract_info_should_reject_without_name() { - ["src/contracts/", "src/contracts/Contracts.sol"].iter().for_each(|input| { + for input in &["src/contracts/", "src/contracts/Contracts.sol"] { let contract = ContractInfo::from_str(input); assert!(contract.is_err()) - }); + } } #[test] diff --git a/crates/cli/src/utils/cmd.rs b/crates/cli/src/utils/cmd.rs index 3dcec54ec218d..957a335acaa10 100644 --- a/crates/cli/src/utils/cmd.rs +++ b/crates/cli/src/utils/cmd.rs @@ -455,12 +455,12 @@ pub fn cache_local_signatures(output: &ProjectCompileOutput, cache_path: PathBuf } // External libraries doesn't have functions included in abi, but `methodIdentifiers`. if let Some(method_identifiers) = &artifact.method_identifiers { - method_identifiers.iter().for_each(|(signature, selector)| { + for (signature, selector) in method_identifiers { cached_signatures .functions .entry(format!("0x{selector}")) .or_insert(signature.to_string()); - }); + } } } }); diff --git a/crates/common/fmt/src/console.rs b/crates/common/fmt/src/console.rs index d8197f2d388b9..d6c349cda3f7f 100644 --- a/crates/common/fmt/src/console.rs +++ b/crates/common/fmt/src/console.rs @@ -127,15 +127,15 @@ impl<'a> Parser<'a> { self.input[start..end].parse().ok() } - fn current_pos(&mut self) -> usize { + fn current_pos(&self) -> usize { self.peek().map(|(n, _)| n).unwrap_or(self.input.len()) } - fn peek(&mut self) -> Option<(usize, char)> { + fn peek(&self) -> Option<(usize, char)> { self.peek_n(0) } - fn peek_n(&mut self, n: usize) -> Option<(usize, char)> { + fn peek_n(&self, n: usize) -> Option<(usize, char)> { self.chars.clone().nth(n) } } diff --git a/crates/doc/src/parser/mod.rs b/crates/doc/src/parser/mod.rs index 1cf496c22f94b..7f97e1d797358 100644 --- a/crates/doc/src/parser/mod.rs +++ b/crates/doc/src/parser/mod.rs @@ -99,18 +99,18 @@ impl Parser { } /// Create new [ParseItem] with comments and formatted code. - fn new_item(&mut self, source: ParseSource, loc_start: usize) -> ParserResult { + fn new_item(&self, source: ParseSource, loc_start: usize) -> ParserResult { let docs = self.parse_docs(loc_start)?; ParseItem::new(source).with_comments(docs).with_code(&self.source, self.fmt.clone()) } /// Parse the doc comments from the current start location. - fn parse_docs(&mut self, end: usize) -> ParserResult { + fn parse_docs(&self, end: usize) -> ParserResult { self.parse_docs_range(self.context.doc_start_loc, end) } /// Parse doc comments from the within specified range. - fn parse_docs_range(&mut self, start: usize, end: usize) -> ParserResult { + fn parse_docs_range(&self, start: usize, end: usize) -> ParserResult { let mut res = vec![]; for comment in parse_doccomments(&self.comments, start, end) { match comment { diff --git a/crates/evm/traces/src/folded_stack_trace.rs b/crates/evm/traces/src/folded_stack_trace.rs index 603ff96a7e3d9..3dc2a5ecfb4d6 100644 --- a/crates/evm/traces/src/folded_stack_trace.rs +++ b/crates/evm/traces/src/folded_stack_trace.rs @@ -179,7 +179,7 @@ impl FoldedStackTraceBuilder { /// Internal method to build the folded stack trace without subtracting gas consumed by /// the children function calls. - fn build_without_subtraction(&mut self) -> Vec { + fn build_without_subtraction(&self) -> Vec { let mut lines = Vec::new(); for TraceEntry { names, gas } in &self.traces { lines.push(format!("{} {}", names.join(";"), gas)); diff --git a/crates/fmt/src/comments.rs b/crates/fmt/src/comments.rs index eafdb998910d9..4bf613a064268 100644 --- a/crates/fmt/src/comments.rs +++ b/crates/fmt/src/comments.rs @@ -338,7 +338,7 @@ impl<'a> CommentStateCharIndices<'a> { } #[inline] - pub fn peek(&mut self) -> Option<(usize, char)> { + pub fn peek(&self) -> Option<(usize, char)> { self.iter.clone().next() } } diff --git a/crates/fmt/src/formatter.rs b/crates/fmt/src/formatter.rs index 2d421a6fd7c96..8a5031b375606 100644 --- a/crates/fmt/src/formatter.rs +++ b/crates/fmt/src/formatter.rs @@ -323,7 +323,7 @@ impl<'a, W: Write> Formatter<'a, W> { /// lookup whether there was a newline introduced in `[start_from, end_at]` range /// where `end_at` is the start of the block. fn should_attempt_block_single_line( - &mut self, + &self, stmt: &mut Statement, start_from: usize, ) -> bool { diff --git a/crates/forge/src/cmd/clone.rs b/crates/forge/src/cmd/clone.rs index c08f267fd5416..cb405fd58f2dd 100644 --- a/crates/forge/src/cmd/clone.rs +++ b/crates/forge/src/cmd/clone.rs @@ -645,7 +645,7 @@ mod tests { stripped_creation_code: &str, ) { compiled.compiled_contracts_by_compiler_version().iter().for_each(|(_, contracts)| { - contracts.iter().for_each(|(name, contract)| { + for (name, contract) in contracts { if name == contract_name { let compiled_creation_code = contract.bin_ref().expect("creation code not found"); @@ -655,7 +655,7 @@ mod tests { "inconsistent creation code" ); } - }); + } }); } diff --git a/crates/forge/src/cmd/test/mod.rs b/crates/forge/src/cmd/test/mod.rs index e99ff09a25e8c..0192f2651c894 100644 --- a/crates/forge/src/cmd/test/mod.rs +++ b/crates/forge/src/cmd/test/mod.rs @@ -472,7 +472,7 @@ impl TestArgs { // Run tests in a non-streaming fashion and collect results for serialization. if !self.gas_report && !self.summary && shell::is_json() { let mut results = runner.test_collect(filter); - results.values_mut().for_each(|suite_result| { + for suite_result in results.values_mut() { for test_result in suite_result.test_results.values_mut() { if verbosity >= 2 { // Decode logs at level 2 and above. @@ -482,7 +482,7 @@ impl TestArgs { test_result.logs = vec![]; } } - }); + } sh_println!("{}", serde_json::to_string(&results)?)?; return Ok(TestOutcome::new(results, self.allow_failure)); } diff --git a/crates/forge/src/multi_runner.rs b/crates/forge/src/multi_runner.rs index 8ecb0e63a6152..2747f1df0adce 100644 --- a/crates/forge/src/multi_runner.rs +++ b/crates/forge/src/multi_runner.rs @@ -211,9 +211,9 @@ impl MultiContractRunner { tests_progress.inner.lock().clear(); - results.iter().for_each(|result| { + for result in &results { let _ = tx.send(result.to_owned()); - }); + } } else { contracts.par_iter().for_each(|&(id, contract)| { let _guard = tokio_handle.enter(); diff --git a/crates/forge/src/progress.rs b/crates/forge/src/progress.rs index 9ca182f769d50..4269c5d736e36 100644 --- a/crates/forge/src/progress.rs +++ b/crates/forge/src/progress.rs @@ -61,7 +61,7 @@ impl TestsProgressState { /// phase. Test progress is placed under test suite progress entry so all tests within suite /// are grouped. pub fn start_fuzz_progress( - &mut self, + &self, suite_name: &str, test_name: &String, runs: u32, @@ -84,7 +84,7 @@ impl TestsProgressState { } /// Removes overall test progress. - pub fn clear(&mut self) { + pub fn clear(&self) { self.multi.clear().unwrap(); } } diff --git a/crates/forge/src/runner.rs b/crates/forge/src/runner.rs index 6cb3b058015e6..5cb5f9457fc74 100644 --- a/crates/forge/src/runner.rs +++ b/crates/forge/src/runner.rs @@ -241,7 +241,7 @@ impl<'a> ContractRunner<'a> { /// `function fixture_owner() public returns (address[] memory){}` /// returns an array of addresses to be used for fuzzing `owner` named parameter in scope of the /// current test. - fn fuzz_fixtures(&mut self, address: Address) -> FuzzFixtures { + fn fuzz_fixtures(&self, address: Address) -> FuzzFixtures { let mut fixtures = HashMap::default(); let fixture_functions = self.contract.abi.functions().filter(|func| func.is_fixture()); for func in fixture_functions { diff --git a/crates/script/src/progress.rs b/crates/script/src/progress.rs index a0a5ba5609030..b80aa98b962a8 100644 --- a/crates/script/src/progress.rs +++ b/crates/script/src/progress.rs @@ -121,7 +121,7 @@ impl SequenceProgressState { } /// Sets status for the current sequence progress. - pub fn set_status(&mut self, status: &str) { + pub fn set_status(&self, status: &str) { self.top_spinner.set_message(format!(" | {status}")); } diff --git a/crates/verify/src/etherscan/mod.rs b/crates/verify/src/etherscan/mod.rs index 098cc1af89e96..204a19fd73fa9 100644 --- a/crates/verify/src/etherscan/mod.rs +++ b/crates/verify/src/etherscan/mod.rs @@ -387,7 +387,7 @@ impl EtherscanVerificationProvider { /// match provided creation code with local bytecode of the target contract. /// If bytecode match, returns latest bytes of on-chain creation code as constructor arguments. async fn guess_constructor_args( - &mut self, + &self, args: &VerifyArgs, context: &VerificationContext, ) -> Result { From c06d1170ee60273f407d521596a8d7b5be786f39 Mon Sep 17 00:00:00 2001 From: taikoonwang Date: Sat, 22 Mar 2025 22:15:23 +0800 Subject: [PATCH 5/8] fmt --- crates/cheatcodes/src/inspector.rs | 10 +++++----- crates/config/src/etherscan.rs | 2 +- crates/config/src/lib.rs | 5 ++--- crates/evm/evm/src/executors/invariant/mod.rs | 2 +- crates/evm/evm/src/inspectors/stack.rs | 4 ++-- crates/evm/fuzz/src/inspector.rs | 2 +- crates/fmt/src/formatter.rs | 6 +----- crates/forge/src/cmd/install.rs | 2 +- crates/script/src/lib.rs | 1 - crates/verify/src/etherscan/mod.rs | 6 +++--- 10 files changed, 17 insertions(+), 23 deletions(-) diff --git a/crates/cheatcodes/src/inspector.rs b/crates/cheatcodes/src/inspector.rs index 76f8807f45525..6a929c43d179a 100644 --- a/crates/cheatcodes/src/inspector.rs +++ b/crates/cheatcodes/src/inspector.rs @@ -1798,7 +1798,7 @@ impl Cheatcodes { } #[cold] - fn meter_gas_end(&mut self, interpreter: &mut Interpreter) { + fn meter_gas_end(&mut self, interpreter: &Interpreter) { // Remove recorded gas if we exit frame. if will_exit(interpreter.instruction_result) { self.gas_metering.paused_frames.pop(); @@ -1812,7 +1812,7 @@ impl Cheatcodes { } #[cold] - fn meter_gas_check(&mut self, interpreter: &mut Interpreter) { + fn meter_gas_check(&self, interpreter: &mut Interpreter) { if will_exit(interpreter.instruction_result) { // Reset gas if spent is less than refunded. // This can happen if gas was paused / resumed or reset. @@ -1833,7 +1833,7 @@ impl Cheatcodes { /// cache) from mapped source address to the target address. /// - generates arbitrary value and saves it in target address storage. #[cold] - fn arbitrary_storage_end(&mut self, interpreter: &mut Interpreter, ecx: Ecx) { + fn arbitrary_storage_end(&mut self, interpreter: &Interpreter, ecx: Ecx) { let (key, target_address) = if interpreter.current_opcode() == op::SLOAD { (try_or_return!(interpreter.stack().peek(0)), interpreter.contract().target_address) } else { @@ -1867,7 +1867,7 @@ impl Cheatcodes { /// Records storage slots reads and writes. #[cold] - fn record_accesses(&mut self, interpreter: &mut Interpreter) { + fn record_accesses(&mut self, interpreter: &Interpreter) { let Some(access) = &mut self.accesses else { return }; match interpreter.current_opcode() { op::SLOAD => { @@ -1883,7 +1883,7 @@ impl Cheatcodes { } #[cold] - fn record_state_diffs(&mut self, interpreter: &mut Interpreter, ecx: Ecx) { + fn record_state_diffs(&mut self, interpreter: &Interpreter, ecx: Ecx) { let Some(account_accesses) = &mut self.recorded_account_diffs_stack else { return }; match interpreter.current_opcode() { op::SELFDESTRUCT => { diff --git a/crates/config/src/etherscan.rs b/crates/config/src/etherscan.rs index 2771d45eb7cc0..75d17c2a70995 100644 --- a/crates/config/src/etherscan.rs +++ b/crates/config/src/etherscan.rs @@ -138,7 +138,7 @@ impl ResolvedEtherscanConfigs { match config { Ok(c) if c.chain == Some(chain) => return Some(Ok(c)), Err(e) => return Some(Err(e)), - _ => continue, + Ok(_) => {} } } None diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs index 23edf19f3f926..7911a9139f84b 100644 --- a/crates/config/src/lib.rs +++ b/crates/config/src/lib.rs @@ -1960,9 +1960,8 @@ impl Config { } if let Ok(entries) = cache_dir.as_path().read_dir() { for entry in entries.flatten().filter(|x| x.path().is_dir()) { - match Chain::from_str(&entry.file_name().to_string_lossy()) { - Ok(chain) => cache.chains.push(Self::list_foundry_chain_cache(chain)?), - Err(_) => continue, + if let Ok(chain) = Chain::from_str(&entry.file_name().to_string_lossy()) { + cache.chains.push(Self::list_foundry_chain_cache(chain)?); } } Ok(cache) diff --git a/crates/evm/evm/src/executors/invariant/mod.rs b/crates/evm/evm/src/executors/invariant/mod.rs index aaf9a881a1f50..939533818a3cb 100644 --- a/crates/evm/evm/src/executors/invariant/mod.rs +++ b/crates/evm/evm/src/executors/invariant/mod.rs @@ -663,7 +663,7 @@ impl<'a> InvariantExecutor<'a> { /// Makes sure that the contract exists in the project. If so, it returns its artifact /// identifier. fn validate_selected_contract( - &mut self, + &self, contract: String, selectors: &[FixedBytes<4>], ) -> Result { diff --git a/crates/evm/evm/src/inspectors/stack.rs b/crates/evm/evm/src/inspectors/stack.rs index e23adfcae0661..d742d9e603f39 100644 --- a/crates/evm/evm/src/inspectors/stack.rs +++ b/crates/evm/evm/src/inspectors/stack.rs @@ -487,7 +487,7 @@ impl InspectorStackRefMut<'_> { /// Should be called on the top-level call of inner context (depth == 0 && /// self.in_inner_context) Decreases sender nonce for CALLs to keep backwards compatibility /// Updates tx.origin to the value before entering inner context - fn adjust_evm_data_for_inner_context(&mut self, ecx: &mut EvmContext<&mut dyn DatabaseExt>) { + fn adjust_evm_data_for_inner_context(&self, ecx: &mut EvmContext<&mut dyn DatabaseExt>) { let inner_context_data = self.inner_context_data.as_ref().expect("should be called in inner context"); ecx.env.tx.caller = inner_context_data.original_origin; @@ -717,7 +717,7 @@ impl InspectorStackRefMut<'_> { } /// Invoked at the beginning of a new top-level (0 depth) frame. - fn top_level_frame_start(&mut self, ecx: &mut EvmContext<&mut dyn DatabaseExt>) { + fn top_level_frame_start(&mut self, ecx: &EvmContext<&mut dyn DatabaseExt>) { if self.enable_isolation { // If we're in isolation mode, we need to keep track of the state at the beginning of // the frame to be able to roll back on revert diff --git a/crates/evm/fuzz/src/inspector.rs b/crates/evm/fuzz/src/inspector.rs index 052d87dac2dd1..0caf9c33101b2 100644 --- a/crates/evm/fuzz/src/inspector.rs +++ b/crates/evm/fuzz/src/inspector.rs @@ -60,7 +60,7 @@ impl Inspector for Fuzzer { impl Fuzzer { /// Collects `stack` and `memory` values into the fuzz dictionary. - fn collect_data(&mut self, interpreter: &Interpreter) { + fn collect_data(&self, interpreter: &Interpreter) { self.fuzz_state.collect_values(interpreter.stack().data().iter().copied().map(Into::into)); // TODO: disabled for now since it's flooding the dictionary diff --git a/crates/fmt/src/formatter.rs b/crates/fmt/src/formatter.rs index 8a5031b375606..340b578d1e40a 100644 --- a/crates/fmt/src/formatter.rs +++ b/crates/fmt/src/formatter.rs @@ -322,11 +322,7 @@ impl<'a, W: Write> Formatter<'a, W> { /// If the block style is configured to [SingleLineBlockStyle::Preserve], /// lookup whether there was a newline introduced in `[start_from, end_at]` range /// where `end_at` is the start of the block. - fn should_attempt_block_single_line( - &self, - stmt: &mut Statement, - start_from: usize, - ) -> bool { + fn should_attempt_block_single_line(&self, stmt: &mut Statement, start_from: usize) -> bool { match self.config.single_line_statement_blocks { SingleLineBlockStyle::Single => true, SingleLineBlockStyle::Multi => false, diff --git a/crates/forge/src/cmd/install.rs b/crates/forge/src/cmd/install.rs index 7672787ce26f6..c3567895ef120 100644 --- a/crates/forge/src/cmd/install.rs +++ b/crates/forge/src/cmd/install.rs @@ -432,7 +432,7 @@ impl Installer<'_> { sh_println!("[{i}] {c} selected")?; return Ok(c.clone()) } - _ => continue, + _ => {} } } } diff --git a/crates/script/src/lib.rs b/crates/script/src/lib.rs index 60a68990bbdf7..152d6a58146d1 100644 --- a/crates/script/src/lib.rs +++ b/crates/script/src/lib.rs @@ -414,7 +414,6 @@ impl ScriptArgs { bytecodes.push((format!("Unknown{unknown_c}"), init_code, deployed_code)); unknown_c += 1; } - continue; } let mut prompt_user = false; diff --git a/crates/verify/src/etherscan/mod.rs b/crates/verify/src/etherscan/mod.rs index 204a19fd73fa9..8ef12f9190197 100644 --- a/crates/verify/src/etherscan/mod.rs +++ b/crates/verify/src/etherscan/mod.rs @@ -214,7 +214,7 @@ impl EtherscanVerificationProvider { /// Configures the API request to the Etherscan API using the given [`VerifyArgs`]. async fn prepare_verify_request( - &mut self, + &self, args: &VerifyArgs, context: &VerificationContext, ) -> Result<(Client, VerifyContract)> { @@ -305,7 +305,7 @@ impl EtherscanVerificationProvider { /// If `--flatten` is set to `true` then this will send with [`CodeFormat::SingleFile`] /// otherwise this will use the [`CodeFormat::StandardJsonInput`] pub async fn create_verify_request( - &mut self, + &self, args: &VerifyArgs, context: &VerificationContext, ) -> Result { @@ -353,7 +353,7 @@ impl EtherscanVerificationProvider { /// constructor arguments was provided, read them and encode. Otherwise, /// return whatever was set in the [VerifyArgs] args. async fn constructor_args( - &mut self, + &self, args: &VerifyArgs, context: &VerificationContext, ) -> Result> { From 1f91d178e3fb8c225ff46885180c98734b980f4b Mon Sep 17 00:00:00 2001 From: taikoonwang Date: Sat, 22 Mar 2025 22:30:35 +0800 Subject: [PATCH 6/8] fix --- crates/script/src/build.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/script/src/build.rs b/crates/script/src/build.rs index 8211745d6fcfd..ceb2012bce8bb 100644 --- a/crates/script/src/build.rs +++ b/crates/script/src/build.rs @@ -182,7 +182,6 @@ impl PreprocessedState { } }; - #[expect(clippy::redundant_clone)] let sources_to_compile = source_files_iter( project.paths.sources.as_path(), MultiCompilerLanguage::FILE_EXTENSIONS, From 042569a47f4aaa20e7b413c8f49e060e36e9875c Mon Sep 17 00:00:00 2001 From: zerosnacks Date: Tue, 25 Mar 2025 13:47:27 +0100 Subject: [PATCH 7/8] sort lint rules --- Cargo.toml | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 17be25850e5d7..130c69b7a1559 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -58,14 +58,15 @@ needless_continue = "warn" needless_for_each = "warn" needless_pass_by_ref_mut = "warn" nonstandard_macro_braces = "warn" -uninlined-format-args = "warn" -use-self = "warn" read_zero_byte_vec = "warn" -result_large_err = "allow" redundant_clone = "warn" -octal-escapes = "allow" +uninlined-format-args = "warn" +use-self = "warn" + # until is fixed literal-string-with-formatting-args = "allow" +octal-escapes = "allow" +result_large_err = "allow" [workspace.lints.rust] rust-2018-idioms = "warn" From e740a61a5ce11ff90c6d2e4e15f740e6cfe3e685 Mon Sep 17 00:00:00 2001 From: zerosnacks Date: Tue, 25 Mar 2025 14:13:04 +0100 Subject: [PATCH 8/8] fix nit --- crates/evm/fuzz/src/strategies/param.rs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/crates/evm/fuzz/src/strategies/param.rs b/crates/evm/fuzz/src/strategies/param.rs index fd8b79d441c36..c292d42f9148f 100644 --- a/crates/evm/fuzz/src/strategies/param.rs +++ b/crates/evm/fuzz/src/strategies/param.rs @@ -149,11 +149,8 @@ pub fn fuzz_param_from_state( break; } } - - DynSolValue::Address(fuzzed_addr) - } else { - DynSolValue::Address(fuzzed_addr) } + DynSolValue::Address(fuzzed_addr) }) .boxed() }