From d34990608d12bd359b583ea9d9d55d72183b9eba Mon Sep 17 00:00:00 2001 From: zeroXbrock <2791467+zeroXbrock@users.noreply.github.com> Date: Wed, 17 Jul 2024 16:30:38 -0700 Subject: [PATCH] lint --- crates/anvil/core/src/eth/serde_helpers.rs | 4 +- crates/anvil/core/src/eth/transaction/mod.rs | 44 ++-- crates/anvil/server/src/ipc.rs | 2 +- crates/anvil/server/src/pubsub.rs | 16 +- crates/anvil/src/anvil.rs | 2 +- crates/anvil/src/cmd.rs | 12 +- crates/anvil/src/eth/backend/cheats.rs | 2 +- crates/anvil/src/eth/backend/executor.rs | 14 +- crates/anvil/src/eth/backend/mem/mod.rs | 42 ++-- crates/anvil/src/eth/backend/mem/storage.rs | 6 +- crates/anvil/src/eth/backend/time.rs | 2 +- crates/anvil/src/eth/fees.rs | 8 +- crates/anvil/src/eth/miner.rs | 6 +- crates/anvil/src/eth/pool/mod.rs | 14 +- crates/anvil/src/eth/pool/transactions.rs | 8 +- crates/anvil/src/filter.rs | 6 +- crates/anvil/src/logging.rs | 6 +- crates/anvil/src/pubsub.rs | 8 +- crates/anvil/src/service.rs | 4 +- crates/anvil/src/tasks/block_listener.rs | 4 +- crates/anvil/tests/it/transaction.rs | 2 +- crates/cast/bin/cmd/logs.rs | 2 +- crates/cast/bin/cmd/run.rs | 6 +- crates/cast/bin/cmd/storage.rs | 2 +- crates/cast/bin/tx.rs | 4 +- crates/cast/src/lib.rs | 30 +-- crates/cast/src/rlp_converter.rs | 2 +- crates/cheatcodes/spec/src/cheatcode.rs | 14 +- crates/cheatcodes/spec/src/lib.rs | 2 +- crates/cheatcodes/src/error.rs | 2 +- crates/cheatcodes/src/evm.rs | 14 +- crates/cheatcodes/src/evm/fork.rs | 4 +- crates/cheatcodes/src/evm/mapping.rs | 2 +- crates/cheatcodes/src/fs.rs | 6 +- crates/cheatcodes/src/json.rs | 2 +- crates/cheatcodes/src/string.rs | 8 +- crates/cheatcodes/src/test/assert.rs | 16 +- crates/cheatcodes/src/test/expect.rs | 10 +- crates/chisel/bin/main.rs | 12 +- crates/chisel/src/dispatcher.rs | 56 +++--- crates/chisel/src/executor.rs | 52 ++--- crates/chisel/src/runner.rs | 12 +- crates/chisel/src/session.rs | 2 +- crates/chisel/src/solidity_helper.rs | 48 ++--- crates/cli/src/handler.rs | 2 +- crates/cli/src/opts/dependency.rs | 2 +- crates/cli/src/utils/abi.rs | 2 +- crates/cli/src/utils/cmd.rs | 24 +-- crates/common/fmt/src/console.rs | 10 +- crates/common/fmt/src/exp.rs | 2 +- crates/common/fmt/src/ui.rs | 4 +- crates/common/src/abi.rs | 6 +- crates/common/src/ens.rs | 2 +- crates/common/src/errors/fs.rs | 40 ++-- crates/common/src/term.rs | 4 +- crates/common/src/transactions.rs | 2 +- crates/config/src/cache.rs | 2 +- crates/config/src/endpoints.rs | 6 +- crates/config/src/fix.rs | 10 +- crates/config/src/fuzz.rs | 2 +- crates/config/src/inline/natspec.rs | 12 +- crates/config/src/invariant.rs | 2 +- crates/config/src/providers/mod.rs | 4 +- crates/config/src/providers/remappings.rs | 4 +- crates/config/src/utils.rs | 6 +- crates/debugger/src/node.rs | 2 +- crates/doc/src/builder.rs | 4 +- crates/doc/src/document.rs | 8 +- crates/doc/src/parser/comment.rs | 6 +- .../src/preprocessor/contract_inheritance.rs | 2 +- .../doc/src/preprocessor/infer_hyperlinks.rs | 20 +- crates/doc/src/preprocessor/inheritdoc.rs | 2 +- crates/doc/src/writer/buf_writer.rs | 2 +- crates/evm/core/src/backend/mod.rs | 8 +- crates/evm/core/src/fork/multi.rs | 4 +- crates/evm/core/src/opcodes.rs | 24 +-- crates/evm/core/src/utils.rs | 10 +- crates/evm/coverage/src/analysis.rs | 62 +++--- crates/evm/coverage/src/anchors.rs | 2 +- crates/evm/evm/src/executors/fuzz/mod.rs | 2 +- crates/evm/evm/src/executors/invariant/mod.rs | 38 ++-- crates/evm/evm/src/inspectors/logs.rs | 2 +- crates/evm/fuzz/src/inspector.rs | 6 +- crates/evm/fuzz/src/invariant/filters.rs | 10 +- crates/evm/fuzz/src/strategies/int.rs | 10 +- crates/evm/fuzz/src/strategies/uint.rs | 6 +- crates/evm/traces/src/debug/mod.rs | 12 +- crates/evm/traces/src/identifier/etherscan.rs | 12 +- crates/fmt/src/buffer.rs | 18 +- crates/fmt/src/comments.rs | 8 +- crates/fmt/src/formatter.rs | 189 +++++++++--------- crates/fmt/src/helpers.rs | 2 +- crates/fmt/src/macros.rs | 4 +- crates/fmt/src/solang_ext/ast_eq.rs | 30 +-- crates/fmt/src/string.rs | 14 +- crates/fmt/tests/formatter.rs | 2 +- crates/forge/bin/cmd/bind_json.rs | 4 +- crates/forge/bin/cmd/build.rs | 4 +- crates/forge/bin/cmd/cache.rs | 2 +- crates/forge/bin/cmd/clone.rs | 30 +-- crates/forge/bin/cmd/config.rs | 2 +- crates/forge/bin/cmd/eip712.rs | 14 +- crates/forge/bin/cmd/fmt.rs | 12 +- crates/forge/bin/cmd/geiger/find.rs | 18 +- crates/forge/bin/cmd/inspect.rs | 30 +-- crates/forge/bin/cmd/install.rs | 22 +- crates/forge/bin/cmd/selectors.rs | 4 +- crates/forge/bin/cmd/snapshot.rs | 4 +- crates/forge/bin/cmd/test/filter.rs | 12 +- crates/forge/bin/cmd/watch.rs | 12 +- crates/forge/tests/cli/cmd.rs | 2 +- crates/forge/tests/cli/utils.rs | 4 +- crates/forge/tests/cli/verify.rs | 2 +- crates/forge/tests/it/config.rs | 4 +- crates/macros/src/cheatcodes.rs | 10 +- crates/macros/src/console_fmt.rs | 2 +- crates/script/src/broadcast.rs | 19 +- crates/script/src/build.rs | 4 +- crates/script/src/execute.rs | 4 +- crates/script/src/lib.rs | 8 +- crates/script/src/receipts.rs | 4 +- crates/script/src/runner.rs | 12 +- crates/script/src/sequence.rs | 12 +- crates/script/src/transaction.rs | 2 +- crates/script/src/verify.rs | 2 +- crates/sol-macro-gen/src/sol_macro_gen.rs | 6 +- crates/test-utils/src/script.rs | 22 +- crates/test-utils/src/util.rs | 2 +- crates/verify/src/bytecode.rs | 10 +- crates/verify/src/etherscan/mod.rs | 20 +- crates/verify/src/lib.rs | 2 +- 131 files changed, 760 insertions(+), 752 deletions(-) diff --git a/crates/anvil/core/src/eth/serde_helpers.rs b/crates/anvil/core/src/eth/serde_helpers.rs index f7d5bd46dba2..d2071aeb5202 100644 --- a/crates/anvil/core/src/eth/serde_helpers.rs +++ b/crates/anvil/core/src/eth/serde_helpers.rs @@ -27,7 +27,7 @@ pub mod sequence { return Err(serde::de::Error::custom(format!( "expected params sequence with length 1 but got {}", seq.len() - ))) + ))); } Ok(seq.remove(0)) } @@ -46,7 +46,7 @@ pub mod empty_params { return Err(serde::de::Error::custom(format!( "expected params sequence with length 0 but got {}", seq.len() - ))) + ))); } Ok(()) } diff --git a/crates/anvil/core/src/eth/transaction/mod.rs b/crates/anvil/core/src/eth/transaction/mod.rs index 509e8327eedb..b9fdb53d3bf5 100644 --- a/crates/anvil/core/src/eth/transaction/mod.rs +++ b/crates/anvil/core/src/eth/transaction/mod.rs @@ -80,8 +80,8 @@ pub fn transaction_request_to_typed( to, ) { // legacy transaction - (Some(0), _, None, None, None, None, None, None, _) | - (None, Some(_), None, None, None, None, None, None, _) => { + (Some(0), _, None, None, None, None, None, None, _) + | (None, Some(_), None, None, None, None, None, None, _) => { Some(TypedTransactionRequest::Legacy(TxLegacy { nonce: nonce.unwrap_or_default(), gas_price: gas_price.unwrap_or_default(), @@ -93,8 +93,8 @@ pub fn transaction_request_to_typed( })) } // EIP2930 - (Some(1), _, None, None, _, None, None, None, _) | - (None, _, None, None, Some(_), None, None, None, _) => { + (Some(1), _, None, None, _, None, None, None, _) + | (None, _, None, None, Some(_), None, None, None, _) => { Some(TypedTransactionRequest::EIP2930(TxEip2930 { nonce: nonce.unwrap_or_default(), gas_price: gas_price.unwrap_or_default(), @@ -107,10 +107,10 @@ pub fn transaction_request_to_typed( })) } // EIP1559 - (Some(2), None, _, _, _, _, None, None, _) | - (None, None, Some(_), _, _, _, None, None, _) | - (None, None, _, Some(_), _, _, None, None, _) | - (None, None, None, None, None, _, None, None, _) => { + (Some(2), None, _, _, _, _, None, None, _) + | (None, None, Some(_), _, _, _, None, None, _) + | (None, None, _, Some(_), _, _, None, None, _) + | (None, None, None, None, None, _, None, None, _) => { // Empty fields fall back to the canonical transaction schema. Some(TypedTransactionRequest::EIP1559(TxEip1559 { nonce: nonce.unwrap_or_default(), @@ -151,9 +151,9 @@ pub fn transaction_request_to_typed( } fn has_optimism_fields(other: &OtherFields) -> bool { - other.contains_key("sourceHash") && - other.contains_key("mint") && - other.contains_key("isSystemTx") + other.contains_key("sourceHash") + && other.contains_key("mint") + && other.contains_key("isSystemTx") } #[derive(Clone, Debug, PartialEq, Eq)] @@ -214,7 +214,7 @@ impl MaybeImpersonatedTransaction { #[cfg(feature = "impersonated-tx")] pub fn hash(&self) -> B256 { if let Some(sender) = self.impersonated_sender { - return self.transaction.impersonated_hash(sender) + return self.transaction.impersonated_hash(sender); } self.transaction.hash() } @@ -1137,12 +1137,12 @@ pub struct DepositReceipt { impl DepositReceipt { fn payload_len(&self) -> usize { - self.inner.receipt.status.length() + - self.inner.receipt.cumulative_gas_used.length() + - self.inner.logs_bloom.length() + - self.inner.receipt.logs.length() + - self.deposit_nonce.map_or(0, |n| n.length()) + - self.deposit_receipt_version.map_or(0, |n| n.length()) + self.inner.receipt.status.length() + + self.inner.receipt.cumulative_gas_used.length() + + self.inner.logs_bloom.length() + + self.inner.receipt.logs.length() + + self.deposit_nonce.map_or(0, |n| n.length()) + + self.deposit_receipt_version.map_or(0, |n| n.length()) } /// Returns the rlp header for the receipt payload. @@ -1249,10 +1249,10 @@ impl TypedReceipt { impl From> for ReceiptWithBloom { fn from(value: TypedReceipt) -> Self { match value { - TypedReceipt::Legacy(r) | - TypedReceipt::EIP1559(r) | - TypedReceipt::EIP2930(r) | - TypedReceipt::EIP4844(r) => r, + TypedReceipt::Legacy(r) + | TypedReceipt::EIP1559(r) + | TypedReceipt::EIP2930(r) + | TypedReceipt::EIP4844(r) => r, TypedReceipt::Deposit(r) => r.inner, } } diff --git a/crates/anvil/server/src/ipc.rs b/crates/anvil/server/src/ipc.rs index 8743f06424d0..5df345452770 100644 --- a/crates/anvil/server/src/ipc.rs +++ b/crates/anvil/server/src/ipc.rs @@ -159,7 +159,7 @@ impl tokio_util::codec::Decoder for JsonRpcCodec { return match String::from_utf8(bts.as_ref().to_vec()) { Ok(val) => Ok(Some(val)), Err(_) => Ok(None), - } + }; } } Ok(None) diff --git a/crates/anvil/server/src/pubsub.rs b/crates/anvil/server/src/pubsub.rs index 8e5ac9b3849b..24476f67be57 100644 --- a/crates/anvil/server/src/pubsub.rs +++ b/crates/anvil/server/src/pubsub.rs @@ -68,7 +68,7 @@ impl PubSubContext { let mut subscriptions = self.subscriptions.lock(); if let Some(idx) = subscriptions.iter().position(|(i, _)| id == i) { trace!(target: "rpc", ?id, "removed subscription"); - return Some(subscriptions.swap_remove(idx).1) + return Some(subscriptions.swap_remove(idx).1); } None } @@ -174,7 +174,7 @@ where error!(target: "rpc", ?err, "Failed to send message"); } } else { - break + break; } } @@ -183,7 +183,7 @@ where if let Poll::Ready(Err(err)) = pin.connection.poll_flush_unpin(cx) { trace!(target: "rpc", ?err, "websocket err"); // close the connection - return Poll::Ready(()) + return Poll::Ready(()); } loop { @@ -195,25 +195,25 @@ where Err(err) => match err { RequestError::Axum(err) => { trace!(target: "rpc", ?err, "client disconnected"); - return Poll::Ready(()) + return Poll::Ready(()); } RequestError::Io(err) => { trace!(target: "rpc", ?err, "client disconnected"); - return Poll::Ready(()) + return Poll::Ready(()); } RequestError::Serde(err) => { pin.process_request(Err(err)); } RequestError::Disconnect => { trace!(target: "rpc", "client disconnected"); - return Poll::Ready(()) + return Poll::Ready(()); } }, _ => {} }, Poll::Ready(None) => { trace!(target: "rpc", "socket connection finished"); - return Poll::Ready(()) + return Poll::Ready(()); } Poll::Pending => break, } @@ -256,7 +256,7 @@ where } if !progress { - return Poll::Pending + return Poll::Pending; } } } diff --git a/crates/anvil/src/anvil.rs b/crates/anvil/src/anvil.rs index 1aa204587b20..17994da6bb4c 100644 --- a/crates/anvil/src/anvil.rs +++ b/crates/anvil/src/anvil.rs @@ -57,7 +57,7 @@ async fn main() -> eyre::Result<()> { &mut std::io::stdout(), ), } - return Ok(()) + return Ok(()); } let _ = fdlimit::raise_fd_limit(); diff --git a/crates/anvil/src/cmd.rs b/crates/anvil/src/cmd.rs index f867030230a2..0e217ea3002b 100644 --- a/crates/anvil/src/cmd.rs +++ b/crates/anvil/src/cmd.rs @@ -596,7 +596,7 @@ impl Future for PeriodicStateDumper { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { let this = self.get_mut(); if this.dump_state.is_none() { - return Poll::Pending + return Poll::Pending; } loop { @@ -607,7 +607,7 @@ impl Future for PeriodicStateDumper { } Poll::Pending => { this.in_progress_dump = Some(flush); - return Poll::Pending + return Poll::Pending; } } } @@ -617,7 +617,7 @@ impl Future for PeriodicStateDumper { let path = this.dump_state.clone().expect("exists; see above"); this.in_progress_dump = Some(Box::pin(Self::dump_state(api, path))); } else { - break + break; } } @@ -647,7 +647,7 @@ impl StateFile { } let mut state = Self { path, state: None }; if !state.path.exists() { - return Ok(state) + return Ok(state); } state.state = Some(SerializableState::load(&state.path).map_err(|err| err.to_string())?); @@ -682,14 +682,14 @@ impl FromStr for ForkUrl { fn from_str(s: &str) -> Result { if let Some((url, block)) = s.rsplit_once('@') { if block == "latest" { - return Ok(Self { url: url.to_string(), block: None }) + return Ok(Self { url: url.to_string(), block: None }); } // this will prevent false positives for auths `user:password@example.com` if !block.is_empty() && !block.contains(':') && !block.contains('.') { let block: u64 = block .parse() .map_err(|_| format!("Failed to parse block number: `{block}`"))?; - return Ok(Self { url: url.to_string(), block: Some(block) }) + return Ok(Self { url: url.to_string(), block: Some(block) }); } } Ok(Self { url: s.to_string(), block: None }) diff --git a/crates/anvil/src/eth/backend/cheats.rs b/crates/anvil/src/eth/backend/cheats.rs index 5b498f963c84..a679696ca135 100644 --- a/crates/anvil/src/eth/backend/cheats.rs +++ b/crates/anvil/src/eth/backend/cheats.rs @@ -27,7 +27,7 @@ impl CheatsManager { // which does not check that list when auto impersonation is enabeld. if state.impersonated_accounts.contains(&addr) { // need to check if already impersonated, so we don't overwrite the code - return true + return true; } state.impersonated_accounts.insert(addr) } diff --git a/crates/anvil/src/eth/backend/executor.rs b/crates/anvil/src/eth/backend/executor.rs index 23d890cfa726..738def527224 100644 --- a/crates/anvil/src/eth/backend/executor.rs +++ b/crates/anvil/src/eth/backend/executor.rs @@ -143,22 +143,22 @@ impl<'a, DB: Db + ?Sized, Validator: TransactionValidator> TransactionExecutor<' } TransactionExecutionOutcome::Exhausted(tx) => { trace!(target: "backend", tx_gas_limit = %tx.pending_transaction.transaction.gas_limit(), ?tx, "block gas limit exhausting, skipping transaction"); - continue + continue; } TransactionExecutionOutcome::BlobGasExhausted(tx) => { trace!(target: "backend", blob_gas = %tx.pending_transaction.transaction.blob_gas().unwrap_or_default(), ?tx, "block blob gas limit exhausting, skipping transaction"); - continue + continue; } TransactionExecutionOutcome::Invalid(tx, _) => { trace!(target: "backend", ?tx, "skipping invalid transaction"); invalid.push(tx); - continue + continue; } TransactionExecutionOutcome::DatabaseError(_, err) => { // Note: this is only possible in forking mode, if for example a rpc request // failed trace!(target: "backend", ?err, "Failed to execute transaction due to database error"); - continue + continue; } }; if is_cancun { @@ -277,7 +277,7 @@ impl<'a, 'b, DB: Db + ?Sized, Validator: TransactionValidator> Iterator // check that we comply with the block's gas limit, if not disabled let max_gas = self.gas_used.saturating_add(env.tx.gas_limit as u128); if !env.cfg.disable_block_gas_limit && max_gas > env.block.gas_limit.to::() { - return Some(TransactionExecutionOutcome::Exhausted(transaction)) + return Some(TransactionExecutionOutcome::Exhausted(transaction)); } // check that we comply with the block's blob gas limit @@ -285,7 +285,7 @@ impl<'a, 'b, DB: Db + ?Sized, Validator: TransactionValidator> Iterator transaction.pending_transaction.transaction.transaction.blob_gas().unwrap_or(0u128), ); if max_blob_gas > MAX_BLOB_GAS_PER_BLOCK as u128 { - return Some(TransactionExecutionOutcome::BlobGasExhausted(transaction)) + return Some(TransactionExecutionOutcome::BlobGasExhausted(transaction)); } // validate before executing @@ -295,7 +295,7 @@ impl<'a, 'b, DB: Db + ?Sized, Validator: TransactionValidator> Iterator &env, ) { warn!(target: "backend", "Skipping invalid tx execution [{:?}] {}", transaction.hash(), err); - return Some(TransactionExecutionOutcome::Invalid(transaction, err)) + return Some(TransactionExecutionOutcome::Invalid(transaction, err)); } let nonce = account.nonce; diff --git a/crates/anvil/src/eth/backend/mem/mod.rs b/crates/anvil/src/eth/backend/mem/mod.rs index f89ba6a50568..58e3aa0fec9f 100644 --- a/crates/anvil/src/eth/backend/mem/mod.rs +++ b/crates/anvil/src/eth/backend/mem/mod.rs @@ -326,7 +326,7 @@ impl Backend { /// Returns `true` if the account is already impersonated pub fn impersonate(&self, addr: Address) -> bool { if self.cheats.impersonated_accounts().contains(&addr) { - return true + return true; } // Ensure EIP-3607 is disabled let mut env = self.env.write(); @@ -606,7 +606,7 @@ impl Backend { /// Returns an error if op-stack deposits are not active pub fn ensure_op_deposits_active(&self) -> Result<(), BlockchainError> { if self.is_optimism() { - return Ok(()) + return Ok(()); } Err(BlockchainError::DepositTransactionUnsupported) } @@ -1240,9 +1240,9 @@ impl Backend { .into()) } GethDebugBuiltInTracerType::NoopTracer => Ok(NoopFrame::default().into()), - GethDebugBuiltInTracerType::FourByteTracer | - GethDebugBuiltInTracerType::PreStateTracer | - GethDebugBuiltInTracerType::MuxTracer => { + GethDebugBuiltInTracerType::FourByteTracer + | GethDebugBuiltInTracerType::PreStateTracer + | GethDebugBuiltInTracerType::MuxTracer => { Err(RpcError::invalid_params("unsupported tracer type").into()) } }, @@ -1250,7 +1250,7 @@ impl Backend { GethDebugTracerType::JsTracer(_code) => { Err(RpcError::invalid_params("unsupported tracer type").into()) } - } + }; } // defaults to StructLog tracer used since no tracer is specified @@ -1490,7 +1490,7 @@ impl Backend { } if let Some(fork) = self.get_fork() { - return Ok(fork.block_by_hash_full(hash).await?) + return Ok(fork.block_by_hash_full(hash).await?); } Ok(None) @@ -1541,7 +1541,7 @@ impl Backend { if let Some(fork) = self.get_fork() { let number = self.convert_block_number(Some(number)); if fork.predates_fork_inclusive(number) { - return Ok(fork.block_by_number(number).await?) + return Ok(fork.block_by_number(number).await?); } } @@ -1560,7 +1560,7 @@ impl Backend { if let Some(fork) = self.get_fork() { let number = self.convert_block_number(Some(number)); if fork.predates_fork_inclusive(number) { - return Ok(fork.block_by_number_full(number).await?) + return Ok(fork.block_by_number_full(number).await?); } } @@ -1905,7 +1905,7 @@ impl Backend { } if let Some(fork) = self.get_fork() { - return Ok(fork.trace_transaction(hash).await?) + return Ok(fork.trace_transaction(hash).await?); } Ok(vec![]) @@ -1949,7 +1949,7 @@ impl Backend { } if let Some(fork) = self.get_fork() { - return Ok(fork.debug_trace_transaction(hash, opts).await?) + return Ok(fork.debug_trace_transaction(hash, opts).await?); } Ok(GethTrace::Default(Default::default())) @@ -1975,7 +1975,7 @@ impl Backend { if let Some(fork) = self.get_fork() { if fork.predates_fork(number) { - return Ok(fork.trace_block(number).await?) + return Ok(fork.trace_block(number).await?); } } @@ -2151,7 +2151,7 @@ impl Backend { if let Some(fork) = self.get_fork() { let number = self.convert_block_number(Some(number)); if fork.predates_fork(number) { - return Ok(fork.transaction_by_block_number_and_index(number, index.into()).await?) + return Ok(fork.transaction_by_block_number_and_index(number, index.into()).await?); } } @@ -2168,7 +2168,7 @@ impl Backend { } if let Some(fork) = self.get_fork() { - return Ok(fork.transaction_by_block_hash_and_index(hash, index.into()).await?) + return Ok(fork.transaction_by_block_hash_and_index(hash, index.into()).await?); } Ok(None) @@ -2207,7 +2207,7 @@ impl Backend { } if let Some(fork) = self.get_fork() { - return fork.transaction_by_hash(hash).await.map_err(BlockchainError::AlloyForkProvider) + return fork.transaction_by_hash(hash).await.map_err(BlockchainError::AlloyForkProvider); } Ok(None) @@ -2317,7 +2317,7 @@ fn get_pool_transactions_nonce( .max() { let tx_count = highest_nonce.saturating_add(1); - return Some(tx_count) + return Some(tx_count); } None } @@ -2347,8 +2347,8 @@ impl TransactionValidator for Backend { if chain_id.to::() != tx_chain_id { if let Some(legacy) = tx.as_legacy() { // - if env.handler_cfg.spec_id >= SpecId::SPURIOUS_DRAGON && - !meets_eip155(chain_id.to::(), legacy.signature().v()) + if env.handler_cfg.spec_id >= SpecId::SPURIOUS_DRAGON + && !meets_eip155(chain_id.to::(), legacy.signature().v()) { warn!(target: "backend", ?chain_id, ?tx_chain_id, "incompatible EIP155-based V"); return Err(InvalidTransactionError::IncompatibleEIP155); @@ -2420,17 +2420,17 @@ impl TransactionValidator for Backend { // Ensure there are blob hashes. if blob_count == 0 { - return Err(InvalidTransactionError::NoBlobHashes) + return Err(InvalidTransactionError::NoBlobHashes); } // Ensure the tx does not exceed the max blobs per block. if blob_count > MAX_BLOBS_PER_BLOCK { - return Err(InvalidTransactionError::TooManyBlobs(MAX_BLOBS_PER_BLOCK, blob_count)) + return Err(InvalidTransactionError::TooManyBlobs(MAX_BLOBS_PER_BLOCK, blob_count)); } // Check for any blob validation errors if let Err(err) = tx.validate(env.cfg.kzg_settings.get()) { - return Err(InvalidTransactionError::BlobTransactionValidationError(err)) + return Err(InvalidTransactionError::BlobTransactionValidationError(err)); } } diff --git a/crates/anvil/src/eth/backend/mem/storage.rs b/crates/anvil/src/eth/backend/mem/storage.rs index 8a92e242df80..122f454621f2 100644 --- a/crates/anvil/src/eth/backend/mem/storage.rs +++ b/crates/anvil/src/eth/backend/mem/storage.rs @@ -478,9 +478,9 @@ impl MinedTransaction { Err(e) => Err(RpcError::invalid_params(e.to_string()).into()), }; } - GethDebugBuiltInTracerType::PreStateTracer | - GethDebugBuiltInTracerType::NoopTracer | - GethDebugBuiltInTracerType::MuxTracer => {} + GethDebugBuiltInTracerType::PreStateTracer + | GethDebugBuiltInTracerType::NoopTracer + | GethDebugBuiltInTracerType::MuxTracer => {} }, GethDebugTracerType::JsTracer(_code) => {} } diff --git a/crates/anvil/src/eth/backend/time.rs b/crates/anvil/src/eth/backend/time.rs index 0822baa04716..76af1d025468 100644 --- a/crates/anvil/src/eth/backend/time.rs +++ b/crates/anvil/src/eth/backend/time.rs @@ -73,7 +73,7 @@ impl TimeManager { if timestamp <= *self.last_timestamp.read() { return Err(BlockchainError::TimestampError(format!( "{timestamp} is lower than or equal to previous block's timestamp" - ))) + ))); } self.next_exact_timestamp.write().replace(timestamp); Ok(()) diff --git a/crates/anvil/src/eth/fees.rs b/crates/anvil/src/eth/fees.rs index ab65fcc46bd7..6c19d6b50d08 100644 --- a/crates/anvil/src/eth/fees.rs +++ b/crates/anvil/src/eth/fees.rs @@ -157,7 +157,7 @@ impl FeeManager { // It means it was set by the user deliberately and therefore we treat it as a constant. // Therefore, we skip the base fee calculation altogether and we return 0. if self.base_fee() == 0 { - return 0 + return 0; } calculate_next_block_base_fee(gas_used, gas_limit, last_fee_per_gas) } @@ -305,7 +305,7 @@ impl FeeHistoryService { for (gas_used, effective_reward) in transactions.iter().cloned() { sum_gas += gas_used; if target_gas <= sum_gas { - return Some(effective_reward) + return Some(effective_reward); } } None @@ -427,7 +427,7 @@ impl FeeDetails { if let Some(max_priority) = max_priority { let max_fee = max_fee.unwrap_or_default(); if max_priority > max_fee { - return Err(BlockchainError::InvalidFeeInput) + return Err(BlockchainError::InvalidFeeInput); } } Ok(Self { @@ -443,7 +443,7 @@ impl FeeDetails { if let Some(max_priority) = max_priority { let max_fee = max_fee.unwrap_or_default(); if max_priority > max_fee { - return Err(BlockchainError::InvalidFeeInput) + return Err(BlockchainError::InvalidFeeInput); } } Ok(Self { diff --git a/crates/anvil/src/eth/miner.rs b/crates/anvil/src/eth/miner.rs index ddd27185075a..177581c3d2da 100644 --- a/crates/anvil/src/eth/miner.rs +++ b/crates/anvil/src/eth/miner.rs @@ -185,7 +185,7 @@ impl FixedBlockTimeMiner { fn poll(&mut self, pool: &Arc, cx: &mut Context<'_>) -> Poll>> { if self.interval.poll_tick(cx).is_ready() { // drain the pool - return Poll::Ready(pool.ready_transactions().collect()) + return Poll::Ready(pool.ready_transactions().collect()); } Poll::Pending } @@ -215,7 +215,7 @@ impl ReadyTransactionMiner { } if self.has_pending_txs == Some(false) { - return Poll::Pending + return Poll::Pending; } let transactions = @@ -225,7 +225,7 @@ impl ReadyTransactionMiner { self.has_pending_txs = Some(transactions.len() >= self.max_transactions); if transactions.is_empty() { - return Poll::Pending + return Poll::Pending; } Poll::Ready(transactions) diff --git a/crates/anvil/src/eth/pool/mod.rs b/crates/anvil/src/eth/pool/mod.rs index 9ef45ace2c2c..7f16d43e90ed 100644 --- a/crates/anvil/src/eth/pool/mod.rs +++ b/crates/anvil/src/eth/pool/mod.rs @@ -228,7 +228,7 @@ impl PoolInner { /// Returns `None` if the transaction does not exist in the pool fn get_transaction(&self, hash: TxHash) -> Option { if let Some(pending) = self.pending_transactions.get(&hash) { - return Some(pending.transaction.pending_transaction.clone()) + return Some(pending.transaction.pending_transaction.clone()); } Some( self.ready_transactions.get(&hash)?.transaction.transaction.pending_transaction.clone(), @@ -261,7 +261,7 @@ impl PoolInner { fn add_transaction(&mut self, tx: PoolTransaction) -> Result { if self.contains(&tx.hash()) { warn!(target: "txpool", "[{:?}] Already imported", tx.hash()); - return Err(PoolError::AlreadyImported(Box::new(tx))) + return Err(PoolError::AlreadyImported(Box::new(tx))); } let tx = PendingPoolTransaction::new(tx, self.ready_transactions.provided_markers()); @@ -271,7 +271,7 @@ impl PoolInner { if !tx.is_ready() { let hash = tx.transaction.hash(); self.pending_transactions.add_transaction(tx)?; - return Ok(AddedTransaction::Pending { hash }) + return Ok(AddedTransaction::Pending { hash }); } self.add_ready_transaction(tx) } @@ -311,7 +311,7 @@ impl PoolInner { if is_new_tx { debug!(target: "txpool", "[{:?}] Failed to add tx: {:?}", current_hash, err); - return Err(err) + return Err(err); } else { ready.discarded.push(current_hash); } @@ -325,7 +325,7 @@ impl PoolInner { // the pending queue if ready.removed.iter().any(|tx| *tx.hash() == hash) { self.ready_transactions.clear_transactions(&ready.promoted); - return Err(PoolError::CyclicTransaction) + return Err(PoolError::CyclicTransaction); } Ok(AddedTransaction::Ready(ready)) @@ -366,7 +366,7 @@ impl PoolInner { pub fn remove_invalid(&mut self, tx_hashes: Vec) -> Vec> { // early exit in case there is no invalid transactions. if tx_hashes.is_empty() { - return vec![] + return vec![]; } trace!(target: "txpool", "Removing invalid transactions: {:?}", tx_hashes); @@ -384,7 +384,7 @@ impl PoolInner { self.transactions_by_sender(sender).map(move |tx| tx.hash()).collect::>(); if tx_hashes.is_empty() { - return vec![] + return vec![]; } trace!(target: "txpool", "Removing transactions: {:?}", tx_hashes); diff --git a/crates/anvil/src/eth/pool/transactions.rs b/crates/anvil/src/eth/pool/transactions.rs index 502ee1e7886f..6d88a6d7278f 100644 --- a/crates/anvil/src/eth/pool/transactions.rs +++ b/crates/anvil/src/eth/pool/transactions.rs @@ -177,7 +177,7 @@ impl PendingTransactions { warn!(target: "txpool", "pending replacement transaction underpriced [{:?}]", tx.transaction.hash()); return Err(PoolError::ReplacementUnderpriced(Box::new( tx.transaction.as_ref().clone(), - ))) + ))); } } @@ -363,7 +363,7 @@ impl Iterator for TransactionsIterator { } } - return Some(best.transaction) + return Some(best.transaction); } } } @@ -490,7 +490,7 @@ impl ReadyTransactions { // early exit if we are not replacing anything. if remove_hashes.is_empty() { - return Ok((Vec::new(), Vec::new())) + return Ok((Vec::new(), Vec::new())); } // check if we're replacing the same transaction and if it can be replaced @@ -507,7 +507,7 @@ impl ReadyTransactions { // check if underpriced if tx.pending_transaction.transaction.gas_price() <= to_remove.gas_price() { warn!(target: "txpool", "ready replacement transaction underpriced [{:?}]", tx.hash()); - return Err(PoolError::ReplacementUnderpriced(Box::new(tx.clone()))) + return Err(PoolError::ReplacementUnderpriced(Box::new(tx.clone()))); } else { trace!(target: "txpool", "replacing ready transaction [{:?}] with higher gas price [{:?}]", to_remove.transaction.transaction.hash(), tx.hash()); } diff --git a/crates/anvil/src/filter.rs b/crates/anvil/src/filter.rs index 2144ce27c988..532279700508 100644 --- a/crates/anvil/src/filter.rs +++ b/crates/anvil/src/filter.rs @@ -52,7 +52,7 @@ impl Filters { .await .unwrap_or_else(|| ResponseResult::success(Vec::<()>::new())); *deadline = self.next_deadline(); - return resp + return resp; } } warn!(target: "node::filter", "No filter found for {}", id); @@ -63,7 +63,7 @@ impl Filters { pub async fn get_log_filter(&self, id: &str) -> Option { let filters = self.active_filters.lock().await; if let Some((EthFilter::Logs(ref log), _)) = filters.get(id) { - return log.filter.filter.clone() + return log.filter.filter.clone(); } None } @@ -92,7 +92,7 @@ impl Filters { active_filters.retain(|id, (_, deadline)| { if now > *deadline { trace!(target: "node::filter",?id, "Evicting stale filter"); - return false + return false; } true }); diff --git a/crates/anvil/src/logging.rs b/crates/anvil/src/logging.rs index e738254cbbec..4408b9df6ede 100644 --- a/crates/anvil/src/logging.rs +++ b/crates/anvil/src/logging.rs @@ -42,9 +42,9 @@ where } fn enabled(&self, metadata: &Metadata<'_>, _ctx: Context<'_, S>) -> bool { - self.state.is_enabled() && - (metadata.target() == NODE_USER_LOG_TARGET || - metadata.target() == EVM_CONSOLE_LOG_TARGET) + self.state.is_enabled() + && (metadata.target() == NODE_USER_LOG_TARGET + || metadata.target() == EVM_CONSOLE_LOG_TARGET) } } diff --git a/crates/anvil/src/pubsub.rs b/crates/anvil/src/pubsub.rs index 21a5c631c9c0..d52a1b410ef8 100644 --- a/crates/anvil/src/pubsub.rs +++ b/crates/anvil/src/pubsub.rs @@ -147,10 +147,10 @@ pub fn filter_logs(block: Block, receipts: Vec, filter: &FilteredP ) -> bool { if params.filter.is_some() { let block_number = block.header.number; - if !params.filter_block_range(block_number) || - !params.filter_block_hash(block_hash) || - !params.filter_address(&l.address) || - !params.filter_topics(l.topics()) + if !params.filter_block_range(block_number) + || !params.filter_block_hash(block_hash) + || !params.filter_address(&l.address) + || !params.filter_topics(l.topics()) { return false; } diff --git a/crates/anvil/src/service.rs b/crates/anvil/src/service.rs index 0f70ad3b0b4a..390438054d02 100644 --- a/crates/anvil/src/service.rs +++ b/crates/anvil/src/service.rs @@ -82,7 +82,7 @@ impl Future for NodeService { pin.block_producer.queued.push_back(transactions); } else { // no progress made - break + break; } } @@ -153,7 +153,7 @@ impl Stream for BlockProducer { Err(err) => { panic!("miner task failed: {err}"); } - } + }; } else { pin.block_mining = Some(mining) } diff --git a/crates/anvil/src/tasks/block_listener.rs b/crates/anvil/src/tasks/block_listener.rs index 0b9388224ca0..2b3e2cb574c7 100644 --- a/crates/anvil/src/tasks/block_listener.rs +++ b/crates/anvil/src/tasks/block_listener.rs @@ -38,7 +38,7 @@ where let pin = self.get_mut(); if pin.on_shutdown.poll_unpin(cx).is_ready() { - return Poll::Ready(()) + return Poll::Ready(()); } let mut block = None; @@ -46,7 +46,7 @@ where while let Poll::Ready(maybe_block) = pin.stream.poll_next_unpin(cx) { if maybe_block.is_none() { // stream complete - return Poll::Ready(()) + return Poll::Ready(()); } block = maybe_block; } diff --git a/crates/anvil/tests/it/transaction.rs b/crates/anvil/tests/it/transaction.rs index 5f9abe80b6bd..335b953941d4 100644 --- a/crates/anvil/tests/it/transaction.rs +++ b/crates/anvil/tests/it/transaction.rs @@ -954,7 +954,7 @@ async fn can_stream_pending_transactions() { let sent_txs = sent.iter().map(|tx| tx.transaction_hash).collect::>(); assert_eq!(sent_txs, watch_received.iter().copied().collect()); assert_eq!(sent_txs, sub_received.iter().copied().collect()); - break + break; } } } diff --git a/crates/cast/bin/cmd/logs.rs b/crates/cast/bin/cmd/logs.rs index c51bad8cc7d9..43429dcae0f6 100644 --- a/crates/cast/bin/cmd/logs.rs +++ b/crates/cast/bin/cmd/logs.rs @@ -92,7 +92,7 @@ impl LogsArgs { println!("{logs}"); - return Ok(()) + return Ok(()); } // FIXME: this is a hotfix for diff --git a/crates/cast/bin/cmd/run.rs b/crates/cast/bin/cmd/run.rs index b7f31cfc7514..bdcfdb8977f2 100644 --- a/crates/cast/bin/cmd/run.rs +++ b/crates/cast/bin/cmd/run.rs @@ -160,15 +160,15 @@ impl RunArgs { pb.set_position(0); let BlockTransactions::Full(txs) = block.transactions else { - return Err(eyre::eyre!("Could not get block txs")) + return Err(eyre::eyre!("Could not get block txs")); }; for (index, tx) in txs.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) || - tx.transaction_type == Some(SYSTEM_TRANSACTION_TYPE) + if is_known_system_sender(tx.from) + || tx.transaction_type == Some(SYSTEM_TRANSACTION_TYPE) { pb.set_position((index + 1) as u64); continue; diff --git a/crates/cast/bin/cmd/storage.rs b/crates/cast/bin/cmd/storage.rs index 117130943dc5..d2ed98e07600 100644 --- a/crates/cast/bin/cmd/storage.rs +++ b/crates/cast/bin/cmd/storage.rs @@ -256,7 +256,7 @@ async fn fetch_storage_slots, T: Transport + Clone>( fn print_storage(layout: StorageLayout, values: Vec, pretty: bool) -> Result<()> { if !pretty { println!("{}", serde_json::to_string_pretty(&serde_json::to_value(layout)?)?); - return Ok(()) + return Ok(()); } let mut table = Table::new(); diff --git a/crates/cast/bin/tx.rs b/crates/cast/bin/tx.rs index 9a731187a570..c3fd765678d7 100644 --- a/crates/cast/bin/tx.rs +++ b/crates/cast/bin/tx.rs @@ -253,8 +253,8 @@ where self.tx.max_fee_per_blob_gas = Some(self.provider.get_blob_base_fee().await?) } - if !self.legacy && - (self.tx.max_fee_per_gas.is_none() || self.tx.max_priority_fee_per_gas.is_none()) + if !self.legacy + && (self.tx.max_fee_per_gas.is_none() || self.tx.max_priority_fee_per_gas.is_none()) { let estimate = self.provider.estimate_eip1559_fees(None).await?; diff --git a/crates/cast/src/lib.rs b/crates/cast/src/lib.rs index e1a70b36c832..cb9a987a1fbb 100644 --- a/crates/cast/src/lib.rs +++ b/crates/cast/src/lib.rs @@ -1095,7 +1095,7 @@ impl SimpleCast { pub fn to_ascii(hex: &str) -> Result { let bytes = hex::decode(hex)?; if !bytes.iter().all(u8::is_ascii) { - return Err(eyre::eyre!("Invalid ASCII bytes")) + return Err(eyre::eyre!("Invalid ASCII bytes")); } Ok(String::from_utf8(bytes).unwrap()) } @@ -1397,7 +1397,7 @@ impl SimpleCast { let base_in = Base::unwrap_or_detect(base_in, value)?; let base_out: Base = base_out.parse()?; if base_in == base_out { - return Ok(value.to_string()) + return Ok(value.to_string()); } let mut n = NumberWithBase::parse_int(value, Some(&base_in.to_string()))?; @@ -1461,7 +1461,7 @@ impl SimpleCast { let s = if let Some(stripped) = s.strip_prefix("000000000000000000000000") { stripped } else { - return Err(eyre::eyre!("Not convertible to address, there are non-zero bytes")) + return Err(eyre::eyre!("Not convertible to address, there are non-zero bytes")); }; let lowercase_address_string = format!("0x{s}"); @@ -1670,20 +1670,20 @@ impl SimpleCast { match v_ty { // For value types, `h` pads the value to 32 bytes in the same way as when storing the // value in memory. - DynSolType::Bool | - DynSolType::Int(_) | - DynSolType::Uint(_) | - DynSolType::FixedBytes(_) | - DynSolType::Address | - DynSolType::Function => hasher.update(v.as_word().unwrap()), + DynSolType::Bool + | DynSolType::Int(_) + | DynSolType::Uint(_) + | DynSolType::FixedBytes(_) + | DynSolType::Address + | DynSolType::Function => hasher.update(v.as_word().unwrap()), // For strings and byte arrays, `h(k)` is just the unpadded data. DynSolType::String | DynSolType::Bytes => hasher.update(v.as_packed_seq().unwrap()), - DynSolType::Array(..) | - DynSolType::FixedArray(..) | - DynSolType::Tuple(..) | - DynSolType::CustomStruct { .. } => { + DynSolType::Array(..) + | DynSolType::FixedArray(..) + | DynSolType::Tuple(..) + | DynSolType::CustomStruct { .. } => { eyre::bail!("Type `{v_ty}` is not supported as a mapping key") } } @@ -1917,7 +1917,7 @@ impl SimpleCast { } if optimize == 0 { let selector = get_func(signature)?.selector(); - return Ok((selector.to_string(), String::from(signature))) + return Ok((selector.to_string(), String::from(signature))); } let Some((name, params)) = signature.split_once('(') else { eyre::bail!("invalid function signature"); @@ -1939,7 +1939,7 @@ impl SimpleCast { if selector.iter().take_while(|&&byte| byte == 0).count() == optimize { found.store(true, Ordering::Relaxed); - return Some((nonce, hex::encode_prefixed(selector), input)) + return Some((nonce, hex::encode_prefixed(selector), input)); } nonce += nonce_step; diff --git a/crates/cast/src/rlp_converter.rs b/crates/cast/src/rlp_converter.rs index ad1787438046..1b0f958d0de8 100644 --- a/crates/cast/src/rlp_converter.rs +++ b/crates/cast/src/rlp_converter.rs @@ -60,7 +60,7 @@ impl Item { Value::Object(_) => { eyre::bail!("RLP input can not contain objects") } - } + }; } } diff --git a/crates/cheatcodes/spec/src/cheatcode.rs b/crates/cheatcodes/spec/src/cheatcode.rs index 91573d89ea20..f318a51379d1 100644 --- a/crates/cheatcodes/spec/src/cheatcode.rs +++ b/crates/cheatcodes/spec/src/cheatcode.rs @@ -131,13 +131,13 @@ impl Group { pub const fn safety(self) -> Option { match self { Self::Evm | Self::Testing => None, - Self::Scripting | - Self::Filesystem | - Self::Environment | - Self::String | - Self::Json | - Self::Toml | - Self::Utilities => Some(Safety::Safe), + Self::Scripting + | Self::Filesystem + | Self::Environment + | Self::String + | Self::Json + | Self::Toml + | Self::Utilities => Some(Safety::Safe), } } diff --git a/crates/cheatcodes/spec/src/lib.rs b/crates/cheatcodes/spec/src/lib.rs index fffc146a9d2c..5e0c157bef2d 100644 --- a/crates/cheatcodes/spec/src/lib.rs +++ b/crates/cheatcodes/spec/src/lib.rs @@ -164,7 +164,7 @@ interface Vm {{ if let Ok(old_contents) = fs::read_to_string(file) { if normalize_newlines(&old_contents) == normalize_newlines(contents) { // File is already up to date. - return + return; } } diff --git a/crates/cheatcodes/src/error.rs b/crates/cheatcodes/src/error.rs index 26aba7348088..9b70dce2d136 100644 --- a/crates/cheatcodes/src/error.rs +++ b/crates/cheatcodes/src/error.rs @@ -71,7 +71,7 @@ macro_rules! ensure_not_precompile { return Err($crate::error::precompile_error( ::CHEATCODE.func.id, $address, - )) + )); } }; } diff --git a/crates/cheatcodes/src/evm.rs b/crates/cheatcodes/src/evm.rs index 33b064201159..1c1735398808 100644 --- a/crates/cheatcodes/src/evm.rs +++ b/crates/cheatcodes/src/evm.rs @@ -116,13 +116,13 @@ impl Cheatcode for dumpStateCall { // Do not include system account or empty accounts in the dump. let skip = |key: &Address, val: &Account| { - key == &CHEATCODE_ADDRESS || - key == &CALLER || - key == &HARDHAT_CONSOLE_ADDRESS || - key == &TEST_CONTRACT_ADDRESS || - key == &ccx.caller || - key == &ccx.state.config.evm_opts.sender || - val.is_empty() + key == &CHEATCODE_ADDRESS + || key == &CALLER + || key == &HARDHAT_CONSOLE_ADDRESS + || key == &TEST_CONTRACT_ADDRESS + || key == &ccx.caller + || key == &ccx.state.config.evm_opts.sender + || val.is_empty() }; let alloc = ccx diff --git a/crates/cheatcodes/src/evm/fork.rs b/crates/cheatcodes/src/evm/fork.rs index a8cc830009fe..bbdfc4364645 100644 --- a/crates/cheatcodes/src/evm/fork.rs +++ b/crates/cheatcodes/src/evm/fork.rs @@ -357,8 +357,8 @@ fn create_fork_request( let mut evm_opts = ccx.state.config.evm_opts.clone(); evm_opts.fork_block_number = block; let fork = CreateFork { - enable_caching: !ccx.state.config.no_storage_caching && - ccx.state.config.rpc_storage_caching.enable_for_endpoint(&url), + enable_caching: !ccx.state.config.no_storage_caching + && ccx.state.config.rpc_storage_caching.enable_for_endpoint(&url), url, env: (*ccx.ecx.env).clone(), evm_opts, diff --git a/crates/cheatcodes/src/evm/mapping.rs b/crates/cheatcodes/src/evm/mapping.rs index 679609274ed6..86bda9162003 100644 --- a/crates/cheatcodes/src/evm/mapping.rs +++ b/crates/cheatcodes/src/evm/mapping.rs @@ -29,7 +29,7 @@ impl MappingSlots { match self.seen_sha3.get(&slot).copied() { Some((key, parent)) => { if self.keys.contains_key(&slot) { - return false + return false; } self.keys.insert(slot, key); self.parent_slots.insert(slot, parent); diff --git a/crates/cheatcodes/src/fs.rs b/crates/cheatcodes/src/fs.rs index 129f8a22e939..c725c460dcf7 100644 --- a/crates/cheatcodes/src/fs.rs +++ b/crates/cheatcodes/src/fs.rs @@ -376,9 +376,9 @@ fn get_artifact_code(state: &Cheatcodes, path: &str, deployed: bool) -> Result Result { resolver.ingest(t.to_owned()); } - return Ok(resolver.resolve(main_type)?) + return Ok(resolver.resolve(main_type)?); }; bail!("type description should be a valid Solidity type or a EIP712 `encodeType` string") diff --git a/crates/cheatcodes/src/string.rs b/crates/cheatcodes/src/string.rs index 7b7d9b505356..3198b9d1e30f 100644 --- a/crates/cheatcodes/src/string.rs +++ b/crates/cheatcodes/src/string.rs @@ -192,10 +192,10 @@ fn parse_value_fallback(s: &str, ty: &DynSolType) -> Option { + DynSolType::Int(_) + | DynSolType::Uint(_) + | DynSolType::FixedBytes(_) + | DynSolType::Bytes => { if !s.starts_with("0x") && s.chars().all(|c| c.is_ascii_hexdigit()) { return Some(Err("missing hex prefix (\"0x\") for hex string")); } diff --git a/crates/cheatcodes/src/test/assert.rs b/crates/cheatcodes/src/test/assert.rs index 4ab97c031e5a..409d7e5d8702 100644 --- a/crates/cheatcodes/src/test/assert.rs +++ b/crates/cheatcodes/src/test/assert.rs @@ -537,21 +537,21 @@ fn uint_assert_approx_eq_rel( ) -> Result, EqRelAssertionError> { if right.is_zero() { if left.is_zero() { - return Ok(Default::default()) + return Ok(Default::default()); } else { return Err(EqRelAssertionError::Failure(Box::new(EqRelAssertionFailure { left, right, max_delta, real_delta: EqRelDelta::Undefined, - }))) + }))); }; } let delta = get_delta_uint(left, right) .checked_mul(U256::pow(U256::from(10), EQ_REL_DELTA_RESOLUTION)) - .ok_or(EqRelAssertionError::Overflow)? / - right; + .ok_or(EqRelAssertionError::Overflow)? + / right; if delta <= max_delta { Ok(Default::default()) @@ -572,22 +572,22 @@ fn int_assert_approx_eq_rel( ) -> Result, EqRelAssertionError> { if right.is_zero() { if left.is_zero() { - return Ok(Default::default()) + return Ok(Default::default()); } else { return Err(EqRelAssertionError::Failure(Box::new(EqRelAssertionFailure { left, right, max_delta, real_delta: EqRelDelta::Undefined, - }))) + }))); } } let (_, abs_right) = right.into_sign_and_abs(); let delta = get_delta_int(left, right) .checked_mul(U256::pow(U256::from(10), EQ_REL_DELTA_RESOLUTION)) - .ok_or(EqRelAssertionError::Overflow)? / - abs_right; + .ok_or(EqRelAssertionError::Overflow)? + / abs_right; if delta <= max_delta { Ok(Default::default()) diff --git a/crates/cheatcodes/src/test/expect.rs b/crates/cheatcodes/src/test/expect.rs index f2b7cbc06546..c4e3a167ad8d 100644 --- a/crates/cheatcodes/src/test/expect.rs +++ b/crates/cheatcodes/src/test/expect.rs @@ -456,7 +456,7 @@ pub(crate) fn handle_expect_emit(state: &mut Cheatcodes, log: &alloy_primitives: // This allows a contract to arbitrarily emit more events than expected (additive behavior), // as long as all the previous events were matched in the order they were expected to be. if state.expected_emits.iter().all(|expected| expected.found) { - return + return; } // If there's anything to fill, we need to pop back. @@ -478,13 +478,13 @@ pub(crate) fn handle_expect_emit(state: &mut Cheatcodes, log: &alloy_primitives: event_to_fill_or_check.log = Some(log.data.clone()); } state.expected_emits.push_back(event_to_fill_or_check); - return + return; }; event_to_fill_or_check.found = || -> bool { // Topic count must match. if expected.topics().len() != log.topics().len() { - return false + return false; } // Match topics according to the checks. if !log @@ -494,7 +494,7 @@ pub(crate) fn handle_expect_emit(state: &mut Cheatcodes, log: &alloy_primitives: .filter(|(i, _)| event_to_fill_or_check.checks[*i]) .all(|(i, topic)| topic == &expected.topics()[i]) { - return false + return false; } // Maybe match source address. if event_to_fill_or_check.address.map_or(false, |addr| addr != log.address) { @@ -502,7 +502,7 @@ pub(crate) fn handle_expect_emit(state: &mut Cheatcodes, log: &alloy_primitives: } // Maybe match data. if event_to_fill_or_check.checks[4] && expected.data.as_ref() != log.data.data.as_ref() { - return false + return false; } true diff --git a/crates/chisel/bin/main.rs b/crates/chisel/bin/main.rs index d2b3a726f48e..52eb8d014102 100644 --- a/crates/chisel/bin/main.rs +++ b/crates/chisel/bin/main.rs @@ -134,7 +134,7 @@ async fn main() -> eyre::Result<()> { DispatchResult::CommandFailed(e) => eprintln!("{e}"), _ => panic!("Unexpected result: Please report this bug."), } - return Ok(()) + return Ok(()); } Some(ChiselSubcommand::Load { id }) | Some(ChiselSubcommand::View { id }) => { // For both of these subcommands, we need to attempt to load the session from cache @@ -142,7 +142,7 @@ async fn main() -> eyre::Result<()> { DispatchResult::CommandSuccess(_) => { /* Continue */ } DispatchResult::CommandFailed(e) => { eprintln!("{e}"); - return Ok(()) + return Ok(()); } _ => panic!("Unexpected result! Please report this bug."), } @@ -155,7 +155,7 @@ async fn main() -> eyre::Result<()> { } _ => panic!("Unexpected result! Please report this bug."), } - return Ok(()) + return Ok(()); } } Some(ChiselSubcommand::ClearCache) => { @@ -164,7 +164,7 @@ async fn main() -> eyre::Result<()> { DispatchResult::CommandFailed(e) => eprintln!("{e}"), _ => panic!("Unexpected result! Please report this bug."), } - return Ok(()) + return Ok(()); } None => { /* No chisel subcommand present; Continue */ } } @@ -206,7 +206,7 @@ async fn main() -> eyre::Result<()> { } Err(ReadlineError::Interrupted) => { if interrupt { - break + break; } else { println!("(To exit, press Ctrl+C again)"); interrupt = true; @@ -215,7 +215,7 @@ async fn main() -> eyre::Result<()> { Err(ReadlineError::Eof) => break, Err(err) => { println!("Error: {err:?}"); - break + break; } } } diff --git a/crates/chisel/src/dispatcher.rs b/crates/chisel/src/dispatcher.rs index 909b7525c9f5..b654cc9a36dd 100644 --- a/crates/chisel/src/dispatcher.rs +++ b/crates/chisel/src/dispatcher.rs @@ -87,11 +87,11 @@ impl DispatchResult { pub fn is_error(&self) -> bool { matches!( self, - Self::Failure(_) | - Self::CommandFailed(_) | - Self::UnrecognizedCommand(_) | - Self::SolangParserFailed(_) | - Self::FileIoError(_) + Self::Failure(_) + | Self::CommandFailed(_) + | Self::UnrecognizedCommand(_) + | Self::SolangParserFailed(_) + | Self::FileIoError(_) ) } } @@ -249,7 +249,7 @@ impl ChiselDispatcher { } if let Err(e) = self.session.write() { - return DispatchResult::FileIoError(e.into()) + return DispatchResult::FileIoError(e.into()); } DispatchResult::CommandSuccess(Some(format!( "Saved session to cache with ID = {}", @@ -264,7 +264,7 @@ impl ChiselDispatcher { // Must supply a session ID as the argument. return DispatchResult::CommandFailed(Self::make_error( "Must supply a session ID as the argument.", - )) + )); } // Use args as the name @@ -273,7 +273,7 @@ impl ChiselDispatcher { // Don't save an empty session if !self.source().run_code.is_empty() { if let Err(e) = self.session.write() { - return DispatchResult::FileIoError(e.into()) + return DispatchResult::FileIoError(e.into()); } println!("{}", "Saved current session!".green()); } @@ -338,12 +338,12 @@ impl ChiselDispatcher { self.source_mut().config.evm_opts.fork_url = None; return DispatchResult::CommandSuccess(Some( "Now using local environment.".to_string(), - )) + )); } if args.len() != 1 { return DispatchResult::CommandFailed(Self::make_error( "Must supply a session ID as the argument.", - )) + )); } let arg = *args.first().unwrap(); @@ -369,7 +369,7 @@ impl ChiselDispatcher { // Check validity of URL if Url::parse(&fork_url).is_err() { - return DispatchResult::CommandFailed(Self::make_error("Invalid fork URL!")) + return DispatchResult::CommandFailed(Self::make_error("Invalid fork URL!")); } // Create success message before moving the fork_url @@ -402,7 +402,7 @@ impl ChiselDispatcher { if arg.is_empty() { self.source_mut().config.calldata = None; - return DispatchResult::CommandSuccess(Some("Calldata cleared.".to_string())) + return DispatchResult::CommandSuccess(Some("Calldata cleared.".to_string())); } let calldata = hex::decode(arg); @@ -465,7 +465,7 @@ impl ChiselDispatcher { // Create "script" dir if it does not already exist. if !Path::new("script").exists() { if let Err(e) = std::fs::create_dir_all("script") { - return DispatchResult::CommandFailed(Self::make_error(e.to_string())) + return DispatchResult::CommandFailed(Self::make_error(e.to_string())); } } @@ -475,7 +475,7 @@ impl ChiselDispatcher { if let Err(e) = std::fs::write(PathBuf::from("script/REPL.s.sol"), formatted_source) { - return DispatchResult::CommandFailed(Self::make_error(e.to_string())) + return DispatchResult::CommandFailed(Self::make_error(e.to_string())); } DispatchResult::CommandSuccess(Some(String::from( @@ -491,7 +491,7 @@ impl ChiselDispatcher { if args.len() != 2 { return DispatchResult::CommandFailed(Self::make_error( "Incorrect number of arguments supplied. Expected:
", - )) + )); } let request_url = format!( @@ -618,7 +618,7 @@ impl ChiselDispatcher { } ChiselCommand::Exec => { if args.is_empty() { - return DispatchResult::CommandFailed(Self::make_error("No command supplied!")) + return DispatchResult::CommandFailed(Self::make_error("No command supplied!")); } let mut cmd = Command::new(args[0]); @@ -644,7 +644,7 @@ impl ChiselDispatcher { if let Err(e) = result { return DispatchResult::CommandFailed(format!( "Could not write to a temporary file: {e}" - )) + )); } // open the temp file with the editor @@ -658,11 +658,11 @@ impl ChiselDispatcher { if let Some(status_code) = status.code() { return DispatchResult::CommandFailed(format!( "Editor exited with status {status_code}" - )) + )); } else { return DispatchResult::CommandFailed( "Editor exited without a status code".to_string(), - ) + ); } } } @@ -680,7 +680,7 @@ impl ChiselDispatcher { } else { return DispatchResult::CommandFailed( "Could not read the edited file".to_string(), - ) + ); } // if the editor exited successfully, try to compile the new code @@ -692,7 +692,7 @@ impl ChiselDispatcher { Self::decode_traces(&new_session_source.config, &mut res).await { if let Err(e) = Self::show_traces(&decoder, &mut res).await { - return DispatchResult::CommandFailed(e.to_string()) + return DispatchResult::CommandFailed(e.to_string()); }; // Show console logs, if there are any @@ -730,7 +730,7 @@ impl ChiselDispatcher { 0 => "No variable supplied!", _ => "!rawstack only takes one argument.", }; - return DispatchResult::CommandFailed(Self::make_error(msg)) + return DispatchResult::CommandFailed(Self::make_error(msg)); } // Store the variable that we want to inspect @@ -768,11 +768,11 @@ impl ChiselDispatcher { return match raw_cmd.parse::() { Ok(cmd) => self.dispatch_command(cmd, &split[1..]).await, Err(e) => DispatchResult::UnrecognizedCommand(e), - } + }; } if input.trim().is_empty() { debug!("empty dispatch input"); - return DispatchResult::Success(None) + return DispatchResult::Success(None); } // Get a mutable reference to the session source @@ -782,7 +782,7 @@ impl ChiselDispatcher { if COMMENT_RE.is_match(input) { debug!(%input, "matched comment"); source.with_run_code(input); - return DispatchResult::Success(None) + return DispatchResult::Success(None); } // If there is an address (or multiple addresses) in the input, ensure that they are @@ -819,7 +819,7 @@ impl ChiselDispatcher { // Return successfully Ok((false, res)) => { debug!(%input, ?res, "inspect success"); - return DispatchResult::Success(res) + return DispatchResult::Success(res); } // Return with the error @@ -837,7 +837,7 @@ impl ChiselDispatcher { if let Ok(decoder) = Self::decode_traces(&new_source.config, &mut res).await { if let Err(e) = Self::show_traces(&decoder, &mut res).await { - return DispatchResult::CommandFailed(e.to_string()) + return DispatchResult::CommandFailed(e.to_string()); }; // Show console logs, if there are any @@ -854,7 +854,7 @@ impl ChiselDispatcher { if failed { return DispatchResult::Failure(Some(Self::make_error( "Failed to execute REPL contract!", - ))) + ))); } } } diff --git a/crates/chisel/src/executor.rs b/crates/chisel/src/executor.rs index a0b9fc391e9b..93c0b59ead5f 100644 --- a/crates/chisel/src/executor.rs +++ b/crates/chisel/src/executor.rs @@ -136,7 +136,7 @@ impl SessionSource { Ok((source, _)) => source, Err(err) => { debug!(%err, "failed to build new source"); - return Ok((true, None)) + return Ok((true, None)); } }; @@ -154,7 +154,7 @@ impl SessionSource { if self.config.foundry_config.verbosity >= 3 { eprintln!("Could not inspect: {err}"); } - return Ok((true, None)) + return Ok((true, None)); } } } @@ -175,7 +175,7 @@ impl SessionSource { if let Some(event_definition) = intermediate_contract.event_definitions.get(input) { let formatted = format_event_definition(event_definition)?; - return Ok((false, Some(formatted))) + return Ok((false, Some(formatted))); } // we were unable to check the event @@ -184,7 +184,7 @@ impl SessionSource { } debug!(%err, %input, "failed abi encode input"); - return Ok((false, None)) + return Ok((false, None)); } let Some((stack, memory, _)) = &res.state else { @@ -200,7 +200,7 @@ impl SessionSource { } } - return Err(eyre::eyre!("Failed to inspect expression")) + return Err(eyre::eyre!("Failed to inspect expression")); }; let generated_output = source @@ -762,7 +762,7 @@ impl Type { /// See: fn map_special(self) -> Self { if !matches!(self, Self::Function(_, _, _) | Self::Access(_, _) | Self::Custom(_)) { - return self + return self; } let mut types = Vec::with_capacity(5); @@ -771,7 +771,7 @@ impl Type { let len = types.len(); if len == 0 { - return self + return self; } // Type members, like array, bytes etc @@ -809,8 +809,8 @@ impl Type { match name { "block" => match access { "coinbase" => Some(DynSolType::Address), - "timestamp" | "difficulty" | "prevrandao" | "number" | "gaslimit" | - "chainid" | "basefee" | "blobbasefee" => Some(DynSolType::Uint(256)), + "timestamp" | "difficulty" | "prevrandao" | "number" | "gaslimit" + | "chainid" | "basefee" | "blobbasefee" => Some(DynSolType::Uint(256)), _ => None, }, "msg" => match access { @@ -931,7 +931,7 @@ impl Type { custom_type.pop(); } if custom_type.is_empty() { - return Ok(None) + return Ok(None); } // If a contract exists with the given name, check its definitions for a match. @@ -946,7 +946,7 @@ impl Type { if let Some(func) = intermediate_contract.function_definitions.get(cur_type) { // Check if the custom type is a function pointer member access if let res @ Some(_) = func_members(func, custom_type) { - return Ok(res) + return Ok(res); } // Because tuple types cannot be passed to `abi.encode`, we will only be @@ -967,7 +967,7 @@ impl Type { // struct, array, etc. if let pt::Expression::Variable(ident) = return_ty { custom_type.push(ident.name.clone()); - return Self::infer_custom_type(intermediate, custom_type, Some(contract_name)) + return Self::infer_custom_type(intermediate, custom_type, Some(contract_name)); } // Check if our final function call alters the state. If it does, we bail so that it @@ -1006,7 +1006,7 @@ impl Type { // anything. If it is, we can stop here. if let Ok(res) = Self::infer_custom_type(intermediate, custom_type, Some("REPL".into())) { - return Ok(res) + return Ok(res); } // Check if the first element of the custom type is a known contract. If it is, begin @@ -1015,13 +1015,13 @@ impl Type { let contract = intermediate.intermediate_contracts.get(name); if contract.is_some() { let contract_name = custom_type.pop(); - return Self::infer_custom_type(intermediate, custom_type, contract_name) + return Self::infer_custom_type(intermediate, custom_type, contract_name); } // See [`Type::infer_var_expr`] let name = custom_type.last().unwrap(); if let Some(expr) = intermediate.repl_contract_expressions.get(name) { - return Self::infer_var_expr(expr, Some(intermediate), custom_type) + return Self::infer_var_expr(expr, Some(intermediate), custom_type); } // The first element of our custom type was neither a variable or a function within the @@ -1149,7 +1149,7 @@ impl Type { let pt::Expression::Variable(contract_name) = intermediate.repl_contract_expressions.get(&contract_name.name)? else { - return None + return None; }; let contract = intermediate @@ -1187,9 +1187,9 @@ impl Type { Some(DynSolType::Array(inner)) | Some(DynSolType::FixedArray(inner, _)) => { Some(*inner) } - Some(DynSolType::Bytes) | - Some(DynSolType::String) | - Some(DynSolType::FixedBytes(_)) => Some(DynSolType::FixedBytes(1)), + Some(DynSolType::Bytes) + | Some(DynSolType::String) + | Some(DynSolType::FixedBytes(_)) => Some(DynSolType::FixedBytes(1)), ty => ty, } } @@ -1214,10 +1214,10 @@ impl Type { fn is_array(&self) -> bool { matches!( self, - Self::Array(_) | - Self::FixedArray(_, _) | - Self::Builtin(DynSolType::Array(_)) | - Self::Builtin(DynSolType::FixedArray(_, _)) + Self::Array(_) + | Self::FixedArray(_, _) + | Self::Builtin(DynSolType::Array(_)) + | Self::Builtin(DynSolType::FixedArray(_, _)) ) } @@ -1238,7 +1238,7 @@ impl Type { #[inline] fn func_members(func: &pt::FunctionDefinition, custom_type: &[String]) -> Option { if !matches!(func.ty, pt::FunctionTy::Function) { - return None + return None; } let vis = func.attributes.iter().find_map(|attr| match attr { @@ -1683,7 +1683,7 @@ mod tests { Ok((v, solc)) => { // successfully installed eprintln!("found installed Solc v{v} @ {}", solc.solc.display()); - break + break; } Err(e) => { // try reinstalling @@ -1691,7 +1691,7 @@ mod tests { let solc = Solc::blocking_install(&version.parse().unwrap()); if solc.map_err(SolcError::from).is_ok() { *is_preinstalled = true; - break + break; } } } diff --git a/crates/chisel/src/runner.rs b/crates/chisel/src/runner.rs index e78454ee363b..80692f658b46 100644 --- a/crates/chisel/src/runner.rs +++ b/crates/chisel/src/runner.rs @@ -152,9 +152,9 @@ impl ChiselRunner { self.executor.env_mut().tx.gas_limit = mid_gas_limit; let res = self.executor.call_raw(from, to, calldata.clone(), value)?; match res.exit_reason { - InstructionResult::Revert | - InstructionResult::OutOfGas | - InstructionResult::OutOfFunds => { + InstructionResult::Revert + | InstructionResult::OutOfGas + | InstructionResult::OutOfFunds => { lowest_gas_limit = mid_gas_limit; } _ => { @@ -162,9 +162,9 @@ impl ChiselRunner { // if last two successful estimations only vary by 10%, we consider this to // sufficiently accurate const ACCURACY: u64 = 10; - if (last_highest_gas_limit - highest_gas_limit) * ACCURACY / - last_highest_gas_limit < - 1 + if (last_highest_gas_limit - highest_gas_limit) * ACCURACY + / last_highest_gas_limit + < 1 { // update the gas gas_used = highest_gas_limit; diff --git a/crates/chisel/src/session.rs b/crates/chisel/src/session.rs index 2f293c1cd917..b20fb8ff5619 100644 --- a/crates/chisel/src/session.rs +++ b/crates/chisel/src/session.rs @@ -116,7 +116,7 @@ impl ChiselSession { let mut latest = if let Some(e) = entries.next() { e? } else { - return Ok((String::from("0"), format!("{cache_dir}chisel-0.json"))) + return Ok((String::from("0"), format!("{cache_dir}chisel-0.json"))); }; let mut session_num = 1; diff --git a/crates/chisel/src/solidity_helper.rs b/crates/chisel/src/solidity_helper.rs index 84140c820a54..7b381f63cfd1 100644 --- a/crates/chisel/src/solidity_helper.rs +++ b/crates/chisel/src/solidity_helper.rs @@ -66,10 +66,10 @@ impl SolidityHelper { // highlight comments too let comments_iter = comments.into_iter().map(|comment| { let loc = match comment { - pt::Comment::Line(loc, _) | - pt::Comment::Block(loc, _) | - pt::Comment::DocLine(loc, _) | - pt::Comment::DocBlock(loc, _) => loc, + pt::Comment::Line(loc, _) + | pt::Comment::Block(loc, _) + | pt::Comment::DocLine(loc, _) + | pt::Comment::DocBlock(loc, _) => loc, }; (loc.start(), Style::new().dim(), loc.end()) }); @@ -103,7 +103,7 @@ impl SolidityHelper { /// Highlights a solidity source string pub fn highlight(input: &str) -> Cow<'_, str> { if !yansi::is_enabled() { - return Cow::Borrowed(input) + return Cow::Borrowed(input); } // Highlight commands separately @@ -221,7 +221,7 @@ impl Highlighter for SolidityHelper { _default: bool, ) -> Cow<'b, str> { if !yansi::is_enabled() { - return Cow::Borrowed(prompt) + return Cow::Borrowed(prompt); } let mut out = prompt.to_string(); @@ -284,27 +284,27 @@ impl<'a> TokenStyle for Token<'a> { match self { StringLiteral(_, _) => Color::Green.foreground(), - AddressLiteral(_) | - HexLiteral(_) | - Number(_, _) | - RationalNumber(_, _, _) | - HexNumber(_) | - True | - False => Color::Yellow.foreground(), - - Memory | Storage | Calldata | Public | Private | Internal | External | Constant | - Pure | View | Payable | Anonymous | Indexed | Abstract | Virtual | Override | - Modifier | Immutable | Unchecked => Color::Cyan.foreground(), - - Contract | Library | Interface | Function | Pragma | Import | Struct | Event | - Enum | Type | Constructor | As | Is | Using | New | Delete | Do | Continue | - Break | Throw | Emit | Return | Returns | Revert | For | While | If | Else | Try | - Catch | Assembly | Let | Leave | Switch | Case | Default | YulArrow | Arrow => { + AddressLiteral(_) + | HexLiteral(_) + | Number(_, _) + | RationalNumber(_, _, _) + | HexNumber(_) + | True + | False => Color::Yellow.foreground(), + + Memory | Storage | Calldata | Public | Private | Internal | External | Constant + | Pure | View | Payable | Anonymous | Indexed | Abstract | Virtual | Override + | Modifier | Immutable | Unchecked => Color::Cyan.foreground(), + + Contract | Library | Interface | Function | Pragma | Import | Struct | Event | Enum + | Type | Constructor | As | Is | Using | New | Delete | Do | Continue | Break + | Throw | Emit | Return | Returns | Revert | For | While | If | Else | Try | Catch + | Assembly | Let | Leave | Switch | Case | Default | YulArrow | Arrow => { Color::Magenta.foreground() } - Uint(_) | Int(_) | Bytes(_) | Byte | DynamicBytes | Bool | Address | String | - Mapping => Color::Blue.foreground(), + Uint(_) | Int(_) | Bytes(_) | Byte | DynamicBytes | Bool | Address | String + | Mapping => Color::Blue.foreground(), Identifier(_) => Style::default(), diff --git a/crates/cli/src/handler.rs b/crates/cli/src/handler.rs index 4f69c2ca445c..a0136108fc8b 100644 --- a/crates/cli/src/handler.rs +++ b/crates/cli/src/handler.rs @@ -13,7 +13,7 @@ impl EyreHandler for Handler { f: &mut core::fmt::Formatter<'_>, ) -> core::fmt::Result { if f.alternate() { - return core::fmt::Debug::fmt(error, f) + return core::fmt::Debug::fmt(error, f); } writeln!(f)?; write!(f, "{}", error.red())?; diff --git a/crates/cli/src/opts/dependency.rs b/crates/cli/src/opts/dependency.rs index 945386d2b64a..281d18676010 100644 --- a/crates/cli/src/opts/dependency.rs +++ b/crates/cli/src/opts/dependency.rs @@ -60,7 +60,7 @@ impl FromStr for Dependency { for (alias, real_org) in COMMON_ORG_ALIASES.iter() { if dependency.starts_with(alias) { dependency = dependency.replacen(alias, real_org, 1); - break + break; } } diff --git a/crates/cli/src/utils/abi.rs b/crates/cli/src/utils/abi.rs index e903804ded91..a582eb15210e 100644 --- a/crates/cli/src/utils/abi.rs +++ b/crates/cli/src/utils/abi.rs @@ -43,7 +43,7 @@ pub async fn parse_function_args bool { if let Some(chain) = Chain::from(chain_id).named() { return matches!( chain, - NamedChain::Arbitrum | - NamedChain::ArbitrumTestnet | - NamedChain::ArbitrumGoerli | - NamedChain::ArbitrumSepolia | - NamedChain::Moonbeam | - NamedChain::Moonriver | - NamedChain::Moonbase | - NamedChain::MoonbeamDev + NamedChain::Arbitrum + | NamedChain::ArbitrumTestnet + | NamedChain::ArbitrumGoerli + | NamedChain::ArbitrumSepolia + | NamedChain::Moonbeam + | NamedChain::Moonriver + | NamedChain::Moonbase + | NamedChain::MoonbeamDev ); } false @@ -181,10 +181,10 @@ pub fn has_batch_support(chain_id: u64) -> bool { if let Some(chain) = Chain::from(chain_id).named() { return !matches!( chain, - NamedChain::Arbitrum | - NamedChain::ArbitrumTestnet | - NamedChain::ArbitrumGoerli | - NamedChain::ArbitrumSepolia + NamedChain::Arbitrum + | NamedChain::ArbitrumTestnet + | NamedChain::ArbitrumGoerli + | NamedChain::ArbitrumSepolia ); } true diff --git a/crates/common/fmt/src/console.rs b/crates/common/fmt/src/console.rs index efade2e436a6..ac491ef4036a 100644 --- a/crates/common/fmt/src/console.rs +++ b/crates/common/fmt/src/console.rs @@ -44,10 +44,10 @@ impl ConsoleFmt for String { match spec { FormatSpec::String => self.clone(), FormatSpec::Object => format!("'{}'", self.clone()), - FormatSpec::Number | - FormatSpec::Integer | - FormatSpec::Exponential | - FormatSpec::Hexadecimal => Self::from("NaN"), + FormatSpec::Number + | FormatSpec::Integer + | FormatSpec::Exponential + | FormatSpec::Hexadecimal => Self::from("NaN"), } } } @@ -238,7 +238,7 @@ fn format_spec<'a>( // no more values if current_value.is_none() { result.push_str(&s[i..].replace("%%", "%")); - break + break; } if expect_fmt { diff --git a/crates/common/fmt/src/exp.rs b/crates/common/fmt/src/exp.rs index 84444615e6d0..cfecf0247809 100644 --- a/crates/common/fmt/src/exp.rs +++ b/crates/common/fmt/src/exp.rs @@ -55,7 +55,7 @@ pub fn to_exp_notation(value: U256, precision: usize, trim_end_zeros: bool, sign /// ``` pub fn format_uint_exp(num: U256) -> String { if num < U256::from(10_000) { - return num.to_string() + return num.to_string(); } let exp = to_exp_notation(num, 4, true, Sign::Positive); diff --git a/crates/common/fmt/src/ui.rs b/crates/common/fmt/src/ui.rs index b9deffc7eda2..84d0d36f04ef 100644 --- a/crates/common/fmt/src/ui.rs +++ b/crates/common/fmt/src/ui.rs @@ -392,7 +392,7 @@ pub fn get_pretty_tx_attr(transaction: &Transaction, attr: &str) -> Option Some(transaction.value.pretty()), other => { if let Some(value) = transaction.other.get(other) { - return Some(value.to_string().trim_matches('"').to_string()) + return Some(value.to_string().trim_matches('"').to_string()); } None } @@ -424,7 +424,7 @@ pub fn get_pretty_block_attr(block: &Block, attr: &str) -> Option { other => { if let Some(value) = block.other.get(other) { let val = EthValue::from(value.clone()); - return Some(val.pretty()) + return Some(val.pretty()); } None } diff --git a/crates/common/src/abi.rs b/crates/common/src/abi.rs index a7c545bc82c6..b2b2c8210282 100644 --- a/crates/common/src/abi.rs +++ b/crates/common/src/abi.rs @@ -90,8 +90,8 @@ pub fn get_indexed_event(mut event: Event, raw_log: &LogData) -> Event { if param.name.is_empty() { param.name = format!("param{index}"); } - if num_inputs == indexed_params || - (num_address_params == indexed_params && param.ty == "address") + if num_inputs == indexed_params + || (num_address_params == indexed_params && param.ty == "address") { param.indexed = true; } @@ -119,7 +119,7 @@ pub async fn get_func_etherscan( for func in funcs { let res = encode_function_args(&func, args); if res.is_ok() { - return Ok(func) + return Ok(func); } } diff --git a/crates/common/src/ens.rs b/crates/common/src/ens.rs index f84ea84cecab..14c067adbaaa 100644 --- a/crates/common/src/ens.rs +++ b/crates/common/src/ens.rs @@ -162,7 +162,7 @@ where /// Returns the ENS namehash as specified in [EIP-137](https://eips.ethereum.org/EIPS/eip-137) pub fn namehash(name: &str) -> B256 { if name.is_empty() { - return B256::ZERO + return B256::ZERO; } // Remove the variation selector `U+FE0F` if present. diff --git a/crates/common/src/errors/fs.rs b/crates/common/src/errors/fs.rs index 9ea84b9ce444..f68bb8ffb3c4 100644 --- a/crates/common/src/errors/fs.rs +++ b/crates/common/src/errors/fs.rs @@ -96,17 +96,17 @@ impl FsPathError { impl AsRef for FsPathError { fn as_ref(&self) -> &Path { match self { - Self::Write { path, .. } | - Self::Read { path, .. } | - Self::ReadLink { path, .. } | - Self::Copy { from: path, .. } | - Self::CreateDir { path, .. } | - Self::RemoveDir { path, .. } | - Self::CreateFile { path, .. } | - Self::RemoveFile { path, .. } | - Self::Open { path, .. } | - Self::ReadJson { path, .. } | - Self::WriteJson { path, .. } => path, + Self::Write { path, .. } + | Self::Read { path, .. } + | Self::ReadLink { path, .. } + | Self::Copy { from: path, .. } + | Self::CreateDir { path, .. } + | Self::RemoveDir { path, .. } + | Self::CreateFile { path, .. } + | Self::RemoveFile { path, .. } + | Self::Open { path, .. } + | Self::ReadJson { path, .. } + | Self::WriteJson { path, .. } => path, } } } @@ -114,15 +114,15 @@ impl AsRef for FsPathError { impl From for io::Error { fn from(value: FsPathError) -> Self { match value { - FsPathError::Write { source, .. } | - FsPathError::Read { source, .. } | - FsPathError::ReadLink { source, .. } | - FsPathError::Copy { source, .. } | - FsPathError::CreateDir { source, .. } | - FsPathError::RemoveDir { source, .. } | - FsPathError::CreateFile { source, .. } | - FsPathError::RemoveFile { source, .. } | - FsPathError::Open { source, .. } => source, + FsPathError::Write { source, .. } + | FsPathError::Read { source, .. } + | FsPathError::ReadLink { source, .. } + | FsPathError::Copy { source, .. } + | FsPathError::CreateDir { source, .. } + | FsPathError::RemoveDir { source, .. } + | FsPathError::CreateFile { source, .. } + | FsPathError::RemoveFile { source, .. } + | FsPathError::Open { source, .. } => source, FsPathError::ReadJson { source, .. } | FsPathError::WriteJson { source, .. } => { source.into() diff --git a/crates/common/src/term.rs b/crates/common/src/term.rs index 925456e4c65f..4cc06db0242e 100644 --- a/crates/common/src/term.rs +++ b/crates/common/src/term.rs @@ -65,7 +65,7 @@ impl Spinner { pub fn tick(&mut self) { if self.no_progress { - return + return; } let indicator = self.indicator[self.idx % self.indicator.len()].green(); @@ -116,7 +116,7 @@ impl SpinnerReporter { // end with a newline println!(); let _ = ack.send(()); - break + break; } Err(TryRecvError::Disconnected) => break, Err(TryRecvError::Empty) => thread::sleep(Duration::from_millis(100)), diff --git a/crates/common/src/transactions.rs b/crates/common/src/transactions.rs index 2693c8ac249b..facacf25e455 100644 --- a/crates/common/src/transactions.rs +++ b/crates/common/src/transactions.rs @@ -41,7 +41,7 @@ impl TransactionReceiptWithRevertReason { provider: &P, ) -> Result> { if !self.is_failure() { - return Ok(None) + return Ok(None); } let transaction = provider diff --git a/crates/config/src/cache.rs b/crates/config/src/cache.rs index d087b5e6a2c2..229af4cf8227 100644 --- a/crates/config/src/cache.rs +++ b/crates/config/src/cache.rs @@ -24,7 +24,7 @@ impl StorageCachingConfig { pub fn enable_for_chain_id(&self, chain_id: u64) -> bool { // ignore dev chains if [99, 1337, 31337].contains(&chain_id) { - return false + return false; } self.chains.is_match(chain_id) } diff --git a/crates/config/src/endpoints.rs b/crates/config/src/endpoints.rs index eabc5acb196e..2afb7751b6be 100644 --- a/crates/config/src/endpoints.rs +++ b/crates/config/src/endpoints.rs @@ -262,9 +262,9 @@ impl Serialize for RpcEndpointConfig { where S: Serializer, { - if self.retries.is_none() && - self.retry_backoff.is_none() && - self.compute_units_per_second.is_none() + if self.retries.is_none() + && self.retry_backoff.is_none() + && self.compute_units_per_second.is_none() { // serialize as endpoint if there's no additional config self.endpoint.serialize(serializer) diff --git a/crates/config/src/fix.rs b/crates/config/src/fix.rs index 73d52d979cbc..78fed4ff5bd8 100644 --- a/crates/config/src/fix.rs +++ b/crates/config/src/fix.rs @@ -78,7 +78,7 @@ impl TomlFile { return Err(InsertProfileError { message: format!("Expected [{profile_str}] to be a Table"), value, - }) + }); } // get or create the profile section let profile_map = if let Some(map) = self.get_mut(Config::PROFILE_SECTION) { @@ -98,7 +98,7 @@ impl TomlFile { return Err(InsertProfileError { message: format!("Expected [{}] to be a Table", Config::PROFILE_SECTION), value, - }) + }); }; // check the profile map for structure and existing keys if let Some(profile) = profile_map.get(profile_str) { @@ -111,7 +111,7 @@ impl TomlFile { profile_str ), value, - }) + }); } } else { return Err(InsertProfileError { @@ -121,7 +121,7 @@ impl TomlFile { profile_str ), value, - }) + }); } } // insert the profile @@ -186,7 +186,7 @@ pub fn fix_tomls() -> Vec { Ok(toml_file) => toml_file, Err(err) => { warnings.push(Warning::CouldNotReadToml { path: toml, err: err.to_string() }); - continue + continue; } }; diff --git a/crates/config/src/fuzz.rs b/crates/config/src/fuzz.rs index fb04383228a9..38b330eaead6 100644 --- a/crates/config/src/fuzz.rs +++ b/crates/config/src/fuzz.rs @@ -74,7 +74,7 @@ impl InlineConfigParser for FuzzConfig { let overrides: Vec<(String, String)> = Self::get_config_overrides(configs); if overrides.is_empty() { - return Ok(None) + return Ok(None); } let mut conf_clone = self.clone(); diff --git a/crates/config/src/inline/natspec.rs b/crates/config/src/inline/natspec.rs index 6dd6b696c015..b04d1f4c5a22 100644 --- a/crates/config/src/inline/natspec.rs +++ b/crates/config/src/inline/natspec.rs @@ -99,7 +99,7 @@ impl SolcParser { let contract_data = &n.other; if let Value::String(contract_name) = contract_data.get("name")? { if contract_id.ends_with(contract_name) { - return Some(n) + return Some(n); } } } @@ -141,7 +141,7 @@ impl SolcParser { let fn_data = &node.other; let fn_name: String = self.get_fn_name(fn_data)?; let (fn_docs, docs_src_line) = self.get_node_docs(fn_data)?; - return Some((fn_name, fn_docs, docs_src_line)) + return Some((fn_name, fn_docs, docs_src_line)); } None @@ -170,7 +170,7 @@ impl SolcParser { .unwrap_or_else(|| String::from("")); src_line.retain(|c| c != '"'); - return Some((comment.into(), src_line)) + return Some((comment.into(), src_line)); } } } @@ -223,15 +223,15 @@ impl SolangParser { for item in &pt.0 { let pt::SourceUnitPart::ContractDefinition(c) = item else { prev_item_end = item.loc().end(); - continue + continue; }; let Some(id) = c.name.as_ref() else { prev_item_end = item.loc().end(); - continue + continue; }; if id.name != contract_name { prev_item_end = item.loc().end(); - continue + continue; }; // Handle doc comments in between the previous contract and the current one. diff --git a/crates/config/src/invariant.rs b/crates/config/src/invariant.rs index 698f63c26922..2fd4b7009a43 100644 --- a/crates/config/src/invariant.rs +++ b/crates/config/src/invariant.rs @@ -86,7 +86,7 @@ impl InlineConfigParser for InvariantConfig { let overrides: Vec<(String, String)> = Self::get_config_overrides(configs); if overrides.is_empty() { - return Ok(None) + return Ok(None); } let mut conf_clone = self.clone(); diff --git a/crates/config/src/providers/mod.rs b/crates/config/src/providers/mod.rs index 1f9f5c88ea89..9b2c41b471cb 100644 --- a/crates/config/src/providers/mod.rs +++ b/crates/config/src/providers/mod.rs @@ -54,8 +54,8 @@ impl WarningsProvider

{ out.extend( data.keys() .filter(|k| { - **k != Config::PROFILE_SECTION && - !Config::STANDALONE_SECTIONS.iter().any(|s| s == k) + **k != Config::PROFILE_SECTION + && !Config::STANDALONE_SECTIONS.iter().any(|s| s == k) }) .map(|unknown_section| { let source = self.provider.metadata().source.map(|s| s.to_string()); diff --git a/crates/config/src/providers/remappings.rs b/crates/config/src/providers/remappings.rs index 171967934f44..26e2ab5a7ae4 100644 --- a/crates/config/src/providers/remappings.rs +++ b/crates/config/src/providers/remappings.rs @@ -170,7 +170,7 @@ impl<'a> RemappingsProvider<'a> { // this is an additional safety check for weird auto-detected remappings if ["lib/", "src/", "contracts/"].contains(&r.name.as_str()) { trace!(target: "forge", "- skipping the remapping"); - continue + continue; } insert_closest(&mut lib_remappings, r.context, r.name, r.path.into()); } @@ -252,7 +252,7 @@ impl<'a> Provider for RemappingsProvider<'a> { if let figment::error::Kind::MissingField(_) = err.kind { self.get_remappings(vec![]) } else { - return Err(err.clone()) + return Err(err.clone()); } } }?; diff --git a/crates/config/src/utils.rs b/crates/config/src/utils.rs index b58565c4cecb..9910e7e0944f 100644 --- a/crates/config/src/utils.rs +++ b/crates/config/src/utils.rs @@ -73,12 +73,12 @@ pub fn find_project_root_path(path: Option<&PathBuf>) -> std::io::Result) -> eyre::Result) { // Skip nodes with empty steps as there's nothing to display for them. if steps.is_empty() { - continue + continue; } let call = &arena_nodes[pending.node_idx].trace; diff --git a/crates/doc/src/builder.rs b/crates/doc/src/builder.rs index e21e80c22bd5..42fc23cbeb7c 100644 --- a/crates/doc/src/builder.rs +++ b/crates/doc/src/builder.rs @@ -106,7 +106,7 @@ impl DocBuilder { if sources.is_empty() { println!("No sources detected at {}", self.sources.display()); - return Ok(()) + return Ok(()); } let library_sources = self @@ -385,7 +385,7 @@ impl DocBuilder { depth: usize, ) -> eyre::Result<()> { if files.is_empty() { - return Ok(()) + return Ok(()); } if let Some(path) = base_path { diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index be4c1e647670..b3893bf6869f 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -148,10 +148,10 @@ impl<'a> Iterator for ParseItemIter<'a> { fn next(&mut self) -> Option { if let Some(next) = self.next.take() { - return Some(next) + return Some(next); } if let Some(other) = self.other.as_mut() { - return other.next() + return other.next(); } None @@ -169,10 +169,10 @@ impl<'a> Iterator for ParseItemIterMut<'a> { fn next(&mut self) -> Option { if let Some(next) = self.next.take() { - return Some(next) + return Some(next); } if let Some(other) = self.other.as_mut() { - return other.next() + return other.next(); } None diff --git a/crates/doc/src/parser/comment.rs b/crates/doc/src/parser/comment.rs index 280dcfd0d712..d6a1216c6ae9 100644 --- a/crates/doc/src/parser/comment.rs +++ b/crates/doc/src/parser/comment.rs @@ -46,7 +46,7 @@ impl CommentTag { } _ => { warn!(target: "forge::doc", tag=trimmed, "unknown comment tag. custom tags must be preceded by `custom:`"); - return None + return None; } }; Some(tag) @@ -179,8 +179,8 @@ impl<'a> CommentsRef<'a> { self.iter().any(|c| match (&c.tag, &target.tag) { (CommentTag::Inheritdoc, CommentTag::Inheritdoc) => c.value == target.value, (CommentTag::Param, CommentTag::Param) | (CommentTag::Return, CommentTag::Return) => { - c.split_first_word().map(|(name, _)| name) == - target.split_first_word().map(|(name, _)| name) + c.split_first_word().map(|(name, _)| name) + == target.split_first_word().map(|(name, _)| name) } (tag1, tag2) => tag1 == tag2, }) diff --git a/crates/doc/src/preprocessor/contract_inheritance.rs b/crates/doc/src/preprocessor/contract_inheritance.rs index 894f373e775f..f0cf146fad47 100644 --- a/crates/doc/src/preprocessor/contract_inheritance.rs +++ b/crates/doc/src/preprocessor/contract_inheritance.rs @@ -59,7 +59,7 @@ impl ContractInheritance { if let DocumentContent::Single(ref item) = candidate.content { if let ParseSource::Contract(ref contract) = item.source { if base == contract.name.safe_unwrap().name { - return Some(candidate.target_path.clone()) + return Some(candidate.target_path.clone()); } } } diff --git a/crates/doc/src/preprocessor/infer_hyperlinks.rs b/crates/doc/src/preprocessor/infer_hyperlinks.rs index a7f7c19c4cb7..a5b55bbd0aa5 100644 --- a/crates/doc/src/preprocessor/infer_hyperlinks.rs +++ b/crates/doc/src/preprocessor/infer_hyperlinks.rs @@ -88,10 +88,13 @@ impl InferInlineHyperlinks { let name = &contract.name.safe_unwrap().name; if name == link.identifier { if link.part.is_none() { - return Some(InlineLinkTarget::borrowed(name, target_path.to_path_buf())) + return Some(InlineLinkTarget::borrowed( + name, + target_path.to_path_buf(), + )); } // try to find the referenced item in the contract's children - return Self::find_match(link, target_path, item.children.iter()) + return Self::find_match(link, target_path, item.children.iter()); } } ParseSource::Function(fun) => { @@ -104,26 +107,29 @@ impl InferInlineHyperlinks { return Some(InlineLinkTarget::borrowed( &id.name, target_path.to_path_buf(), - )) + )); } } else if link.ref_name() == "constructor" { return Some(InlineLinkTarget::borrowed( "constructor", target_path.to_path_buf(), - )) + )); } } ParseSource::Variable(_) => {} ParseSource::Event(ev) => { let ev_name = &ev.name.safe_unwrap().name; if ev_name == link.ref_name() { - return Some(InlineLinkTarget::borrowed(ev_name, target_path.to_path_buf())) + return Some(InlineLinkTarget::borrowed(ev_name, target_path.to_path_buf())); } } ParseSource::Error(err) => { let err_name = &err.name.safe_unwrap().name; if err_name == link.ref_name() { - return Some(InlineLinkTarget::borrowed(err_name, target_path.to_path_buf())) + return Some(InlineLinkTarget::borrowed( + err_name, + target_path.to_path_buf(), + )); } } ParseSource::Struct(structdef) => { @@ -132,7 +138,7 @@ impl InferInlineHyperlinks { return Some(InlineLinkTarget::borrowed( struct_name, target_path.to_path_buf(), - )) + )); } } ParseSource::Enum(_) => {} diff --git a/crates/doc/src/preprocessor/inheritdoc.rs b/crates/doc/src/preprocessor/inheritdoc.rs index 8d29a64fcf3a..9412a800413c 100644 --- a/crates/doc/src/preprocessor/inheritdoc.rs +++ b/crates/doc/src/preprocessor/inheritdoc.rs @@ -80,7 +80,7 @@ impl Inheritdoc { // TODO: improve matching logic if source.ident() == children.source.ident() { let key = format!("{}.{}", base, source.ident()); - return Some((key, children.comments.clone())) + return Some((key, children.comments.clone())); } } } diff --git a/crates/doc/src/writer/buf_writer.rs b/crates/doc/src/writer/buf_writer.rs index 7ab47c953c5f..a9bbaf911141 100644 --- a/crates/doc/src/writer/buf_writer.rs +++ b/crates/doc/src/writer/buf_writer.rs @@ -130,7 +130,7 @@ impl BufWriter { // There is nothing to write. if params.is_empty() || comments.is_empty() { - return Ok(()) + return Ok(()); } self.write_bold(heading)?; diff --git a/crates/evm/core/src/backend/mod.rs b/crates/evm/core/src/backend/mod.rs index 7839bb262e93..f19c4c500c43 100644 --- a/crates/evm/core/src/backend/mod.rs +++ b/crates/evm/core/src/backend/mod.rs @@ -797,7 +797,7 @@ impl Backend { // created account takes precedence: for example contract creation in setups if init_account.is_created() { trace!(?loaded_account, "skipping created account"); - continue + continue; } // otherwise we need to replace the account's info with the one from the fork's @@ -861,8 +861,8 @@ impl Backend { for tx in txs.into_iter() { // System transactions such as on L2s don't contain any pricing info so we skip them // otherwise this would cause reverts - if is_known_system_sender(tx.from) || - tx.transaction_type == Some(SYSTEM_TRANSACTION_TYPE) + if is_known_system_sender(tx.from) + || tx.transaction_type == Some(SYSTEM_TRANSACTION_TYPE) { trace!(tx=?tx.hash, "skipping system transaction"); continue; @@ -870,7 +870,7 @@ impl Backend { if tx.hash == tx_hash { // found the target transaction - return Ok(Some(tx)) + return Ok(Some(tx)); } trace!(tx=?tx.hash, "committing transaction"); diff --git a/crates/evm/core/src/fork/multi.rs b/crates/evm/core/src/fork/multi.rs index 372794ed1eb7..7e6021b9f854 100644 --- a/crates/evm/core/src/fork/multi.rs +++ b/crates/evm/core/src/fork/multi.rs @@ -410,8 +410,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/evm/core/src/opcodes.rs b/crates/evm/core/src/opcodes.rs index 3251036c78f7..4d8ff49b8ef1 100644 --- a/crates/evm/core/src/opcodes.rs +++ b/crates/evm/core/src/opcodes.rs @@ -9,17 +9,17 @@ use revm::interpreter::OpCode; pub const fn modifies_memory(opcode: OpCode) -> bool { matches!( opcode, - OpCode::EXTCODECOPY | - OpCode::MLOAD | - OpCode::MSTORE | - OpCode::MSTORE8 | - OpCode::MCOPY | - OpCode::CODECOPY | - OpCode::CALLDATACOPY | - OpCode::RETURNDATACOPY | - OpCode::CALL | - OpCode::CALLCODE | - OpCode::DELEGATECALL | - OpCode::STATICCALL + OpCode::EXTCODECOPY + | OpCode::MLOAD + | OpCode::MSTORE + | OpCode::MSTORE8 + | OpCode::MCOPY + | OpCode::CODECOPY + | OpCode::CALLDATACOPY + | OpCode::RETURNDATACOPY + | OpCode::CALL + | OpCode::CALLCODE + | OpCode::DELEGATECALL + | OpCode::STATICCALL ) } diff --git a/crates/evm/core/src/utils.rs b/crates/evm/core/src/utils.rs index 76a738c52540..c61bf2e47104 100644 --- a/crates/evm/core/src/utils.rs +++ b/crates/evm/core/src/utils.rs @@ -37,10 +37,10 @@ pub fn apply_chain_and_block_specific_env_changes(env: &mut revm::primitives::En return; } - NamedChain::Arbitrum | - NamedChain::ArbitrumGoerli | - NamedChain::ArbitrumNova | - NamedChain::ArbitrumTestnet => { + NamedChain::Arbitrum + | NamedChain::ArbitrumGoerli + | NamedChain::ArbitrumNova + | NamedChain::ArbitrumTestnet => { // on arbitrum `block.number` is the L1 block which is included in the // `l1BlockNumber` field if let Some(l1_block_number) = block.other.get("l1BlockNumber").cloned() { @@ -151,7 +151,7 @@ pub fn create2_handler_register>( gas: Gas::new(gas_limit), }, memory_offset: 0..0, - }))) + }))); } // Handle potential inspector override. diff --git a/crates/evm/coverage/src/analysis.rs b/crates/evm/coverage/src/analysis.rs index 1541f0b49268..1667ef9db009 100644 --- a/crates/evm/coverage/src/analysis.rs +++ b/crates/evm/coverage/src/analysis.rs @@ -54,7 +54,7 @@ impl<'a> ContractVisitor<'a> { let kind: String = node.attribute("kind").ok_or_else(|| eyre::eyre!("Function has no kind"))?; if kind == "receive" { - return Ok(()) + return Ok(()); } match &node.body { @@ -111,14 +111,14 @@ impl<'a> ContractVisitor<'a> { .ok_or_else(|| eyre::eyre!("inline assembly block with no AST attribute"))?, ), // Simple statements - NodeType::Break | - NodeType::Continue | - NodeType::EmitStatement | - NodeType::RevertStatement | - NodeType::YulAssignment | - NodeType::YulBreak | - NodeType::YulContinue | - NodeType::YulLeave => { + NodeType::Break + | NodeType::Continue + | NodeType::EmitStatement + | NodeType::RevertStatement + | NodeType::YulAssignment + | NodeType::YulBreak + | NodeType::YulContinue + | NodeType::YulLeave => { self.push_item(CoverageItem { kind: CoverageItemKind::Statement, loc: self.source_location_for(&node.src), @@ -414,13 +414,13 @@ impl<'a> ContractVisitor<'a> { Ok(()) } // Does not count towards coverage - NodeType::FunctionCallOptions | - NodeType::Identifier | - NodeType::IndexAccess | - NodeType::IndexRangeAccess | - NodeType::Literal | - NodeType::YulLiteralValue | - NodeType::YulIdentifier => Ok(()), + NodeType::FunctionCallOptions + | NodeType::Identifier + | NodeType::IndexAccess + | NodeType::IndexRangeAccess + | NodeType::Literal + | NodeType::YulLiteralValue + | NodeType::YulIdentifier => Ok(()), _ => { warn!("unexpected node type, expected an expression: {:?}", node.node_type); Ok(()) @@ -431,19 +431,19 @@ impl<'a> ContractVisitor<'a> { fn visit_block_or_statement(&mut self, node: &Node) -> eyre::Result<()> { match node.node_type { NodeType::Block => self.visit_block(node), - NodeType::Break | - NodeType::Continue | - NodeType::DoWhileStatement | - NodeType::EmitStatement | - NodeType::ExpressionStatement | - NodeType::ForStatement | - NodeType::IfStatement | - NodeType::InlineAssembly | - NodeType::Return | - NodeType::RevertStatement | - NodeType::TryStatement | - NodeType::VariableDeclarationStatement | - NodeType::WhileStatement => self.visit_statement(node), + NodeType::Break + | NodeType::Continue + | NodeType::DoWhileStatement + | NodeType::EmitStatement + | NodeType::ExpressionStatement + | NodeType::ForStatement + | NodeType::IfStatement + | NodeType::InlineAssembly + | NodeType::Return + | NodeType::RevertStatement + | NodeType::TryStatement + | NodeType::VariableDeclarationStatement + | NodeType::WhileStatement => self.visit_statement(node), // Skip placeholder statements as they are never referenced in source maps. NodeType::PlaceholderStatement => Ok(()), _ => { @@ -458,8 +458,8 @@ impl<'a> ContractVisitor<'a> { let source_location = &item.loc; // Push a line item if we haven't already - if matches!(item.kind, CoverageItemKind::Statement | CoverageItemKind::Branch { .. }) && - self.last_line < source_location.line + if matches!(item.kind, CoverageItemKind::Statement | CoverageItemKind::Branch { .. }) + && self.last_line < source_location.line { self.items.push(CoverageItem { kind: CoverageItemKind::Line, diff --git a/crates/evm/coverage/src/anchors.rs b/crates/evm/coverage/src/anchors.rs index 983cc77d4a1b..ab9cd82d0a65 100644 --- a/crates/evm/coverage/src/anchors.rs +++ b/crates/evm/coverage/src/anchors.rs @@ -123,7 +123,7 @@ pub fn find_anchor_branch( } else { // NOTE(onbjerg): For some reason the last few bytes of the bytecode do not have // a source map associated, so at that point we just stop searching - break + break; }; // Do push byte accounting diff --git a/crates/evm/evm/src/executors/fuzz/mod.rs b/crates/evm/evm/src/executors/fuzz/mod.rs index 76f01541d5e8..fba09d425dd7 100644 --- a/crates/evm/evm/src/executors/fuzz/mod.rs +++ b/crates/evm/evm/src/executors/fuzz/mod.rs @@ -216,7 +216,7 @@ impl FuzzedExecutor { // When the `assume` cheatcode is called it returns a special string if call.result.as_ref() == MAGIC_ASSUME { - return Err(TestCaseError::reject(FuzzError::AssumeReject)) + return Err(TestCaseError::reject(FuzzError::AssumeReject)); } let breakpoints = call diff --git a/crates/evm/evm/src/executors/invariant/mod.rs b/crates/evm/evm/src/executors/invariant/mod.rs index 7dcdc15680e1..8704ea0f3678 100644 --- a/crates/evm/evm/src/executors/invariant/mod.rs +++ b/crates/evm/evm/src/executors/invariant/mod.rs @@ -290,7 +290,7 @@ impl<'a> InvariantExecutor<'a> { ) -> Result { // Throw an error to abort test run if the invariant function accepts input params if !invariant_contract.invariant_function.inputs.is_empty() { - return Err(eyre!("Invariant test function should have no inputs")) + return Err(eyre!("Invariant test function should have no inputs")); } let (invariant_test, invariant_strategy) = @@ -307,7 +307,7 @@ impl<'a> InvariantExecutor<'a> { // We stop the run immediately if we have reverted, and `fail_on_revert` is set. if self.config.fail_on_revert && invariant_test.reverts() > 0 { - return Err(TestCaseError::fail("Revert occurred.")) + return Err(TestCaseError::fail("Revert occurred.")); } while current_run.depth < self.config.depth { @@ -338,7 +338,7 @@ impl<'a> InvariantExecutor<'a> { invariant_test.set_error(InvariantFuzzError::MaxAssumeRejects( self.config.max_assume_rejects, )); - return Err(TestCaseError::fail("Max number of vm.assume rejects reached.")) + return Err(TestCaseError::fail("Max number of vm.assume rejects reached.")); } } else { // Collect data for fuzzing from the state changeset. @@ -390,7 +390,7 @@ impl<'a> InvariantExecutor<'a> { // If test cannot continue then stop current run and exit test suite. if !result.can_continue { - return Err(TestCaseError::fail("Test cannot continue.")) + return Err(TestCaseError::fail("Test cannot continue.")); } invariant_test.set_last_call_results(result.call_result); @@ -506,7 +506,7 @@ impl<'a> InvariantExecutor<'a> { &mut failures, )?; if let Some(error) = failures.error { - return Err(eyre!(error.revert_reason().unwrap_or_default())) + return Err(eyre!(error.revert_reason().unwrap_or_default())); } Ok(( @@ -564,13 +564,13 @@ impl<'a> InvariantExecutor<'a> { .filter(|func| { !matches!( func.state_mutability, - alloy_json_abi::StateMutability::Pure | - alloy_json_abi::StateMutability::View + alloy_json_abi::StateMutability::Pure + | alloy_json_abi::StateMutability::View ) }) - .count() == - 0 && - !self.artifact_filters.excluded.contains(&artifact.identifier()) + .count() + == 0 + && !self.artifact_filters.excluded.contains(&artifact.identifier()) { self.artifact_filters.excluded.push(artifact.identifier()); } @@ -581,8 +581,8 @@ impl<'a> InvariantExecutor<'a> { for contract in selected.targetedArtifacts { let identifier = self.validate_selected_contract(contract, &[])?; - if !self.artifact_filters.targeted.contains_key(&identifier) && - !self.artifact_filters.excluded.contains(&identifier) + if !self.artifact_filters.targeted.contains_key(&identifier) + && !self.artifact_filters.excluded.contains(&identifier) { self.artifact_filters.targeted.insert(identifier, vec![]); } @@ -609,7 +609,7 @@ impl<'a> InvariantExecutor<'a> { .wrap_err(format!("{contract} does not have the selector {selector:?}"))?; } - return Ok(artifact.identifier()) + return Ok(artifact.identifier()); } eyre::bail!("{contract} not found in the project. Allowed format: `contract_name` or `contract_path:contract_name`."); } @@ -643,12 +643,12 @@ impl<'a> InvariantExecutor<'a> { .setup_contracts .iter() .filter(|&(addr, (identifier, _))| { - *addr != to && - *addr != CHEATCODE_ADDRESS && - *addr != HARDHAT_CONSOLE_ADDRESS && - (selected.is_empty() || selected.contains(addr)) && - (excluded.is_empty() || !excluded.contains(addr)) && - self.artifact_filters.matches(identifier) + *addr != to + && *addr != CHEATCODE_ADDRESS + && *addr != HARDHAT_CONSOLE_ADDRESS + && (selected.is_empty() || selected.contains(addr)) + && (excluded.is_empty() || !excluded.contains(addr)) + && self.artifact_filters.matches(identifier) }) .map(|(addr, (identifier, abi))| { (*addr, TargetedContract::new(identifier.clone(), abi.clone())) diff --git a/crates/evm/evm/src/inspectors/logs.rs b/crates/evm/evm/src/inspectors/logs.rs index 03b677fcdf84..cb7febf0edbf 100644 --- a/crates/evm/evm/src/inspectors/logs.rs +++ b/crates/evm/evm/src/inspectors/logs.rs @@ -60,7 +60,7 @@ impl Inspector for LogCollector { gas: Gas::new(inputs.gas_limit), }, memory_offset: inputs.return_memory_offset.clone(), - }) + }); } } diff --git a/crates/evm/fuzz/src/inspector.rs b/crates/evm/fuzz/src/inspector.rs index 052d87dac2dd..684cd2cb2671 100644 --- a/crates/evm/fuzz/src/inspector.rs +++ b/crates/evm/fuzz/src/inspector.rs @@ -76,9 +76,9 @@ impl Fuzzer { fn override_call(&mut self, call: &mut CallInputs) { if let Some(ref mut call_generator) = self.call_generator { // We only override external calls which are not coming from the test contract. - if call.caller != call_generator.test_address && - call.scheme == CallScheme::Call && - !call_generator.used + if call.caller != call_generator.test_address + && call.scheme == CallScheme::Call + && !call_generator.used { // There's only a 30% chance that an override happens. if let Some(tx) = call_generator.next(call.caller, call.target_address) { diff --git a/crates/evm/fuzz/src/invariant/filters.rs b/crates/evm/fuzz/src/invariant/filters.rs index 520e5b5afcd6..f9f068161f5e 100644 --- a/crates/evm/fuzz/src/invariant/filters.rs +++ b/crates/evm/fuzz/src/invariant/filters.rs @@ -18,8 +18,8 @@ pub struct ArtifactFilters { impl ArtifactFilters { /// Returns `true` if the given identifier matches this filter. pub fn matches(&self, identifier: &str) -> bool { - (self.targeted.is_empty() || self.targeted.contains_key(identifier)) && - (self.excluded.is_empty() || !self.excluded.iter().any(|id| id == identifier)) + (self.targeted.is_empty() || self.targeted.contains_key(identifier)) + && (self.excluded.is_empty() || !self.excluded.iter().any(|id| id == identifier)) } /// Gets all the targeted functions from `artifact`. Returns error, if selectors do not match @@ -38,14 +38,14 @@ impl ArtifactFilters { .collect::>>()?; // targetArtifactSelectors > excludeArtifacts > targetArtifacts if functions.is_empty() && self.excluded.contains(&artifact.identifier()) { - return Ok(None) + return Ok(None); } - return Ok(Some(functions)) + return Ok(Some(functions)); } // If no contract is specifically targeted, and this contract is not excluded, then accept // all functions. if self.targeted.is_empty() && !self.excluded.contains(&artifact.identifier()) { - return Ok(Some(vec![])) + return Ok(Some(vec![])); } Ok(None) } diff --git a/crates/evm/fuzz/src/strategies/int.rs b/crates/evm/fuzz/src/strategies/int.rs index 3732de061732..943eca6529f9 100644 --- a/crates/evm/fuzz/src/strategies/int.rs +++ b/crates/evm/fuzz/src/strategies/int.rs @@ -41,7 +41,7 @@ impl IntValueTree { fn magnitude_greater(lhs: I256, rhs: I256) -> bool { if lhs.is_zero() { - return false + return false; } (lhs > rhs) ^ (lhs.is_negative()) } @@ -56,7 +56,7 @@ impl ValueTree for IntValueTree { fn simplify(&mut self) -> bool { if self.fixed || !Self::magnitude_greater(self.hi, self.lo) { - return false + return false; } self.hi = self.curr; self.reposition() @@ -64,7 +64,7 @@ impl ValueTree for IntValueTree { fn complicate(&mut self) -> bool { if self.fixed || !Self::magnitude_greater(self.hi, self.lo) { - return false + return false; } self.lo = if self.curr != I256::MIN && self.curr != I256::MAX { @@ -142,7 +142,7 @@ impl IntStrategy { fn generate_fixtures_tree(&self, runner: &mut TestRunner) -> NewTree { // generate random cases if there's no fixtures if self.fixtures.is_empty() { - return self.generate_random_tree(runner) + return self.generate_random_tree(runner); } // Generate value tree from fixture. @@ -165,7 +165,7 @@ impl IntStrategy { let bits = rng.gen_range(0..=self.bits); if bits == 0 { - return Ok(IntValueTree::new(I256::ZERO, false)) + return Ok(IntValueTree::new(I256::ZERO, false)); } // init 2 128-bit randoms diff --git a/crates/evm/fuzz/src/strategies/uint.rs b/crates/evm/fuzz/src/strategies/uint.rs index af133efa0082..fab664566550 100644 --- a/crates/evm/fuzz/src/strategies/uint.rs +++ b/crates/evm/fuzz/src/strategies/uint.rs @@ -49,7 +49,7 @@ impl ValueTree for UintValueTree { fn simplify(&mut self) -> bool { if self.fixed || (self.hi <= self.lo) { - return false + return false; } self.hi = self.curr; self.reposition() @@ -57,7 +57,7 @@ impl ValueTree for UintValueTree { fn complicate(&mut self) -> bool { if self.fixed || (self.hi <= self.lo) { - return false + return false; } self.lo = self.curr + U256::from(1); @@ -120,7 +120,7 @@ impl UintStrategy { fn generate_fixtures_tree(&self, runner: &mut TestRunner) -> NewTree { // generate random cases if there's no fixtures if self.fixtures.is_empty() { - return self.generate_random_tree(runner) + return self.generate_random_tree(runner); } // Generate value tree from fixture. diff --git a/crates/evm/traces/src/debug/mod.rs b/crates/evm/traces/src/debug/mod.rs index a651a3acc5cb..39595840eae4 100644 --- a/crates/evm/traces/src/debug/mod.rs +++ b/crates/evm/traces/src/debug/mod.rs @@ -105,9 +105,9 @@ impl<'a> DebugStepsWalker<'a> { return false; }; - loc.offset() == other_loc.offset() && - loc.length() == other_loc.length() && - loc.index() == other_loc.index() + loc.offset() == other_loc.offset() + && loc.length() == other_loc.length() + && loc.index() == other_loc.index() } /// Invoked when current step is a JUMPDEST preceeded by a JUMP marked as [Jump::In]. @@ -131,10 +131,10 @@ impl<'a> DebugStepsWalker<'a> { /// Invoked when current step is a JUMPDEST preceeded by a JUMP marked as [Jump::Out]. fn jump_out(&mut self) { let Some((i, _)) = self.stack.iter().enumerate().rfind(|(_, (_, step_idx))| { - self.is_same_loc(*step_idx, self.current_step) || - self.is_same_loc(step_idx + 1, self.current_step - 1) + self.is_same_loc(*step_idx, self.current_step) + || self.is_same_loc(step_idx + 1, self.current_step - 1) }) else { - return + return; }; // We've found a match, remove all records between start and end, those // are considered invalid. diff --git a/crates/evm/traces/src/identifier/etherscan.rs b/crates/evm/traces/src/identifier/etherscan.rs index 4a34b31b3651..c11ba57cf1d7 100644 --- a/crates/evm/traces/src/identifier/etherscan.rs +++ b/crates/evm/traces/src/identifier/etherscan.rs @@ -103,7 +103,7 @@ impl TraceIdentifier for EtherscanIdentifier { if self.invalid_api_key.load(Ordering::Relaxed) { // api key was marked as invalid - return Vec::new() + return Vec::new(); } let mut identities = Vec::new(); @@ -222,7 +222,7 @@ impl Stream for EtherscanFetcher { if let Some(mut backoff) = pin.backoff.take() { if backoff.poll_tick(cx).is_pending() { pin.backoff = Some(backoff); - return Poll::Pending + return Poll::Pending; } } @@ -237,7 +237,7 @@ impl Stream for EtherscanFetcher { match res { Ok(mut metadata) => { if let Some(item) = metadata.items.pop() { - return Poll::Ready(Some((addr, item))) + return Poll::Ready(Some((addr, item))); } } Err(EtherscanError::RateLimitExceeded) => { @@ -249,13 +249,13 @@ impl Stream for EtherscanFetcher { warn!(target: "traces::etherscan", "invalid api key"); // mark key as invalid pin.invalid_api_key.store(true, Ordering::Relaxed); - return Poll::Ready(None) + return Poll::Ready(None); } Err(EtherscanError::BlockedByCloudflare) => { warn!(target: "traces::etherscan", "blocked by cloudflare"); // mark key as invalid pin.invalid_api_key.store(true, Ordering::Relaxed); - return Poll::Ready(None) + return Poll::Ready(None); } Err(err) => { warn!(target: "traces::etherscan", "could not get etherscan info: {:?}", err); @@ -265,7 +265,7 @@ impl Stream for EtherscanFetcher { } if !made_progress_this_iter { - return Poll::Pending + return Poll::Pending; } } } diff --git a/crates/fmt/src/buffer.rs b/crates/fmt/src/buffer.rs index 8d62a70f9881..a766d70054cd 100644 --- a/crates/fmt/src/buffer.rs +++ b/crates/fmt/src/buffer.rs @@ -189,7 +189,7 @@ impl FormatBuffer { } if lines.peek().is_some() || s.as_ref().ends_with('\n') { if self.restrict_to_single_line { - return Err(std::fmt::Error) + return Err(std::fmt::Error); } self.w.write_char('\n')?; self.handle_newline(comment_state); @@ -202,7 +202,7 @@ impl FormatBuffer { impl Write for FormatBuffer { fn write_str(&mut self, mut s: &str) -> std::fmt::Result { if s.is_empty() { - return Ok(()) + return Ok(()); } let mut indent = " ".repeat(self.current_indent_len()); @@ -217,7 +217,7 @@ impl Write for FormatBuffer { self.w.write_str(s)?; self.handle_newline(comment_state); } - break + break; } // We can see the next non-empty line. Write up to the @@ -246,7 +246,7 @@ impl Write for FormatBuffer { } WriteState::WriteTokens(comment_state) => { if s.is_empty() { - break + break; } // find the next newline or non-comment string separator (e.g. ' or ") @@ -257,13 +257,13 @@ impl Write for FormatBuffer { len = idx; if ch == '\n' { if self.restrict_to_single_line { - return Err(std::fmt::Error) + return Err(std::fmt::Error); } new_state = WriteState::LineStart(state); - break + break; } else if state == CommentState::None && (ch == '\'' || ch == '"') { new_state = WriteState::WriteString(ch); - break + break; } else { new_state = WriteState::WriteTokens(state); } @@ -275,7 +275,7 @@ impl Write for FormatBuffer { self.current_line_len += s.len(); self.last_char = s.chars().next_back(); self.state = new_state; - break + break; } else { // A newline or string has been found. Write up to that character and // continue on the tail @@ -301,7 +301,7 @@ impl Write for FormatBuffer { self.w.write_str(s)?; self.current_line_len += s.len(); self.last_char = s.chars().next_back(); - break + break; } // String end found, write the string and continue to add tokens after Some((_, _, len)) => { diff --git a/crates/fmt/src/comments.rs b/crates/fmt/src/comments.rs index 5b9d7fb27667..1ee337b96f69 100644 --- a/crates/fmt/src/comments.rs +++ b/crates/fmt/src/comments.rs @@ -75,7 +75,7 @@ impl CommentWithMetadata { fn from_comment_and_src(comment: Comment, src: &str, last_comment: Option<&Self>) -> Self { let src_before = &src[..comment.loc().start()]; if src_before.is_empty() { - return Self::new(comment, CommentPosition::Prefix, false, 0) + return Self::new(comment, CommentPosition::Prefix, false, 0); } let mut lines_before = src_before.lines().rev(); @@ -90,7 +90,7 @@ impl CommentWithMetadata { CommentPosition::Prefix, last_line.map_or(true, str::is_empty), indent_len, - ) + ); } // TODO: this loop takes almost the entirety of the time spent in parsing, which is up to @@ -241,7 +241,7 @@ impl Comments { .map(|(idx, _)| idx) .unwrap_or_else(|| comments.len()); if pos == 0 { - return Vec::new() + return Vec::new(); } comments.rotate_left(pos); comments.split_off(comments.len() - pos).into() @@ -416,7 +416,7 @@ impl<'a> Iterator for NonCommentChars<'a> { fn next(&mut self) -> Option { for (state, _, ch) in self.0.by_ref() { if state == CommentState::None { - return Some(ch) + return Some(ch); } } None diff --git a/crates/fmt/src/formatter.rs b/crates/fmt/src/formatter.rs index 94052d9a93df..a09e57f43718 100644 --- a/crates/fmt/src/formatter.rs +++ b/crates/fmt/src/formatter.rs @@ -176,12 +176,12 @@ impl<'a, W: Write> Formatter<'a, W> { /// Does the next written character require whitespace before fn next_char_needs_space(&self, next_char: char) -> bool { if self.is_beginning_of_line() { - return false + return false; } let last_char = if let Some(last_char) = self.last_char() { last_char } else { return false }; if last_char.is_whitespace() || next_char.is_whitespace() { - return false + return false; } match last_char { '{' => match next_char { @@ -203,14 +203,15 @@ impl<'a, W: Write> Formatter<'a, W> { fn will_it_fit(&self, text: impl AsRef) -> bool { let text = text.as_ref(); if text.is_empty() { - return true + return true; } if text.contains('\n') { - return false + return false; } let space: usize = self.next_char_needs_space(text.chars().next().unwrap()).into(); - self.config.line_length >= - self.total_indent_len() + self.config.line_length + >= self + .total_indent_len() .saturating_add(self.current_line_len()) .saturating_add(text.chars().count() + space) } @@ -250,7 +251,7 @@ impl<'a, W: Write> Formatter<'a, W> { fn blank_lines(&self, start: usize, end: usize) -> usize { // because of sorting import statements, start can be greater than end if start > end { - return 0 + return 0; } self.source[start..end].trim_comments().matches('\n').count() } @@ -288,10 +289,10 @@ impl<'a, W: Write> Formatter<'a, W> { subset .comment_state_char_indices() .position(|(state, idx, ch)| { - first_char == ch && - state == CommentState::None && - idx + needle.len() <= subset.len() && - subset[idx..idx + needle.len()] == *needle + first_char == ch + && state == CommentState::None + && idx + needle.len() <= subset.len() + && subset[idx..idx + needle.len()] == *needle }) .map(|p| byte_offset + p) }) @@ -422,7 +423,7 @@ impl<'a, W: Write> Formatter<'a, W> { /// or if the comment are wrapped fn write_comment(&mut self, comment: &CommentWithMetadata, is_first: bool) -> Result<()> { if self.inline_config.is_disabled(comment.loc) { - return self.write_raw_comment(comment) + return self.write_raw_comment(comment); } match comment.position { @@ -450,7 +451,7 @@ impl<'a, W: Write> Formatter<'a, W> { lines.try_for_each(|l| self.write_doc_block_line(comment, l))?; write!(self.buf(), " {}", comment.end_token().unwrap())?; self.write_preserved_line()?; - return Ok(()) + return Ok(()); } write!(self.buf(), "{}", comment.start_token())?; @@ -525,7 +526,7 @@ impl<'a, W: Write> Formatter<'a, W> { write!(self.buf(), " *{}", if needs_space { " " } else { "" })?; self.write_comment_line(comment, line)?; self.write_whitespace_separator(true)?; - return Ok(()) + return Ok(()); } let indent_whitespace_count = line @@ -551,7 +552,7 @@ impl<'a, W: Write> Formatter<'a, W> { line.chars().next().map(|ch| ch.is_whitespace()).unwrap_or_default(); if !self.is_beginning_of_line() || !start_with_ws { write!(self.buf(), "{line}")?; - return Ok(false) + return Ok(false); } // if this is the beginning of the line, @@ -563,7 +564,7 @@ impl<'a, W: Write> Formatter<'a, W> { .map(|(_, ch)| ch); let padded = format!("{}{}", " ".repeat(indent), chars.join("")); self.write_raw(padded)?; - return Ok(false) + return Ok(false); } let mut words = line.split(' ').peekable(); @@ -582,7 +583,7 @@ impl<'a, W: Write> Formatter<'a, W> { // write newline wrap token write!(self.buf(), "{}", comment.wrap_token())?; self.write_comment_line(comment, &words.join(" "))?; - return Ok(true) + return Ok(true); } self.write_whitespace_separator(false)?; @@ -1027,9 +1028,9 @@ impl<'a, W: Write> Formatter<'a, W> { Some(CommentWithMetadata { ty: CommentType::DocBlock, .. }) ); - if needs_space || - (!is_last_doc_comment && - self.blank_lines(last_loc.end(), loc.start()) > 1) + if needs_space + || (!is_last_doc_comment + && self.blank_lines(last_loc.end(), loc.start()) > 1) { writeln!(self.buf())?; } @@ -1089,14 +1090,14 @@ impl<'a, W: Write> Formatter<'a, W> { /// expression decide how to split itself on multiple lines fn visit_assignment(&mut self, expr: &mut Expression) -> Result<()> { if self.try_on_single_line(|fmt| expr.visit(fmt))? { - return Ok(()) + return Ok(()); } self.write_postfix_comments_before(expr.loc().start())?; self.write_prefix_comments_before(expr.loc().start())?; if self.try_on_single_line(|fmt| fmt.indented(1, |fmt| expr.visit(fmt)))? { - return Ok(()) + return Ok(()); } let mut fit_on_next_line = false; @@ -1188,7 +1189,7 @@ impl<'a, W: Write> Formatter<'a, W> { })?; if fits_on_single { - return Ok(true) + return Ok(true); } } @@ -1353,7 +1354,7 @@ impl<'a, W: Write> Formatter<'a, W> { let add_underscores = |string: &str, reversed: bool| -> String { if !config.is_thousands() || string.len() < 5 { - return string.to_string() + return string.to_string(); } if reversed { Box::new(string.as_bytes().chunks(3)) as Box> @@ -1491,14 +1492,14 @@ impl<'a, W: Write> Formatter<'a, W> { } else { ";" }; - let should_multiline = header_multiline && - matches!( + let should_multiline = header_multiline + && matches!( fmt.config.multiline_func_header, MultilineFuncHeaderStyle::ParamsFirst | MultilineFuncHeaderStyle::All ); - params_multiline = should_multiline || - multiline || - fmt.are_chunks_separated_multiline( + params_multiline = should_multiline + || multiline + || fmt.are_chunks_separated_multiline( &format!("{{}}){after_params}"), ¶ms, ",", @@ -1578,8 +1579,8 @@ impl<'a, W: Write> Formatter<'a, W> { Ok(()) }; - let should_multiline = header_multiline && - if params_multiline { + let should_multiline = header_multiline + && if params_multiline { matches!(self.config.multiline_func_header, MultilineFuncHeaderStyle::All) } else { matches!( @@ -1587,8 +1588,8 @@ impl<'a, W: Write> Formatter<'a, W> { MultilineFuncHeaderStyle::AttributesFirst ) }; - let attrs_multiline = should_multiline || - !self.try_on_single_line(|fmt| { + let attrs_multiline = should_multiline + || !self.try_on_single_line(|fmt| { write_attributes(fmt, false)?; if !fmt.will_it_fit(if func.body.is_some() { " {" } else { ";" }) { bail!(FormatterError::fmt()) @@ -1624,8 +1625,8 @@ impl<'a, W: Write> Formatter<'a, W> { let cond_close_paren_loc = self.find_next_in_src(cond.loc().end(), ')').unwrap_or_else(|| cond.loc().end()); - let attempt_single_line = single_line_stmt_wide && - self.should_attempt_block_single_line(if_branch.as_mut(), cond_close_paren_loc); + let attempt_single_line = single_line_stmt_wide + && self.should_attempt_block_single_line(if_branch.as_mut(), cond_close_paren_loc); let if_branch_is_single_line = self.visit_stmt_as_block(if_branch, attempt_single_line)?; if single_line_stmt_wide && !if_branch_is_single_line { bail!(FormatterError::fmt()) @@ -1680,7 +1681,7 @@ impl<'a, W: Write> Formatter<'a, W> { if import_groups.is_empty() { // nothing to sort - return + return; } // order all groups alphabetically @@ -1849,7 +1850,7 @@ impl<'a, W: Write> Visitor for Formatter<'a, W> { fmt.write_postfix_comments_before(first.loc().start())?; fmt.write_whitespace_separator(true)?; } else { - return Ok(()) + return Ok(()); } if fmt.config.contract_new_lines { @@ -1997,7 +1998,7 @@ impl<'a, W: Write> Visitor for Formatter<'a, W> { fmt.write_semicolon()?; Ok(()) })?; - return Ok(()) + return Ok(()); } let imports_start = imports.first().unwrap().0.loc.start(); @@ -2165,9 +2166,9 @@ impl<'a, W: Write> Visitor for Formatter<'a, W> { } if let Some(first) = chunks.first_mut() { - if first.prefixes.is_empty() && - first.postfixes_before.is_empty() && - !self.config.bracket_spacing + if first.prefixes.is_empty() + && first.postfixes_before.is_empty() + && !self.config.bracket_spacing { first.needs_space = Some(false); } @@ -2321,9 +2322,9 @@ impl<'a, W: Write> Visitor for Formatter<'a, W> { fmt.chunked(end.loc().start(), Some(loc.end()), |fmt| { end.visit(fmt) })?; - if chunk.prefixes.is_empty() && - chunk.postfixes_before.is_empty() && - (start.is_none() || fmt.will_it_fit(&chunk.content)) + if chunk.prefixes.is_empty() + && chunk.postfixes_before.is_empty() + && (start.is_none() || fmt.will_it_fit(&chunk.content)) { chunk.needs_space = Some(false); } @@ -2361,33 +2362,33 @@ impl<'a, W: Write> Visitor for Formatter<'a, W> { })?; write_chunk!(self, loc.end(), "]")?; } - Expression::PreIncrement(..) | - Expression::PostIncrement(..) | - Expression::PreDecrement(..) | - Expression::PostDecrement(..) | - Expression::Not(..) | - Expression::UnaryPlus(..) | - Expression::Add(..) | - Expression::Negate(..) | - Expression::Subtract(..) | - Expression::Power(..) | - Expression::Multiply(..) | - Expression::Divide(..) | - Expression::Modulo(..) | - Expression::ShiftLeft(..) | - Expression::ShiftRight(..) | - Expression::BitwiseNot(..) | - Expression::BitwiseAnd(..) | - Expression::BitwiseXor(..) | - Expression::BitwiseOr(..) | - Expression::Less(..) | - Expression::More(..) | - Expression::LessEqual(..) | - Expression::MoreEqual(..) | - Expression::And(..) | - Expression::Or(..) | - Expression::Equal(..) | - Expression::NotEqual(..) => { + Expression::PreIncrement(..) + | Expression::PostIncrement(..) + | Expression::PreDecrement(..) + | Expression::PostDecrement(..) + | Expression::Not(..) + | Expression::UnaryPlus(..) + | Expression::Add(..) + | Expression::Negate(..) + | Expression::Subtract(..) + | Expression::Power(..) + | Expression::Multiply(..) + | Expression::Divide(..) + | Expression::Modulo(..) + | Expression::ShiftLeft(..) + | Expression::ShiftRight(..) + | Expression::BitwiseNot(..) + | Expression::BitwiseAnd(..) + | Expression::BitwiseXor(..) + | Expression::BitwiseOr(..) + | Expression::Less(..) + | Expression::More(..) + | Expression::LessEqual(..) + | Expression::MoreEqual(..) + | Expression::And(..) + | Expression::Or(..) + | Expression::Equal(..) + | Expression::NotEqual(..) => { let spaced = expr.has_space_around(); let op = expr.operator().unwrap(); @@ -2418,17 +2419,17 @@ impl<'a, W: Write> Visitor for Formatter<'a, W> { (None, None) => {} } } - Expression::Assign(..) | - Expression::AssignOr(..) | - Expression::AssignAnd(..) | - Expression::AssignXor(..) | - Expression::AssignShiftLeft(..) | - Expression::AssignShiftRight(..) | - Expression::AssignAdd(..) | - Expression::AssignSubtract(..) | - Expression::AssignMultiply(..) | - Expression::AssignDivide(..) | - Expression::AssignModulo(..) => { + Expression::Assign(..) + | Expression::AssignOr(..) + | Expression::AssignAnd(..) + | Expression::AssignXor(..) + | Expression::AssignShiftLeft(..) + | Expression::AssignShiftRight(..) + | Expression::AssignAdd(..) + | Expression::AssignSubtract(..) + | Expression::AssignMultiply(..) + | Expression::AssignDivide(..) + | Expression::AssignModulo(..) => { let op = expr.operator().unwrap(); let (left, right) = expr.components_mut(); let (left, right) = (left.unwrap(), right.unwrap()); @@ -2530,7 +2531,7 @@ impl<'a, W: Write> Visitor for Formatter<'a, W> { #[instrument(name = "ident_path", skip_all)] fn visit_ident_path(&mut self, idents: &mut IdentifierPath) -> Result<(), Self::Error> { if idents.identifiers.is_empty() { - return Ok(()) + return Ok(()); } return_source_if_disabled!(self, idents.loc); @@ -2638,7 +2639,7 @@ impl<'a, W: Write> Visitor for Formatter<'a, W> { if expr.is_none() { write_chunk!(self, loc.end(), "return;")?; - return Ok(()) + return Ok(()); } let expr = expr.as_mut().unwrap(); @@ -2655,7 +2656,7 @@ impl<'a, W: Write> Visitor for Formatter<'a, W> { expr.visit(fmt) })?; if fits_on_single { - return Ok(()) + return Ok(()); } let mut fit_on_next_line = false; @@ -2672,7 +2673,7 @@ impl<'a, W: Write> Visitor for Formatter<'a, W> { })?; if fit_on_next_line { tx.commit()?; - return Ok(()) + return Ok(()); } write_return(fmt)?; @@ -2723,7 +2724,7 @@ impl<'a, W: Write> Visitor for Formatter<'a, W> { if args.is_empty() { write!(self.buf(), "({{}});")?; - return Ok(()) + return Ok(()); } write!(self.buf(), "(")?; @@ -2829,7 +2830,7 @@ impl<'a, W: Write> Visitor for Formatter<'a, W> { let multiline = self.are_chunks_separated_multiline("{}", &chunks, "")?; if !multiline { self.write_chunks_separated(&chunks, "", false)?; - return Ok(()) + return Ok(()); } let mut chunks = chunks.iter_mut().peekable(); @@ -2877,7 +2878,7 @@ impl<'a, W: Write> Visitor for Formatter<'a, W> { if !is_first_stmt { self.write_if_stmt(loc, cond, if_branch, else_branch)?; - return Ok(()) + return Ok(()); } self.context.if_stmt_single_line = Some(true); @@ -3159,7 +3160,7 @@ impl<'a, W: Write> Visitor for Formatter<'a, W> { name.content.push_str("()"); } self.write_chunk(&name)?; - return Ok(()) + return Ok(()); } let args = base.args.as_mut().unwrap(); @@ -3178,9 +3179,9 @@ impl<'a, W: Write> Visitor for Formatter<'a, W> { Some(base.loc.end()), args.iter_mut().map(|arg| (arg.loc(), arg)), )?; - let multiline = multiline || - multiline_hint || - fmt.are_chunks_separated_multiline("{}", &args, ",")?; + let multiline = multiline + || multiline_hint + || fmt.are_chunks_separated_multiline("{}", &args, ",")?; fmt.write_chunks_separated(&args, ",", multiline)?; Ok(()) }, @@ -3213,7 +3214,7 @@ impl<'a, W: Write> Visitor for Formatter<'a, W> { write_chunk!(fmt, struct_name.loc.start(), "struct")?; struct_name.visit(fmt)?; if structure.fields.is_empty() { - return fmt.write_empty_brackets() + return fmt.write_empty_brackets(); } write!(fmt.buf(), " {{")?; diff --git a/crates/fmt/src/helpers.rs b/crates/fmt/src/helpers.rs index 7f05a9c093bf..848af76b741e 100644 --- a/crates/fmt/src/helpers.rs +++ b/crates/fmt/src/helpers.rs @@ -76,7 +76,7 @@ pub fn offset_to_line_column(content: &str, start: usize) -> (usize, usize) { line_counter += 1; } if offset > start { - return (line_counter, offset - start) + return (line_counter, offset - start); } } diff --git a/crates/fmt/src/macros.rs b/crates/fmt/src/macros.rs index c5c9d31a7d0e..68305d9f2f11 100644 --- a/crates/fmt/src/macros.rs +++ b/crates/fmt/src/macros.rs @@ -91,7 +91,7 @@ macro_rules! return_source_if_disabled { let loc = $loc; if $self.inline_config.is_disabled(loc) { trace!("Returning because disabled: {loc:?}"); - return $self.visit_source(loc) + return $self.visit_source(loc); } }}; ($self:expr, $loc:expr, $suffix:literal) => {{ @@ -103,7 +103,7 @@ macro_rules! return_source_if_disabled { if !has_suffix { write!($self.buf(), "{}", $suffix)?; } - return Ok(()) + return Ok(()); } }}; } diff --git a/crates/fmt/src/solang_ext/ast_eq.rs b/crates/fmt/src/solang_ext/ast_eq.rs index 2640008e2eaa..5b31e4b7c8d4 100644 --- a/crates/fmt/src/solang_ext/ast_eq.rs +++ b/crates/fmt/src/solang_ext/ast_eq.rs @@ -5,7 +5,7 @@ use std::str::FromStr; /// Helper to convert a string number into a comparable one fn to_num(string: &str) -> I256 { if string.is_empty() { - return I256::ZERO + return I256::ZERO; } string.replace('_', "").trim().parse().unwrap() } @@ -14,7 +14,7 @@ fn to_num(string: &str) -> I256 { /// This will reverse the number so that 0's can be ignored fn to_num_reversed(string: &str) -> U256 { if string.is_empty() { - return U256::from(0) + return U256::from(0); } string.replace('_', "").trim().chars().rev().collect::().parse().unwrap() } @@ -56,10 +56,10 @@ impl AstEq for VariableDefinition { attrs.sort(); attrs }; - self.ty.ast_eq(&other.ty) && - self.name.ast_eq(&other.name) && - self.initializer.ast_eq(&other.initializer) && - sorted_attrs(self).ast_eq(&sorted_attrs(other)) + self.ty.ast_eq(&other.ty) + && self.name.ast_eq(&other.name) + && self.initializer.ast_eq(&other.initializer) + && sorted_attrs(self).ast_eq(&sorted_attrs(other)) } } @@ -78,20 +78,20 @@ impl AstEq for FunctionDefinition { let left_returns = filter_params(&self.returns); let right_returns = filter_params(&other.returns); - self.ty.ast_eq(&other.ty) && - self.name.ast_eq(&other.name) && - left_params.ast_eq(&right_params) && - self.return_not_returns.ast_eq(&other.return_not_returns) && - left_returns.ast_eq(&right_returns) && - self.body.ast_eq(&other.body) && - sorted_attrs(self).ast_eq(&sorted_attrs(other)) + self.ty.ast_eq(&other.ty) + && self.name.ast_eq(&other.name) + && left_params.ast_eq(&right_params) + && self.return_not_returns.ast_eq(&other.return_not_returns) + && left_returns.ast_eq(&right_returns) + && self.body.ast_eq(&other.body) + && sorted_attrs(self).ast_eq(&sorted_attrs(other)) } } impl AstEq for Base { fn ast_eq(&self, other: &Self) -> bool { - self.name.ast_eq(&other.name) && - self.args.clone().unwrap_or_default().ast_eq(&other.args.clone().unwrap_or_default()) + self.name.ast_eq(&other.name) + && self.args.clone().unwrap_or_default().ast_eq(&other.args.clone().unwrap_or_default()) } } diff --git a/crates/fmt/src/string.rs b/crates/fmt/src/string.rs index 1dbc2f2f61b5..aa7ff381c5ed 100644 --- a/crates/fmt/src/string.rs +++ b/crates/fmt/src/string.rs @@ -81,17 +81,17 @@ impl<'a> Iterator for QuotedRanges<'a> { let (quote, start) = loop { let (state, idx, _) = self.0.next()?; match state { - QuoteState::Opening(quote) | - QuoteState::Escaping(quote) | - QuoteState::Escaped(quote) | - QuoteState::String(quote) => break (quote, idx), + QuoteState::Opening(quote) + | QuoteState::Escaping(quote) + | QuoteState::Escaped(quote) + | QuoteState::String(quote) => break (quote, idx), QuoteState::Closing(quote) => return Some((quote, idx, idx)), QuoteState::None => {} } }; for (state, idx, _) in self.0.by_ref() { if matches!(state, QuoteState::Closing(_)) { - return Some((quote, start, idx)) + return Some((quote, start, idx)); } } None @@ -113,11 +113,11 @@ pub trait QuotedStringExt { fn is_quoted(&self) -> bool { let mut iter = self.quote_state_char_indices(); if !matches!(iter.next(), Some((QuoteState::Opening(_), _, _))) { - return false + return false; } while let Some((state, _, _)) = iter.next() { if matches!(state, QuoteState::Closing(_)) { - return iter.next().is_none() + return iter.next().is_none(); } } false diff --git a/crates/fmt/tests/formatter.rs b/crates/fmt/tests/formatter.rs index ba1d9216d92d..a2177032aaba 100644 --- a/crates/fmt/tests/formatter.rs +++ b/crates/fmt/tests/formatter.rs @@ -60,7 +60,7 @@ fn test_directory(base_name: &str, test_config: TestConfig) { .try_into() .unwrap_or_else(|err| panic!("Invalid config for {filename}: {err}")); - return Some((filename.to_string(), config, lines.join("\n"))) + return Some((filename.to_string(), config, lines.join("\n"))); } } diff --git a/crates/forge/bin/cmd/bind_json.rs b/crates/forge/bin/cmd/bind_json.rs index bd2d0ea30d67..8d8041cb79f0 100644 --- a/crates/forge/bin/cmd/bind_json.rs +++ b/crates/forge/bin/cmd/bind_json.rs @@ -311,7 +311,7 @@ impl CompiledState { // those. let Some(schema) = resolver.resolve_struct_eip712(id, &mut Default::default(), true)? else { - continue + continue; }; if !include.is_empty() { @@ -378,7 +378,7 @@ impl StructsState { for (name, paths) in names_to_paths { if paths.len() <= 1 { // no alias needed - continue + continue; } for (i, path) in paths.into_iter().enumerate() { diff --git a/crates/forge/bin/cmd/build.rs b/crates/forge/bin/cmd/build.rs index f242d3d191d6..006f883de2a0 100644 --- a/crates/forge/bin/cmd/build.rs +++ b/crates/forge/bin/cmd/build.rs @@ -79,8 +79,8 @@ impl BuildArgs { pub fn run(self) -> Result { let mut config = self.try_load_config_emit_warnings()?; - if install::install_missing_dependencies(&mut config, self.args.silent) && - config.auto_detect_remappings + if install::install_missing_dependencies(&mut config, self.args.silent) + && config.auto_detect_remappings { // need to re-configure here to also catch additional remappings config = self.load_config(); diff --git a/crates/forge/bin/cmd/cache.rs b/crates/forge/bin/cmd/cache.rs index 1adaf4d26779..47dac5f617dc 100644 --- a/crates/forge/bin/cmd/cache.rs +++ b/crates/forge/bin/cmd/cache.rs @@ -131,7 +131,7 @@ fn clean_chain_cache(chain: impl Into, blocks: Vec, etherscan: bool) if blocks.is_empty() { Config::clean_foundry_etherscan_chain_cache(chain)?; if etherscan { - return Ok(()) + return Ok(()); } Config::clean_foundry_chain_cache(chain)?; } else { diff --git a/crates/forge/bin/cmd/clone.rs b/crates/forge/bin/cmd/clone.rs index f2c07294a835..131dbfbaddb6 100644 --- a/crates/forge/bin/cmd/clone.rs +++ b/crates/forge/bin/cmd/clone.rs @@ -266,7 +266,7 @@ impl CloneArgs { let remappings_txt_content = config.remappings.iter().map(|r| r.to_string()).collect::>().join("\n"); if fs::write(&remappings_txt, remappings_txt_content).is_err() { - return false + return false; } let profile = config.profile.as_str().as_str(); @@ -442,16 +442,16 @@ fn dump_sources(meta: &Metadata, root: &PathBuf, no_reorg: bool) -> Result Result Result>() { if subtype_id == id { - continue + continue; } let Some(encoded_subtype) = self.resolve_struct_eip712(subtype_id, subtypes, false)? else { - return Ok(None) + return Ok(None); }; result.push_str(&encoded_subtype); } @@ -188,7 +188,7 @@ impl Resolver { TypeName::ElementaryTypeName(ty) => Ok(Some(ty.name.clone())), TypeName::ArrayTypeName(ty) => { let Some(inner) = self.resolve_type(&ty.base_type, subtypes)? else { - return Ok(None) + return Ok(None); }; let len = parse_array_length(&ty.type_descriptions)?; @@ -215,9 +215,9 @@ impl Resolver { name }; - return Ok(Some(name)) + return Ok(Some(name)); } else { - return Ok(None) + return Ok(None); } } } diff --git a/crates/forge/bin/cmd/fmt.rs b/crates/forge/bin/cmd/fmt.rs index c467048368f0..a8cd68c50927 100644 --- a/crates/forge/bin/cmd/fmt.rs +++ b/crates/forge/bin/cmd/fmt.rs @@ -72,11 +72,11 @@ impl FmtArgs { paths => { let mut inputs = Vec::with_capacity(paths.len()); for path in paths { - if !ignored.is_empty() && - ((path.is_absolute() && ignored.contains(path)) || - ignored.contains(&cwd.join(path))) + if !ignored.is_empty() + && ((path.is_absolute() && ignored.contains(path)) + || ignored.contains(&cwd.join(path))) { - continue + continue; } if path.is_dir() { @@ -132,7 +132,7 @@ impl FmtArgs { let diff = TextDiff::from_lines(&source, &output); if diff.ratio() < 1.0 { - return Ok(Some(format_diff_summary(&name, &diff))) + return Ok(Some(format_diff_summary(&name, &diff))); } } else if let Some(path) = path { fs::write(path, output)?; @@ -149,7 +149,7 @@ impl FmtArgs { HINT: If you are working outside of the project, \ try providing paths to your source files: `forge fmt `" ); - return Ok(()) + return Ok(()); } paths .par_iter() diff --git a/crates/forge/bin/cmd/geiger/find.rs b/crates/forge/bin/cmd/geiger/find.rs index 6629390caeea..bba4ec1b0282 100644 --- a/crates/forge/bin/cmd/geiger/find.rs +++ b/crates/forge/bin/cmd/geiger/find.rs @@ -115,15 +115,15 @@ impl UnsafeCheatcodes { /// The total number of unsafe calls. pub fn len(&self) -> usize { - self.ffi.len() + - self.read_file.len() + - self.read_line.len() + - self.write_file.len() + - self.write_line.len() + - self.close_file.len() + - self.set_env.len() + - self.derive_key.len() + - self.remove_file.len() + self.ffi.len() + + self.read_file.len() + + self.read_line.len() + + self.write_file.len() + + self.write_line.len() + + self.close_file.len() + + self.set_env.len() + + self.derive_key.len() + + self.remove_file.len() } } diff --git a/crates/forge/bin/cmd/inspect.rs b/crates/forge/bin/cmd/inspect.rs index a6f162556027..0c3c47199e3f 100644 --- a/crates/forge/bin/cmd/inspect.rs +++ b/crates/forge/bin/cmd/inspect.rs @@ -172,7 +172,7 @@ pub fn print_storage_layout(storage_layout: Option<&StorageLayout>, pretty: bool }; if !pretty { - return print_json(&storage_layout) + return print_json(&storage_layout); } let mut table = Table::new(); @@ -334,20 +334,20 @@ impl PartialEq for ContractArtifactField { type Eos = EvmOutputSelection; matches!( (self, other), - (Self::Abi | Self::Events, Cos::Abi) | - (Self::Errors, Cos::Abi) | - (Self::Bytecode, Cos::Evm(Eos::ByteCode(_))) | - (Self::DeployedBytecode, Cos::Evm(Eos::DeployedByteCode(_))) | - (Self::Assembly | Self::AssemblyOptimized, Cos::Evm(Eos::Assembly)) | - (Self::MethodIdentifiers, Cos::Evm(Eos::MethodIdentifiers)) | - (Self::GasEstimates, Cos::Evm(Eos::GasEstimates)) | - (Self::StorageLayout, Cos::StorageLayout) | - (Self::DevDoc, Cos::DevDoc) | - (Self::Ir, Cos::Ir) | - (Self::IrOptimized, Cos::IrOptimized) | - (Self::Metadata, Cos::Metadata) | - (Self::UserDoc, Cos::UserDoc) | - (Self::Ewasm, Cos::Ewasm(_)) + (Self::Abi | Self::Events, Cos::Abi) + | (Self::Errors, Cos::Abi) + | (Self::Bytecode, Cos::Evm(Eos::ByteCode(_))) + | (Self::DeployedBytecode, Cos::Evm(Eos::DeployedByteCode(_))) + | (Self::Assembly | Self::AssemblyOptimized, Cos::Evm(Eos::Assembly)) + | (Self::MethodIdentifiers, Cos::Evm(Eos::MethodIdentifiers)) + | (Self::GasEstimates, Cos::Evm(Eos::GasEstimates)) + | (Self::StorageLayout, Cos::StorageLayout) + | (Self::DevDoc, Cos::DevDoc) + | (Self::Ir, Cos::Ir) + | (Self::IrOptimized, Cos::IrOptimized) + | (Self::Metadata, Cos::Metadata) + | (Self::UserDoc, Cos::UserDoc) + | (Self::Ewasm, Cos::Ewasm(_)) ) } } diff --git a/crates/forge/bin/cmd/install.rs b/crates/forge/bin/cmd/install.rs index 57096f8592e6..8db359aeb1c5 100644 --- a/crates/forge/bin/cmd/install.rs +++ b/crates/forge/bin/cmd/install.rs @@ -302,7 +302,7 @@ impl Installer<'_> { for &prefix in common_prefixes { if let Some(rem) = tag.strip_prefix(prefix) { maybe_semver = rem; - break + break; } } match Version::parse(maybe_semver) { @@ -358,7 +358,7 @@ impl Installer<'_> { if e.to_string().contains("did not match any file(s) known to git") { e = eyre::eyre!("Tag: \"{tag}\" not found for repo \"{url}\"!") } - return Err(e) + return Err(e); } if is_branch { @@ -372,7 +372,7 @@ impl Installer<'_> { fn match_tag(self, tag: &str, path: &Path) -> Result { // only try to match if it looks like a version tag if !DEPENDENCY_VERSION_TAG_REGEX.is_match(tag) { - return Ok(tag.into()) + return Ok(tag.into()); } // generate candidate list by filtering `git tag` output, valid ones are those "starting @@ -390,13 +390,13 @@ impl Installer<'_> { // no match found, fall back to the user-provided tag if candidates.is_empty() { - return Ok(tag.into()) + return Ok(tag.into()); } // have exact match for candidate in candidates.iter() { if candidate == tag { - return Ok(tag.into()) + return Ok(tag.into()); } } @@ -406,7 +406,7 @@ impl Installer<'_> { let input = prompt!( "Found a similar version tag: {matched_tag}, do you want to use this instead? [Y/n] " )?; - return if match_yn(input) { Ok(matched_tag.clone()) } else { Ok(tag.into()) } + return if match_yn(input) { Ok(matched_tag.clone()) } else { Ok(tag.into()) }; } // multiple candidates, ask the user to choose one or skip @@ -429,7 +429,7 @@ impl Installer<'_> { Ok(i) if (1..=n_candidates).contains(&i) => { let c = &candidates[i]; println!("[{i}] {c} selected"); - return Ok(c.clone()) + return Ok(c.clone()); } _ => continue, } @@ -452,13 +452,13 @@ impl Installer<'_> { // no match found, fall back to the user-provided tag if candidates.is_empty() { - return Ok(None) + return Ok(None); } // have exact match for candidate in candidates.iter() { if candidate == tag { - return Ok(Some(tag.to_string())) + return Ok(Some(tag.to_string())); } } @@ -468,7 +468,7 @@ impl Installer<'_> { let input = prompt!( "Found a similar branch: {matched_tag}, do you want to use this instead? [Y/n] " )?; - return if match_yn(input) { Ok(Some(matched_tag.clone())) } else { Ok(None) } + return if match_yn(input) { Ok(Some(matched_tag.clone())) } else { Ok(None) }; } // multiple candidates, ask the user to choose one or skip @@ -488,7 +488,7 @@ impl Installer<'_> { // default selection, return None if input.is_empty() { println!("Canceled branch matching"); - return Ok(None) + return Ok(None); } // match user input, 0 indicates skipping and use original tag diff --git a/crates/forge/bin/cmd/selectors.rs b/crates/forge/bin/cmd/selectors.rs index c1626e99fc7a..64ed591caff6 100644 --- a/crates/forge/bin/cmd/selectors.rs +++ b/crates/forge/bin/cmd/selectors.rs @@ -106,7 +106,7 @@ impl SelectorsSubcommands { while let Some((contract, artifact)) = artifacts.next() { let abi = artifact.abi.ok_or_else(|| eyre::eyre!("Unable to fetch abi"))?; if abi.functions.is_empty() && abi.events.is_empty() && abi.errors.is_empty() { - continue + continue; } println!("Uploading selectors for {contract}..."); @@ -226,7 +226,7 @@ impl SelectorsSubcommands { while let Some((contract, artifact)) = artifacts.next() { let abi = artifact.abi.ok_or_else(|| eyre::eyre!("Unable to fetch abi"))?; if abi.functions.is_empty() && abi.events.is_empty() && abi.errors.is_empty() { - continue + continue; } println!("{contract}"); diff --git a/crates/forge/bin/cmd/snapshot.rs b/crates/forge/bin/cmd/snapshot.rs index 6c102c9d6fc5..86dec369e466 100644 --- a/crates/forge/bin/cmd/snapshot.rs +++ b/crates/forge/bin/cmd/snapshot.rs @@ -160,12 +160,12 @@ impl SnapshotConfig { fn is_in_gas_range(&self, gas_used: u64) -> bool { if let Some(min) = self.min { if gas_used < min { - return false + return false; } } if let Some(max) = self.max { if gas_used > max { - return false + return false; } } true diff --git a/crates/forge/bin/cmd/test/filter.rs b/crates/forge/bin/cmd/test/filter.rs index ec2e9b01b50e..537c36ef6a83 100644 --- a/crates/forge/bin/cmd/test/filter.rs +++ b/crates/forge/bin/cmd/test/filter.rs @@ -47,12 +47,12 @@ pub struct FilterArgs { impl FilterArgs { /// Returns true if the filter is empty. pub fn is_empty(&self) -> bool { - self.test_pattern.is_none() && - self.test_pattern_inverse.is_none() && - self.contract_pattern.is_none() && - self.contract_pattern_inverse.is_none() && - self.path_pattern.is_none() && - self.path_pattern_inverse.is_none() + self.test_pattern.is_none() + && self.test_pattern_inverse.is_none() + && self.contract_pattern.is_none() + && self.contract_pattern_inverse.is_none() + && self.path_pattern.is_none() + && self.path_pattern_inverse.is_none() } /// Merges the set filter globs with the config's values diff --git a/crates/forge/bin/cmd/watch.rs b/crates/forge/bin/cmd/watch.rs index 0dfb734688e6..f39491bf7b1a 100644 --- a/crates/forge/bin/cmd/watch.rs +++ b/crates/forge/bin/cmd/watch.rs @@ -260,10 +260,10 @@ pub async fn watch_test(args: TestArgs) -> Result<()> { let config: Config = args.build_args().into(); let filter = args.filter(&config); // Marker to check whether to override the command. - let _no_reconfigure = filter.args().test_pattern.is_some() || - filter.args().path_pattern.is_some() || - filter.args().contract_pattern.is_some() || - args.watch.run_all; + let _no_reconfigure = filter.args().test_pattern.is_some() + || filter.args().path_pattern.is_some() + || filter.args().contract_pattern.is_some() + || args.watch.run_all; let last_test_files = Mutex::new(HashSet::::new()); let project_root = config.root.0.to_string_lossy().into_owned(); @@ -342,11 +342,11 @@ fn clean_cmd_args(num: usize, mut cmd_args: Vec) -> Vec { fn contains_w_in_short(arg: &str) -> Option { let mut iter = arg.chars().peekable(); if *iter.peek()? != '-' { - return None + return None; } iter.next(); if *iter.peek()? == '-' { - return None + return None; } Some(iter.any(|c| c == 'w')) } diff --git a/crates/forge/tests/cli/cmd.rs b/crates/forge/tests/cli/cmd.rs index 23cb3ca8a0f7..90c60af74004 100644 --- a/crates/forge/tests/cli/cmd.rs +++ b/crates/forge/tests/cli/cmd.rs @@ -519,7 +519,7 @@ forgetest!(can_clone_keep_directory_structure, |prj, cmd| { // Gateway\r\n


nginx
\r\n\r\n\r\n" eprintln!("Skipping test due to 502 Bad Gateway: {}", cmd.make_error_message(&out, false)); - return + return; } cmd.ensure_success(&out).unwrap(); diff --git a/crates/forge/tests/cli/utils.rs b/crates/forge/tests/cli/utils.rs index 094255195c1e..d205fd614af1 100644 --- a/crates/forge/tests/cli/utils.rs +++ b/crates/forge/tests/cli/utils.rs @@ -126,7 +126,7 @@ impl EnvExternalities { pub fn parse_deployed_address(out: &str) -> Option { for line in out.lines() { if line.starts_with("Deployed to") { - return Some(line.trim_start_matches("Deployed to: ").to_string()) + return Some(line.trim_start_matches("Deployed to: ").to_string()); } } None @@ -135,7 +135,7 @@ pub fn parse_deployed_address(out: &str) -> Option { pub fn parse_verification_guid(out: &str) -> Option { for line in out.lines() { if line.contains("GUID") { - return Some(line.replace("GUID:", "").replace('`', "").trim().to_string()) + return Some(line.replace("GUID:", "").replace('`', "").trim().to_string()); } } None diff --git a/crates/forge/tests/cli/verify.rs b/crates/forge/tests/cli/verify.rs index 2f1f1368d190..f69cf8eb7b01 100644 --- a/crates/forge/tests/cli/verify.rs +++ b/crates/forge/tests/cli/verify.rs @@ -81,7 +81,7 @@ fn parse_verification_result(cmd: &mut TestCommand, retries: u32) -> eyre::Resul let out = String::from_utf8_lossy(&output.stdout); println!("{out}"); if out.contains("Contract successfully verified") { - return Ok(()) + return Ok(()); } eyre::bail!( "Failed to get verification, stdout: {}, stderr: {}", diff --git a/crates/forge/tests/it/config.rs b/crates/forge/tests/it/config.rs index 9cabd998a01a..b6dcf3eddbf3 100644 --- a/crates/forge/tests/it/config.rs +++ b/crates/forge/tests/it/config.rs @@ -66,8 +66,8 @@ impl TestConfig { } for (_, SuiteResult { test_results, .. }) in suite_result { for (test_name, mut result) in test_results { - if self.should_fail && (result.status == TestStatus::Success) || - !self.should_fail && (result.status == TestStatus::Failure) + if self.should_fail && (result.status == TestStatus::Success) + || !self.should_fail && (result.status == TestStatus::Failure) { let logs = decode_console_logs(&result.logs); let outcome = if self.should_fail { "fail" } else { "pass" }; diff --git a/crates/macros/src/cheatcodes.rs b/crates/macros/src/cheatcodes.rs index b38186e57732..a2db16cb6acb 100644 --- a/crates/macros/src/cheatcodes.rs +++ b/crates/macros/src/cheatcodes.rs @@ -94,7 +94,7 @@ fn derive_call(name: &Ident, data: &DataStruct, attrs: &[Attribute]) -> Result Result { if input.variants.iter().any(|v| v.fields.len() != 1) { - return Err(syn::Error::new(name.span(), "expected all variants to have a single field")) + return Err(syn::Error::new(name.span(), "expected all variants to have a single field")); } // keep original order for matching @@ -127,7 +127,7 @@ fn derive_errors_events_enum( events: bool, ) -> Result { if input.variants.iter().any(|v| v.fields.len() != 1) { - return Err(syn::Error::new(name.span(), "expected all variants to have a single field")) + return Err(syn::Error::new(name.span(), "expected all variants to have a single field")); } let (ident, ty_assoc_name, ty, doc) = if events { @@ -317,14 +317,14 @@ fn get_docstring(attrs: &[Attribute]) -> String { let mut doc = String::new(); for attr in attrs { if !attr.path().is_ident("doc") { - continue + continue; } let syn::Meta::NameValue(syn::MetaNameValue { value: syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(s), .. }), .. }) = &attr.meta else { - continue + continue; }; let value = s.value(); @@ -398,7 +398,7 @@ fn func_docstring(doc: &str) -> (&str, &str, &str, &str) { /// Returns `(visibility, mutability)` from a given Solidity function declaration. fn parse_function_attrs(f: &str, span: Span) -> Result<(&str, &str)> { let Some(ext_start) = f.find("external") else { - return Err(Error::new(span, "functions must have `external` visibility")) + return Err(Error::new(span, "functions must have `external` visibility")); }; let visibility = "External"; diff --git a/crates/macros/src/console_fmt.rs b/crates/macros/src/console_fmt.rs index 2522afb2c5b9..414c3328231c 100644 --- a/crates/macros/src/console_fmt.rs +++ b/crates/macros/src/console_fmt.rs @@ -33,7 +33,7 @@ fn impl_struct(s: &DataStruct) -> Option { }; if fields.is_empty() { - return None + return None; } let first_ty = match &fields.first().unwrap().ty { diff --git a/crates/script/src/broadcast.rs b/crates/script/src/broadcast.rs index b7eb9f5b0bb6..ff84fd21c7a9 100644 --- a/crates/script/src/broadcast.rs +++ b/crates/script/src/broadcast.rs @@ -40,9 +40,9 @@ where tx.gas = None; tx.set_gas_limit( - provider.estimate_gas(tx).await.wrap_err("Failed to estimate gas for tx")? * - estimate_multiplier as u128 / - 100, + provider.estimate_gas(tx).await.wrap_err("Failed to estimate gas for tx")? + * estimate_multiplier as u128 + / 100, ); Ok(()) } @@ -313,10 +313,10 @@ impl BundledState { // their order otherwise. // Or if the chain does not support batched transactions (eg. Arbitrum). // Or if we need to invoke eth_estimateGas before sending transactions. - let sequential_broadcast = estimate_via_rpc || - self.args.slow || - send_kind.signers_count() != 1 || - !has_batch_support(sequence.chain); + let sequential_broadcast = estimate_via_rpc + || self.args.slow + || send_kind.signers_count() != 1 + || !has_batch_support(sequence.chain); // We send transactions and wait for receipts in batches. let batch_size = if sequential_broadcast { 1 } else { self.args.batch_size }; @@ -402,8 +402,9 @@ impl BundledState { pub fn verify_preflight_check(&self) -> Result<()> { for sequence in self.sequence.sequences() { - if self.args.verifier.verifier == VerificationProviderType::Etherscan && - self.script_config + if self.args.verifier.verifier == VerificationProviderType::Etherscan + && self + .script_config .config .get_etherscan_api_key(Some(sequence.chain.into())) .is_none() diff --git a/crates/script/src/build.rs b/crates/script/src/build.rs index 14feb42ff00e..9d45581bad90 100644 --- a/crates/script/src/build.rs +++ b/crates/script/src/build.rs @@ -203,8 +203,8 @@ impl PreprocessedState { if id.name != *name { continue; } - } else if contract.abi.as_ref().map_or(true, |abi| abi.is_empty()) || - contract.bytecode.as_ref().map_or(true, |b| match &b.object { + } else if contract.abi.as_ref().map_or(true, |abi| abi.is_empty()) + || contract.bytecode.as_ref().map_or(true, |b| match &b.object { BytecodeObject::Bytecode(b) => b.is_empty(), BytecodeObject::Unlinked(_) => false, }) diff --git a/crates/script/src/execute.rs b/crates/script/src/execute.rs index bfa9de0d2bc1..0b9b4faf208e 100644 --- a/crates/script/src/execute.rs +++ b/crates/script/src/execute.rs @@ -185,8 +185,8 @@ impl PreExecutionState { if let Some(txs) = transactions { // If the user passed a `--sender` don't check anything. - if self.build_data.predeploy_libraries.libraries_count() > 0 && - self.args.evm_opts.sender.is_none() + if self.build_data.predeploy_libraries.libraries_count() > 0 + && self.args.evm_opts.sender.is_none() { for tx in txs.iter() { if tx.transaction.to.is_none() { diff --git a/crates/script/src/lib.rs b/crates/script/src/lib.rs index af7000672b3f..7a32a9ffed17 100644 --- a/crates/script/src/lib.rs +++ b/crates/script/src/lib.rs @@ -234,7 +234,7 @@ impl ScriptArgs { .await?; if pre_simulation.args.debug { - return pre_simulation.run_debugger() + return pre_simulation.run_debugger(); } if pre_simulation.args.json { @@ -426,9 +426,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/script/src/receipts.rs b/crates/script/src/receipts.rs index c0fbd56119db..f42a1ba1b320 100644 --- a/crates/script/src/receipts.rs +++ b/crates/script/src/receipts.rs @@ -44,14 +44,14 @@ pub async fn check_tx_status( .get_receipt() .await { - return Ok(receipt.into()) + return Ok(receipt.into()); } if provider.get_transaction_by_hash(hash).await?.is_some() { trace!("tx is still known to the node, waiting for receipt"); } else { trace!("eth_getTransactionByHash returned null, assuming dropped"); - break + break; } } diff --git a/crates/script/src/runner.rs b/crates/script/src/runner.rs index a4f437644dbc..b402db6f1fd1 100644 --- a/crates/script/src/runner.rs +++ b/crates/script/src/runner.rs @@ -330,9 +330,9 @@ impl ScriptRunner { self.executor.env_mut().tx.gas_limit = mid_gas_limit; let res = self.executor.call_raw(from, to, calldata.0.clone().into(), value)?; match res.exit_reason { - InstructionResult::Revert | - InstructionResult::OutOfGas | - InstructionResult::OutOfFunds => { + InstructionResult::Revert + | InstructionResult::OutOfGas + | InstructionResult::OutOfFunds => { lowest_gas_limit = mid_gas_limit; } _ => { @@ -340,9 +340,9 @@ impl ScriptRunner { // if last two successful estimations only vary by 10%, we consider this to // sufficiently accurate const ACCURACY: u64 = 10; - if (last_highest_gas_limit - highest_gas_limit) * ACCURACY / - last_highest_gas_limit < - 1 + if (last_highest_gas_limit - highest_gas_limit) * ACCURACY + / last_highest_gas_limit + < 1 { // update the gas gas_used = highest_gas_limit; diff --git a/crates/script/src/sequence.rs b/crates/script/src/sequence.rs index 5a8e789a60b0..8d5c21d3dd78 100644 --- a/crates/script/src/sequence.rs +++ b/crates/script/src/sequence.rs @@ -158,7 +158,7 @@ impl ScriptSequence { self.sort_receipts(); if self.transactions.is_empty() { - return Ok(()) + return Ok(()); } let Some((path, sensitive_path)) = self.paths.clone() else { return Ok(()) }; @@ -263,8 +263,8 @@ impl ScriptSequence { verify.set_chain(config, self.chain.into()); - if verify.etherscan.has_key() || - verify.verifier.verifier != VerificationProviderType::Etherscan + if verify.etherscan.has_key() + || verify.verifier.verifier != VerificationProviderType::Etherscan { trace!(target: "script", "prepare future verifications"); @@ -319,7 +319,7 @@ impl ScriptSequence { } if num_of_successful_verifications < num_verifications { - return Err(eyre!("Not all ({num_of_successful_verifications} / {num_verifications}) contracts were verified!")) + return Err(eyre!("Not all ({num_of_successful_verifications} / {num_verifications}) contracts were verified!")); } println!("All ({num_verifications}) contracts were verified!"); @@ -382,12 +382,12 @@ impl ScriptSequence { pub fn sig_to_file_name(sig: &str) -> String { if let Some((name, _)) = sig.split_once('(') { // strip until call argument parenthesis - return name.to_string() + return name.to_string(); } // assume calldata if `sig` is hex if let Ok(calldata) = hex::decode(sig) { // in which case we return the function signature - return hex::encode(&calldata[..SELECTOR_LEN]) + return hex::encode(&calldata[..SELECTOR_LEN]); } // return sig as is diff --git a/crates/script/src/transaction.rs b/crates/script/src/transaction.rs index de91ab3e3b0f..ad862658744e 100644 --- a/crates/script/src/transaction.rs +++ b/crates/script/src/transaction.rs @@ -137,7 +137,7 @@ impl TransactionWithMetadata { // `create2` transactions are prefixed by a 32 byte salt. let creation_code = if is_create2 { if data.len() < 32 { - return Ok(()) + return Ok(()); } &data[32..] } else { diff --git a/crates/script/src/verify.rs b/crates/script/src/verify.rs index 10c877ce6a41..b991bdf77e6f 100644 --- a/crates/script/src/verify.rs +++ b/crates/script/src/verify.rs @@ -152,7 +152,7 @@ impl VerifyBundle { guess_constructor_args: false, }; - return Some(verify) + return Some(verify); } } None diff --git a/crates/sol-macro-gen/src/sol_macro_gen.rs b/crates/sol-macro-gen/src/sol_macro_gen.rs index 7309104fec61..c6d5915a47fb 100644 --- a/crates/sol-macro-gen/src/sol_macro_gen.rs +++ b/crates/sol-macro-gen/src/sol_macro_gen.rs @@ -320,9 +320,9 @@ edition = "2021" } else { r#"alloy = { git = "https://github.com/alloy-rs/alloy", features = ["sol-types", "contract"] }"#.to_string() }; - let toml_consistent = cargo_toml_contents.contains(&name_check) && - cargo_toml_contents.contains(&version_check) && - cargo_toml_contents.contains(&alloy_dep_check); + let toml_consistent = cargo_toml_contents.contains(&name_check) + && cargo_toml_contents.contains(&version_check) + && cargo_toml_contents.contains(&alloy_dep_check); eyre::ensure!( toml_consistent, r#"The contents of Cargo.toml do not match the expected output of the latest `sol!` version. diff --git a/crates/test-utils/src/script.rs b/crates/test-utils/src/script.rs index 0bc4d399db52..fbff9c174dc5 100644 --- a/crates/test-utils/src/script.rs +++ b/crates/test-utils/src/script.rs @@ -297,17 +297,17 @@ impl ScriptOutcome { pub fn is_err(&self) -> bool { match self { - Self::OkNoEndpoint | - Self::OkSimulation | - Self::OkBroadcast | - Self::WarnSpecifyDeployer | - Self::OkRun => false, - Self::MissingSender | - Self::MissingWallet | - Self::StaticCallNotAllowed | - Self::UnsupportedLibraries | - Self::ErrorSelectForkOnBroadcast | - Self::ScriptFailed => true, + Self::OkNoEndpoint + | Self::OkSimulation + | Self::OkBroadcast + | Self::WarnSpecifyDeployer + | Self::OkRun => false, + Self::MissingSender + | Self::MissingWallet + | Self::StaticCallNotAllowed + | Self::UnsupportedLibraries + | Self::ErrorSelectForkOnBroadcast + | Self::ScriptFailed => true, } } } diff --git a/crates/test-utils/src/util.rs b/crates/test-utils/src/util.rs index 56d492ebdff8..3becd0b6ba43 100644 --- a/crates/test-utils/src/util.rs +++ b/crates/test-utils/src/util.rs @@ -1149,7 +1149,7 @@ pub fn tty_fixture_path(path: impl AsRef) -> PathBuf { path.with_extension(format!("tty.{ext}")) } else { path.with_extension("tty") - } + }; } path.to_path_buf() } diff --git a/crates/verify/src/bytecode.rs b/crates/verify/src/bytecode.rs index dfa8c31a96bb..452192c377df 100644 --- a/crates/verify/src/bytecode.rs +++ b/crates/verify/src/bytecode.rs @@ -458,9 +458,9 @@ impl VerifyBytecodeArgs { // Check if Solidity version matches if let Ok(version) = Version::parse(&version) { - if !(artifact.version.major == version.major && - artifact.version.minor == version.minor && - artifact.version.patch == version.patch) + if !(artifact.version.major == version.major + && artifact.version.minor == version.minor + && artifact.version.patch == version.patch) { continue; } @@ -474,7 +474,7 @@ impl VerifyBytecodeArgs { .cloned(); } - return None + return None; } } @@ -618,7 +618,7 @@ fn try_partial_match( // 1. Check length of constructor args if constructor_args.is_empty() || is_runtime { // Assume metadata is at the end of the bytecode - return try_extract_and_compare_bytecode(local_bytecode, bytecode, has_metadata) + return try_extract_and_compare_bytecode(local_bytecode, bytecode, has_metadata); } // If not runtime, extract constructor args from the end of the bytecode diff --git a/crates/verify/src/etherscan/mod.rs b/crates/verify/src/etherscan/mod.rs index 6fd6ffb7e3bb..4f01a8f1ea9a 100644 --- a/crates/verify/src/etherscan/mod.rs +++ b/crates/verify/src/etherscan/mod.rs @@ -60,8 +60,8 @@ impl VerificationProvider for EtherscanVerificationProvider { async fn verify(&mut self, args: VerifyArgs, context: VerificationContext) -> Result<()> { let (etherscan, verify_args) = self.prepare_request(&args, &context).await?; - if !args.skip_is_verified_check && - self.is_contract_verified(ðerscan, &verify_args).await? + if !args.skip_is_verified_check + && self.is_contract_verified(ðerscan, &verify_args).await? { println!( "\nContract [{}] {:?} is already verified. Skipping verification.", @@ -69,7 +69,7 @@ impl VerificationProvider for EtherscanVerificationProvider { verify_args.address.to_checksum(None) ); - return Ok(()) + return Ok(()); } trace!(target: "forge::verify", ?verify_args, "submitting verification request"); @@ -134,7 +134,7 @@ impl VerificationProvider for EtherscanVerificationProvider { verifier: args.verifier, }; // return check_args.run().await - return self.check(check_args).await + return self.check(check_args).await; } } else { println!("Contract source code already verified"); @@ -170,20 +170,20 @@ impl VerificationProvider for EtherscanVerificationProvider { ); if resp.result == "Pending in queue" { - return Err(RetryError::Retry(eyre!("Verification is still pending...",))) + return Err(RetryError::Retry(eyre!("Verification is still pending...",))); } if resp.result == "Unable to verify" { - return Err(RetryError::Retry(eyre!("Unable to verify.",))) + return Err(RetryError::Retry(eyre!("Unable to verify.",))); } if resp.result == "Already Verified" { println!("Contract source code already verified"); - return Ok(()) + return Ok(()); } if resp.status == "0" { - return Err(RetryError::Break(eyre!("Contract failed to verify.",))) + return Err(RetryError::Break(eyre!("Contract failed to verify.",))); } if resp.result == "Pass - Verified" { @@ -359,10 +359,10 @@ impl EtherscanVerificationProvider { read_constructor_args_file(constructor_args_path.to_path_buf())?, )?; let encoded_args = hex::encode(encoded_args); - return Ok(Some(encoded_args[8..].into())) + return Ok(Some(encoded_args[8..].into())); } if args.guess_constructor_args { - return Ok(Some(self.guess_constructor_args(args, context).await?)) + return Ok(Some(self.guess_constructor_args(args, context).await?)); } Ok(args.constructor_args.clone()) diff --git a/crates/verify/src/lib.rs b/crates/verify/src/lib.rs index 5edda5b085c3..a374d2bc2797 100644 --- a/crates/verify/src/lib.rs +++ b/crates/verify/src/lib.rs @@ -212,7 +212,7 @@ impl VerifyArgs { .create_verify_request(&self, &context) .await?; println!("{}", args.source); - return Ok(()) + return Ok(()); } let verifier_url = self.verifier.verifier_url.clone();