From 78e3faa5d851848bfbb282a476e4dd1e715ad2a6 Mon Sep 17 00:00:00 2001 From: Dave Belvedere Date: Tue, 9 May 2023 23:43:16 +1000 Subject: [PATCH 1/7] Remove the eip712 feature flag and have it enabled by default. Fmt files --- ethers-contract/Cargo.toml | 3 - .../src/contract/methods.rs | 22 +-- .../src/contract/structs.rs | 8 +- .../src/contract/types.rs | 16 +- .../ethers-contract-abigen/src/filter.rs | 2 +- .../ethers-contract-abigen/src/multi.rs | 2 +- .../ethers-contract-abigen/src/source/mod.rs | 2 +- .../src/source/online.rs | 2 +- .../ethers-contract-abigen/src/util.rs | 2 +- .../ethers-contract-derive/src/abigen.rs | 6 +- .../ethers-contract-derive/src/call.rs | 2 +- .../ethers-contract-derive/src/error.rs | 2 +- .../ethers-contract-derive/src/event.rs | 6 +- .../ethers-contract-derive/src/utils.rs | 14 +- ethers-contract/src/base.rs | 2 +- ethers-contract/src/error.rs | 4 +- ethers-contract/src/multicall/mod.rs | 8 +- ethers-core/Cargo.toml | 3 - ethers-core/src/abi/human_readable/lexer.rs | 28 +-- ethers-core/src/abi/human_readable/mod.rs | 6 +- ethers-core/src/abi/mod.rs | 12 +- ethers-core/src/abi/packed.rs | 2 +- ethers-core/src/abi/struct_def.rs | 8 +- ethers-core/src/abi/tokens.rs | 6 +- ethers-core/src/macros/ethers_crate.rs | 14 +- ethers-core/src/types/block.rs | 20 +-- ethers-core/src/types/chain.rs | 168 +++++++++--------- ethers-core/src/types/ens.rs | 2 +- ethers-core/src/types/filter.rs | 48 ++--- ethers-core/src/types/i256.rs | 10 +- ethers-core/src/types/serde_helpers.rs | 1 - ethers-core/src/types/signature.rs | 5 +- ethers-core/src/types/trace/filter.rs | 2 +- ethers-core/src/types/transaction/eip2718.rs | 6 +- ethers-core/src/types/transaction/eip712.rs | 4 +- ethers-core/src/types/transaction/mod.rs | 4 +- ethers-core/src/types/txpool.rs | 8 +- ethers-core/src/types/u256.rs | 4 +- ethers-core/src/types/uint8.rs | 4 +- ethers-core/src/utils/anvil.rs | 6 +- ethers-core/src/utils/ganache.rs | 2 +- ethers-core/src/utils/geth.rs | 8 +- ethers-core/src/utils/mod.rs | 12 +- ethers-etherscan/src/contract.rs | 10 +- ethers-etherscan/src/errors.rs | 4 +- ethers-etherscan/src/lib.rs | 30 ++-- ethers-middleware/src/gas_oracle/cache.rs | 4 +- ethers-middleware/src/gas_oracle/median.rs | 6 +- ethers-middleware/src/nonce_manager.rs | 4 +- ethers-middleware/src/signer.rs | 2 +- ethers-middleware/src/timelag/mod.rs | 4 +- ethers-providers/src/ext/ens.rs | 2 +- ethers-providers/src/ext/erc.rs | 4 +- ethers-providers/src/rpc/provider.rs | 24 +-- ethers-providers/src/rpc/pubsub.rs | 6 +- ethers-providers/src/rpc/transports/common.rs | 19 +- ethers-providers/src/rpc/transports/http.rs | 2 +- ethers-providers/src/rpc/transports/ipc.rs | 6 +- .../src/rpc/transports/legacy_ws.rs | 6 +- ethers-providers/src/rpc/transports/quorum.rs | 26 +-- ethers-providers/src/rpc/transports/retry.rs | 28 +-- .../src/rpc/transports/ws/backend.rs | 2 +- .../src/rpc/transports/ws/manager.rs | 6 +- .../src/rpc/transports/ws/types.rs | 16 +- ethers-providers/src/stream/tx_stream.rs | 10 +- ethers-providers/src/stream/watcher.rs | 2 +- ethers-providers/src/toolbox/log_query.rs | 2 +- .../src/toolbox/pending_escalator.rs | 2 +- .../src/toolbox/pending_transaction.rs | 6 +- ethers-signers/src/ledger/app.rs | 10 +- ethers-signers/src/trezor/app.rs | 2 +- ethers-signers/src/wallet/private_key.rs | 8 +- .../src/artifact_output/configurable.rs | 10 +- ethers-solc/src/artifact_output/mod.rs | 14 +- ethers-solc/src/artifacts/bytecode.rs | 16 +- ethers-solc/src/artifacts/contract.rs | 6 +- ethers-solc/src/artifacts/mod.rs | 26 +-- ethers-solc/src/artifacts/output_selection.rs | 10 +- ethers-solc/src/artifacts/serde_helpers.rs | 6 +- ethers-solc/src/cache.rs | 20 +-- ethers-solc/src/compile/mod.rs | 8 +- ethers-solc/src/compile/output/info.rs | 2 +- ethers-solc/src/compile/output/mod.rs | 16 +- ethers-solc/src/compile/project.rs | 8 +- ethers-solc/src/config.rs | 32 ++-- ethers-solc/src/lib.rs | 6 +- ethers-solc/src/remappings.rs | 56 +++--- ethers-solc/src/report/mod.rs | 6 +- ethers-solc/src/resolver/mod.rs | 16 +- ethers-solc/src/resolver/tree.rs | 4 +- ethers-solc/src/sourcemap.rs | 48 ++--- ethers-solc/src/utils.rs | 18 +- ethers/Cargo.toml | 1 - .../transactions/examples/call_override.rs | 2 +- .../transactions/examples/remove_liquidity.rs | 4 +- 95 files changed, 541 insertions(+), 543 deletions(-) diff --git a/ethers-contract/Cargo.toml b/ethers-contract/Cargo.toml index fe8bcbe92..d5acc5832 100644 --- a/ethers-contract/Cargo.toml +++ b/ethers-contract/Cargo.toml @@ -58,6 +58,3 @@ legacy = [] rustls = ["ethers-contract-abigen/rustls"] openssl = ["ethers-contract-abigen/openssl"] - -# Deprecated -eip712 = [] diff --git a/ethers-contract/ethers-contract-abigen/src/contract/methods.rs b/ethers-contract/ethers-contract-abigen/src/contract/methods.rs index de11b029e..a2b3666da 100644 --- a/ethers-contract/ethers-contract-abigen/src/contract/methods.rs +++ b/ethers-contract/ethers-contract-abigen/src/contract/methods.rs @@ -144,7 +144,7 @@ impl Context { ) -> Result> { // no point in having structs when there is no data returned if function.outputs.is_empty() { - return Ok(None) + return Ok(None); } let name = &function.name; @@ -192,7 +192,7 @@ impl Context { if struct_defs.len() <= 1 { // no need for an enum - return Ok(struct_def_tokens) + return Ok(struct_def_tokens); } let mut derives = self.expand_extra_derives(); @@ -390,7 +390,7 @@ impl Context { for functions in all_functions.values() { if functions.iter().filter(|f| !aliases.contains_key(&f.abi_signature())).count() <= 1 { // no overloads, hence no conflicts - continue + continue; } let num_functions = functions.len(); @@ -427,7 +427,7 @@ impl Context { if a.iter() .all(|d| b.iter().any(|o| o.name.to_snake_case() == d.name.to_snake_case())) { - return true + return true; } } false @@ -493,14 +493,14 @@ impl Context { struct_name: util::safe_ident(&first_fun.name), }; aliases.insert(first_fun.abi_signature(), first_fun_alias); - continue + continue; } } 1 => { // single additional input params - if diff[0].name.is_empty() || - num_functions > NAME_ALIASING_OVERLOADED_FUNCTIONS_CAP || - name_conflicts(*idx, &diffs) + if diff[0].name.is_empty() + || num_functions > NAME_ALIASING_OVERLOADED_FUNCTIONS_CAP + || name_conflicts(*idx, &diffs) { needs_alias_for_first_fun_using_idx = true; format!("{}{idx}", overloaded_fun.name.to_snake_case()) @@ -513,9 +513,9 @@ impl Context { } } _ => { - if diff.iter().any(|d| d.name.is_empty()) || - num_functions > NAME_ALIASING_OVERLOADED_FUNCTIONS_CAP || - name_conflicts(*idx, &diffs) + if diff.iter().any(|d| d.name.is_empty()) + || num_functions > NAME_ALIASING_OVERLOADED_FUNCTIONS_CAP + || name_conflicts(*idx, &diffs) { needs_alias_for_first_fun_using_idx = true; format!("{}{idx}", overloaded_fun.name.to_snake_case()) diff --git a/ethers-contract/ethers-contract-abigen/src/contract/structs.rs b/ethers-contract/ethers-contract-abigen/src/contract/structs.rs index a0fd3af2b..fd22bacb3 100644 --- a/ethers-contract/ethers-contract-abigen/src/contract/structs.rs +++ b/ethers-contract/ethers-contract-abigen/src/contract/structs.rs @@ -254,7 +254,7 @@ impl InternalStructs { if is_event { // no outputs in an event - continue + continue; } let mut output_structs = Vec::new(); @@ -424,7 +424,7 @@ fn resolve_struct_tuples(all_structs: &HashMap) -> HashMap structs.len() { - break + break; } if let Some(tuple) = ty.as_tuple() { params.insert(id.to_string(), tuple); @@ -454,7 +454,7 @@ fn resolve_struct_tuples(all_structs: &HashMap) -> HashMap { @@ -477,7 +477,7 @@ fn insert_structs(structs: &mut HashMap, tuple: &Component) { if let Some(internal_ty) = tuple.internal_type.as_ref() { let ident = struct_type_identifier(internal_ty); if structs.contains_key(ident) { - return + return; } if let Some(fields) = tuple .components diff --git a/ethers-contract/ethers-contract-abigen/src/contract/types.rs b/ethers-contract/ethers-contract-abigen/src/contract/types.rs index b49120de3..b57ac7cb4 100644 --- a/ethers-contract/ethers-contract-abigen/src/contract/types.rs +++ b/ethers-contract/ethers-contract-abigen/src/contract/types.rs @@ -89,18 +89,18 @@ fn expand_event_input( ) -> Result { let kind = &input.kind; match (kind, input.indexed) { - (ParamType::Array(_), true) | - (ParamType::FixedArray(_, _), true) | - (ParamType::Tuple(_), true) | - (ParamType::Bytes, true) | - (ParamType::String, true) => { + (ParamType::Array(_), true) + | (ParamType::FixedArray(_, _), true) + | (ParamType::Tuple(_), true) + | (ParamType::Bytes, true) + | (ParamType::String, true) => { let ethers_core = ethers_core_crate(); Ok(quote!(#ethers_core::types::H256)) } - (ParamType::Array(_), false) | - (ParamType::FixedArray(_, _), false) | - (ParamType::Tuple(_), false) => { + (ParamType::Array(_), false) + | (ParamType::FixedArray(_, _), false) + | (ParamType::Tuple(_), false) => { match internal_structs.get_event_input_struct_type(name, index) { Some(ty) => { let ty = util::ident(ty); diff --git a/ethers-contract/ethers-contract-abigen/src/filter.rs b/ethers-contract/ethers-contract-abigen/src/filter.rs index 1a97c728f..d3e814dd1 100644 --- a/ethers-contract/ethers-contract-abigen/src/filter.rs +++ b/ethers-contract/ethers-contract-abigen/src/filter.rs @@ -131,7 +131,7 @@ macro_rules! impl_filter { pub fn is_match(&self, name: impl AsRef) -> bool { let name = name.as_ref(); if self.exact.contains(name) { - return true + return true; } self.patterns.iter().any(|re| re.is_match(name)) } diff --git a/ethers-contract/ethers-contract-abigen/src/multi.rs b/ethers-contract/ethers-contract-abigen/src/multi.rs index 0f9127b6b..6030c9d63 100644 --- a/ethers-contract/ethers-contract-abigen/src/multi.rs +++ b/ethers-contract/ethers-contract-abigen/src/multi.rs @@ -628,7 +628,7 @@ impl MultiBindingsInner { .join("Cargo.toml"); if !cargo_toml.exists() { - return Ok(DEFAULT_ETHERS_DEP.to_string()) + return Ok(DEFAULT_ETHERS_DEP.to_string()); } let data = fs::read_to_string(cargo_toml)?; diff --git a/ethers-contract/ethers-contract-abigen/src/source/mod.rs b/ethers-contract/ethers-contract-abigen/src/source/mod.rs index 95f05d4dc..42a2a1794 100644 --- a/ethers-contract/ethers-contract-abigen/src/source/mod.rs +++ b/ethers-contract/ethers-contract-abigen/src/source/mod.rs @@ -107,7 +107,7 @@ impl Source { if let Ok(canonicalized) = dunce::canonicalize(&resolved) { resolved = canonicalized; } else { - return Err(eyre::eyre!("File does not exist: {}", resolved.display())) + return Err(eyre::eyre!("File does not exist: {}", resolved.display())); } Ok(Source::Local(resolved)) diff --git a/ethers-contract/ethers-contract-abigen/src/source/online.rs b/ethers-contract/ethers-contract-abigen/src/source/online.rs index 212aff967..2eba1fc95 100644 --- a/ethers-contract/ethers-contract-abigen/src/source/online.rs +++ b/ethers-contract/ethers-contract-abigen/src/source/online.rs @@ -208,7 +208,7 @@ mod tests { fn get_mainnet_contract() { // Skip if ETHERSCAN_API_KEY is not set if std::env::var("ETHERSCAN_API_KEY").is_err() { - return + return; } let source = Source::parse("mainnet:0x6b175474e89094c44da98b954eedeac495271d0f").unwrap(); diff --git a/ethers-contract/ethers-contract-abigen/src/util.rs b/ethers-contract/ethers-contract-abigen/src/util.rs index 0c6f4756a..c8385605b 100644 --- a/ethers-contract/ethers-contract-abigen/src/util.rs +++ b/ethers-contract/ethers-contract-abigen/src/util.rs @@ -152,7 +152,7 @@ fn take_while(s: &str, mut predicate: impl FnMut(char) -> bool) -> (&str, &str) if predicate(c) { index += c.len_utf8(); } else { - break + break; } } s.split_at(index) diff --git a/ethers-contract/ethers-contract-derive/src/abigen.rs b/ethers-contract/ethers-contract-derive/src/abigen.rs index a01063216..631c8d3d0 100644 --- a/ethers-contract/ethers-contract-derive/src/abigen.rs +++ b/ethers-contract/ethers-contract-derive/src/abigen.rs @@ -94,7 +94,7 @@ impl Parse for ContractArgs { if input.parse::().is_ok() { loop { if input.is_empty() || input.peek(Token![;]) { - break + break; } parameters.push_value(input.parse()?); if let Ok(comma) = input.parse() { @@ -128,10 +128,10 @@ impl Parse for Parameter { let mut aliases = HashSet::new(); for method in parsed { if !signatures.insert(method.signature.clone()) { - return Err(Error::new(method.span(), "duplicate method signature")) + return Err(Error::new(method.span(), "duplicate method signature")); } if !aliases.insert(method.alias.clone()) { - return Err(Error::new(method.alias.span(), "duplicate method alias")) + return Err(Error::new(method.alias.span(), "duplicate method alias")); } methods.push(method.into_inner()); } diff --git a/ethers-contract/ethers-contract-derive/src/call.rs b/ethers-contract/ethers-contract-derive/src/call.rs index fb941c593..13f193127 100644 --- a/ethers-contract/ethers-contract-derive/src/call.rs +++ b/ethers-contract/ethers-contract-derive/src/call.rs @@ -30,7 +30,7 @@ pub(crate) fn derive_eth_call_impl(input: DeriveInput) -> Result Result Result Result Result Option { pub fn topic_param_type_quote(kind: &ParamType) -> TokenStream { let ethers_core = ethers_core_crate(); match kind { - ParamType::String | - ParamType::Bytes | - ParamType::Array(_) | - ParamType::FixedArray(_, _) | - ParamType::Tuple(_) => quote! {#ethers_core::abi::ParamType::FixedBytes(32)}, + ParamType::String + | ParamType::Bytes + | ParamType::Array(_) + | ParamType::FixedArray(_, _) + | ParamType::Tuple(_) => quote! {#ethers_core::abi::ParamType::FixedBytes(32)}, ty => param_type_quote(ty), } } @@ -144,7 +144,7 @@ pub fn find_parameter_type(ty: &Type) -> Result { return match (ty, len) { (ParamType::Uint(8), 32) => Ok(ParamType::FixedBytes(32)), (ty, len) => Ok(ParamType::FixedArray(Box::new(ty), len)), - } + }; } } } @@ -159,7 +159,7 @@ pub fn find_parameter_type(ty: &Type) -> Result { debug_assert!(matches!(args.args.len(), 1 | 2)); let ty = args.args.iter().next().unwrap(); if let GenericArgument::Type(ref ty) = ty { - return find_parameter_type(ty).map(|kind| ParamType::Array(Box::new(kind))) + return find_parameter_type(ty).map(|kind| ParamType::Array(Box::new(kind))); } } } diff --git a/ethers-contract/src/base.rs b/ethers-contract/src/base.rs index b949b89a0..743306c95 100644 --- a/ethers-contract/src/base.rs +++ b/ethers-contract/src/base.rs @@ -267,7 +267,7 @@ pub fn decode_function_data_raw>( let bytes = bytes.as_ref(); Ok(if is_input { if bytes.len() < 4 || bytes[..4] != function.selector() { - return Err(AbiError::WrongSelector) + return Err(AbiError::WrongSelector); } function.decode_input(&bytes[4..])? } else { diff --git a/ethers-contract/src/error.rs b/ethers-contract/src/error.rs index e7373c8ad..3a1ea3991 100644 --- a/ethers-contract/src/error.rs +++ b/ethers-contract/src/error.rs @@ -27,11 +27,11 @@ pub trait ContractRevert: AbiDecode + AbiEncode + Send + Sync { /// Decode the error from EVM revert data including an Error selector fn decode_with_selector(data: &[u8]) -> Option { if data.len() < 4 { - return None + return None; } let selector = data[..4].try_into().expect("checked by len"); if !Self::valid_selector(selector) { - return None + return None; } ::decode(&data[4..]).ok() } diff --git a/ethers-contract/src/multicall/mod.rs b/ethers-contract/src/multicall/mod.rs index 7c1011316..1875dfa37 100644 --- a/ethers-contract/src/multicall/mod.rs +++ b/ethers-contract/src/multicall/mod.rs @@ -265,7 +265,7 @@ impl Multicall { .map_err(ContractError::from_middleware_error)? .as_u64(); if !constants::MULTICALL_SUPPORTED_CHAIN_IDS.contains(&chain_id) { - return Err(error::MulticallError::InvalidChainId(chain_id)) + return Err(error::MulticallError::InvalidChainId(chain_id)); } constants::MULTICALL_ADDRESS } @@ -309,7 +309,7 @@ impl Multicall { (_, Some(chain_id)) => { let chain_id = chain_id.into(); if !constants::MULTICALL_SUPPORTED_CHAIN_IDS.contains(&chain_id) { - return Err(error::MulticallError::InvalidChainId(chain_id)) + return Err(error::MulticallError::InvalidChainId(chain_id)); } constants::MULTICALL_ADDRESS } @@ -388,7 +388,7 @@ impl Multicall { TypedTransaction::Eip1559(tx) => (tx.to, tx.data, tx.value), }; if data.is_none() && !call.function.outputs.is_empty() { - return self + return self; } if let Some(NameOrAddress::Address(target)) = to { let call = Call { @@ -718,7 +718,7 @@ impl Multicall { // still do so because of other calls that are in the same multicall // aggregate. if !success && !call.allow_failure { - return Err(error::MulticallError::IllegalRevert) + return Err(error::MulticallError::IllegalRevert); } Err(return_data) diff --git a/ethers-core/Cargo.toml b/ethers-core/Cargo.toml index 03cc9d419..909304f5f 100644 --- a/ethers-core/Cargo.toml +++ b/ethers-core/Cargo.toml @@ -70,6 +70,3 @@ rand.workspace = true celo = ["legacy"] # celo support extends the transaction format with extra fields legacy = [] macros = ["syn", "cargo_metadata", "once_cell"] - -# Deprecated -eip712 = [] diff --git a/ethers-core/src/abi/human_readable/lexer.rs b/ethers-core/src/abi/human_readable/lexer.rs index 08ee00207..cccb52549 100644 --- a/ethers-core/src/abi/human_readable/lexer.rs +++ b/ethers-core/src/abi/human_readable/lexer.rs @@ -182,12 +182,12 @@ impl<'input> HumanReadableLexer<'input> { if let Some((i, ch)) = self.chars.peek() { if !UnicodeXID::is_xid_continue(*ch) && *ch != '$' { end = *i; - break + break; } self.chars.next(); } else { end = self.input.len(); - break + break; } } let id = &self.input[start..end]; @@ -196,7 +196,7 @@ impl<'input> HumanReadableLexer<'input> { Some(Ok((start, w, end))) } else { Some(Ok((start, Token::Identifier(id), end))) - } + }; } Some((start, ch)) if ch.is_ascii_digit() => { let mut end = start + 1; @@ -220,7 +220,7 @@ impl<'input> HumanReadableLexer<'input> { while let Some((i, ch)) = self.chars.peek() { if !ch.is_ascii_hexdigit() && *ch != '_' { - break + break; } end = *i; self.chars.next(); @@ -230,23 +230,23 @@ impl<'input> HumanReadableLexer<'input> { start, Token::HexNumber(&self.input[start..=end]), end + 1, - ))) + ))); } } loop { if let Some((i, ch)) = self.chars.peek().cloned() { if !ch.is_ascii_digit() { - break + break; } self.chars.next(); end = i + 1; } else { end = self.input.len(); - break + break; } } - return Some(Ok((start, Token::Number(&self.input[start..end]), end + 1))) + return Some(Ok((start, Token::Number(&self.input[start..end]), end + 1))); } Some((i, '(')) => return Some(Ok((i, Token::OpenParenthesis, i + 1))), Some((i, ')')) => return Some(Ok((i, Token::CloseParenthesis, i + 1))), @@ -262,11 +262,11 @@ impl<'input> HumanReadableLexer<'input> { if let Some((i, ch)) = self.chars.next() { end = i; if ch.is_whitespace() { - break + break; } } else { end = self.input.len(); - break + break; } } @@ -274,7 +274,7 @@ impl<'input> HumanReadableLexer<'input> { start, end, self.input[start..end].to_owned(), - ))) + ))); } None => return None, } @@ -527,7 +527,7 @@ impl<'input> HumanReadableParser<'input> { let mut params = Vec::new(); if self.peek_next(token) { - return Ok(params) + return Ok(params); } loop { @@ -581,7 +581,7 @@ impl<'input> HumanReadableParser<'input> { Token::Identifier(id) => { name = id; self.next(); - break + break; } _ => break, }; @@ -594,7 +594,7 @@ impl<'input> HumanReadableParser<'input> { let mut params = Vec::new(); if self.peek_next(Token::CloseParenthesis) { - return Ok(params) + return Ok(params); } loop { params.push(self.take_param()?); diff --git a/ethers-core/src/abi/human_readable/mod.rs b/ethers-core/src/abi/human_readable/mod.rs index db5d97ac5..d2fa28fdc 100644 --- a/ethers-core/src/abi/human_readable/mod.rs +++ b/ethers-core/src/abi/human_readable/mod.rs @@ -144,7 +144,7 @@ impl AbiParser { tuple.push(ty.as_param(ParamType::Tuple(param))) } else { resolved = false; - break + break; } } FieldType::Mapping(_) => { @@ -227,7 +227,7 @@ impl AbiParser { }; let event = Event { name, inputs, anonymous }; - return Ok(event) + return Ok(event); } Some(' ') | Some('\t') => continue, Some(c) => { @@ -526,7 +526,7 @@ pub(crate) fn parse_identifier(input: &mut &str) -> Result { } } if name.is_empty() { - return Err(ParseError::ParseError(super::Error::InvalidName(input.to_string()))) + return Err(ParseError::ParseError(super::Error::InvalidName(input.to_string()))); } *input = chars.as_str(); Ok(name) diff --git a/ethers-core/src/abi/mod.rs b/ethers-core/src/abi/mod.rs index dfb6c5128..7f1ff1874 100644 --- a/ethers-core/src/abi/mod.rs +++ b/ethers-core/src/abi/mod.rs @@ -97,7 +97,7 @@ pub trait ErrorExt: sealed::Sealed { impl ErrorExt for ethabi::AbiError { fn abi_signature(&self) -> String { if self.inputs.is_empty() { - return format!("{}()", self.name) + return format!("{}()", self.name); } let inputs = self.inputs.iter().map(|p| p.kind.to_string()).collect::>().join(","); format!("{}({inputs})", self.name) @@ -123,11 +123,11 @@ pub trait AbiType { pub fn minimum_size(ty: &ParamType) -> usize { match ty { // 1 word - ParamType::Uint(_) | - ParamType::Int(_) | - ParamType::Bool | - ParamType::Address | - ParamType::FixedBytes(_) => 32, + ParamType::Uint(_) + | ParamType::Int(_) + | ParamType::Bool + | ParamType::Address + | ParamType::FixedBytes(_) => 32, // min 2 words (offset, length) ParamType::Bytes | ParamType::String | ParamType::Array(_) => 64, // sum of all elements diff --git a/ethers-core/src/abi/packed.rs b/ethers-core/src/abi/packed.rs index e491f8ddf..736b02555 100644 --- a/ethers-core/src/abi/packed.rs +++ b/ethers-core/src/abi/packed.rs @@ -91,7 +91,7 @@ fn check(token: &Token) -> Result<(), EncodePackedError> { Array(vec) | FixedArray(vec) => { for t in vec.iter() { if t.is_dynamic() || matches!(t, Array(_)) { - return Err(EncodePackedError::InvalidToken(token.clone())) + return Err(EncodePackedError::InvalidToken(token.clone())); } check(t)?; } diff --git a/ethers-core/src/abi/struct_def.rs b/ethers-core/src/abi/struct_def.rs index cc588fcab..3dda14b5c 100644 --- a/ethers-core/src/abi/struct_def.rs +++ b/ethers-core/src/abi/struct_def.rs @@ -198,7 +198,7 @@ impl StructFieldType { Box::new(StructFieldType::Type(ty)), size, ))) - } + }; } Some(c) => { if c.is_numeric() { @@ -270,7 +270,7 @@ impl SolStruct { .map(parse_struct_field) .collect::, _>>()? }; - return Ok(SolStruct { name, fields }) + return Ok(SolStruct { name, fields }); } Some(' ') | Some('\t') => continue, Some(c) => { @@ -303,7 +303,7 @@ impl SolStruct { if let FieldType::Elementary(ref param) = field.ty { params.push(param.clone()) } else { - return None + return None; } } Some(ParamType::Tuple(params)) @@ -341,7 +341,7 @@ fn parse_struct_field(s: &str) -> Result { fn parse_field_type(s: &str) -> Result { let mut input = s.trim_start(); if input.starts_with("mapping") { - return Ok(FieldType::Mapping(Box::new(parse_mapping(input)?))) + return Ok(FieldType::Mapping(Box::new(parse_mapping(input)?))); } if input.ends_with(" payable") { // special case for `address payable` diff --git a/ethers-core/src/abi/tokens.rs b/ethers-core/src/abi/tokens.rs index 33b0034d3..d0028fc3b 100644 --- a/ethers-core/src/abi/tokens.rs +++ b/ethers-core/src/abi/tokens.rs @@ -189,7 +189,7 @@ impl Tokenizable for H256 { match token { Token::FixedBytes(mut s) => { if s.len() != 32 { - return Err(InvalidOutputType(format!("Expected `H256`, got {s:?}"))) + return Err(InvalidOutputType(format!("Expected `H256`, got {s:?}"))); } let mut data = [0; 32]; for (idx, val) in s.drain(..).enumerate() { @@ -337,7 +337,7 @@ impl Tokenizable for [u8; N] { "Expected `FixedBytes({})`, got FixedBytes({})", N, bytes.len() - ))) + ))); } let mut arr = [0; N]; @@ -362,7 +362,7 @@ impl Tokenizable for [T; N] { "Expected `FixedArray({})`, got FixedArray({})", N, tokens.len() - ))) + ))); } let mut arr = ArrayVec::::new(); diff --git a/ethers-core/src/macros/ethers_crate.rs b/ethers-core/src/macros/ethers_crate.rs index 9b4d9b802..37afceb46 100644 --- a/ethers-core/src/macros/ethers_crate.rs +++ b/ethers-core/src/macros/ethers_crate.rs @@ -100,7 +100,7 @@ impl ProjectEnvironment { // return ethers_* if the root package is an internal ethers crate since `ethers` is not // available if pkg.name.parse::().is_ok() || pkg.name == "ethers" { - return Some(EthersCrate::path_names().collect()) + return Some(EthersCrate::path_names().collect()); } let mut names: CrateNames = EthersCrate::ethers_path_names().collect(); @@ -108,7 +108,7 @@ impl ProjectEnvironment { let name = dep.name.as_str(); if name.starts_with("ethers") { if name == "ethers" { - return None + return None; } else if let Ok(dep) = name.parse::() { names.insert(dep, dep.path_name()); } @@ -130,12 +130,12 @@ impl ProjectEnvironment { /// [ref]: https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates #[inline] pub fn is_crate_root(&self) -> bool { - env::var_os("CARGO_TARGET_TMPDIR").is_none() && - self.manifest_dir.components().all(|c| { + env::var_os("CARGO_TARGET_TMPDIR").is_none() + && self.manifest_dir.components().all(|c| { let s = c.as_os_str(); s != "examples" && s != "benches" - }) && - !self.is_crate_name_in_dirs() + }) + && !self.is_crate_name_in_dirs() } /// Returns whether `crate_name` is the name of a file or directory in the first level of @@ -328,7 +328,7 @@ impl EthersCrate { fn file_stem_eq, U: AsRef>(path: T, s: U) -> bool { if let Some(stem) = path.as_ref().file_stem() { if let Some(stem) = stem.to_str() { - return stem == s.as_ref() + return stem == s.as_ref(); } } false diff --git a/ethers-core/src/types/block.rs b/ethers-core/src/types/block.rs index 2dffe090c..8d0240256 100644 --- a/ethers-core/src/types/block.rs +++ b/ethers-core/src/types/block.rs @@ -160,9 +160,9 @@ impl Block { Ordering::Greater => { let gas_used_delta = self.gas_used - self.gas_target(); let base_fee_per_gas_delta = U256::max( - base_fee_per_gas * gas_used_delta / - target_usage / - BASE_FEE_MAX_CHANGE_DENOMINATOR, + base_fee_per_gas * gas_used_delta + / target_usage + / BASE_FEE_MAX_CHANGE_DENOMINATOR, U256::from(1u32), ); let expected_base_fee_per_gas = base_fee_per_gas + base_fee_per_gas_delta; @@ -170,9 +170,9 @@ impl Block { } Ordering::Less => { let gas_used_delta = self.gas_target() - self.gas_used; - let base_fee_per_gas_delta = base_fee_per_gas * gas_used_delta / - target_usage / - BASE_FEE_MAX_CHANGE_DENOMINATOR; + let base_fee_per_gas_delta = base_fee_per_gas * gas_used_delta + / target_usage + / BASE_FEE_MAX_CHANGE_DENOMINATOR; let expected_base_fee_per_gas = base_fee_per_gas - base_fee_per_gas_delta; Some(expected_base_fee_per_gas) } @@ -189,10 +189,10 @@ impl Block { /// [`DateTime`]. pub fn time(&self) -> Result, TimeError> { if self.timestamp.is_zero() { - return Err(TimeError::TimestampZero) + return Err(TimeError::TimestampZero); } if self.timestamp.bits() > 63 { - return Err(TimeError::TimestampOverflow) + return Err(TimeError::TimestampOverflow); } // Casting to i64 is safe because the timestamp is guaranteed to be less than 2^63. // TODO: It would be nice if there was `TryInto for U256`. @@ -520,13 +520,13 @@ impl<'de> Deserialize<'de> for BlockId { match key.as_str() { "blockNumber" => { if number.is_some() || hash.is_some() { - return Err(serde::de::Error::duplicate_field("blockNumber")) + return Err(serde::de::Error::duplicate_field("blockNumber")); } number = Some(BlockId::Number(map.next_value::()?)) } "blockHash" => { if number.is_some() || hash.is_some() { - return Err(serde::de::Error::duplicate_field("blockHash")) + return Err(serde::de::Error::duplicate_field("blockHash")); } hash = Some(BlockId::Hash(map.next_value::()?)) } diff --git a/ethers-core/src/types/chain.rs b/ethers-core/src/types/chain.rs index 8ddb19a6d..49a4fdd1c 100644 --- a/ethers-core/src/types/chain.rs +++ b/ethers-core/src/types/chain.rs @@ -289,10 +289,10 @@ impl Chain { FilecoinHyperspaceTestnet | FilecoinMainnet => 30_000, ScrollAlphaTestnet => 3_000, // Explicitly exhaustive. See NB above. - Morden | Ropsten | Rinkeby | Goerli | Kovan | XDai | Chiado | Sepolia | Moonbase | - MoonbeamDev | Optimism | OptimismGoerli | OptimismKovan | Poa | Sokol | Rsk | - EmeraldTestnet | Boba | BaseGoerli | ZkSync | ZkSyncTestnet | PolygonZkEvm | - PolygonZkEvmTestnet | Metis => return None, + Morden | Ropsten | Rinkeby | Goerli | Kovan | XDai | Chiado | Sepolia | Moonbase + | MoonbeamDev | Optimism | OptimismGoerli | OptimismKovan | Poa | Sokol | Rsk + | EmeraldTestnet | Boba | BaseGoerli | ZkSync | ZkSyncTestnet | PolygonZkEvm + | PolygonZkEvmTestnet | Metis => return None, }; Some(Duration::from_millis(ms)) @@ -313,47 +313,47 @@ impl Chain { match self { // Known legacy chains / non EIP-1559 compliant - Optimism | - OptimismGoerli | - OptimismKovan | - Fantom | - FantomTestnet | - BinanceSmartChain | - BinanceSmartChainTestnet | - Arbitrum | - ArbitrumTestnet | - ArbitrumGoerli | - ArbitrumNova | - Rsk | - Oasis | - Emerald | - EmeraldTestnet | - Celo | - CeloAlfajores | - CeloBaklava | - Boba | - ZkSync | - ZkSyncTestnet | - BaseGoerli | - PolygonZkEvm | - PolygonZkEvmTestnet => true, + Optimism + | OptimismGoerli + | OptimismKovan + | Fantom + | FantomTestnet + | BinanceSmartChain + | BinanceSmartChainTestnet + | Arbitrum + | ArbitrumTestnet + | ArbitrumGoerli + | ArbitrumNova + | Rsk + | Oasis + | Emerald + | EmeraldTestnet + | Celo + | CeloAlfajores + | CeloBaklava + | Boba + | ZkSync + | ZkSyncTestnet + | BaseGoerli + | PolygonZkEvm + | PolygonZkEvmTestnet => true, // Known EIP-1559 chains - Mainnet | - Goerli | - Sepolia | - Polygon | - PolygonMumbai | - Avalanche | - AvalancheFuji | - FilecoinMainnet | - FilecoinHyperspaceTestnet => false, + Mainnet + | Goerli + | Sepolia + | Polygon + | PolygonMumbai + | Avalanche + | AvalancheFuji + | FilecoinMainnet + | FilecoinHyperspaceTestnet => false, // Unknown / not applicable, default to false for backwards compatibility - Dev | AnvilHardhat | Morden | Ropsten | Rinkeby | Cronos | CronosTestnet | Kovan | - Sokol | Poa | XDai | Moonbeam | MoonbeamDev | Moonriver | Moonbase | Evmos | - EvmosTestnet | Chiado | Aurora | AuroraTestnet | Canto | CantoTestnet | - ScrollAlphaTestnet | Metis => false, + Dev | AnvilHardhat | Morden | Ropsten | Rinkeby | Cronos | CronosTestnet | Kovan + | Sokol | Poa | XDai | Moonbeam | MoonbeamDev | Moonriver | Moonbase | Evmos + | EvmosTestnet | Chiado | Aurora | AuroraTestnet | Canto | CantoTestnet + | ScrollAlphaTestnet | Metis => false, } } @@ -515,7 +515,7 @@ impl Chain { AnvilHardhat | Dev | Morden | MoonbeamDev | FilecoinMainnet => { // this is explicitly exhaustive so we don't forget to add new urls when adding a // new chain - return None + return None; } }; @@ -536,29 +536,29 @@ impl Chain { use Chain::*; let api_key_name = match self { - Mainnet | - Morden | - Ropsten | - Kovan | - Rinkeby | - Goerli | - Optimism | - OptimismGoerli | - OptimismKovan | - BinanceSmartChain | - BinanceSmartChainTestnet | - Arbitrum | - ArbitrumTestnet | - ArbitrumGoerli | - ArbitrumNova | - Cronos | - CronosTestnet | - Aurora | - AuroraTestnet | - Celo | - CeloAlfajores | - CeloBaklava | - BaseGoerli => "ETHERSCAN_API_KEY", + Mainnet + | Morden + | Ropsten + | Kovan + | Rinkeby + | Goerli + | Optimism + | OptimismGoerli + | OptimismKovan + | BinanceSmartChain + | BinanceSmartChainTestnet + | Arbitrum + | ArbitrumTestnet + | ArbitrumGoerli + | ArbitrumNova + | Cronos + | CronosTestnet + | Aurora + | AuroraTestnet + | Celo + | CeloAlfajores + | CeloBaklava + | BaseGoerli => "ETHERSCAN_API_KEY", Avalanche | AvalancheFuji => "SNOWTRACE_API_KEY", @@ -573,25 +573,25 @@ impl Chain { Boba => "BOBASCAN_API_KEY", // Explicitly exhaustive. See NB above. - XDai | - ScrollAlphaTestnet | - Metis | - Chiado | - Sepolia | - Rsk | - Sokol | - Poa | - Oasis | - Emerald | - EmeraldTestnet | - Evmos | - EvmosTestnet | - AnvilHardhat | - Dev | - ZkSync | - ZkSyncTestnet | - FilecoinMainnet | - FilecoinHyperspaceTestnet => return None, + XDai + | ScrollAlphaTestnet + | Metis + | Chiado + | Sepolia + | Rsk + | Sokol + | Poa + | Oasis + | Emerald + | EmeraldTestnet + | Evmos + | EvmosTestnet + | AnvilHardhat + | Dev + | ZkSync + | ZkSyncTestnet + | FilecoinMainnet + | FilecoinHyperspaceTestnet => return None, }; Some(api_key_name) diff --git a/ethers-core/src/types/ens.rs b/ethers-core/src/types/ens.rs index baa2bebe6..ad7cf7ffb 100644 --- a/ethers-core/src/types/ens.rs +++ b/ethers-core/src/types/ens.rs @@ -34,7 +34,7 @@ impl Decodable for NameOrAddress { fn decode(rlp: &rlp::Rlp) -> Result { // An address (H160) is 20 bytes, so let's only accept 20 byte rlp string encodings. if !rlp.is_data() { - return Err(rlp::DecoderError::RlpExpectedToBeData) + return Err(rlp::DecoderError::RlpExpectedToBeData); } // the data needs to be 20 bytes long diff --git a/ethers-core/src/types/filter.rs b/ethers-core/src/types/filter.rs index 605c14bea..432af1575 100644 --- a/ethers-core/src/types/filter.rs +++ b/ethers-core/src/types/filter.rs @@ -443,46 +443,46 @@ impl<'de> Deserialize<'de> for Filter { match key.as_str() { "fromBlock" => { if from_block.is_some() { - return Err(serde::de::Error::duplicate_field("fromBlock")) + return Err(serde::de::Error::duplicate_field("fromBlock")); } if block_hash.is_some() { return Err(serde::de::Error::custom( "fromBlock not allowed with blockHash", - )) + )); } from_block = Some(map.next_value()?) } "toBlock" => { if to_block.is_some() { - return Err(serde::de::Error::duplicate_field("toBlock")) + return Err(serde::de::Error::duplicate_field("toBlock")); } if block_hash.is_some() { return Err(serde::de::Error::custom( "toBlock not allowed with blockHash", - )) + )); } to_block = Some(map.next_value()?) } "blockHash" => { if block_hash.is_some() { - return Err(serde::de::Error::duplicate_field("blockHash")) + return Err(serde::de::Error::duplicate_field("blockHash")); } if from_block.is_some() || to_block.is_some() { return Err(serde::de::Error::custom( "fromBlock,toBlock not allowed with blockHash", - )) + )); } block_hash = Some(map.next_value()?) } "address" => { if address.is_some() { - return Err(serde::de::Error::duplicate_field("address")) + return Err(serde::de::Error::duplicate_field("address")); } address = Some(map.next_value()?) } "topics" => { if topics.is_some() { - return Err(serde::de::Error::duplicate_field("topics")) + return Err(serde::de::Error::duplicate_field("topics")); } topics = Some(map.next_value()?) } @@ -504,7 +504,7 @@ impl<'de> Deserialize<'de> for Filter { // maximum allowed filter len if topics_vec.len() > 4 { - return Err(serde::de::Error::custom("exceeded maximum topics len")) + return Err(serde::de::Error::custom("exceeded maximum topics len")); } let mut topics: [Option; 4] = [None, None, None, None]; for (idx, topic) in topics_vec.into_iter().enumerate() { @@ -615,7 +615,7 @@ where let value = serde_json::Value::deserialize(deserializer)?; if value.is_null() { - return Ok(ValueOrArray::Array(Vec::new())) + return Ok(ValueOrArray::Array(Vec::new())); } #[derive(Deserialize)] @@ -668,7 +668,7 @@ impl FilteredParams { /// Returns `true` if the bloom matches the topics pub fn matches_topics(bloom: Bloom, topic_filters: &[BloomFilter]) -> bool { if topic_filters.is_empty() { - return true + return true; } // returns true if a filter matches @@ -677,11 +677,11 @@ impl FilteredParams { for maybe_bloom in filter { is_match = maybe_bloom.as_ref().map(|b| bloom.contains_bloom(b)).unwrap_or(true); if !is_match { - break + break; } } if is_match { - return true + return true; } } false @@ -690,11 +690,11 @@ impl FilteredParams { /// Returns `true` if the bloom contains the address pub fn matches_address(bloom: Bloom, address_filter: &BloomFilter) -> bool { if address_filter.is_empty() { - return true + return true; } else { for maybe_bloom in address_filter { if maybe_bloom.as_ref().map(|b| bloom.contains_bloom(b)).unwrap_or(true) { - return true + return true; } } } @@ -721,14 +721,14 @@ impl FilteredParams { } }; if out.is_empty() { - return None + return None; } Some(out) } pub fn filter_block_range(&self, block_number: u64) -> bool { if self.filter.is_none() { - return true + return true; } let filter = self.filter.as_ref().unwrap(); let mut res = true; @@ -758,7 +758,7 @@ impl FilteredParams { pub fn filter_block_hash(&self, block_hash: H256) -> bool { if let Some(h) = self.filter.as_ref().and_then(|f| f.get_block_hash()) { if h != block_hash { - return false + return false; } } true @@ -769,15 +769,15 @@ impl FilteredParams { match input_address { ValueOrArray::Value(x) => { if log.address != *x { - return false + return false; } } ValueOrArray::Array(x) => { if x.is_empty() { - return true + return true; } if !x.contains(&log.address) { - return false + return false; } } } @@ -799,7 +799,7 @@ impl FilteredParams { ValueOrArray::Array(multi) => { if multi.is_empty() { out = true; - continue + continue; } // Shrink the topics until the last item is Some. let mut new_multi = multi; @@ -809,7 +809,7 @@ impl FilteredParams { // We can discard right away any logs with lesser topics than the filter. if new_multi.len() > log.topics.len() { out = false; - break + break; } let replaced: Option> = self.replace(log, ValueOrArray::Array(new_multi)); @@ -817,7 +817,7 @@ impl FilteredParams { out = false; if log.topics.starts_with(&replaced[..]) { out = true; - break + break; } } } diff --git a/ethers-core/src/types/i256.rs b/ethers-core/src/types/i256.rs index c846bf9bd..02e7a48d8 100644 --- a/ethers-core/src/types/i256.rs +++ b/ethers-core/src/types/i256.rs @@ -226,7 +226,7 @@ impl I256 { // NOTE: Do the hex conversion here as `U256` implementation can panic. if value.len() > 64 { - return Err(ParseI256Error::IntegerOverflow) + return Err(ParseI256Error::IntegerOverflow); } let mut abs = U256::zero(); @@ -506,8 +506,8 @@ impl I256 { // the result. let overflow = matches!( (self.sign(), rhs.sign(), result.sign()), - (Sign::Positive, Sign::Positive, Sign::Negative) | - (Sign::Negative, Sign::Negative, Sign::Positive) + (Sign::Positive, Sign::Positive, Sign::Negative) + | (Sign::Negative, Sign::Negative, Sign::Positive) ); (result, overflow) @@ -565,8 +565,8 @@ impl I256 { // the result. let overflow = matches!( (self.sign(), rhs.sign(), result.sign()), - (Sign::Positive, Sign::Negative, Sign::Negative) | - (Sign::Negative, Sign::Positive, Sign::Positive) + (Sign::Positive, Sign::Negative, Sign::Negative) + | (Sign::Negative, Sign::Positive, Sign::Positive) ); (result, overflow) diff --git a/ethers-core/src/types/serde_helpers.rs b/ethers-core/src/types/serde_helpers.rs index e36a97f42..72c5f7337 100644 --- a/ethers-core/src/types/serde_helpers.rs +++ b/ethers-core/src/types/serde_helpers.rs @@ -301,7 +301,6 @@ mod tests { use crate::types::U256; #[test] - #[cfg(feature = "eip712")] fn test_deserialize_string_chain_id() { use crate::types::transaction::eip712::EIP712Domain; diff --git a/ethers-core/src/types/signature.rs b/ethers-core/src/types/signature.rs index 47ac9cfda..1a6e86bc1 100644 --- a/ethers-core/src/types/signature.rs +++ b/ethers-core/src/types/signature.rs @@ -69,7 +69,6 @@ impl fmt::Display for Signature { } } -#[cfg(feature = "eip712")] impl Signature { /// Recovers the ethereum address which was used to sign a given EIP712 /// typed data payload. @@ -95,7 +94,7 @@ impl Signature { let address = address.into(); let recovered = self.recover(message)?; if recovered != address { - return Err(SignatureError::VerificationError(address, recovered)) + return Err(SignatureError::VerificationError(address, recovered)); } Ok(()) @@ -201,7 +200,7 @@ impl<'a> TryFrom<&'a [u8]> for Signature { /// and the final byte is the `v` value in 'Electrum' notation. fn try_from(bytes: &'a [u8]) -> Result { if bytes.len() != 65 { - return Err(SignatureError::InvalidLength(bytes.len())) + return Err(SignatureError::InvalidLength(bytes.len())); } let v = bytes[64]; diff --git a/ethers-core/src/types/trace/filter.rs b/ethers-core/src/types/trace/filter.rs index c09b076ff..0403c2909 100644 --- a/ethers-core/src/types/trace/filter.rs +++ b/ethers-core/src/types/trace/filter.rs @@ -376,7 +376,7 @@ impl Decodable for TraceError { impl open_fastrlp::Decodable for TraceError { fn decode(buf: &mut &[u8]) -> Result { if buf.is_empty() { - return Err(DecodeError::InputTooShort) + return Err(DecodeError::InputTooShort); } let val = buf[0]; let val = Self::from_u8(val).map_err(|_| DecodeError::Custom("Invalid error code"))?; diff --git a/ethers-core/src/types/transaction/eip2718.rs b/ethers-core/src/types/transaction/eip2718.rs index 32d0d8f52..26ad7b0ca 100644 --- a/ethers-core/src/types/transaction/eip2718.rs +++ b/ethers-core/src/types/transaction/eip2718.rs @@ -326,7 +326,7 @@ impl TypedTransaction { // Legacy (0x00) // use the original rlp let decoded_request = TransactionRequest::decode_signed_rlp(rlp)?; - return Ok((Self::Legacy(decoded_request.0), decoded_request.1)) + return Ok((Self::Legacy(decoded_request.0), decoded_request.1)); } let rest = rlp::Rlp::new( @@ -336,12 +336,12 @@ impl TypedTransaction { if first == 0x01 { // EIP-2930 (0x01) let decoded_request = Eip2930TransactionRequest::decode_signed_rlp(&rest)?; - return Ok((Self::Eip2930(decoded_request.0), decoded_request.1)) + return Ok((Self::Eip2930(decoded_request.0), decoded_request.1)); } if first == 0x02 { // EIP-1559 (0x02) let decoded_request = Eip1559TransactionRequest::decode_signed_rlp(&rest)?; - return Ok((Self::Eip1559(decoded_request.0), decoded_request.1)) + return Ok((Self::Eip1559(decoded_request.0), decoded_request.1)); } Err(rlp::DecoderError::Custom("invalid tx type").into()) diff --git a/ethers-core/src/types/transaction/eip712.rs b/ethers-core/src/types/transaction/eip712.rs index d3df08a85..2cb6e9d2e 100644 --- a/ethers-core/src/types/transaction/eip712.rs +++ b/ethers-core/src/types/transaction/eip712.rs @@ -399,7 +399,7 @@ pub fn encode_data( } else if types.contains_key(&field.r#type) { tokens.push(Token::Uint(U256::zero())); } else { - return Err(Eip712Error::Message(format!("No data found for: `{}`", field.name))) + return Err(Eip712Error::Message(format!("No data found for: `{}`", field.name))); } } } @@ -471,7 +471,7 @@ fn find_type_dependencies<'a>( found: &mut HashSet<&'a str>, ) { if found.contains(primary_type) { - return + return; } if let Some(fields) = types.get(primary_type) { found.insert(primary_type); diff --git a/ethers-core/src/types/transaction/mod.rs b/ethers-core/src/types/transaction/mod.rs index 41c277cba..65f17fa3d 100644 --- a/ethers-core/src/types/transaction/mod.rs +++ b/ethers-core/src/types/transaction/mod.rs @@ -47,7 +47,7 @@ pub(crate) fn extract_chain_id(v: u64) -> Option { // https://eips.ethereum.org/EIPS/eip-155 // if chainid is available, v = {0, 1} + CHAIN_ID * 2 + 35 if v >= 35 { - return Some(crate::types::U64::from((v - 35) >> 1)) + return Some(crate::types::U64::from((v - 35) >> 1)); } None } @@ -81,7 +81,7 @@ fn decode_to( if to.is_data() { None } else { - return Err(rlp::DecoderError::RlpExpectedToBeData) + return Err(rlp::DecoderError::RlpExpectedToBeData); } } else { Some(to.as_val()?) diff --git a/ethers-core/src/types/txpool.rs b/ethers-core/src/types/txpool.rs index dc6a38ef8..c0607c45a 100644 --- a/ethers-core/src/types/txpool.rs +++ b/ethers-core/src/types/txpool.rs @@ -43,19 +43,19 @@ impl<'de> Visitor<'de> for TxpoolInspectSummaryVisitor { { let addr_split: Vec<&str> = value.split(": ").collect(); if addr_split.len() != 2 { - return Err(de::Error::custom("invalid format for TxpoolInspectSummary: to")) + return Err(de::Error::custom("invalid format for TxpoolInspectSummary: to")); } let value_split: Vec<&str> = addr_split[1].split(" wei + ").collect(); if value_split.len() != 2 { - return Err(de::Error::custom("invalid format for TxpoolInspectSummary: gasLimit")) + return Err(de::Error::custom("invalid format for TxpoolInspectSummary: gasLimit")); } let gas_split: Vec<&str> = value_split[1].split(" gas × ").collect(); if gas_split.len() != 2 { - return Err(de::Error::custom("invalid format for TxpoolInspectSummary: gas")) + return Err(de::Error::custom("invalid format for TxpoolInspectSummary: gas")); } let gas_price_split: Vec<&str> = gas_split[1].split(" wei").collect(); if gas_price_split.len() != 2 { - return Err(de::Error::custom("invalid format for TxpoolInspectSummary: gas_price")) + return Err(de::Error::custom("invalid format for TxpoolInspectSummary: gas_price")); } let addr = match addr_split[0] { "" => None, diff --git a/ethers-core/src/types/u256.rs b/ethers-core/src/types/u256.rs index 6d3187ffa..fc45868b3 100644 --- a/ethers-core/src/types/u256.rs +++ b/ethers-core/src/types/u256.rs @@ -17,10 +17,10 @@ pub fn u256_from_f64_saturating(mut f: f64) -> U256 { panic!("NaN is not a valid value for U256"); } if f < 0.5 { - return U256::zero() + return U256::zero(); } if f >= 1.157_920_892_373_162e77_f64 { - return U256::max_value() + return U256::max_value(); } // All non-normal cases should have been handled above assert!(f.is_normal()); diff --git a/ethers-core/src/types/uint8.rs b/ethers-core/src/types/uint8.rs index 5803961b6..1f8852028 100644 --- a/ethers-core/src/types/uint8.rs +++ b/ethers-core/src/types/uint8.rs @@ -79,7 +79,9 @@ impl Tokenizable for Uint8 { match token { Token::Int(data) | Token::Uint(data) => { if data > U256::from(u8::MAX) { - return Err(InvalidOutputType("Integer overflow when casting to u8".to_string())) + return Err(InvalidOutputType( + "Integer overflow when casting to u8".to_string(), + )); } Ok(Uint8(data.low_u32() as u8)) } diff --git a/ethers-core/src/utils/anvil.rs b/ethers-core/src/utils/anvil.rs index 1fe5baf7e..97d65c59a 100644 --- a/ethers-core/src/utils/anvil.rs +++ b/ethers-core/src/utils/anvil.rs @@ -255,8 +255,8 @@ impl Anvil { let mut addresses = Vec::new(); let mut is_private_key = false; loop { - if start + Duration::from_millis(self.timeout.unwrap_or(ANVIL_STARTUP_TIMEOUT_MILLIS)) <= - Instant::now() + if start + Duration::from_millis(self.timeout.unwrap_or(ANVIL_STARTUP_TIMEOUT_MILLIS)) + <= Instant::now() { panic!("Timed out waiting for anvil to start. Is anvil installed?") } @@ -264,7 +264,7 @@ impl Anvil { let mut line = String::new(); reader.read_line(&mut line).expect("Failed to read line from anvil process"); if line.contains("Listening on") { - break + break; } if line.starts_with("Private Keys") { diff --git a/ethers-core/src/utils/ganache.rs b/ethers-core/src/utils/ganache.rs index d040eb73e..11721ed52 100644 --- a/ethers-core/src/utils/ganache.rs +++ b/ethers-core/src/utils/ganache.rs @@ -194,7 +194,7 @@ impl Ganache { let mut line = String::new(); reader.read_line(&mut line).expect("Failed to read line from ganache process"); if line.contains("Listening on") { - break + break; } if line.starts_with("Private Keys") { diff --git a/ethers-core/src/utils/geth.rs b/ethers-core/src/utils/geth.rs index 5e1567881..f6608b900 100644 --- a/ethers-core/src/utils/geth.rs +++ b/ethers-core/src/utils/geth.rs @@ -117,7 +117,7 @@ impl GethInstance { // geth ids are trunated let truncated_id = hex::encode(&id.0[..8]); if line.contains("Adding p2p peer") && line.contains(&truncated_id) { - return Ok(()) + return Ok(()); } } Err(GethInstanceError::Timeout("Timed out waiting for geth to add a peer".into())) @@ -532,14 +532,14 @@ impl Geth { // geth 1.9.23 uses "server started" while 1.9.18 uses "endpoint opened" // the unauthenticated api is used for regular non-engine API requests - if line.contains("HTTP endpoint opened") || - (line.contains("HTTP server started") && !line.contains("auth=true")) + if line.contains("HTTP endpoint opened") + || (line.contains("HTTP server started") && !line.contains("auth=true")) { http_started = true; } if p2p_started && http_started { - break + break; } } diff --git a/ethers-core/src/utils/mod.rs b/ethers-core/src/utils/mod.rs index faa9052ee..e415fdb3f 100644 --- a/ethers-core/src/utils/mod.rs +++ b/ethers-core/src/utils/mod.rs @@ -446,7 +446,7 @@ pub fn parse_checksummed(addr: &str, chain_id: Option) -> Result Result<[u8; 32], ConversionError> { let str_bytes: &[u8] = text.as_bytes(); if str_bytes.len() > 32 { - return Err(ConversionError::TextTooLong) + return Err(ConversionError::TextTooLong); } let mut bytes32: [u8; 32] = [0u8; 32]; @@ -492,7 +492,7 @@ where D: Deserializer<'de>, { if bytes.0.len() > 32 { - return Err(serde::de::Error::custom("input too long to be a H256")) + return Err(serde::de::Error::custom("input too long to be a H256")); } // left pad with zeros to 32 bytes @@ -530,10 +530,10 @@ fn estimate_priority_fee(rewards: Vec>) -> U256 { let mut rewards: Vec = rewards.iter().map(|r| r[0]).filter(|r| *r > U256::zero()).collect(); if rewards.is_empty() { - return U256::zero() + return U256::zero(); } if rewards.len() == 1 { - return rewards[0] + return rewards[0]; } // Sort the rewards as we will eventually take the median. rewards.sort(); @@ -560,8 +560,8 @@ fn estimate_priority_fee(rewards: Vec>) -> U256 { // If we encountered a big change in fees at a certain position, then consider only // the values >= it. - let values = if *max_change >= EIP1559_FEE_ESTIMATION_THRESHOLD_MAX_CHANGE.into() && - (max_change_index >= (rewards.len() / 2)) + let values = if *max_change >= EIP1559_FEE_ESTIMATION_THRESHOLD_MAX_CHANGE.into() + && (max_change_index >= (rewards.len() / 2)) { rewards[max_change_index..].to_vec() } else { diff --git a/ethers-etherscan/src/contract.rs b/ethers-etherscan/src/contract.rs index 2942afa66..1aff83910 100644 --- a/ethers-etherscan/src/contract.rs +++ b/ethers-etherscan/src/contract.rs @@ -326,20 +326,20 @@ impl Client { return match src { Some(src) => Ok(src), None => Err(EtherscanError::ContractCodeNotVerified(address)), - } + }; } } let query = self.create_query("contract", "getabi", HashMap::from([("address", address)])); let resp: Response = self.get_json(&query).await?; if resp.result.starts_with("Max rate limit reached") { - return Err(EtherscanError::RateLimitExceeded) + return Err(EtherscanError::RateLimitExceeded); } if resp.result.starts_with("Contract source code not verified") { if let Some(ref cache) = self.cache { cache.set_abi(address, None); } - return Err(EtherscanError::ContractCodeNotVerified(address)) + return Err(EtherscanError::ContractCodeNotVerified(address)); } let abi = serde_json::from_str(&resp.result)?; @@ -370,7 +370,7 @@ impl Client { return match src { Some(src) => Ok(src), None => Err(EtherscanError::ContractCodeNotVerified(address)), - } + }; } } @@ -383,7 +383,7 @@ impl Client { if let Some(ref cache) = self.cache { cache.set_source(address, None); } - return Err(EtherscanError::ContractCodeNotVerified(address)) + return Err(EtherscanError::ContractCodeNotVerified(address)); } let response: Response = self.sanitize_response(response)?; diff --git a/ethers-etherscan/src/errors.rs b/ethers-etherscan/src/errors.rs index 5f71f52d9..b545bd2b1 100644 --- a/ethers-etherscan/src/errors.rs +++ b/ethers-etherscan/src/errors.rs @@ -57,8 +57,8 @@ pub(crate) fn is_blocked_by_cloudflare_response(txt: &str) -> bool { /// etherscan/polyscan is protected by cloudflare, which can require captchas to "review the /// security of your connection before proceeding" pub(crate) fn is_cloudflare_security_challenge(txt: &str) -> bool { - txt.contains("https://www.cloudflare.com?utm_source=challenge") || - txt.to_lowercase().contains("checking if the site connection is secure") + txt.contains("https://www.cloudflare.com?utm_source=challenge") + || txt.to_lowercase().contains("checking if the site connection is secure") } #[cfg(test)] diff --git a/ethers-etherscan/src/lib.rs b/ethers-etherscan/src/lib.rs index c1ea855e4..9669aff65 100644 --- a/ethers-etherscan/src/lib.rs +++ b/ethers-etherscan/src/lib.rs @@ -88,17 +88,17 @@ impl Client { .map_err(Into::into), // Backwards compatibility, ideally these should return an error. - Chain::XDai | - Chain::Chiado | - Chain::Sepolia | - Chain::Rsk | - Chain::Sokol | - Chain::Poa | - Chain::Oasis | - Chain::Emerald | - Chain::EmeraldTestnet | - Chain::Evmos | - Chain::EvmosTestnet => Ok(String::new()), + Chain::XDai + | Chain::Chiado + | Chain::Sepolia + | Chain::Rsk + | Chain::Sokol + | Chain::Poa + | Chain::Oasis + | Chain::Emerald + | Chain::EmeraldTestnet + | Chain::Evmos + | Chain::EvmosTestnet => Ok(String::new()), Chain::AnvilHardhat | Chain::Dev => Err(EtherscanError::LocalNetworksNotSupported), _ => chain @@ -218,9 +218,9 @@ impl Client { ResponseData::Error { result, message, status } => { if let Some(ref result) = result { if result.starts_with("Max rate limit reached") { - return Err(EtherscanError::RateLimitExceeded) + return Err(EtherscanError::RateLimitExceeded); } else if result.to_lowercase() == "invalid api key" { - return Err(EtherscanError::InvalidApiKey) + return Err(EtherscanError::InvalidApiKey); } } Err(EtherscanError::ErrorResponse { status, message, result }) @@ -407,10 +407,10 @@ impl Cache { .checked_sub(Duration::from_secs(inner.expiry)) .is_some() { - return None + return None; } - return Some(inner.data) + return Some(inner.data); } None } diff --git a/ethers-middleware/src/gas_oracle/cache.rs b/ethers-middleware/src/gas_oracle/cache.rs index 482d96250..320fc8b90 100644 --- a/ethers-middleware/src/gas_oracle/cache.rs +++ b/ethers-middleware/src/gas_oracle/cache.rs @@ -45,7 +45,7 @@ impl Cached { let lock = self.0.read().await; if let Some((last_fetch, value)) = lock.as_ref() { if Instant::now().duration_since(*last_fetch) < validity { - return Ok(value.clone()) + return Ok(value.clone()); } } } @@ -55,7 +55,7 @@ impl Cached { // Check again, a concurrent thread may have raced us to the write. if let Some((last_fetch, value)) = lock.as_ref() { if Instant::now().duration_since(*last_fetch) < validity { - return Ok(value.clone()) + return Ok(value.clone()); } } // Set a fresh value diff --git a/ethers-middleware/src/gas_oracle/median.rs b/ethers-middleware/src/gas_oracle/median.rs index def9c55f2..73aff5eb6 100644 --- a/ethers-middleware/src/gas_oracle/median.rs +++ b/ethers-middleware/src/gas_oracle/median.rs @@ -50,7 +50,7 @@ impl Median { ); let values = values.collect::>(); if values.is_empty() { - return Err(GasOracleError::NoValues) + return Err(GasOracleError::NoValues); } Ok(values) } @@ -100,7 +100,7 @@ where { assert!((0.0..=1.0).contains(&fractile)); if values.is_empty() { - return None + return None; } let weight_rank = fractile * values.iter().map(|(weight, _)| *weight).sum::(); values.sort_unstable_by(|a, b| key(&a.1).cmp(key(&b.1))); @@ -108,7 +108,7 @@ where for (weight, value) in values.iter() { cumulative_weight += *weight; if cumulative_weight >= weight_rank { - return Some(value) + return Some(value); } } // By the last element, cumulative_weight == weight_rank and we should have diff --git a/ethers-middleware/src/nonce_manager.rs b/ethers-middleware/src/nonce_manager.rs index 996f30f58..b7781f600 100644 --- a/ethers-middleware/src/nonce_manager.rs +++ b/ethers-middleware/src/nonce_manager.rs @@ -43,7 +43,7 @@ where ) -> Result> { if self.initialized.load(Ordering::SeqCst) { // return current nonce - return Ok(self.nonce.load(Ordering::SeqCst).into()) + return Ok(self.nonce.load(Ordering::SeqCst).into()); } let _guard = self.init_guard.lock().await; @@ -51,7 +51,7 @@ where // do this again in case multiple tasks enter this codepath if self.initialized.load(Ordering::SeqCst) { // return current nonce - return Ok(self.nonce.load(Ordering::SeqCst).into()) + return Ok(self.nonce.load(Ordering::SeqCst).into()); } // initialize the nonce the first time the manager is called diff --git a/ethers-middleware/src/signer.rs b/ethers-middleware/src/signer.rs index 648d2039b..f757dc01e 100644 --- a/ethers-middleware/src/signer.rs +++ b/ethers-middleware/src/signer.rs @@ -301,7 +301,7 @@ where .inner .send_transaction(tx, block) .await - .map_err(SignerMiddlewareError::MiddlewareError) + .map_err(SignerMiddlewareError::MiddlewareError); } // if we have a nonce manager set, we should try handling the result in diff --git a/ethers-middleware/src/timelag/mod.rs b/ethers-middleware/src/timelag/mod.rs index 258fc15ad..1d1b786f1 100644 --- a/ethers-middleware/src/timelag/mod.rs +++ b/ethers-middleware/src/timelag/mod.rs @@ -244,12 +244,12 @@ where .map_err(ethers_providers::MiddlewareError::from_err)?; if receipt.is_none() { - return Ok(None) + return Ok(None); } let receipt = receipt.expect("checked is_none"); if receipt.block_number.is_none() { - return Ok(Some(receipt)) + return Ok(Some(receipt)); } let number = receipt.block_number.expect("checked is_none"); diff --git a/ethers-providers/src/ext/ens.rs b/ethers-providers/src/ext/ens.rs index f3b0e9de4..2cdd04dde 100644 --- a/ethers-providers/src/ext/ens.rs +++ b/ethers-providers/src/ext/ens.rs @@ -78,7 +78,7 @@ pub fn reverse_address(addr: Address) -> String { /// Returns the ENS namehash as specified in [EIP-137](https://eips.ethereum.org/EIPS/eip-137) pub fn namehash(name: &str) -> H256 { if name.is_empty() { - return H256::zero() + return H256::zero(); } // iterate in reverse diff --git a/ethers-providers/src/ext/erc.rs b/ethers-providers/src/ext/erc.rs index 538ffe712..4c7d132f7 100644 --- a/ethers-providers/src/ext/erc.rs +++ b/ethers-providers/src/ext/erc.rs @@ -35,7 +35,7 @@ impl FromStr for ERCNFT { split[1], ) } else { - return Err("Unsupported ERC link".to_string()) + return Err("Unsupported ERC link".to_string()); }; let token_split: Vec<&str> = inner_path.split('/').collect(); @@ -50,7 +50,7 @@ impl FromStr for ERCNFT { token_id_bytes, ) } else { - return Err("Unsupported ERC link path".to_string()) + return Err("Unsupported ERC link path".to_string()); }; Ok(ERCNFT { id: token_id, type_: token_type, contract: contract_addr }) } diff --git a/ethers-providers/src/rpc/provider.rs b/ethers-providers/src/rpc/provider.rs index 68c6da4ce..7dadbf2b7 100644 --- a/ethers-providers/src/rpc/provider.rs +++ b/ethers-providers/src/rpc/provider.rs @@ -803,7 +803,7 @@ impl Middleware for Provider

{ }; let data = self.call(&tx.into(), None).await?; if decode_bytes::

(ParamType::Address, data) != owner { - return Err(ProviderError::CustomError("Incorrect owner.".to_string())) + return Err(ProviderError::CustomError("Incorrect owner.".to_string())); } } erc::ERCNFTType::ERC1155 => { @@ -823,7 +823,9 @@ impl Middleware for Provider

{ }; let data = self.call(&tx.into(), None).await?; if decode_bytes::(ParamType::Uint(64), data) == 0 { - return Err(ProviderError::CustomError("Incorrect balance.".to_string())) + return Err(ProviderError::CustomError( + "Incorrect balance.".to_string(), + )); } } } @@ -1108,7 +1110,7 @@ impl Middleware for Provider

{ if fallback.is_err() { // if the older fallback also resulted in an error, we return the error from the // initial attempt - return err + return err; } fallback } @@ -1142,12 +1144,12 @@ impl Provider

{ // otherwise, decode_bytes panics if data.0.is_empty() { - return Err(ProviderError::EnsError(ens_name.to_string())) + return Err(ProviderError::EnsError(ens_name.to_string())); } let resolver_address: Address = decode_bytes(ParamType::Address, data); if resolver_address == Address::zero() { - return Err(ProviderError::EnsError(ens_name.to_string())) + return Err(ProviderError::EnsError(ens_name.to_string())); } if let ParamType::Address = param { @@ -1176,7 +1178,7 @@ impl Provider

{ if data.is_empty() { return Err(ProviderError::EnsError(format!( "`{ens_name}` resolver ({resolver_address:?}) is invalid." - ))) + ))); } let supports_selector = abi::decode(&[ParamType::Bool], data.as_ref()) @@ -1189,7 +1191,7 @@ impl Provider

{ ens_name, resolver_address, hex::encode(selector) - ))) + ))); } Ok(()) @@ -1478,10 +1480,10 @@ pub fn is_local_endpoint(endpoint: &str) -> bool { match host { Host::Domain(domain) => return domain.contains("localhost"), Host::Ipv4(ipv4) => { - return ipv4 == Ipv4Addr::LOCALHOST || - ipv4.is_link_local() || - ipv4.is_loopback() || - ipv4.is_private() + return ipv4 == Ipv4Addr::LOCALHOST + || ipv4.is_link_local() + || ipv4.is_loopback() + || ipv4.is_private() } Host::Ipv6(ipv6) => return ipv6.is_loopback(), } diff --git a/ethers-providers/src/rpc/pubsub.rs b/ethers-providers/src/rpc/pubsub.rs index a11579501..061a71542 100644 --- a/ethers-providers/src/rpc/pubsub.rs +++ b/ethers-providers/src/rpc/pubsub.rs @@ -91,7 +91,7 @@ where fn poll_next(self: Pin<&mut Self>, ctx: &mut Context) -> Poll> { if !self.loaded_elements.is_empty() { let next_element = self.get_mut().loaded_elements.pop_front(); - return Poll::Ready(next_element) + return Poll::Ready(next_element); } let mut this = self.project(); @@ -101,11 +101,11 @@ where Ok(res) => Poll::Ready(Some(res)), Err(err) => { error!("failed to deserialize item {:?}", err); - continue + continue; } }, None => Poll::Ready(None), - } + }; } } } diff --git a/ethers-providers/src/rpc/transports/common.rs b/ethers-providers/src/rpc/transports/common.rs index 072cf7d63..965693ab1 100644 --- a/ethers-providers/src/rpc/transports/common.rs +++ b/ethers-providers/src/rpc/transports/common.rs @@ -144,19 +144,22 @@ impl<'de: 'a, 'a> Deserialize<'de> for Response<'a> { match key { "jsonrpc" => { if jsonrpc { - return Err(de::Error::duplicate_field("jsonrpc")) + return Err(de::Error::duplicate_field("jsonrpc")); } let value = map.next_value()?; if value != "2.0" { - return Err(de::Error::invalid_value(Unexpected::Str(value), &"2.0")) + return Err(de::Error::invalid_value( + Unexpected::Str(value), + &"2.0", + )); } jsonrpc = true; } "id" => { if id.is_some() { - return Err(de::Error::duplicate_field("id")) + return Err(de::Error::duplicate_field("id")); } let value: u64 = map.next_value()?; @@ -164,7 +167,7 @@ impl<'de: 'a, 'a> Deserialize<'de> for Response<'a> { } "result" => { if result.is_some() { - return Err(de::Error::duplicate_field("result")) + return Err(de::Error::duplicate_field("result")); } let value: &RawValue = map.next_value()?; @@ -172,7 +175,7 @@ impl<'de: 'a, 'a> Deserialize<'de> for Response<'a> { } "error" => { if error.is_some() { - return Err(de::Error::duplicate_field("error")) + return Err(de::Error::duplicate_field("error")); } let value: JsonRpcError = map.next_value()?; @@ -180,7 +183,7 @@ impl<'de: 'a, 'a> Deserialize<'de> for Response<'a> { } "method" => { if method.is_some() { - return Err(de::Error::duplicate_field("method")) + return Err(de::Error::duplicate_field("method")); } let value: &str = map.next_value()?; @@ -188,7 +191,7 @@ impl<'de: 'a, 'a> Deserialize<'de> for Response<'a> { } "params" => { if params.is_some() { - return Err(de::Error::duplicate_field("params")) + return Err(de::Error::duplicate_field("params")); } let value: Params = map.next_value()?; @@ -205,7 +208,7 @@ impl<'de: 'a, 'a> Deserialize<'de> for Response<'a> { // jsonrpc version must be present in all responses if !jsonrpc { - return Err(de::Error::missing_field("jsonrpc")) + return Err(de::Error::missing_field("jsonrpc")); } match (id, result, error, method, params) { diff --git a/ethers-providers/src/rpc/transports/http.rs b/ethers-providers/src/rpc/transports/http.rs index 6198bf2fe..2fa745d9e 100644 --- a/ethers-providers/src/rpc/transports/http.rs +++ b/ethers-providers/src/rpc/transports/http.rs @@ -104,7 +104,7 @@ impl JsonRpcClient for Provider { err: serde::de::Error::custom("unexpected notification over HTTP transport"), text: String::from_utf8_lossy(&body).to_string(), }; - return Err(err) + return Err(err); } Err(err) => { return Err(ClientError::SerdeJson { diff --git a/ethers-providers/src/rpc/transports/ipc.rs b/ethers-providers/src/rpc/transports/ipc.rs index 2ead47299..2db0b2e54 100644 --- a/ethers-providers/src/rpc/transports/ipc.rs +++ b/ethers-providers/src/rpc/transports/ipc.rs @@ -351,7 +351,7 @@ impl Shared { let read = reader.read_buf(&mut buf).await?; if read == 0 { // eof, socket was closed - return Err(IpcError::ServerExit) + return Err(IpcError::ServerExit); } // parse the received bytes into 0-n jsonrpc messages @@ -427,7 +427,7 @@ impl Shared { Some(tx) => tx, None => { tracing::warn!(%id, "no pending request exists for the response ID"); - return + return; } }; @@ -448,7 +448,7 @@ impl Shared { id = ?params.subscription, "no subscription exists for the notification ID" ); - return + return; } }; diff --git a/ethers-providers/src/rpc/transports/legacy_ws.rs b/ethers-providers/src/rpc/transports/legacy_ws.rs index a150868a6..104c25b67 100644 --- a/ethers-providers/src/rpc/transports/legacy_ws.rs +++ b/ethers-providers/src/rpc/transports/legacy_ws.rs @@ -258,13 +258,13 @@ where loop { if self.is_done() { debug!("work complete"); - break + break; } if let Err(e) = self.tick().await { error!("Received a WebSocket error: {:?}", e); self.close_all_subscriptions(); - break + break; } } }; @@ -361,7 +361,7 @@ where // subscription channel was closed on the receiver end stream.remove(); } - return Err(to_client_error(err)) + return Err(to_client_error(err)); } } diff --git a/ethers-providers/src/rpc/transports/quorum.rs b/ethers-providers/src/rpc/transports/quorum.rs index 127419fc8..0447ca44f 100644 --- a/ethers-providers/src/rpc/transports/quorum.rs +++ b/ethers-providers/src/rpc/transports/quorum.rs @@ -188,16 +188,16 @@ impl QuorumProvider { v } else { // at this time no normalization is required for calls with zero parameters. - return + return; }; match method { - "eth_call" | - "eth_createAccessList" | - "eth_getStorageAt" | - "eth_getCode" | - "eth_getProof" | - "trace_call" | - "trace_block" => { + "eth_call" + | "eth_createAccessList" + | "eth_getStorageAt" + | "eth_getCode" + | "eth_getProof" + | "trace_call" + | "trace_block" => { // calls that include the block number in the params at the last index of json array if let Some(block) = params.as_array_mut().and_then(|arr| arr.last_mut()) { if Some("latest") == block.as_str() { @@ -303,13 +303,13 @@ impl<'a, T> Future for QuorumRequest<'a, T> { *weight += response_weight; if *weight >= this.inner.quorum_weight { // reached quorum with multiple responses - return Poll::Ready(Ok(val)) + return Poll::Ready(Ok(val)); } else { this.responses.push((val, response_weight)); } } else if response_weight >= this.inner.quorum_weight { // reached quorum with single response - return Poll::Ready(Ok(val)) + return Poll::Ready(Ok(val)); } else { this.responses.push((val, response_weight)); } @@ -536,14 +536,14 @@ impl Stream for QuorumStream { if *weight >= this.quorum_weight { // reached quorum with multiple notification this.benched.push(stream); - return Poll::Ready(Some(val)) + return Poll::Ready(Some(val)); } else { this.responses.push((val, response_weight)); } } else if response_weight >= this.quorum_weight { // reached quorum with single notification this.benched.push(stream); - return Poll::Ready(Some(val)) + return Poll::Ready(Some(val)); } else { this.responses.push((val, response_weight)); } @@ -558,7 +558,7 @@ impl Stream for QuorumStream { } if this.active.is_empty() && this.benched.is_empty() { - return Poll::Ready(None) + return Poll::Ready(None); } Poll::Pending } diff --git a/ethers-providers/src/rpc/transports/retry.rs b/ethers-providers/src/rpc/transports/retry.rs index ba283b311..1065dcd64 100644 --- a/ethers-providers/src/rpc/transports/retry.rs +++ b/ethers-providers/src/rpc/transports/retry.rs @@ -76,7 +76,7 @@ where /// # Example /// /// ``` - /// + /// /// # async fn demo() { /// use ethers_providers::{Http, RetryClient, HttpRateLimitRetryPolicy}; /// use std::time::Duration; @@ -293,7 +293,7 @@ where match resp { Ok(ret) => { self.requests_enqueued.fetch_sub(1, Ordering::SeqCst); - return Ok(ret) + return Ok(ret); } Err(err_) => err = err_, } @@ -304,7 +304,7 @@ where rate_limit_retry_number += 1; if rate_limit_retry_number > self.rate_limit_retries { trace!("request timed out after {} retries", self.rate_limit_retries); - return Err(RetryClientError::TimeoutError) + return Err(RetryClientError::TimeoutError); } let current_queued_requests = self.requests_enqueued.load(Ordering::SeqCst) as u64; @@ -344,12 +344,12 @@ where if timeout_retries < self.timeout_retries && maybe_connectivity(&err) { timeout_retries += 1; trace!(err = ?err, "retrying due to spurious network"); - continue + continue; } trace!(err = ?err, "should not retry"); self.requests_enqueued.fetch_sub(1, Ordering::SeqCst); - return Err(RetryClientError::ProviderError(err)) + return Err(RetryClientError::ProviderError(err)); } } } @@ -369,17 +369,17 @@ impl RetryPolicy for HttpRateLimitRetryPolicy { let JsonRpcError { code, message, .. } = err; // alchemy throws it this way if *code == 429 { - return true + return true; } // This is an infura error code for `exceeded project rate limit` if *code == -32005 { - return true + return true; } // alternative alchemy error for specific IPs if *code == -32016 && message.contains("rate limit") { - return true + return true; } match message.as_str() { @@ -405,7 +405,7 @@ impl RetryPolicy for HttpRateLimitRetryPolicy { } if let Ok(resp) = serde_json::from_str::(text) { - return should_retry_json_rpc_error(&resp.error) + return should_retry_json_rpc_error(&resp.error); } false } @@ -421,10 +421,10 @@ impl RetryPolicy for HttpRateLimitRetryPolicy { let backoff_seconds = &data["rate"]["backoff_seconds"]; // infura rate limit error if let Some(seconds) = backoff_seconds.as_u64() { - return Some(Duration::from_secs(seconds)) + return Some(Duration::from_secs(seconds)); } if let Some(seconds) = backoff_seconds.as_f64() { - return Some(Duration::from_secs(seconds as u64 + 1)) + return Some(Duration::from_secs(seconds as u64 + 1)); } } @@ -462,19 +462,19 @@ fn compute_unit_offset_in_secs( fn maybe_connectivity(err: &ProviderError) -> bool { if let ProviderError::HTTPError(reqwest_err) = err { if reqwest_err.is_timeout() { - return true + return true; } #[cfg(not(target_arch = "wasm32"))] if reqwest_err.is_connect() { - return true + return true; } // Error HTTP codes (5xx) are considered connectivity issues and will prompt retry if let Some(status) = reqwest_err.status() { let code = status.as_u16(); if (500..600).contains(&code) { - return true + return true; } } } diff --git a/ethers-providers/src/rpc/transports/ws/backend.rs b/ethers-providers/src/rpc/transports/ws/backend.rs index 6a4bef661..e06992f60 100644 --- a/ethers-providers/src/rpc/transports/ws/backend.rs +++ b/ethers-providers/src/rpc/transports/ws/backend.rs @@ -88,7 +88,7 @@ impl WsBackend { trace!(%item, "Deserialized message"); let res = self.handler.unbounded_send(item); if res.is_err() { - return Err(WsClientError::DeadChannel) + return Err(WsClientError::DeadChannel); } } Err(e) => { diff --git a/ethers-providers/src/rpc/transports/ws/manager.rs b/ethers-providers/src/rpc/transports/ws/manager.rs index 5f25ad175..46b2a466f 100644 --- a/ethers-providers/src/rpc/transports/ws/manager.rs +++ b/ethers-providers/src/rpc/transports/ws/manager.rs @@ -77,7 +77,7 @@ impl SubscriptionManager { channel, }; // reuse the RPC ID. this is somewhat dirty. - return unsub_request.serialize_raw(id).ok() + return unsub_request.serialize_raw(id).ok(); } tracing::trace!("No current server id"); } @@ -96,7 +96,7 @@ impl SubscriptionManager { server_id = format!("0x{server_id:x}"), "No aliased subscription found" ); - return + return; } let id = id_opt.unwrap(); @@ -236,7 +236,7 @@ impl RequestManager { async fn reconnect(&mut self) -> Result<(), WsClientError> { if self.reconnects == 0 { - return Err(WsClientError::TooManyReconnects) + return Err(WsClientError::TooManyReconnects); } self.reconnects -= 1; diff --git a/ethers-providers/src/rpc/transports/ws/types.rs b/ethers-providers/src/rpc/transports/ws/types.rs index 5dbcc3ab3..055395860 100644 --- a/ethers-providers/src/rpc/transports/ws/types.rs +++ b/ethers-providers/src/rpc/transports/ws/types.rs @@ -67,7 +67,7 @@ impl<'de> Deserialize<'de> for PubSubItem { match key { "jsonrpc" => { if jsonrpc { - return Err(de::Error::duplicate_field("jsonrpc")) + return Err(de::Error::duplicate_field("jsonrpc")); } let value = map.next_value()?; @@ -75,14 +75,14 @@ impl<'de> Deserialize<'de> for PubSubItem { return Err(de::Error::invalid_value( de::Unexpected::Str(value), &"2.0", - )) + )); } jsonrpc = true; } "id" => { if id.is_some() { - return Err(de::Error::duplicate_field("id")) + return Err(de::Error::duplicate_field("id")); } let value: u64 = map.next_value()?; @@ -90,7 +90,7 @@ impl<'de> Deserialize<'de> for PubSubItem { } "result" => { if result.is_some() { - return Err(de::Error::duplicate_field("result")) + return Err(de::Error::duplicate_field("result")); } let value: Box = map.next_value()?; @@ -98,7 +98,7 @@ impl<'de> Deserialize<'de> for PubSubItem { } "error" => { if error.is_some() { - return Err(de::Error::duplicate_field("error")) + return Err(de::Error::duplicate_field("error")); } let value: JsonRpcError = map.next_value()?; @@ -106,7 +106,7 @@ impl<'de> Deserialize<'de> for PubSubItem { } "method" => { if method.is_some() { - return Err(de::Error::duplicate_field("method")) + return Err(de::Error::duplicate_field("method")); } let value: String = map.next_value()?; @@ -114,7 +114,7 @@ impl<'de> Deserialize<'de> for PubSubItem { } "params" => { if params.is_some() { - return Err(de::Error::duplicate_field("params")) + return Err(de::Error::duplicate_field("params")); } let value: Notification = map.next_value()?; @@ -131,7 +131,7 @@ impl<'de> Deserialize<'de> for PubSubItem { // jsonrpc version must be present in all responses if !jsonrpc { - return Err(de::Error::missing_field("jsonrpc")) + return Err(de::Error::missing_field("jsonrpc")); } match (id, result, error, method, params) { diff --git a/ethers-providers/src/stream/tx_stream.rs b/ethers-providers/src/stream/tx_stream.rs index 3444df59f..3067088be 100644 --- a/ethers-providers/src/stream/tx_stream.rs +++ b/ethers-providers/src/stream/tx_stream.rs @@ -101,7 +101,7 @@ where if let Some(tx) = this.buffered.pop_front() { this.push_tx(tx); } else { - break + break; } } @@ -117,7 +117,7 @@ where } Poll::Ready(None) => { this.stream_done = true; - break + break; } _ => break, } @@ -126,12 +126,12 @@ where // poll running futures if let tx @ Poll::Ready(Some(_)) = this.pending.poll_next_unpin(cx) { - return tx + return tx; } if this.stream_done && this.pending.is_empty() { // all done - return Poll::Ready(None) + return Poll::Ready(None); } Poll::Pending @@ -233,7 +233,7 @@ mod tests { sent.iter().map(|tx| tx.transaction_hash).collect::>(); assert_eq!(sent_txs, watch_received.iter().map(|tx| tx.hash).collect()); assert_eq!(sent_txs, sub_received.iter().map(|tx| tx.hash).collect()); - break + break; } } } diff --git a/ethers-providers/src/stream/watcher.rs b/ethers-providers/src/stream/watcher.rs index 8c37ec26f..9ea5e893c 100644 --- a/ethers-providers/src/stream/watcher.rs +++ b/ethers-providers/src/stream/watcher.rs @@ -105,7 +105,7 @@ where // for new logs FilterWatcherState::NextItem(iter) => { if let item @ Some(_) = iter.next() { - return Poll::Ready(item) + return Poll::Ready(item); } FilterWatcherState::WaitForInterval } diff --git a/ethers-providers/src/toolbox/log_query.rs b/ethers-providers/src/toolbox/log_query.rs index f71ab536a..b74551e18 100644 --- a/ethers-providers/src/toolbox/log_query.rs +++ b/ethers-providers/src/toolbox/log_query.rs @@ -136,7 +136,7 @@ where // no more pages to load, and everything is consumed // can safely assume this will always be set in this state if from_block > self.last_block.unwrap() { - return Poll::Ready(None) + return Poll::Ready(None); } // load next page self.from_block = Some(to_block + 1); diff --git a/ethers-providers/src/toolbox/pending_escalator.rs b/ethers-providers/src/toolbox/pending_escalator.rs index b77135257..f8473d650 100644 --- a/ethers-providers/src/toolbox/pending_escalator.rs +++ b/ethers-providers/src/toolbox/pending_escalator.rs @@ -193,7 +193,7 @@ where let fut = this.provider.send_raw_transaction(next_to_broadcast); *this.state = BroadcastingNew(fut); cx.waker().wake_by_ref(); - return Poll::Pending + return Poll::Pending; } } check_all_receipts!(cx, this); diff --git a/ethers-providers/src/toolbox/pending_transaction.rs b/ethers-providers/src/toolbox/pending_transaction.rs index cbe2e0a08..0eb607152 100644 --- a/ethers-providers/src/toolbox/pending_transaction.rs +++ b/ethers-providers/src/toolbox/pending_transaction.rs @@ -183,7 +183,7 @@ impl<'a, P: JsonRpcClient> Future for PendingTransaction<'a, P> { if *this.retries_remaining == 0 { tracing::debug!("Dropped from mempool, pending tx {:?}", *this.tx_hash); *this.state = PendingTxState::Completed; - return Poll::Ready(Ok(None)) + return Poll::Ready(Ok(None)); } *this.retries_remaining -= 1; @@ -242,7 +242,7 @@ impl<'a, P: JsonRpcClient> Future for PendingTransaction<'a, P> { } else { let receipt = receipt.take(); *this.state = PendingTxState::Completed; - return Poll::Ready(Ok(receipt)) + return Poll::Ready(Ok(receipt)); } } PendingTxState::PausedGettingBlockNumber(receipt) => { @@ -273,7 +273,7 @@ impl<'a, P: JsonRpcClient> Future for PendingTransaction<'a, P> { if current_block > inclusion_block + *this.confirmations - 1 { let receipt = Some(receipt); *this.state = PendingTxState::Completed; - return Poll::Ready(Ok(receipt)) + return Poll::Ready(Ok(receipt)); } else { tracing::trace!(tx_hash = ?this.tx_hash, "confirmations {}/{}", current_block - inclusion_block + 1, this.confirmations); *this.state = PendingTxState::PausedGettingBlockNumber(Some(receipt)); diff --git a/ethers-signers/src/ledger/app.rs b/ethers-signers/src/ledger/app.rs index 2f4125eb2..6b7927bda 100644 --- a/ethers-signers/src/ledger/app.rs +++ b/ethers-signers/src/ledger/app.rs @@ -125,7 +125,7 @@ impl LedgerEthereum { let answer = block_on(transport.exchange(&command))?; let result = answer.data().ok_or(LedgerError::UnexpectedNullResponse)?; if result.len() < 4 { - return Err(LedgerError::ShortResponse { got: result.len(), at_least: 4 }) + return Err(LedgerError::ShortResponse { got: result.len(), at_least: 4 }); } let version = format!("{}.{}.{}", result[1], result[2], result[3]); tracing::debug!(version, "Retrieved version from device"); @@ -190,7 +190,7 @@ impl LedgerEthereum { // Enforce app version is greater than EIP712_MIN_VERSION if !req.matches(&version) { - return Err(LedgerError::UnsupportedAppVersion(EIP712_MIN_VERSION.to_string())) + return Err(LedgerError::UnsupportedAppVersion(EIP712_MIN_VERSION.to_string())); } let domain_separator = @@ -214,7 +214,7 @@ impl LedgerEthereum { payload: &Vec, ) -> Result { if payload.is_empty() { - return Err(LedgerError::EmptyPayload) + return Err(LedgerError::EmptyPayload); } let transport = self.transport.lock().await; let mut command = APDUCommand { @@ -244,7 +244,7 @@ impl LedgerEthereum { let data = answer.as_ref().expect("just assigned").data(); if data.is_none() { - return Err(LedgerError::UnexpectedNullResponse) + return Err(LedgerError::UnexpectedNullResponse); } tracing::debug!( response = hex::encode(data.expect("just checked")), @@ -258,7 +258,7 @@ impl LedgerEthereum { let answer = answer.expect("payload is non-empty, therefore loop ran"); let result = answer.data().expect("check in loop"); if result.len() < 65 { - return Err(LedgerError::ShortResponse { got: result.len(), at_least: 65 }) + return Err(LedgerError::ShortResponse { got: result.len(), at_least: 65 }); } let v = result[0] as u64; let r = U256::from_big_endian(&result[1..33]); diff --git a/ethers-signers/src/trezor/app.rs b/ethers-signers/src/trezor/app.rs index e8fb1e297..b2113f5ea 100644 --- a/ethers-signers/src/trezor/app.rs +++ b/ethers-signers/src/trezor/app.rs @@ -88,7 +88,7 @@ impl TrezorEthereum { let req = semver::VersionReq::parse(min_version)?; // Enforce firmware version is greater than "min_version" if !req.matches(&version) { - return Err(TrezorError::UnsupportedFirmwareVersion(min_version.to_string())) + return Err(TrezorError::UnsupportedFirmwareVersion(min_version.to_string())); } Ok(()) diff --git a/ethers-signers/src/wallet/private_key.rs b/ethers-signers/src/wallet/private_key.rs index e90578502..0cb5f30fe 100644 --- a/ethers-signers/src/wallet/private_key.rs +++ b/ethers-signers/src/wallet/private_key.rs @@ -101,9 +101,9 @@ impl Wallet { impl PartialEq for Wallet { fn eq(&self, other: &Self) -> bool { - self.signer.to_bytes().eq(&other.signer.to_bytes()) && - self.address == other.address && - self.chain_id == other.chain_id + self.signer.to_bytes().eq(&other.signer.to_bytes()) + && self.address == other.address + && self.chain_id == other.chain_id } } @@ -134,7 +134,7 @@ impl FromStr for Wallet { let src = hex::decode(src)?; if src.len() != 32 { - return Err(WalletError::HexError(hex::FromHexError::InvalidStringLength)) + return Err(WalletError::HexError(hex::FromHexError::InvalidStringLength)); } let sk = SigningKey::from_bytes(src.as_slice().into())?; diff --git a/ethers-solc/src/artifact_output/configurable.rs b/ethers-solc/src/artifact_output/configurable.rs index 0c87731d0..03ddd5786 100644 --- a/ethers-solc/src/artifact_output/configurable.rs +++ b/ethers-solc/src/artifact_output/configurable.rs @@ -152,7 +152,7 @@ pub struct ConfigurableArtifacts { /// _always_ be done using a public constructor or update syntax: /// /// ```rust - /// + /// /// use ethers_solc::{ExtraOutputFiles, ConfigurableArtifacts}; /// let config = ConfigurableArtifacts { /// additional_files: ExtraOutputFiles { metadata: true, ..Default::default() }, @@ -395,7 +395,7 @@ pub struct ExtraOutputValues { /// _always_ be done using a public constructor or update syntax: /// /// ```rust - /// + /// /// use ethers_solc::ExtraOutputValues; /// let config = ExtraOutputValues { /// ir: true, @@ -516,7 +516,7 @@ pub struct ExtraOutputFiles { /// _always_ be done using a public constructor or update syntax: /// /// ```rust - /// + /// /// use ethers_solc::ExtraOutputFiles; /// let config = ExtraOutputFiles { /// metadata: true, @@ -584,8 +584,8 @@ impl ExtraOutputFiles { EvmOutputSelection::ByteCode(BytecodeOutputSelection::SourceMap) => { config.source_map = true; } - EvmOutputSelection::DeployedByteCode(DeployedBytecodeOutputSelection::All) | - EvmOutputSelection::DeployedByteCode( + EvmOutputSelection::DeployedByteCode(DeployedBytecodeOutputSelection::All) + | EvmOutputSelection::DeployedByteCode( DeployedBytecodeOutputSelection::Object, ) => { config.deployed_bytecode = true; diff --git a/ethers-solc/src/artifact_output/mod.rs b/ethers-solc/src/artifact_output/mod.rs index 5f7b2bc3d..1a30fd9be 100644 --- a/ethers-solc/src/artifact_output/mod.rs +++ b/ethers-solc/src/artifact_output/mod.rs @@ -670,7 +670,7 @@ pub trait ArtifactOutput { let out_path = artifacts_folder.join(&candidate); if !already_taken.contains(&out_path) { trace!("found alternative output file={:?} for {:?}", out_path, contract_file); - return out_path + return out_path; } current_parent = current_parent.and_then(|f| f.parent()); } @@ -700,7 +700,7 @@ pub trait ArtifactOutput { .collect(); if !already_taken.contains(&candidate) { trace!("found alternative output file={:?} for {:?}", candidate, contract_file); - return candidate + return candidate; } num += 1; @@ -841,8 +841,8 @@ pub trait ArtifactOutput { // we keep the top most conflicting file unchanged let is_top_most = contracts.iter().enumerate().filter(|(i, _)| *i != idx).all(|(_, c)| { - Path::new(file).components().count() < - Path::new(c.file).components().count() + Path::new(file).components().count() + < Path::new(c.file).components().count() }); if !is_top_most { // we resolve the conflicting by finding a new unique, alternative path @@ -886,10 +886,10 @@ pub trait ArtifactOutput { // source units // there's also no need to create a standalone artifact for source files that // don't contain an ast - if source.source_file.contains_contract_definition() || - source.source_file.ast.is_none() + if source.source_file.contains_contract_definition() + || source.source_file.ast.is_none() { - continue + continue; } // we use file and file stem diff --git a/ethers-solc/src/artifacts/bytecode.rs b/ethers-solc/src/artifacts/bytecode.rs index 635aba3c0..eaac67025 100644 --- a/ethers-solc/src/artifacts/bytecode.rs +++ b/ethers-solc/src/artifacts/bytecode.rs @@ -71,7 +71,7 @@ impl CompactBytecode { address: Address, ) -> bool { if !self.object.is_unlinked() { - return true + return true; } let file = file.as_ref(); @@ -84,7 +84,7 @@ impl CompactBytecode { self.link_references.insert(key, contracts); } if self.link_references.is_empty() { - return self.object.resolve().is_some() + return self.object.resolve().is_some(); } } false @@ -156,7 +156,7 @@ impl Bytecode { address: Address, ) -> bool { if !self.object.is_unlinked() { - return true + return true; } let file = file.as_ref(); @@ -169,7 +169,7 @@ impl Bytecode { self.link_references.insert(key, contracts); } if self.link_references.is_empty() { - return self.object.resolve().is_some() + return self.object.resolve().is_some(); } } false @@ -184,7 +184,7 @@ impl Bytecode { { for (file, lib, addr) in libs.into_iter() { if self.link(file, lib, addr) { - return true + return true; } } false @@ -198,7 +198,7 @@ impl Bytecode { { for (name, addr) in libs.into_iter() { if self.link_fully_qualified(name, addr) { - return true + return true; } } false @@ -339,8 +339,8 @@ impl BytecodeObject { pub fn contains_fully_qualified_placeholder(&self, name: impl AsRef) -> bool { if let BytecodeObject::Unlinked(unlinked) = self { let name = name.as_ref(); - unlinked.contains(&utils::library_hash_placeholder(name)) || - unlinked.contains(&utils::library_fully_qualified_placeholder(name)) + unlinked.contains(&utils::library_hash_placeholder(name)) + || unlinked.contains(&utils::library_fully_qualified_placeholder(name)) } else { false } diff --git a/ethers-solc/src/artifacts/contract.rs b/ethers-solc/src/artifacts/contract.rs index d0a51fe2a..9e0921a73 100644 --- a/ethers-solc/src/artifacts/contract.rs +++ b/ethers-solc/src/artifacts/contract.rs @@ -236,7 +236,7 @@ impl TryFrom for ContractBytecodeSome { fn try_from(value: ContractBytecode) -> Result { if value.abi.is_none() || value.bytecode.is_none() || value.deployed_bytecode.is_none() { - return Err(value) + return Err(value); } Ok(value.unwrap()) } @@ -258,7 +258,7 @@ impl TryFrom for CompactContractSome { fn try_from(value: CompactContract) -> Result { if value.abi.is_none() || value.bin.is_none() || value.bin_runtime.is_none() { - return Err(value) + return Err(value); } Ok(value.unwrap()) } @@ -448,7 +448,7 @@ impl<'a> TryFrom> for CompactContractRefSome<'a> { fn try_from(value: CompactContractRef<'a>) -> Result { if value.abi.is_none() || value.bin.is_none() || value.bin_runtime.is_none() { - return Err(value) + return Err(value); } Ok(value.unwrap()) } diff --git a/ethers-solc/src/artifacts/mod.rs b/ethers-solc/src/artifacts/mod.rs index 835cf777c..304924a7b 100644 --- a/ethers-solc/src/artifacts/mod.rs +++ b/ethers-solc/src/artifacts/mod.rs @@ -567,7 +567,7 @@ impl Libraries { if items.next().is_some() { return Err(SolcError::msg(format!( "failed to parse, too many arguments passed: {lib}" - ))) + ))); } libraries .entry(file.into()) @@ -700,15 +700,15 @@ pub struct OptimizerDetails { impl OptimizerDetails { /// Returns true if no settings are set. pub fn is_empty(&self) -> bool { - self.peephole.is_none() && - self.inliner.is_none() && - self.jumpdest_remover.is_none() && - self.order_literals.is_none() && - self.deduplicate.is_none() && - self.cse.is_none() && - self.constant_optimizer.is_none() && - self.yul.is_none() && - self.yul_details.as_ref().map(|yul| yul.is_empty()).unwrap_or(true) + self.peephole.is_none() + && self.inliner.is_none() + && self.jumpdest_remover.is_none() + && self.order_literals.is_none() + && self.deduplicate.is_none() + && self.cse.is_none() + && self.constant_optimizer.is_none() + && self.yul.is_none() + && self.yul_details.as_ref().map(|yul| yul.is_empty()).unwrap_or(true) } } @@ -1905,7 +1905,7 @@ impl fmt::Display for Error { let msg = self.formatted_message.as_ref().unwrap_or(&self.message); self.fmt_severity(f)?; f.write_str(": ")?; - return f.write_str(msg) + return f.write_str(msg); } // Error (XXXX): Error Message @@ -2075,7 +2075,7 @@ fn fmt_framed_location( if let Some((space_or_line_number, rest)) = line.split_once('|') { // if the potential frame is not just whitespace or numbers, don't color it if !space_or_line_number.chars().all(|c| c.is_whitespace() || c.is_numeric()) { - return f.write_str(line) + return f.write_str(line); } styled(f, Error::frame_style(), |f| { @@ -2192,7 +2192,7 @@ impl SourceFile { pub fn contains_contract_definition(&self) -> bool { if let Some(ref ast) = self.ast { // contract definitions are only allowed at the source-unit level - return ast.nodes.iter().any(|node| node.node_type == NodeType::ContractDefinition) + return ast.nodes.iter().any(|node| node.node_type == NodeType::ContractDefinition); // abstract contract, interfaces: ContractDefinition } diff --git a/ethers-solc/src/artifacts/output_selection.rs b/ethers-solc/src/artifacts/output_selection.rs index 769b4d4bb..b1b835073 100644 --- a/ethers-solc/src/artifacts/output_selection.rs +++ b/ethers-solc/src/artifacts/output_selection.rs @@ -482,11 +482,11 @@ impl FromStr for DeployedBytecodeOutputSelection { "evm.deployedBytecode.functionDebugData" => { Ok(DeployedBytecodeOutputSelection::FunctionDebugData) } - "deployed-code" | - "deployed-bin" | - "runtime-code" | - "runtime-bin" | - "evm.deployedBytecode.object" => Ok(DeployedBytecodeOutputSelection::Object), + "deployed-code" + | "deployed-bin" + | "runtime-code" + | "runtime-bin" + | "evm.deployedBytecode.object" => Ok(DeployedBytecodeOutputSelection::Object), "evm.deployedBytecode.opcodes" => Ok(DeployedBytecodeOutputSelection::Opcodes), "evm.deployedBytecode.sourceMap" => Ok(DeployedBytecodeOutputSelection::SourceMap), "evm.deployedBytecode.linkReferences" => { diff --git a/ethers-solc/src/artifacts/serde_helpers.rs b/ethers-solc/src/artifacts/serde_helpers.rs index c24c263be..2bbbe3c11 100644 --- a/ethers-solc/src/artifacts/serde_helpers.rs +++ b/ethers-solc/src/artifacts/serde_helpers.rs @@ -63,7 +63,7 @@ pub mod json_string_opt { { if let Some(s) = Option::::deserialize(deserializer)? { if s.is_empty() { - return Ok(None) + return Ok(None); } let value = serde_json::Value::String(s); serde_json::from_value(value).map_err(de::Error::custom).map(Some) @@ -100,10 +100,10 @@ pub mod empty_json_object_opt { { let json = serde_json::Value::deserialize(deserializer)?; if json.is_null() { - return Ok(None) + return Ok(None); } if json.as_object().map(|obj| obj.is_empty()).unwrap_or_default() { - return Ok(None) + return Ok(None); } serde_json::from_value(json).map_err(de::Error::custom).map(Some) } diff --git a/ethers-solc/src/cache.rs b/ethers-solc/src/cache.rs index b0586712c..2d99a0324 100644 --- a/ethers-solc/src/cache.rs +++ b/ethers-solc/src/cache.rs @@ -332,13 +332,13 @@ impl SolFilesCache { if entry.artifacts.is_empty() { // keep entries that didn't emit any artifacts in the first place, such as a // solidity file that only includes error definitions - return true + return true; } if let Some(versions) = files.remove(file.as_path()) { entry.retain_versions(versions); } else { - return false + return false; } !entry.artifacts.is_empty() }); @@ -721,8 +721,8 @@ impl<'a, T: ArtifactOutput> ArtifactsCacheInner<'a, T> { version: &Version, ) -> FilteredSourceInfo { let idx = self.edges.node_id(&file); - if !self.is_dirty(&file, version) && - self.edges.imports(&file).iter().all(|file| !self.is_dirty(file, version)) + if !self.is_dirty(&file, version) + && self.edges.imports(&file).iter().all(|file| !self.is_dirty(file, version)) { FilteredSourceInfo { file, source, idx, dirty: false } } else { @@ -736,11 +736,11 @@ impl<'a, T: ArtifactOutput> ArtifactsCacheInner<'a, T> { if let Some(entry) = self.cache.entry(file) { if entry.content_hash.as_bytes() != hash.as_bytes() { tracing::trace!("changed content hash for source file \"{}\"", file.display()); - return true + return true; } if self.project.solc_config != entry.solc_config { tracing::trace!("changed solc config for source file \"{}\"", file.display()); - return true + return true; } // only check artifact's existence if the file generated artifacts. @@ -753,7 +753,7 @@ impl<'a, T: ArtifactOutput> ArtifactsCacheInner<'a, T> { file.display(), version ); - return true + return true; } if entry.artifacts_for_version(version).any(|artifact_path| { @@ -763,11 +763,11 @@ impl<'a, T: ArtifactOutput> ArtifactsCacheInner<'a, T> { } missing_artifact }) { - return true + return true; } } // all things match, can be reused - return false + return false; } tracing::trace!("Missing cache entry for {}", file.display()); } else { @@ -812,7 +812,7 @@ impl<'a, T: ArtifactOutput> ArtifactsCache<'a, T> { if let Ok(cache) = SolFilesCache::read_joined(&project.paths) { if cache.paths == paths { // unchanged project paths - return cache + return cache; } } } diff --git a/ethers-solc/src/compile/mod.rs b/ethers-solc/src/compile/mod.rs index b513e8e7a..99eda0528 100644 --- a/ethers-solc/src/compile/mod.rs +++ b/ethers-solc/src/compile/mod.rs @@ -164,7 +164,7 @@ pub struct Solc { impl Default for Solc { fn default() -> Self { if let Ok(solc) = std::env::var("SOLC_PATH") { - return Solc::new(solc) + return Solc::new(solc); } #[cfg(not(target_arch = "wasm32"))] { @@ -172,7 +172,7 @@ impl Default for Solc { .and_then(|vers| Solc::find_svm_installed_version(vers.to_string()).ok()) .flatten() { - return solc + return solc; } } @@ -302,7 +302,7 @@ impl Solc { .join(format!("solc-{version}")); if !solc.is_file() { - return Ok(None) + return Ok(None); } Ok(Some(Solc::new(solc))) } @@ -472,7 +472,7 @@ impl Solc { if !RELEASES.2 { // we skip checksum verification because the underlying request to fetch release info // failed so we have nothing to compare against - return Ok(()) + return Ok(()); } use sha2::Digest; diff --git a/ethers-solc/src/compile/output/info.rs b/ethers-solc/src/compile/output/info.rs index 1d2be6d61..58a895a2a 100644 --- a/ethers-solc/src/compile/output/info.rs +++ b/ethers-solc/src/compile/output/info.rs @@ -63,7 +63,7 @@ impl FromStr for ContractInfo { let path = iter.next().map(str::to_string); if name.ends_with(".sol") || name.contains('/') { - return Err(err()) + return Err(err()); } Ok(Self { path, name }) diff --git a/ethers-solc/src/compile/output/mod.rs b/ethers-solc/src/compile/output/mod.rs index 3f9d29fce..373dca405 100644 --- a/ethers-solc/src/compile/output/mod.rs +++ b/ethers-solc/src/compile/output/mod.rs @@ -282,7 +282,7 @@ impl ProjectCompileOutput { let contract_path = path.as_ref(); let contract_name = contract.as_ref(); if let artifact @ Some(_) = self.compiled_artifacts.find(contract_path, contract_name) { - return artifact + return artifact; } self.cached_artifacts.find(contract_path, contract_name) } @@ -291,7 +291,7 @@ impl ProjectCompileOutput { pub fn find_first(&self, contract_name: impl AsRef) -> Option<&T::Artifact> { let contract_name = contract_name.as_ref(); if let artifact @ Some(_) = self.compiled_artifacts.find_first(contract_name) { - return artifact + return artifact; } self.cached_artifacts.find_first(contract_name) } @@ -316,7 +316,7 @@ impl ProjectCompileOutput { let contract_path = path.as_ref(); let contract_name = contract.as_ref(); if let artifact @ Some(_) = self.compiled_artifacts.remove(contract_path, contract_name) { - return artifact + return artifact; } self.cached_artifacts.remove(contract_path, contract_name) } @@ -336,7 +336,7 @@ impl ProjectCompileOutput { pub fn remove_first(&mut self, contract_name: impl AsRef) -> Option { let contract_name = contract_name.as_ref(); if let artifact @ Some(_) = self.compiled_artifacts.remove_first(contract_name) { - return artifact + return artifact; } self.cached_artifacts.remove_first(contract_name) } @@ -439,9 +439,9 @@ impl AggregatedCompilerOutput { self.errors.iter().any(|err| { if compiler_severity_filter.ge(&err.severity) { if compiler_severity_filter.is_warning() { - return self.has_warning(ignored_error_codes) + return self.has_warning(ignored_error_codes); } - return true + return true; } false }) @@ -510,7 +510,7 @@ impl AggregatedCompilerOutput { /// file name pub fn write_build_infos(&self, build_info_dir: impl AsRef) -> Result<(), SolcIoError> { if self.build_infos.is_empty() { - return Ok(()) + return Ok(()); } let build_info_dir = build_info_dir.as_ref(); std::fs::create_dir_all(build_info_dir) @@ -741,7 +741,7 @@ impl<'a> OutputDiagnostics<'a> { /// Returns true if the contract is a expected to be a test fn is_test>(&self, contract_path: T) -> bool { if contract_path.as_ref().ends_with(".t.sol") { - return true + return true; } self.compiler_output.find_first(&contract_path).map_or(false, |contract| { diff --git a/ethers-solc/src/compile/project.rs b/ethers-solc/src/compile/project.rs index 1ea58ef09..5b3e0b7a6 100644 --- a/ethers-solc/src/compile/project.rs +++ b/ethers-solc/src/compile/project.rs @@ -506,7 +506,7 @@ fn compile_sequential( if filtered_sources.is_empty() { // nothing to compile trace!("skip solc {} {} for empty sources set", solc.as_ref().display(), version); - continue + continue; } trace!( "compiling {} sources with solc \"{}\" {:?}", @@ -538,7 +538,7 @@ fn compile_sequential( version, input.language ); - continue + continue; } let input = input .settings(opt_settings.clone()) @@ -591,7 +591,7 @@ fn compile_parallel( if filtered_sources.is_empty() { // nothing to compile trace!("skip solc {} {} for empty sources set", solc.as_ref().display(), version); - continue + continue; } let dirty_files: Vec = filtered_sources.dirty_files().cloned().collect(); @@ -617,7 +617,7 @@ fn compile_parallel( version, input.language ); - continue + continue; } let job = input diff --git a/ethers-solc/src/config.rs b/ethers-solc/src/config.rs index e400e231f..d7b5c4ab9 100644 --- a/ethers-solc/src/config.rs +++ b/ethers-solc/src/config.rs @@ -191,19 +191,19 @@ impl ProjectPathsConfig { let file = file.as_ref(); for lib in &self.libraries { - if lib.is_relative() && - file.is_absolute() && - file.starts_with(&self.root) && - file.starts_with(self.root.join(lib)) || - file.is_relative() && - lib.is_absolute() && - lib.starts_with(&self.root) && - self.root.join(file).starts_with(lib) + if lib.is_relative() + && file.is_absolute() + && file.starts_with(&self.root) + && file.starts_with(self.root.join(lib)) + || file.is_relative() + && lib.is_absolute() + && lib.starts_with(&self.root) + && self.root.join(file).starts_with(lib) { - return Some(lib) + return Some(lib); } if file.starts_with(lib) { - return Some(lib) + return Some(lib); } } @@ -247,14 +247,14 @@ impl ProjectPathsConfig { { // track the path for this absolute import inside a nested library include_paths.insert(include_path); - return Ok(import) + return Ok(import); } } // also try to resolve absolute imports from the project paths for path in [&self.root, &self.sources, &self.tests, &self.scripts] { if cwd.starts_with(path) { if let Ok(import) = utils::canonicalize(path.join(import)) { - return Ok(import) + return Ok(import); } } } @@ -336,7 +336,7 @@ impl ProjectPathsConfig { // (`/=.../contracts`) and the stripped import also starts with `contracts` if let Ok(adjusted_import) = stripped_import.strip_prefix("contracts/") { if r.path.ends_with("contracts/") && !lib_path.exists() { - return Path::new(&r.path).join(adjusted_import) + return Path::new(&r.path).join(adjusted_import); } } lib_path @@ -416,7 +416,7 @@ impl ProjectPathsConfig { if imported.contains(target_index) { // short circuit nodes that were already imported, if both A.sol and B.sol import C.sol - return Ok(String::new()) + return Ok(String::new()); } imported.insert(*target_index); @@ -437,7 +437,7 @@ impl ProjectPathsConfig { let mut replace_offset = 0; for cap in name_regex.captures_iter(&content.clone()) { if cap.name("ignore").is_some() { - continue + continue; } if let Some(name_match) = vec!["n1", "n2", "n3"].iter().find_map(|name| cap.name(name)) @@ -866,7 +866,7 @@ impl AllowedLibPaths { pub fn args(&self) -> Option<[String; 2]> { let args = self.to_string(); if args.is_empty() { - return None + return None; } Some(["--allow-paths".to_string(), args]) } diff --git a/ethers-solc/src/lib.rs b/ethers-solc/src/lib.rs index 10185c91d..c4c541190 100644 --- a/ethers-solc/src/lib.rs +++ b/ethers-solc/src/lib.rs @@ -271,7 +271,7 @@ impl Project { #[cfg(all(feature = "svm-solc", not(target_arch = "wasm32")))] if self.auto_detect { tracing::trace!("using solc auto detection to compile sources"); - return self.svm_compile(sources) + return self.svm_compile(sources); } self.compile_with_version(&self.solc, sources) @@ -348,7 +348,7 @@ impl Project { #[cfg(all(feature = "svm-solc", not(target_arch = "wasm32")))] if self.auto_detect { - return project::ProjectCompiler::with_sources(self, sources)?.compile() + return project::ProjectCompiler::with_sources(self, sources)?.compile(); } let solc = self.configure_solc(self.solc.clone()); @@ -397,7 +397,7 @@ impl Project { if self.auto_detect { return project::ProjectCompiler::with_sources(self, sources)? .with_sparse_output(filter) - .compile() + .compile(); } project::ProjectCompiler::with_sources_and_solc(self, sources, self.solc.clone())? diff --git a/ethers-solc/src/remappings.rs b/ethers-solc/src/remappings.rs index bc403bb85..595c0b0a3 100644 --- a/ethers-solc/src/remappings.rs +++ b/ethers-solc/src/remappings.rs @@ -83,10 +83,10 @@ impl FromStr for Remapping { .split_once('=') .ok_or_else(|| RemappingError::InvalidRemapping(remapping.to_string()))?; if name.trim().is_empty() { - return Err(RemappingError::EmptyRemappingKey(remapping.to_string())) + return Err(RemappingError::EmptyRemappingKey(remapping.to_string())); } if path.trim().is_empty() { - return Err(RemappingError::EmptyRemappingValue(remapping.to_string())) + return Err(RemappingError::EmptyRemappingValue(remapping.to_string())); } Ok(Remapping { name: name.to_string(), path: path.to_string() }) } @@ -179,9 +179,9 @@ impl Remapping { fn insert_prioritized(mappings: &mut HashMap, key: String, path: PathBuf) { match mappings.entry(key) { Entry::Occupied(mut e) => { - if e.get().components().count() > path.components().count() || - (path.ends_with(DAPPTOOLS_CONTRACTS_DIR) && - !e.get().ends_with(DAPPTOOLS_CONTRACTS_DIR)) + if e.get().components().count() > path.components().count() + || (path.ends_with(DAPPTOOLS_CONTRACTS_DIR) + && !e.get().ends_with(DAPPTOOLS_CONTRACTS_DIR)) { e.insert(path); } @@ -353,7 +353,7 @@ impl RelativeRemappingPathBuf { /// path has a root. pub fn relative(&self) -> PathBuf { if self.original().has_root() { - return self.original().into() + return self.original().into(); } self.parent .as_ref() @@ -506,11 +506,11 @@ impl Candidate { // if the window start and the source dir are the same directory we can end early if // we wrongfully detect something like: `/src/lib/` - if current_level > 0 && - source_dir == window_start && - (is_source_dir(&source_dir) || is_lib_dir(&source_dir)) + if current_level > 0 + && source_dir == window_start + && (is_source_dir(&source_dir) || is_lib_dir(&source_dir)) { - return + return; } candidates.push(Candidate { window_start, source_dir, window_level: current_level }); } @@ -588,9 +588,9 @@ fn find_remapping_candidates( let entry: walkdir::DirEntry = entry; // found a solidity file directly the current dir - if !is_candidate && - entry.file_type().is_file() && - entry.path().extension() == Some("sol".as_ref()) + if !is_candidate + && entry.file_type().is_file() + && entry.path().extension() == Some("sol".as_ref()) { is_candidate = true; } else if entry.file_type().is_dir() { @@ -605,11 +605,11 @@ fn find_remapping_candidates( if entry.path_is_symlink() { if let Ok(target) = utils::canonicalize(entry.path()) { // the symlink points to a parent dir of the current window - if open.components().count() > target.components().count() && - utils::common_ancestor(open, &target).is_some() + if open.components().count() > target.components().count() + && utils::common_ancestor(open, &target).is_some() { // short-circuiting - return Vec::new() + return Vec::new(); } } } @@ -649,12 +649,12 @@ fn find_remapping_candidates( // need to find the actual next window in the event `open` is a lib dir let window_start = next_nested_window(open, current_dir); // finally, we need to merge, adjust candidates from the same level and opening window - if is_candidate || - candidates + if is_candidate + || candidates .iter() .filter(|c| c.window_level == current_level && c.window_start == window_start) - .count() > - 1 + .count() + > 1 { Candidate::merge_on_same_level( &mut candidates, @@ -672,8 +672,8 @@ fn find_remapping_candidates( let distance = dir_distance(&candidate.window_start, &candidate.source_dir); if distance > 1 && candidate.source_dir_ends_with_js_source() { candidate.source_dir = window_start; - } else if !is_source_dir(&candidate.source_dir) && - candidate.source_dir != candidate.window_start + } else if !is_source_dir(&candidate.source_dir) + && candidate.source_dir != candidate.window_start { candidate.source_dir = last_nested_source_dir(open, &candidate.source_dir); } @@ -686,7 +686,7 @@ fn find_remapping_candidates( /// `dir_distance("root/a", "root/a/b/c") == 2` fn dir_distance(root: &Path, current: &Path) -> usize { if root == current { - return 0 + return 0; } if let Ok(rem) = current.strip_prefix(root) { rem.components().count() @@ -700,14 +700,14 @@ fn dir_distance(root: &Path, current: &Path) -> usize { /// window opener is found fn next_nested_window(root: &Path, current: &Path) -> PathBuf { if !is_lib_dir(root) || root == current { - return root.to_path_buf() + return root.to_path_buf(); } if let Ok(rem) = current.strip_prefix(root) { let mut p = root.to_path_buf(); for c in rem.components() { let next = p.join(c); if !is_lib_dir(&next) || !next.ends_with(JS_CONTRACTS_DIR) { - return next + return next; } p = next } @@ -718,15 +718,15 @@ fn next_nested_window(root: &Path, current: &Path) -> PathBuf { /// Finds the last valid source directory in the window (root -> dir) fn last_nested_source_dir(root: &Path, dir: &Path) -> PathBuf { if is_source_dir(dir) { - return dir.to_path_buf() + return dir.to_path_buf(); } let mut p = dir; while let Some(parent) = p.parent() { if parent == root { - return root.to_path_buf() + return root.to_path_buf(); } if is_source_dir(parent) { - return parent.to_path_buf() + return parent.to_path_buf(); } p = parent; } diff --git a/ethers-solc/src/report/mod.rs b/ethers-solc/src/report/mod.rs index 99cd60f9e..dc83be3b3 100644 --- a/ethers-solc/src/report/mod.rs +++ b/ethers-solc/src/report/mod.rs @@ -220,7 +220,7 @@ pub(crate) fn unresolved_imports(imports: &[(&Path, &Path)], remappings: &[Remap fn get_global() -> Option<&'static Report> { if GLOBAL_REPORTER_STATE.load(Ordering::SeqCst) != SET { - return None + return None; } unsafe { // This is safe given the invariant that setting the global reporter @@ -240,7 +240,7 @@ where if SCOPED_COUNT.load(Ordering::Acquire) == 0 { // fast path if no scoped reporter has been set; use the global // default. - return if let Some(glob) = get_global() { f(glob) } else { f(&Report::none()) } + return if let Some(glob) = get_global() { f(glob) } else { f(&Report::none()) }; } get_default_scoped(f) @@ -391,7 +391,7 @@ impl Reporter for BasicStdoutReporter { fn on_unresolved_imports(&self, imports: &[(&Path, &Path)], remappings: &[Remapping]) { if imports.is_empty() { - return + return; } println!("{}", format_unresolved_imports(imports, remappings)) } diff --git a/ethers-solc/src/resolver/mod.rs b/ethers-solc/src/resolver/mod.rs index 16f7d1d61..094748f17 100644 --- a/ethers-solc/src/resolver/mod.rs +++ b/ethers-solc/src/resolver/mod.rs @@ -376,8 +376,8 @@ impl Graph { add_node(&mut unresolved, &mut index, &mut resolved_imports, import) .map_err(|err| { match err { - err @ SolcError::ResolveCaseSensitiveFileName { .. } | - err @ SolcError::Resolve(_) => { + err @ SolcError::ResolveCaseSensitiveFileName { .. } + | err @ SolcError::Resolve(_) => { // make the error more helpful by providing additional // context SolcError::FailedResolveImport( @@ -466,7 +466,7 @@ impl Graph { // keep track of processed dependencies, if the dep was already in the set we have // processed it already if !processed_sources.insert(dep) { - continue + continue; } // library import @@ -547,7 +547,7 @@ impl Graph { } if candidates.is_empty() { // nothing to filter anymore - return + return; } } } @@ -668,7 +668,7 @@ impl Graph { mut sets: Vec<&HashSet<&'a crate::SolcVersion>>, ) -> Vec<&'a crate::SolcVersion> { if sets.is_empty() { - return Vec::new() + return Vec::new(); } let mut result = sets.pop().cloned().expect("not empty; qed."); @@ -706,7 +706,7 @@ impl Graph { "resolved solc version compatible with all sources \"{}\"", exact_version ); - return HashMap::from([(exact_version, all_nodes)]) + return HashMap::from([(exact_version, all_nodes)]); } // no version satisfies all nodes @@ -799,7 +799,7 @@ impl VersionedSources { if self.offline { return Err(SolcError::msg(format!( "missing solc \"{version}\" installation in offline mode" - ))) + ))); } else { // install missing solc Solc::blocking_install(version.as_ref())? @@ -922,7 +922,7 @@ impl Node { Err(SourceVersionError::NoMatchingVersionOffline(req)) } else { Err(SourceVersionError::NoMatchingVersion(req)) - } + }; } Ok(()) diff --git a/ethers-solc/src/resolver/tree.rs b/ethers-solc/src/resolver/tree.rs index 96f58a785..e140c3ab1 100644 --- a/ethers-solc/src/resolver/tree.rs +++ b/ethers-solc/src/resolver/tree.rs @@ -111,7 +111,7 @@ fn print_node( writeln!(out, "{}{star}", graph.display_node(node_index))?; if !new_node || in_cycle { - return Ok(()) + return Ok(()); } write_stack.push(node_index); @@ -145,7 +145,7 @@ fn print_imports( ) -> io::Result<()> { let imports = graph.imported_nodes(node_index); if imports.is_empty() { - return Ok(()) + return Ok(()); } let mut iter = imports.iter().peekable(); diff --git a/ethers-solc/src/sourcemap.rs b/ethers-solc/src/sourcemap.rs index f9b758443..1be14c13f 100644 --- a/ethers-solc/src/sourcemap.rs +++ b/ethers-solc/src/sourcemap.rs @@ -79,13 +79,13 @@ impl<'input> TokenStream<'input> { loop { if let Some((_, ch)) = self.chars.peek().cloned() { if !ch.is_ascii_digit() { - break + break; } self.chars.next(); end += 1; } else { end = self.input.len(); - break + break; } } Some(Ok((Token::Number(&self.input[start..end]), start))) @@ -201,13 +201,13 @@ struct SourceElementBuilder { impl fmt::Display for SourceElementBuilder { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - if self.offset.is_none() && - self.length.is_none() && - self.index.is_none() && - self.jump.is_none() && - self.modifier_depth.is_none() + if self.offset.is_none() + && self.length.is_none() + && self.index.is_none() + && self.jump.is_none() + && self.modifier_depth.is_none() { - return Ok(()) + return Ok(()); } if let Some(s) = self.offset { @@ -217,12 +217,12 @@ impl fmt::Display for SourceElementBuilder { s.fmt(f)?; } } - if self.length.is_none() && - self.index.is_none() && - self.jump.is_none() && - self.modifier_depth.is_none() + if self.length.is_none() + && self.index.is_none() + && self.jump.is_none() + && self.modifier_depth.is_none() { - return Ok(()) + return Ok(()); } f.write_char(':')?; @@ -234,7 +234,7 @@ impl fmt::Display for SourceElementBuilder { } } if self.index.is_none() && self.jump.is_none() && self.modifier_depth.is_none() { - return Ok(()) + return Ok(()); } f.write_char(':')?; @@ -243,7 +243,7 @@ impl fmt::Display for SourceElementBuilder { s.fmt(f)?; } if self.jump.is_none() && self.modifier_depth.is_none() { - return Ok(()) + return Ok(()); } f.write_char(':')?; @@ -251,7 +251,7 @@ impl fmt::Display for SourceElementBuilder { s.fmt(f)?; } if self.modifier_depth.is_none() { - return Ok(()) + return Ok(()); } f.write_char(':')?; @@ -291,7 +291,7 @@ impl SourceElementBuilder { fn set_jmp(&mut self, jmp: Jump, i: usize) -> Option { if self.jump.is_some() { - return Some(SyntaxError::new(format!("Jump already set: {i}"))) + return Some(SyntaxError::new(format!("Jump already set: {i}"))); } self.jump = Some(jmp); None @@ -299,7 +299,7 @@ impl SourceElementBuilder { fn set_offset(&mut self, offset: usize, i: usize) -> Option { if self.offset.is_some() { - return Some(SyntaxError::new(format!("Offset already set: {i}"))) + return Some(SyntaxError::new(format!("Offset already set: {i}"))); } self.offset = Some(offset); None @@ -307,7 +307,7 @@ impl SourceElementBuilder { fn set_length(&mut self, length: usize, i: usize) -> Option { if self.length.is_some() { - return Some(SyntaxError::new(format!("Length already set: {i}"))) + return Some(SyntaxError::new(format!("Length already set: {i}"))); } self.length = Some(length); None @@ -315,7 +315,7 @@ impl SourceElementBuilder { fn set_index(&mut self, index: Option, i: usize) -> Option { if self.index.is_some() { - return Some(SyntaxError::new(format!("Index already set: {i}"))) + return Some(SyntaxError::new(format!("Index already set: {i}"))); } self.index = Some(index); None @@ -323,7 +323,7 @@ impl SourceElementBuilder { fn set_modifier(&mut self, modifier_depth: usize, i: usize) -> Option { if self.modifier_depth.is_some() { - return Some(SyntaxError::new(format!("Modifier depth already set: {i}"))) + return Some(SyntaxError::new(format!("Modifier depth already set: {i}"))); } self.modifier_depth = Some(modifier_depth); None @@ -376,7 +376,7 @@ macro_rules! parse_number { macro_rules! bail_opt { ($opt:stmt) => { if let Some(err) = { $opt } { - return Some(Err(err)) + return Some(Err(err)); } }; } @@ -435,10 +435,10 @@ impl<'input> Iterator for Parser<'input> { Some(Err(err)) => return Some(Err(err)), None => { if self.done { - return None + return None; } self.done = true; - break + break; } } } diff --git a/ethers-solc/src/utils.rs b/ethers-solc/src/utils.rs index 24e45fa47..a01d2eea8 100644 --- a/ethers-solc/src/utils.rs +++ b/ethers-solc/src/utils.rs @@ -205,7 +205,7 @@ pub fn resolve_library(libs: &[impl AsRef], source: impl AsRef) -> O let contract = lib.join(source); if contract.exists() { // contract exists in / - return Some(contract) + return Some(contract); } // check for //src/name.sol let contract = lib @@ -213,7 +213,7 @@ pub fn resolve_library(libs: &[impl AsRef], source: impl AsRef) -> O .join("src") .join(source.strip_prefix(first_dir).expect("is first component")); if contract.exists() { - return Some(contract) + return Some(contract); } } None @@ -247,7 +247,7 @@ pub fn resolve_absolute_library( let mut parent = cwd.parent()?; while parent != root { if let Ok(import) = canonicalize(parent.join(import)) { - return Some((parent.to_path_buf(), import)) + return Some((parent.to_path_buf(), import)); } parent = parent.parent()?; } @@ -328,7 +328,7 @@ where if let Some(r) = common_ancestor(ret, path.as_ref()) { ret = r; } else { - return None + return None; } } Some(ret) @@ -359,7 +359,7 @@ pub fn common_ancestor(a: impl AsRef, b: impl AsRef) -> Option, fave: &str, alt: &st if !p.exists() { let alt = root.join(alt); if alt.exists() { - return alt + return alt; } } p @@ -396,10 +396,10 @@ pub(crate) fn find_case_sensitive_existing_file(non_existing: &Path) -> Option

Result<()> { eprint!(": {e}"); } eprintln!(); - return Ok(()) + return Ok(()); } Ok(true) => {} } diff --git a/examples/transactions/examples/remove_liquidity.rs b/examples/transactions/examples/remove_liquidity.rs index 587f64362..036120901 100644 --- a/examples/transactions/examples/remove_liquidity.rs +++ b/examples/transactions/examples/remove_liquidity.rs @@ -59,8 +59,8 @@ async fn example() -> Result<()> { println!("Reserves (token A, Token B): ({reserve0}, {reserve1})"); let price = - if reserve0 > reserve1 { 1000 * reserve0 / reserve1 } else { 1000 * reserve1 / reserve0 } / - 1000; + if reserve0 > reserve1 { 1000 * reserve0 / reserve1 } else { 1000 * reserve1 / reserve0 } + / 1000; println!("token0 / token1 price = {price}"); let liquidity = 100.into(); From 442e4f7e4b0540e1fb1246b67d9a843c02f6ff04 Mon Sep 17 00:00:00 2001 From: Dave Belvedere Date: Tue, 9 May 2023 23:56:37 +1000 Subject: [PATCH 2/7] Nightly fmt --- .../src/contract/methods.rs | 22 +-- .../src/contract/structs.rs | 8 +- .../src/contract/types.rs | 16 +- .../ethers-contract-abigen/src/filter.rs | 2 +- .../ethers-contract-abigen/src/multi.rs | 2 +- .../ethers-contract-abigen/src/source/mod.rs | 2 +- .../src/source/online.rs | 2 +- .../ethers-contract-abigen/src/util.rs | 2 +- .../ethers-contract-derive/src/abigen.rs | 6 +- .../ethers-contract-derive/src/call.rs | 2 +- .../ethers-contract-derive/src/error.rs | 2 +- .../ethers-contract-derive/src/event.rs | 6 +- .../ethers-contract-derive/src/utils.rs | 14 +- ethers-contract/src/base.rs | 2 +- ethers-contract/src/error.rs | 4 +- ethers-contract/src/multicall/mod.rs | 8 +- ethers-core/README.md | 4 - ethers-core/src/abi/human_readable/lexer.rs | 28 +-- ethers-core/src/abi/human_readable/mod.rs | 6 +- ethers-core/src/abi/mod.rs | 12 +- ethers-core/src/abi/packed.rs | 2 +- ethers-core/src/abi/struct_def.rs | 8 +- ethers-core/src/abi/tokens.rs | 6 +- ethers-core/src/macros/ethers_crate.rs | 14 +- ethers-core/src/types/block.rs | 20 +-- ethers-core/src/types/chain.rs | 168 +++++++++--------- ethers-core/src/types/ens.rs | 2 +- ethers-core/src/types/filter.rs | 48 ++--- ethers-core/src/types/i256.rs | 10 +- ethers-core/src/types/signature.rs | 4 +- ethers-core/src/types/trace/filter.rs | 2 +- ethers-core/src/types/transaction/eip2718.rs | 6 +- ethers-core/src/types/transaction/eip712.rs | 4 +- ethers-core/src/types/transaction/mod.rs | 4 +- ethers-core/src/types/txpool.rs | 8 +- ethers-core/src/types/u256.rs | 4 +- ethers-core/src/types/uint8.rs | 4 +- ethers-core/src/utils/anvil.rs | 6 +- ethers-core/src/utils/ganache.rs | 2 +- ethers-core/src/utils/geth.rs | 8 +- ethers-core/src/utils/mod.rs | 12 +- ethers-etherscan/src/contract.rs | 10 +- ethers-etherscan/src/errors.rs | 4 +- ethers-etherscan/src/lib.rs | 30 ++-- ethers-middleware/src/gas_oracle/cache.rs | 4 +- ethers-middleware/src/gas_oracle/median.rs | 6 +- ethers-middleware/src/nonce_manager.rs | 4 +- ethers-middleware/src/signer.rs | 2 +- ethers-middleware/src/timelag/mod.rs | 4 +- ethers-providers/src/ext/ens.rs | 2 +- ethers-providers/src/ext/erc.rs | 4 +- ethers-providers/src/rpc/provider.rs | 24 ++- ethers-providers/src/rpc/pubsub.rs | 6 +- ethers-providers/src/rpc/transports/common.rs | 19 +- ethers-providers/src/rpc/transports/http.rs | 2 +- ethers-providers/src/rpc/transports/ipc.rs | 6 +- .../src/rpc/transports/legacy_ws.rs | 6 +- ethers-providers/src/rpc/transports/quorum.rs | 26 +-- ethers-providers/src/rpc/transports/retry.rs | 28 +-- .../src/rpc/transports/ws/backend.rs | 2 +- .../src/rpc/transports/ws/manager.rs | 6 +- .../src/rpc/transports/ws/types.rs | 16 +- ethers-providers/src/stream/tx_stream.rs | 10 +- ethers-providers/src/stream/watcher.rs | 2 +- ethers-providers/src/toolbox/log_query.rs | 2 +- .../src/toolbox/pending_escalator.rs | 2 +- .../src/toolbox/pending_transaction.rs | 6 +- ethers-signers/src/ledger/app.rs | 10 +- ethers-signers/src/trezor/app.rs | 2 +- ethers-signers/src/wallet/private_key.rs | 8 +- .../src/artifact_output/configurable.rs | 10 +- ethers-solc/src/artifact_output/mod.rs | 14 +- ethers-solc/src/artifacts/bytecode.rs | 16 +- ethers-solc/src/artifacts/contract.rs | 6 +- ethers-solc/src/artifacts/mod.rs | 26 +-- ethers-solc/src/artifacts/output_selection.rs | 10 +- ethers-solc/src/artifacts/serde_helpers.rs | 6 +- ethers-solc/src/cache.rs | 20 +-- ethers-solc/src/compile/mod.rs | 8 +- ethers-solc/src/compile/output/info.rs | 2 +- ethers-solc/src/compile/output/mod.rs | 16 +- ethers-solc/src/compile/project.rs | 8 +- ethers-solc/src/config.rs | 32 ++-- ethers-solc/src/lib.rs | 6 +- ethers-solc/src/remappings.rs | 56 +++--- ethers-solc/src/report/mod.rs | 6 +- ethers-solc/src/resolver/mod.rs | 16 +- ethers-solc/src/resolver/tree.rs | 4 +- ethers-solc/src/sourcemap.rs | 48 ++--- ethers-solc/src/utils.rs | 18 +- .../transactions/examples/call_override.rs | 2 +- .../transactions/examples/remove_liquidity.rs | 4 +- 92 files changed, 534 insertions(+), 545 deletions(-) diff --git a/ethers-contract/ethers-contract-abigen/src/contract/methods.rs b/ethers-contract/ethers-contract-abigen/src/contract/methods.rs index a2b3666da..de11b029e 100644 --- a/ethers-contract/ethers-contract-abigen/src/contract/methods.rs +++ b/ethers-contract/ethers-contract-abigen/src/contract/methods.rs @@ -144,7 +144,7 @@ impl Context { ) -> Result> { // no point in having structs when there is no data returned if function.outputs.is_empty() { - return Ok(None); + return Ok(None) } let name = &function.name; @@ -192,7 +192,7 @@ impl Context { if struct_defs.len() <= 1 { // no need for an enum - return Ok(struct_def_tokens); + return Ok(struct_def_tokens) } let mut derives = self.expand_extra_derives(); @@ -390,7 +390,7 @@ impl Context { for functions in all_functions.values() { if functions.iter().filter(|f| !aliases.contains_key(&f.abi_signature())).count() <= 1 { // no overloads, hence no conflicts - continue; + continue } let num_functions = functions.len(); @@ -427,7 +427,7 @@ impl Context { if a.iter() .all(|d| b.iter().any(|o| o.name.to_snake_case() == d.name.to_snake_case())) { - return true; + return true } } false @@ -493,14 +493,14 @@ impl Context { struct_name: util::safe_ident(&first_fun.name), }; aliases.insert(first_fun.abi_signature(), first_fun_alias); - continue; + continue } } 1 => { // single additional input params - if diff[0].name.is_empty() - || num_functions > NAME_ALIASING_OVERLOADED_FUNCTIONS_CAP - || name_conflicts(*idx, &diffs) + if diff[0].name.is_empty() || + num_functions > NAME_ALIASING_OVERLOADED_FUNCTIONS_CAP || + name_conflicts(*idx, &diffs) { needs_alias_for_first_fun_using_idx = true; format!("{}{idx}", overloaded_fun.name.to_snake_case()) @@ -513,9 +513,9 @@ impl Context { } } _ => { - if diff.iter().any(|d| d.name.is_empty()) - || num_functions > NAME_ALIASING_OVERLOADED_FUNCTIONS_CAP - || name_conflicts(*idx, &diffs) + if diff.iter().any(|d| d.name.is_empty()) || + num_functions > NAME_ALIASING_OVERLOADED_FUNCTIONS_CAP || + name_conflicts(*idx, &diffs) { needs_alias_for_first_fun_using_idx = true; format!("{}{idx}", overloaded_fun.name.to_snake_case()) diff --git a/ethers-contract/ethers-contract-abigen/src/contract/structs.rs b/ethers-contract/ethers-contract-abigen/src/contract/structs.rs index fd22bacb3..a0fd3af2b 100644 --- a/ethers-contract/ethers-contract-abigen/src/contract/structs.rs +++ b/ethers-contract/ethers-contract-abigen/src/contract/structs.rs @@ -254,7 +254,7 @@ impl InternalStructs { if is_event { // no outputs in an event - continue; + continue } let mut output_structs = Vec::new(); @@ -424,7 +424,7 @@ fn resolve_struct_tuples(all_structs: &HashMap) -> HashMap structs.len() { - break; + break } if let Some(tuple) = ty.as_tuple() { params.insert(id.to_string(), tuple); @@ -454,7 +454,7 @@ fn resolve_struct_tuples(all_structs: &HashMap) -> HashMap { @@ -477,7 +477,7 @@ fn insert_structs(structs: &mut HashMap, tuple: &Component) { if let Some(internal_ty) = tuple.internal_type.as_ref() { let ident = struct_type_identifier(internal_ty); if structs.contains_key(ident) { - return; + return } if let Some(fields) = tuple .components diff --git a/ethers-contract/ethers-contract-abigen/src/contract/types.rs b/ethers-contract/ethers-contract-abigen/src/contract/types.rs index b57ac7cb4..b49120de3 100644 --- a/ethers-contract/ethers-contract-abigen/src/contract/types.rs +++ b/ethers-contract/ethers-contract-abigen/src/contract/types.rs @@ -89,18 +89,18 @@ fn expand_event_input( ) -> Result { let kind = &input.kind; match (kind, input.indexed) { - (ParamType::Array(_), true) - | (ParamType::FixedArray(_, _), true) - | (ParamType::Tuple(_), true) - | (ParamType::Bytes, true) - | (ParamType::String, true) => { + (ParamType::Array(_), true) | + (ParamType::FixedArray(_, _), true) | + (ParamType::Tuple(_), true) | + (ParamType::Bytes, true) | + (ParamType::String, true) => { let ethers_core = ethers_core_crate(); Ok(quote!(#ethers_core::types::H256)) } - (ParamType::Array(_), false) - | (ParamType::FixedArray(_, _), false) - | (ParamType::Tuple(_), false) => { + (ParamType::Array(_), false) | + (ParamType::FixedArray(_, _), false) | + (ParamType::Tuple(_), false) => { match internal_structs.get_event_input_struct_type(name, index) { Some(ty) => { let ty = util::ident(ty); diff --git a/ethers-contract/ethers-contract-abigen/src/filter.rs b/ethers-contract/ethers-contract-abigen/src/filter.rs index d3e814dd1..1a97c728f 100644 --- a/ethers-contract/ethers-contract-abigen/src/filter.rs +++ b/ethers-contract/ethers-contract-abigen/src/filter.rs @@ -131,7 +131,7 @@ macro_rules! impl_filter { pub fn is_match(&self, name: impl AsRef) -> bool { let name = name.as_ref(); if self.exact.contains(name) { - return true; + return true } self.patterns.iter().any(|re| re.is_match(name)) } diff --git a/ethers-contract/ethers-contract-abigen/src/multi.rs b/ethers-contract/ethers-contract-abigen/src/multi.rs index 6030c9d63..0f9127b6b 100644 --- a/ethers-contract/ethers-contract-abigen/src/multi.rs +++ b/ethers-contract/ethers-contract-abigen/src/multi.rs @@ -628,7 +628,7 @@ impl MultiBindingsInner { .join("Cargo.toml"); if !cargo_toml.exists() { - return Ok(DEFAULT_ETHERS_DEP.to_string()); + return Ok(DEFAULT_ETHERS_DEP.to_string()) } let data = fs::read_to_string(cargo_toml)?; diff --git a/ethers-contract/ethers-contract-abigen/src/source/mod.rs b/ethers-contract/ethers-contract-abigen/src/source/mod.rs index 42a2a1794..95f05d4dc 100644 --- a/ethers-contract/ethers-contract-abigen/src/source/mod.rs +++ b/ethers-contract/ethers-contract-abigen/src/source/mod.rs @@ -107,7 +107,7 @@ impl Source { if let Ok(canonicalized) = dunce::canonicalize(&resolved) { resolved = canonicalized; } else { - return Err(eyre::eyre!("File does not exist: {}", resolved.display())); + return Err(eyre::eyre!("File does not exist: {}", resolved.display())) } Ok(Source::Local(resolved)) diff --git a/ethers-contract/ethers-contract-abigen/src/source/online.rs b/ethers-contract/ethers-contract-abigen/src/source/online.rs index 2eba1fc95..212aff967 100644 --- a/ethers-contract/ethers-contract-abigen/src/source/online.rs +++ b/ethers-contract/ethers-contract-abigen/src/source/online.rs @@ -208,7 +208,7 @@ mod tests { fn get_mainnet_contract() { // Skip if ETHERSCAN_API_KEY is not set if std::env::var("ETHERSCAN_API_KEY").is_err() { - return; + return } let source = Source::parse("mainnet:0x6b175474e89094c44da98b954eedeac495271d0f").unwrap(); diff --git a/ethers-contract/ethers-contract-abigen/src/util.rs b/ethers-contract/ethers-contract-abigen/src/util.rs index c8385605b..0c6f4756a 100644 --- a/ethers-contract/ethers-contract-abigen/src/util.rs +++ b/ethers-contract/ethers-contract-abigen/src/util.rs @@ -152,7 +152,7 @@ fn take_while(s: &str, mut predicate: impl FnMut(char) -> bool) -> (&str, &str) if predicate(c) { index += c.len_utf8(); } else { - break; + break } } s.split_at(index) diff --git a/ethers-contract/ethers-contract-derive/src/abigen.rs b/ethers-contract/ethers-contract-derive/src/abigen.rs index 631c8d3d0..a01063216 100644 --- a/ethers-contract/ethers-contract-derive/src/abigen.rs +++ b/ethers-contract/ethers-contract-derive/src/abigen.rs @@ -94,7 +94,7 @@ impl Parse for ContractArgs { if input.parse::().is_ok() { loop { if input.is_empty() || input.peek(Token![;]) { - break; + break } parameters.push_value(input.parse()?); if let Ok(comma) = input.parse() { @@ -128,10 +128,10 @@ impl Parse for Parameter { let mut aliases = HashSet::new(); for method in parsed { if !signatures.insert(method.signature.clone()) { - return Err(Error::new(method.span(), "duplicate method signature")); + return Err(Error::new(method.span(), "duplicate method signature")) } if !aliases.insert(method.alias.clone()) { - return Err(Error::new(method.alias.span(), "duplicate method alias")); + return Err(Error::new(method.alias.span(), "duplicate method alias")) } methods.push(method.into_inner()); } diff --git a/ethers-contract/ethers-contract-derive/src/call.rs b/ethers-contract/ethers-contract-derive/src/call.rs index 13f193127..fb941c593 100644 --- a/ethers-contract/ethers-contract-derive/src/call.rs +++ b/ethers-contract/ethers-contract-derive/src/call.rs @@ -30,7 +30,7 @@ pub(crate) fn derive_eth_call_impl(input: DeriveInput) -> Result Result Result Result Result Option { pub fn topic_param_type_quote(kind: &ParamType) -> TokenStream { let ethers_core = ethers_core_crate(); match kind { - ParamType::String - | ParamType::Bytes - | ParamType::Array(_) - | ParamType::FixedArray(_, _) - | ParamType::Tuple(_) => quote! {#ethers_core::abi::ParamType::FixedBytes(32)}, + ParamType::String | + ParamType::Bytes | + ParamType::Array(_) | + ParamType::FixedArray(_, _) | + ParamType::Tuple(_) => quote! {#ethers_core::abi::ParamType::FixedBytes(32)}, ty => param_type_quote(ty), } } @@ -144,7 +144,7 @@ pub fn find_parameter_type(ty: &Type) -> Result { return match (ty, len) { (ParamType::Uint(8), 32) => Ok(ParamType::FixedBytes(32)), (ty, len) => Ok(ParamType::FixedArray(Box::new(ty), len)), - }; + } } } } @@ -159,7 +159,7 @@ pub fn find_parameter_type(ty: &Type) -> Result { debug_assert!(matches!(args.args.len(), 1 | 2)); let ty = args.args.iter().next().unwrap(); if let GenericArgument::Type(ref ty) = ty { - return find_parameter_type(ty).map(|kind| ParamType::Array(Box::new(kind))); + return find_parameter_type(ty).map(|kind| ParamType::Array(Box::new(kind))) } } } diff --git a/ethers-contract/src/base.rs b/ethers-contract/src/base.rs index 743306c95..b949b89a0 100644 --- a/ethers-contract/src/base.rs +++ b/ethers-contract/src/base.rs @@ -267,7 +267,7 @@ pub fn decode_function_data_raw>( let bytes = bytes.as_ref(); Ok(if is_input { if bytes.len() < 4 || bytes[..4] != function.selector() { - return Err(AbiError::WrongSelector); + return Err(AbiError::WrongSelector) } function.decode_input(&bytes[4..])? } else { diff --git a/ethers-contract/src/error.rs b/ethers-contract/src/error.rs index 3a1ea3991..e7373c8ad 100644 --- a/ethers-contract/src/error.rs +++ b/ethers-contract/src/error.rs @@ -27,11 +27,11 @@ pub trait ContractRevert: AbiDecode + AbiEncode + Send + Sync { /// Decode the error from EVM revert data including an Error selector fn decode_with_selector(data: &[u8]) -> Option { if data.len() < 4 { - return None; + return None } let selector = data[..4].try_into().expect("checked by len"); if !Self::valid_selector(selector) { - return None; + return None } ::decode(&data[4..]).ok() } diff --git a/ethers-contract/src/multicall/mod.rs b/ethers-contract/src/multicall/mod.rs index 1875dfa37..7c1011316 100644 --- a/ethers-contract/src/multicall/mod.rs +++ b/ethers-contract/src/multicall/mod.rs @@ -265,7 +265,7 @@ impl Multicall { .map_err(ContractError::from_middleware_error)? .as_u64(); if !constants::MULTICALL_SUPPORTED_CHAIN_IDS.contains(&chain_id) { - return Err(error::MulticallError::InvalidChainId(chain_id)); + return Err(error::MulticallError::InvalidChainId(chain_id)) } constants::MULTICALL_ADDRESS } @@ -309,7 +309,7 @@ impl Multicall { (_, Some(chain_id)) => { let chain_id = chain_id.into(); if !constants::MULTICALL_SUPPORTED_CHAIN_IDS.contains(&chain_id) { - return Err(error::MulticallError::InvalidChainId(chain_id)); + return Err(error::MulticallError::InvalidChainId(chain_id)) } constants::MULTICALL_ADDRESS } @@ -388,7 +388,7 @@ impl Multicall { TypedTransaction::Eip1559(tx) => (tx.to, tx.data, tx.value), }; if data.is_none() && !call.function.outputs.is_empty() { - return self; + return self } if let Some(NameOrAddress::Address(target)) = to { let call = Call { @@ -718,7 +718,7 @@ impl Multicall { // still do so because of other calls that are in the same multicall // aggregate. if !success && !call.allow_failure { - return Err(error::MulticallError::IllegalRevert); + return Err(error::MulticallError::IllegalRevert) } Err(return_data) diff --git a/ethers-core/README.md b/ethers-core/README.md index d41318558..645043192 100644 --- a/ethers-core/README.md +++ b/ethers-core/README.md @@ -10,10 +10,6 @@ other utilities for interacting with the Ethereum ecosystem For more information, please refer to the [book](https://gakonst.com/ethers-rs). -## Feature flags - -- `eip712`: Provides the `Eip712` trait and derive procedural macro for EIP-712 encoding of typed data. - ## ABI This crate re-exports the [`ethabi`](https://docs.rs/ethabi) crate's functions diff --git a/ethers-core/src/abi/human_readable/lexer.rs b/ethers-core/src/abi/human_readable/lexer.rs index cccb52549..08ee00207 100644 --- a/ethers-core/src/abi/human_readable/lexer.rs +++ b/ethers-core/src/abi/human_readable/lexer.rs @@ -182,12 +182,12 @@ impl<'input> HumanReadableLexer<'input> { if let Some((i, ch)) = self.chars.peek() { if !UnicodeXID::is_xid_continue(*ch) && *ch != '$' { end = *i; - break; + break } self.chars.next(); } else { end = self.input.len(); - break; + break } } let id = &self.input[start..end]; @@ -196,7 +196,7 @@ impl<'input> HumanReadableLexer<'input> { Some(Ok((start, w, end))) } else { Some(Ok((start, Token::Identifier(id), end))) - }; + } } Some((start, ch)) if ch.is_ascii_digit() => { let mut end = start + 1; @@ -220,7 +220,7 @@ impl<'input> HumanReadableLexer<'input> { while let Some((i, ch)) = self.chars.peek() { if !ch.is_ascii_hexdigit() && *ch != '_' { - break; + break } end = *i; self.chars.next(); @@ -230,23 +230,23 @@ impl<'input> HumanReadableLexer<'input> { start, Token::HexNumber(&self.input[start..=end]), end + 1, - ))); + ))) } } loop { if let Some((i, ch)) = self.chars.peek().cloned() { if !ch.is_ascii_digit() { - break; + break } self.chars.next(); end = i + 1; } else { end = self.input.len(); - break; + break } } - return Some(Ok((start, Token::Number(&self.input[start..end]), end + 1))); + return Some(Ok((start, Token::Number(&self.input[start..end]), end + 1))) } Some((i, '(')) => return Some(Ok((i, Token::OpenParenthesis, i + 1))), Some((i, ')')) => return Some(Ok((i, Token::CloseParenthesis, i + 1))), @@ -262,11 +262,11 @@ impl<'input> HumanReadableLexer<'input> { if let Some((i, ch)) = self.chars.next() { end = i; if ch.is_whitespace() { - break; + break } } else { end = self.input.len(); - break; + break } } @@ -274,7 +274,7 @@ impl<'input> HumanReadableLexer<'input> { start, end, self.input[start..end].to_owned(), - ))); + ))) } None => return None, } @@ -527,7 +527,7 @@ impl<'input> HumanReadableParser<'input> { let mut params = Vec::new(); if self.peek_next(token) { - return Ok(params); + return Ok(params) } loop { @@ -581,7 +581,7 @@ impl<'input> HumanReadableParser<'input> { Token::Identifier(id) => { name = id; self.next(); - break; + break } _ => break, }; @@ -594,7 +594,7 @@ impl<'input> HumanReadableParser<'input> { let mut params = Vec::new(); if self.peek_next(Token::CloseParenthesis) { - return Ok(params); + return Ok(params) } loop { params.push(self.take_param()?); diff --git a/ethers-core/src/abi/human_readable/mod.rs b/ethers-core/src/abi/human_readable/mod.rs index d2fa28fdc..db5d97ac5 100644 --- a/ethers-core/src/abi/human_readable/mod.rs +++ b/ethers-core/src/abi/human_readable/mod.rs @@ -144,7 +144,7 @@ impl AbiParser { tuple.push(ty.as_param(ParamType::Tuple(param))) } else { resolved = false; - break; + break } } FieldType::Mapping(_) => { @@ -227,7 +227,7 @@ impl AbiParser { }; let event = Event { name, inputs, anonymous }; - return Ok(event); + return Ok(event) } Some(' ') | Some('\t') => continue, Some(c) => { @@ -526,7 +526,7 @@ pub(crate) fn parse_identifier(input: &mut &str) -> Result { } } if name.is_empty() { - return Err(ParseError::ParseError(super::Error::InvalidName(input.to_string()))); + return Err(ParseError::ParseError(super::Error::InvalidName(input.to_string()))) } *input = chars.as_str(); Ok(name) diff --git a/ethers-core/src/abi/mod.rs b/ethers-core/src/abi/mod.rs index 7f1ff1874..dfb6c5128 100644 --- a/ethers-core/src/abi/mod.rs +++ b/ethers-core/src/abi/mod.rs @@ -97,7 +97,7 @@ pub trait ErrorExt: sealed::Sealed { impl ErrorExt for ethabi::AbiError { fn abi_signature(&self) -> String { if self.inputs.is_empty() { - return format!("{}()", self.name); + return format!("{}()", self.name) } let inputs = self.inputs.iter().map(|p| p.kind.to_string()).collect::>().join(","); format!("{}({inputs})", self.name) @@ -123,11 +123,11 @@ pub trait AbiType { pub fn minimum_size(ty: &ParamType) -> usize { match ty { // 1 word - ParamType::Uint(_) - | ParamType::Int(_) - | ParamType::Bool - | ParamType::Address - | ParamType::FixedBytes(_) => 32, + ParamType::Uint(_) | + ParamType::Int(_) | + ParamType::Bool | + ParamType::Address | + ParamType::FixedBytes(_) => 32, // min 2 words (offset, length) ParamType::Bytes | ParamType::String | ParamType::Array(_) => 64, // sum of all elements diff --git a/ethers-core/src/abi/packed.rs b/ethers-core/src/abi/packed.rs index 736b02555..e491f8ddf 100644 --- a/ethers-core/src/abi/packed.rs +++ b/ethers-core/src/abi/packed.rs @@ -91,7 +91,7 @@ fn check(token: &Token) -> Result<(), EncodePackedError> { Array(vec) | FixedArray(vec) => { for t in vec.iter() { if t.is_dynamic() || matches!(t, Array(_)) { - return Err(EncodePackedError::InvalidToken(token.clone())); + return Err(EncodePackedError::InvalidToken(token.clone())) } check(t)?; } diff --git a/ethers-core/src/abi/struct_def.rs b/ethers-core/src/abi/struct_def.rs index 3dda14b5c..cc588fcab 100644 --- a/ethers-core/src/abi/struct_def.rs +++ b/ethers-core/src/abi/struct_def.rs @@ -198,7 +198,7 @@ impl StructFieldType { Box::new(StructFieldType::Type(ty)), size, ))) - }; + } } Some(c) => { if c.is_numeric() { @@ -270,7 +270,7 @@ impl SolStruct { .map(parse_struct_field) .collect::, _>>()? }; - return Ok(SolStruct { name, fields }); + return Ok(SolStruct { name, fields }) } Some(' ') | Some('\t') => continue, Some(c) => { @@ -303,7 +303,7 @@ impl SolStruct { if let FieldType::Elementary(ref param) = field.ty { params.push(param.clone()) } else { - return None; + return None } } Some(ParamType::Tuple(params)) @@ -341,7 +341,7 @@ fn parse_struct_field(s: &str) -> Result { fn parse_field_type(s: &str) -> Result { let mut input = s.trim_start(); if input.starts_with("mapping") { - return Ok(FieldType::Mapping(Box::new(parse_mapping(input)?))); + return Ok(FieldType::Mapping(Box::new(parse_mapping(input)?))) } if input.ends_with(" payable") { // special case for `address payable` diff --git a/ethers-core/src/abi/tokens.rs b/ethers-core/src/abi/tokens.rs index d0028fc3b..33b0034d3 100644 --- a/ethers-core/src/abi/tokens.rs +++ b/ethers-core/src/abi/tokens.rs @@ -189,7 +189,7 @@ impl Tokenizable for H256 { match token { Token::FixedBytes(mut s) => { if s.len() != 32 { - return Err(InvalidOutputType(format!("Expected `H256`, got {s:?}"))); + return Err(InvalidOutputType(format!("Expected `H256`, got {s:?}"))) } let mut data = [0; 32]; for (idx, val) in s.drain(..).enumerate() { @@ -337,7 +337,7 @@ impl Tokenizable for [u8; N] { "Expected `FixedBytes({})`, got FixedBytes({})", N, bytes.len() - ))); + ))) } let mut arr = [0; N]; @@ -362,7 +362,7 @@ impl Tokenizable for [T; N] { "Expected `FixedArray({})`, got FixedArray({})", N, tokens.len() - ))); + ))) } let mut arr = ArrayVec::::new(); diff --git a/ethers-core/src/macros/ethers_crate.rs b/ethers-core/src/macros/ethers_crate.rs index 37afceb46..9b4d9b802 100644 --- a/ethers-core/src/macros/ethers_crate.rs +++ b/ethers-core/src/macros/ethers_crate.rs @@ -100,7 +100,7 @@ impl ProjectEnvironment { // return ethers_* if the root package is an internal ethers crate since `ethers` is not // available if pkg.name.parse::().is_ok() || pkg.name == "ethers" { - return Some(EthersCrate::path_names().collect()); + return Some(EthersCrate::path_names().collect()) } let mut names: CrateNames = EthersCrate::ethers_path_names().collect(); @@ -108,7 +108,7 @@ impl ProjectEnvironment { let name = dep.name.as_str(); if name.starts_with("ethers") { if name == "ethers" { - return None; + return None } else if let Ok(dep) = name.parse::() { names.insert(dep, dep.path_name()); } @@ -130,12 +130,12 @@ impl ProjectEnvironment { /// [ref]: https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates #[inline] pub fn is_crate_root(&self) -> bool { - env::var_os("CARGO_TARGET_TMPDIR").is_none() - && self.manifest_dir.components().all(|c| { + env::var_os("CARGO_TARGET_TMPDIR").is_none() && + self.manifest_dir.components().all(|c| { let s = c.as_os_str(); s != "examples" && s != "benches" - }) - && !self.is_crate_name_in_dirs() + }) && + !self.is_crate_name_in_dirs() } /// Returns whether `crate_name` is the name of a file or directory in the first level of @@ -328,7 +328,7 @@ impl EthersCrate { fn file_stem_eq, U: AsRef>(path: T, s: U) -> bool { if let Some(stem) = path.as_ref().file_stem() { if let Some(stem) = stem.to_str() { - return stem == s.as_ref(); + return stem == s.as_ref() } } false diff --git a/ethers-core/src/types/block.rs b/ethers-core/src/types/block.rs index 8d0240256..2dffe090c 100644 --- a/ethers-core/src/types/block.rs +++ b/ethers-core/src/types/block.rs @@ -160,9 +160,9 @@ impl Block { Ordering::Greater => { let gas_used_delta = self.gas_used - self.gas_target(); let base_fee_per_gas_delta = U256::max( - base_fee_per_gas * gas_used_delta - / target_usage - / BASE_FEE_MAX_CHANGE_DENOMINATOR, + base_fee_per_gas * gas_used_delta / + target_usage / + BASE_FEE_MAX_CHANGE_DENOMINATOR, U256::from(1u32), ); let expected_base_fee_per_gas = base_fee_per_gas + base_fee_per_gas_delta; @@ -170,9 +170,9 @@ impl Block { } Ordering::Less => { let gas_used_delta = self.gas_target() - self.gas_used; - let base_fee_per_gas_delta = base_fee_per_gas * gas_used_delta - / target_usage - / BASE_FEE_MAX_CHANGE_DENOMINATOR; + let base_fee_per_gas_delta = base_fee_per_gas * gas_used_delta / + target_usage / + BASE_FEE_MAX_CHANGE_DENOMINATOR; let expected_base_fee_per_gas = base_fee_per_gas - base_fee_per_gas_delta; Some(expected_base_fee_per_gas) } @@ -189,10 +189,10 @@ impl Block { /// [`DateTime`]. pub fn time(&self) -> Result, TimeError> { if self.timestamp.is_zero() { - return Err(TimeError::TimestampZero); + return Err(TimeError::TimestampZero) } if self.timestamp.bits() > 63 { - return Err(TimeError::TimestampOverflow); + return Err(TimeError::TimestampOverflow) } // Casting to i64 is safe because the timestamp is guaranteed to be less than 2^63. // TODO: It would be nice if there was `TryInto for U256`. @@ -520,13 +520,13 @@ impl<'de> Deserialize<'de> for BlockId { match key.as_str() { "blockNumber" => { if number.is_some() || hash.is_some() { - return Err(serde::de::Error::duplicate_field("blockNumber")); + return Err(serde::de::Error::duplicate_field("blockNumber")) } number = Some(BlockId::Number(map.next_value::()?)) } "blockHash" => { if number.is_some() || hash.is_some() { - return Err(serde::de::Error::duplicate_field("blockHash")); + return Err(serde::de::Error::duplicate_field("blockHash")) } hash = Some(BlockId::Hash(map.next_value::()?)) } diff --git a/ethers-core/src/types/chain.rs b/ethers-core/src/types/chain.rs index 49a4fdd1c..8ddb19a6d 100644 --- a/ethers-core/src/types/chain.rs +++ b/ethers-core/src/types/chain.rs @@ -289,10 +289,10 @@ impl Chain { FilecoinHyperspaceTestnet | FilecoinMainnet => 30_000, ScrollAlphaTestnet => 3_000, // Explicitly exhaustive. See NB above. - Morden | Ropsten | Rinkeby | Goerli | Kovan | XDai | Chiado | Sepolia | Moonbase - | MoonbeamDev | Optimism | OptimismGoerli | OptimismKovan | Poa | Sokol | Rsk - | EmeraldTestnet | Boba | BaseGoerli | ZkSync | ZkSyncTestnet | PolygonZkEvm - | PolygonZkEvmTestnet | Metis => return None, + Morden | Ropsten | Rinkeby | Goerli | Kovan | XDai | Chiado | Sepolia | Moonbase | + MoonbeamDev | Optimism | OptimismGoerli | OptimismKovan | Poa | Sokol | Rsk | + EmeraldTestnet | Boba | BaseGoerli | ZkSync | ZkSyncTestnet | PolygonZkEvm | + PolygonZkEvmTestnet | Metis => return None, }; Some(Duration::from_millis(ms)) @@ -313,47 +313,47 @@ impl Chain { match self { // Known legacy chains / non EIP-1559 compliant - Optimism - | OptimismGoerli - | OptimismKovan - | Fantom - | FantomTestnet - | BinanceSmartChain - | BinanceSmartChainTestnet - | Arbitrum - | ArbitrumTestnet - | ArbitrumGoerli - | ArbitrumNova - | Rsk - | Oasis - | Emerald - | EmeraldTestnet - | Celo - | CeloAlfajores - | CeloBaklava - | Boba - | ZkSync - | ZkSyncTestnet - | BaseGoerli - | PolygonZkEvm - | PolygonZkEvmTestnet => true, + Optimism | + OptimismGoerli | + OptimismKovan | + Fantom | + FantomTestnet | + BinanceSmartChain | + BinanceSmartChainTestnet | + Arbitrum | + ArbitrumTestnet | + ArbitrumGoerli | + ArbitrumNova | + Rsk | + Oasis | + Emerald | + EmeraldTestnet | + Celo | + CeloAlfajores | + CeloBaklava | + Boba | + ZkSync | + ZkSyncTestnet | + BaseGoerli | + PolygonZkEvm | + PolygonZkEvmTestnet => true, // Known EIP-1559 chains - Mainnet - | Goerli - | Sepolia - | Polygon - | PolygonMumbai - | Avalanche - | AvalancheFuji - | FilecoinMainnet - | FilecoinHyperspaceTestnet => false, + Mainnet | + Goerli | + Sepolia | + Polygon | + PolygonMumbai | + Avalanche | + AvalancheFuji | + FilecoinMainnet | + FilecoinHyperspaceTestnet => false, // Unknown / not applicable, default to false for backwards compatibility - Dev | AnvilHardhat | Morden | Ropsten | Rinkeby | Cronos | CronosTestnet | Kovan - | Sokol | Poa | XDai | Moonbeam | MoonbeamDev | Moonriver | Moonbase | Evmos - | EvmosTestnet | Chiado | Aurora | AuroraTestnet | Canto | CantoTestnet - | ScrollAlphaTestnet | Metis => false, + Dev | AnvilHardhat | Morden | Ropsten | Rinkeby | Cronos | CronosTestnet | Kovan | + Sokol | Poa | XDai | Moonbeam | MoonbeamDev | Moonriver | Moonbase | Evmos | + EvmosTestnet | Chiado | Aurora | AuroraTestnet | Canto | CantoTestnet | + ScrollAlphaTestnet | Metis => false, } } @@ -515,7 +515,7 @@ impl Chain { AnvilHardhat | Dev | Morden | MoonbeamDev | FilecoinMainnet => { // this is explicitly exhaustive so we don't forget to add new urls when adding a // new chain - return None; + return None } }; @@ -536,29 +536,29 @@ impl Chain { use Chain::*; let api_key_name = match self { - Mainnet - | Morden - | Ropsten - | Kovan - | Rinkeby - | Goerli - | Optimism - | OptimismGoerli - | OptimismKovan - | BinanceSmartChain - | BinanceSmartChainTestnet - | Arbitrum - | ArbitrumTestnet - | ArbitrumGoerli - | ArbitrumNova - | Cronos - | CronosTestnet - | Aurora - | AuroraTestnet - | Celo - | CeloAlfajores - | CeloBaklava - | BaseGoerli => "ETHERSCAN_API_KEY", + Mainnet | + Morden | + Ropsten | + Kovan | + Rinkeby | + Goerli | + Optimism | + OptimismGoerli | + OptimismKovan | + BinanceSmartChain | + BinanceSmartChainTestnet | + Arbitrum | + ArbitrumTestnet | + ArbitrumGoerli | + ArbitrumNova | + Cronos | + CronosTestnet | + Aurora | + AuroraTestnet | + Celo | + CeloAlfajores | + CeloBaklava | + BaseGoerli => "ETHERSCAN_API_KEY", Avalanche | AvalancheFuji => "SNOWTRACE_API_KEY", @@ -573,25 +573,25 @@ impl Chain { Boba => "BOBASCAN_API_KEY", // Explicitly exhaustive. See NB above. - XDai - | ScrollAlphaTestnet - | Metis - | Chiado - | Sepolia - | Rsk - | Sokol - | Poa - | Oasis - | Emerald - | EmeraldTestnet - | Evmos - | EvmosTestnet - | AnvilHardhat - | Dev - | ZkSync - | ZkSyncTestnet - | FilecoinMainnet - | FilecoinHyperspaceTestnet => return None, + XDai | + ScrollAlphaTestnet | + Metis | + Chiado | + Sepolia | + Rsk | + Sokol | + Poa | + Oasis | + Emerald | + EmeraldTestnet | + Evmos | + EvmosTestnet | + AnvilHardhat | + Dev | + ZkSync | + ZkSyncTestnet | + FilecoinMainnet | + FilecoinHyperspaceTestnet => return None, }; Some(api_key_name) diff --git a/ethers-core/src/types/ens.rs b/ethers-core/src/types/ens.rs index ad7cf7ffb..baa2bebe6 100644 --- a/ethers-core/src/types/ens.rs +++ b/ethers-core/src/types/ens.rs @@ -34,7 +34,7 @@ impl Decodable for NameOrAddress { fn decode(rlp: &rlp::Rlp) -> Result { // An address (H160) is 20 bytes, so let's only accept 20 byte rlp string encodings. if !rlp.is_data() { - return Err(rlp::DecoderError::RlpExpectedToBeData); + return Err(rlp::DecoderError::RlpExpectedToBeData) } // the data needs to be 20 bytes long diff --git a/ethers-core/src/types/filter.rs b/ethers-core/src/types/filter.rs index 432af1575..605c14bea 100644 --- a/ethers-core/src/types/filter.rs +++ b/ethers-core/src/types/filter.rs @@ -443,46 +443,46 @@ impl<'de> Deserialize<'de> for Filter { match key.as_str() { "fromBlock" => { if from_block.is_some() { - return Err(serde::de::Error::duplicate_field("fromBlock")); + return Err(serde::de::Error::duplicate_field("fromBlock")) } if block_hash.is_some() { return Err(serde::de::Error::custom( "fromBlock not allowed with blockHash", - )); + )) } from_block = Some(map.next_value()?) } "toBlock" => { if to_block.is_some() { - return Err(serde::de::Error::duplicate_field("toBlock")); + return Err(serde::de::Error::duplicate_field("toBlock")) } if block_hash.is_some() { return Err(serde::de::Error::custom( "toBlock not allowed with blockHash", - )); + )) } to_block = Some(map.next_value()?) } "blockHash" => { if block_hash.is_some() { - return Err(serde::de::Error::duplicate_field("blockHash")); + return Err(serde::de::Error::duplicate_field("blockHash")) } if from_block.is_some() || to_block.is_some() { return Err(serde::de::Error::custom( "fromBlock,toBlock not allowed with blockHash", - )); + )) } block_hash = Some(map.next_value()?) } "address" => { if address.is_some() { - return Err(serde::de::Error::duplicate_field("address")); + return Err(serde::de::Error::duplicate_field("address")) } address = Some(map.next_value()?) } "topics" => { if topics.is_some() { - return Err(serde::de::Error::duplicate_field("topics")); + return Err(serde::de::Error::duplicate_field("topics")) } topics = Some(map.next_value()?) } @@ -504,7 +504,7 @@ impl<'de> Deserialize<'de> for Filter { // maximum allowed filter len if topics_vec.len() > 4 { - return Err(serde::de::Error::custom("exceeded maximum topics len")); + return Err(serde::de::Error::custom("exceeded maximum topics len")) } let mut topics: [Option; 4] = [None, None, None, None]; for (idx, topic) in topics_vec.into_iter().enumerate() { @@ -615,7 +615,7 @@ where let value = serde_json::Value::deserialize(deserializer)?; if value.is_null() { - return Ok(ValueOrArray::Array(Vec::new())); + return Ok(ValueOrArray::Array(Vec::new())) } #[derive(Deserialize)] @@ -668,7 +668,7 @@ impl FilteredParams { /// Returns `true` if the bloom matches the topics pub fn matches_topics(bloom: Bloom, topic_filters: &[BloomFilter]) -> bool { if topic_filters.is_empty() { - return true; + return true } // returns true if a filter matches @@ -677,11 +677,11 @@ impl FilteredParams { for maybe_bloom in filter { is_match = maybe_bloom.as_ref().map(|b| bloom.contains_bloom(b)).unwrap_or(true); if !is_match { - break; + break } } if is_match { - return true; + return true } } false @@ -690,11 +690,11 @@ impl FilteredParams { /// Returns `true` if the bloom contains the address pub fn matches_address(bloom: Bloom, address_filter: &BloomFilter) -> bool { if address_filter.is_empty() { - return true; + return true } else { for maybe_bloom in address_filter { if maybe_bloom.as_ref().map(|b| bloom.contains_bloom(b)).unwrap_or(true) { - return true; + return true } } } @@ -721,14 +721,14 @@ impl FilteredParams { } }; if out.is_empty() { - return None; + return None } Some(out) } pub fn filter_block_range(&self, block_number: u64) -> bool { if self.filter.is_none() { - return true; + return true } let filter = self.filter.as_ref().unwrap(); let mut res = true; @@ -758,7 +758,7 @@ impl FilteredParams { pub fn filter_block_hash(&self, block_hash: H256) -> bool { if let Some(h) = self.filter.as_ref().and_then(|f| f.get_block_hash()) { if h != block_hash { - return false; + return false } } true @@ -769,15 +769,15 @@ impl FilteredParams { match input_address { ValueOrArray::Value(x) => { if log.address != *x { - return false; + return false } } ValueOrArray::Array(x) => { if x.is_empty() { - return true; + return true } if !x.contains(&log.address) { - return false; + return false } } } @@ -799,7 +799,7 @@ impl FilteredParams { ValueOrArray::Array(multi) => { if multi.is_empty() { out = true; - continue; + continue } // Shrink the topics until the last item is Some. let mut new_multi = multi; @@ -809,7 +809,7 @@ impl FilteredParams { // We can discard right away any logs with lesser topics than the filter. if new_multi.len() > log.topics.len() { out = false; - break; + break } let replaced: Option> = self.replace(log, ValueOrArray::Array(new_multi)); @@ -817,7 +817,7 @@ impl FilteredParams { out = false; if log.topics.starts_with(&replaced[..]) { out = true; - break; + break } } } diff --git a/ethers-core/src/types/i256.rs b/ethers-core/src/types/i256.rs index 02e7a48d8..c846bf9bd 100644 --- a/ethers-core/src/types/i256.rs +++ b/ethers-core/src/types/i256.rs @@ -226,7 +226,7 @@ impl I256 { // NOTE: Do the hex conversion here as `U256` implementation can panic. if value.len() > 64 { - return Err(ParseI256Error::IntegerOverflow); + return Err(ParseI256Error::IntegerOverflow) } let mut abs = U256::zero(); @@ -506,8 +506,8 @@ impl I256 { // the result. let overflow = matches!( (self.sign(), rhs.sign(), result.sign()), - (Sign::Positive, Sign::Positive, Sign::Negative) - | (Sign::Negative, Sign::Negative, Sign::Positive) + (Sign::Positive, Sign::Positive, Sign::Negative) | + (Sign::Negative, Sign::Negative, Sign::Positive) ); (result, overflow) @@ -565,8 +565,8 @@ impl I256 { // the result. let overflow = matches!( (self.sign(), rhs.sign(), result.sign()), - (Sign::Positive, Sign::Negative, Sign::Negative) - | (Sign::Negative, Sign::Positive, Sign::Positive) + (Sign::Positive, Sign::Negative, Sign::Negative) | + (Sign::Negative, Sign::Positive, Sign::Positive) ); (result, overflow) diff --git a/ethers-core/src/types/signature.rs b/ethers-core/src/types/signature.rs index 1a6e86bc1..0ec05e7e6 100644 --- a/ethers-core/src/types/signature.rs +++ b/ethers-core/src/types/signature.rs @@ -94,7 +94,7 @@ impl Signature { let address = address.into(); let recovered = self.recover(message)?; if recovered != address { - return Err(SignatureError::VerificationError(address, recovered)); + return Err(SignatureError::VerificationError(address, recovered)) } Ok(()) @@ -200,7 +200,7 @@ impl<'a> TryFrom<&'a [u8]> for Signature { /// and the final byte is the `v` value in 'Electrum' notation. fn try_from(bytes: &'a [u8]) -> Result { if bytes.len() != 65 { - return Err(SignatureError::InvalidLength(bytes.len())); + return Err(SignatureError::InvalidLength(bytes.len())) } let v = bytes[64]; diff --git a/ethers-core/src/types/trace/filter.rs b/ethers-core/src/types/trace/filter.rs index 0403c2909..c09b076ff 100644 --- a/ethers-core/src/types/trace/filter.rs +++ b/ethers-core/src/types/trace/filter.rs @@ -376,7 +376,7 @@ impl Decodable for TraceError { impl open_fastrlp::Decodable for TraceError { fn decode(buf: &mut &[u8]) -> Result { if buf.is_empty() { - return Err(DecodeError::InputTooShort); + return Err(DecodeError::InputTooShort) } let val = buf[0]; let val = Self::from_u8(val).map_err(|_| DecodeError::Custom("Invalid error code"))?; diff --git a/ethers-core/src/types/transaction/eip2718.rs b/ethers-core/src/types/transaction/eip2718.rs index 26ad7b0ca..32d0d8f52 100644 --- a/ethers-core/src/types/transaction/eip2718.rs +++ b/ethers-core/src/types/transaction/eip2718.rs @@ -326,7 +326,7 @@ impl TypedTransaction { // Legacy (0x00) // use the original rlp let decoded_request = TransactionRequest::decode_signed_rlp(rlp)?; - return Ok((Self::Legacy(decoded_request.0), decoded_request.1)); + return Ok((Self::Legacy(decoded_request.0), decoded_request.1)) } let rest = rlp::Rlp::new( @@ -336,12 +336,12 @@ impl TypedTransaction { if first == 0x01 { // EIP-2930 (0x01) let decoded_request = Eip2930TransactionRequest::decode_signed_rlp(&rest)?; - return Ok((Self::Eip2930(decoded_request.0), decoded_request.1)); + return Ok((Self::Eip2930(decoded_request.0), decoded_request.1)) } if first == 0x02 { // EIP-1559 (0x02) let decoded_request = Eip1559TransactionRequest::decode_signed_rlp(&rest)?; - return Ok((Self::Eip1559(decoded_request.0), decoded_request.1)); + return Ok((Self::Eip1559(decoded_request.0), decoded_request.1)) } Err(rlp::DecoderError::Custom("invalid tx type").into()) diff --git a/ethers-core/src/types/transaction/eip712.rs b/ethers-core/src/types/transaction/eip712.rs index 2cb6e9d2e..d3df08a85 100644 --- a/ethers-core/src/types/transaction/eip712.rs +++ b/ethers-core/src/types/transaction/eip712.rs @@ -399,7 +399,7 @@ pub fn encode_data( } else if types.contains_key(&field.r#type) { tokens.push(Token::Uint(U256::zero())); } else { - return Err(Eip712Error::Message(format!("No data found for: `{}`", field.name))); + return Err(Eip712Error::Message(format!("No data found for: `{}`", field.name))) } } } @@ -471,7 +471,7 @@ fn find_type_dependencies<'a>( found: &mut HashSet<&'a str>, ) { if found.contains(primary_type) { - return; + return } if let Some(fields) = types.get(primary_type) { found.insert(primary_type); diff --git a/ethers-core/src/types/transaction/mod.rs b/ethers-core/src/types/transaction/mod.rs index 65f17fa3d..41c277cba 100644 --- a/ethers-core/src/types/transaction/mod.rs +++ b/ethers-core/src/types/transaction/mod.rs @@ -47,7 +47,7 @@ pub(crate) fn extract_chain_id(v: u64) -> Option { // https://eips.ethereum.org/EIPS/eip-155 // if chainid is available, v = {0, 1} + CHAIN_ID * 2 + 35 if v >= 35 { - return Some(crate::types::U64::from((v - 35) >> 1)); + return Some(crate::types::U64::from((v - 35) >> 1)) } None } @@ -81,7 +81,7 @@ fn decode_to( if to.is_data() { None } else { - return Err(rlp::DecoderError::RlpExpectedToBeData); + return Err(rlp::DecoderError::RlpExpectedToBeData) } } else { Some(to.as_val()?) diff --git a/ethers-core/src/types/txpool.rs b/ethers-core/src/types/txpool.rs index c0607c45a..dc6a38ef8 100644 --- a/ethers-core/src/types/txpool.rs +++ b/ethers-core/src/types/txpool.rs @@ -43,19 +43,19 @@ impl<'de> Visitor<'de> for TxpoolInspectSummaryVisitor { { let addr_split: Vec<&str> = value.split(": ").collect(); if addr_split.len() != 2 { - return Err(de::Error::custom("invalid format for TxpoolInspectSummary: to")); + return Err(de::Error::custom("invalid format for TxpoolInspectSummary: to")) } let value_split: Vec<&str> = addr_split[1].split(" wei + ").collect(); if value_split.len() != 2 { - return Err(de::Error::custom("invalid format for TxpoolInspectSummary: gasLimit")); + return Err(de::Error::custom("invalid format for TxpoolInspectSummary: gasLimit")) } let gas_split: Vec<&str> = value_split[1].split(" gas × ").collect(); if gas_split.len() != 2 { - return Err(de::Error::custom("invalid format for TxpoolInspectSummary: gas")); + return Err(de::Error::custom("invalid format for TxpoolInspectSummary: gas")) } let gas_price_split: Vec<&str> = gas_split[1].split(" wei").collect(); if gas_price_split.len() != 2 { - return Err(de::Error::custom("invalid format for TxpoolInspectSummary: gas_price")); + return Err(de::Error::custom("invalid format for TxpoolInspectSummary: gas_price")) } let addr = match addr_split[0] { "" => None, diff --git a/ethers-core/src/types/u256.rs b/ethers-core/src/types/u256.rs index fc45868b3..6d3187ffa 100644 --- a/ethers-core/src/types/u256.rs +++ b/ethers-core/src/types/u256.rs @@ -17,10 +17,10 @@ pub fn u256_from_f64_saturating(mut f: f64) -> U256 { panic!("NaN is not a valid value for U256"); } if f < 0.5 { - return U256::zero(); + return U256::zero() } if f >= 1.157_920_892_373_162e77_f64 { - return U256::max_value(); + return U256::max_value() } // All non-normal cases should have been handled above assert!(f.is_normal()); diff --git a/ethers-core/src/types/uint8.rs b/ethers-core/src/types/uint8.rs index 1f8852028..5803961b6 100644 --- a/ethers-core/src/types/uint8.rs +++ b/ethers-core/src/types/uint8.rs @@ -79,9 +79,7 @@ impl Tokenizable for Uint8 { match token { Token::Int(data) | Token::Uint(data) => { if data > U256::from(u8::MAX) { - return Err(InvalidOutputType( - "Integer overflow when casting to u8".to_string(), - )); + return Err(InvalidOutputType("Integer overflow when casting to u8".to_string())) } Ok(Uint8(data.low_u32() as u8)) } diff --git a/ethers-core/src/utils/anvil.rs b/ethers-core/src/utils/anvil.rs index 97d65c59a..1fe5baf7e 100644 --- a/ethers-core/src/utils/anvil.rs +++ b/ethers-core/src/utils/anvil.rs @@ -255,8 +255,8 @@ impl Anvil { let mut addresses = Vec::new(); let mut is_private_key = false; loop { - if start + Duration::from_millis(self.timeout.unwrap_or(ANVIL_STARTUP_TIMEOUT_MILLIS)) - <= Instant::now() + if start + Duration::from_millis(self.timeout.unwrap_or(ANVIL_STARTUP_TIMEOUT_MILLIS)) <= + Instant::now() { panic!("Timed out waiting for anvil to start. Is anvil installed?") } @@ -264,7 +264,7 @@ impl Anvil { let mut line = String::new(); reader.read_line(&mut line).expect("Failed to read line from anvil process"); if line.contains("Listening on") { - break; + break } if line.starts_with("Private Keys") { diff --git a/ethers-core/src/utils/ganache.rs b/ethers-core/src/utils/ganache.rs index 11721ed52..d040eb73e 100644 --- a/ethers-core/src/utils/ganache.rs +++ b/ethers-core/src/utils/ganache.rs @@ -194,7 +194,7 @@ impl Ganache { let mut line = String::new(); reader.read_line(&mut line).expect("Failed to read line from ganache process"); if line.contains("Listening on") { - break; + break } if line.starts_with("Private Keys") { diff --git a/ethers-core/src/utils/geth.rs b/ethers-core/src/utils/geth.rs index f6608b900..5e1567881 100644 --- a/ethers-core/src/utils/geth.rs +++ b/ethers-core/src/utils/geth.rs @@ -117,7 +117,7 @@ impl GethInstance { // geth ids are trunated let truncated_id = hex::encode(&id.0[..8]); if line.contains("Adding p2p peer") && line.contains(&truncated_id) { - return Ok(()); + return Ok(()) } } Err(GethInstanceError::Timeout("Timed out waiting for geth to add a peer".into())) @@ -532,14 +532,14 @@ impl Geth { // geth 1.9.23 uses "server started" while 1.9.18 uses "endpoint opened" // the unauthenticated api is used for regular non-engine API requests - if line.contains("HTTP endpoint opened") - || (line.contains("HTTP server started") && !line.contains("auth=true")) + if line.contains("HTTP endpoint opened") || + (line.contains("HTTP server started") && !line.contains("auth=true")) { http_started = true; } if p2p_started && http_started { - break; + break } } diff --git a/ethers-core/src/utils/mod.rs b/ethers-core/src/utils/mod.rs index e415fdb3f..faa9052ee 100644 --- a/ethers-core/src/utils/mod.rs +++ b/ethers-core/src/utils/mod.rs @@ -446,7 +446,7 @@ pub fn parse_checksummed(addr: &str, chain_id: Option) -> Result Result<[u8; 32], ConversionError> { let str_bytes: &[u8] = text.as_bytes(); if str_bytes.len() > 32 { - return Err(ConversionError::TextTooLong); + return Err(ConversionError::TextTooLong) } let mut bytes32: [u8; 32] = [0u8; 32]; @@ -492,7 +492,7 @@ where D: Deserializer<'de>, { if bytes.0.len() > 32 { - return Err(serde::de::Error::custom("input too long to be a H256")); + return Err(serde::de::Error::custom("input too long to be a H256")) } // left pad with zeros to 32 bytes @@ -530,10 +530,10 @@ fn estimate_priority_fee(rewards: Vec>) -> U256 { let mut rewards: Vec = rewards.iter().map(|r| r[0]).filter(|r| *r > U256::zero()).collect(); if rewards.is_empty() { - return U256::zero(); + return U256::zero() } if rewards.len() == 1 { - return rewards[0]; + return rewards[0] } // Sort the rewards as we will eventually take the median. rewards.sort(); @@ -560,8 +560,8 @@ fn estimate_priority_fee(rewards: Vec>) -> U256 { // If we encountered a big change in fees at a certain position, then consider only // the values >= it. - let values = if *max_change >= EIP1559_FEE_ESTIMATION_THRESHOLD_MAX_CHANGE.into() - && (max_change_index >= (rewards.len() / 2)) + let values = if *max_change >= EIP1559_FEE_ESTIMATION_THRESHOLD_MAX_CHANGE.into() && + (max_change_index >= (rewards.len() / 2)) { rewards[max_change_index..].to_vec() } else { diff --git a/ethers-etherscan/src/contract.rs b/ethers-etherscan/src/contract.rs index 1aff83910..2942afa66 100644 --- a/ethers-etherscan/src/contract.rs +++ b/ethers-etherscan/src/contract.rs @@ -326,20 +326,20 @@ impl Client { return match src { Some(src) => Ok(src), None => Err(EtherscanError::ContractCodeNotVerified(address)), - }; + } } } let query = self.create_query("contract", "getabi", HashMap::from([("address", address)])); let resp: Response = self.get_json(&query).await?; if resp.result.starts_with("Max rate limit reached") { - return Err(EtherscanError::RateLimitExceeded); + return Err(EtherscanError::RateLimitExceeded) } if resp.result.starts_with("Contract source code not verified") { if let Some(ref cache) = self.cache { cache.set_abi(address, None); } - return Err(EtherscanError::ContractCodeNotVerified(address)); + return Err(EtherscanError::ContractCodeNotVerified(address)) } let abi = serde_json::from_str(&resp.result)?; @@ -370,7 +370,7 @@ impl Client { return match src { Some(src) => Ok(src), None => Err(EtherscanError::ContractCodeNotVerified(address)), - }; + } } } @@ -383,7 +383,7 @@ impl Client { if let Some(ref cache) = self.cache { cache.set_source(address, None); } - return Err(EtherscanError::ContractCodeNotVerified(address)); + return Err(EtherscanError::ContractCodeNotVerified(address)) } let response: Response = self.sanitize_response(response)?; diff --git a/ethers-etherscan/src/errors.rs b/ethers-etherscan/src/errors.rs index b545bd2b1..5f71f52d9 100644 --- a/ethers-etherscan/src/errors.rs +++ b/ethers-etherscan/src/errors.rs @@ -57,8 +57,8 @@ pub(crate) fn is_blocked_by_cloudflare_response(txt: &str) -> bool { /// etherscan/polyscan is protected by cloudflare, which can require captchas to "review the /// security of your connection before proceeding" pub(crate) fn is_cloudflare_security_challenge(txt: &str) -> bool { - txt.contains("https://www.cloudflare.com?utm_source=challenge") - || txt.to_lowercase().contains("checking if the site connection is secure") + txt.contains("https://www.cloudflare.com?utm_source=challenge") || + txt.to_lowercase().contains("checking if the site connection is secure") } #[cfg(test)] diff --git a/ethers-etherscan/src/lib.rs b/ethers-etherscan/src/lib.rs index 9669aff65..c1ea855e4 100644 --- a/ethers-etherscan/src/lib.rs +++ b/ethers-etherscan/src/lib.rs @@ -88,17 +88,17 @@ impl Client { .map_err(Into::into), // Backwards compatibility, ideally these should return an error. - Chain::XDai - | Chain::Chiado - | Chain::Sepolia - | Chain::Rsk - | Chain::Sokol - | Chain::Poa - | Chain::Oasis - | Chain::Emerald - | Chain::EmeraldTestnet - | Chain::Evmos - | Chain::EvmosTestnet => Ok(String::new()), + Chain::XDai | + Chain::Chiado | + Chain::Sepolia | + Chain::Rsk | + Chain::Sokol | + Chain::Poa | + Chain::Oasis | + Chain::Emerald | + Chain::EmeraldTestnet | + Chain::Evmos | + Chain::EvmosTestnet => Ok(String::new()), Chain::AnvilHardhat | Chain::Dev => Err(EtherscanError::LocalNetworksNotSupported), _ => chain @@ -218,9 +218,9 @@ impl Client { ResponseData::Error { result, message, status } => { if let Some(ref result) = result { if result.starts_with("Max rate limit reached") { - return Err(EtherscanError::RateLimitExceeded); + return Err(EtherscanError::RateLimitExceeded) } else if result.to_lowercase() == "invalid api key" { - return Err(EtherscanError::InvalidApiKey); + return Err(EtherscanError::InvalidApiKey) } } Err(EtherscanError::ErrorResponse { status, message, result }) @@ -407,10 +407,10 @@ impl Cache { .checked_sub(Duration::from_secs(inner.expiry)) .is_some() { - return None; + return None } - return Some(inner.data); + return Some(inner.data) } None } diff --git a/ethers-middleware/src/gas_oracle/cache.rs b/ethers-middleware/src/gas_oracle/cache.rs index 320fc8b90..482d96250 100644 --- a/ethers-middleware/src/gas_oracle/cache.rs +++ b/ethers-middleware/src/gas_oracle/cache.rs @@ -45,7 +45,7 @@ impl Cached { let lock = self.0.read().await; if let Some((last_fetch, value)) = lock.as_ref() { if Instant::now().duration_since(*last_fetch) < validity { - return Ok(value.clone()); + return Ok(value.clone()) } } } @@ -55,7 +55,7 @@ impl Cached { // Check again, a concurrent thread may have raced us to the write. if let Some((last_fetch, value)) = lock.as_ref() { if Instant::now().duration_since(*last_fetch) < validity { - return Ok(value.clone()); + return Ok(value.clone()) } } // Set a fresh value diff --git a/ethers-middleware/src/gas_oracle/median.rs b/ethers-middleware/src/gas_oracle/median.rs index 73aff5eb6..def9c55f2 100644 --- a/ethers-middleware/src/gas_oracle/median.rs +++ b/ethers-middleware/src/gas_oracle/median.rs @@ -50,7 +50,7 @@ impl Median { ); let values = values.collect::>(); if values.is_empty() { - return Err(GasOracleError::NoValues); + return Err(GasOracleError::NoValues) } Ok(values) } @@ -100,7 +100,7 @@ where { assert!((0.0..=1.0).contains(&fractile)); if values.is_empty() { - return None; + return None } let weight_rank = fractile * values.iter().map(|(weight, _)| *weight).sum::(); values.sort_unstable_by(|a, b| key(&a.1).cmp(key(&b.1))); @@ -108,7 +108,7 @@ where for (weight, value) in values.iter() { cumulative_weight += *weight; if cumulative_weight >= weight_rank { - return Some(value); + return Some(value) } } // By the last element, cumulative_weight == weight_rank and we should have diff --git a/ethers-middleware/src/nonce_manager.rs b/ethers-middleware/src/nonce_manager.rs index b7781f600..996f30f58 100644 --- a/ethers-middleware/src/nonce_manager.rs +++ b/ethers-middleware/src/nonce_manager.rs @@ -43,7 +43,7 @@ where ) -> Result> { if self.initialized.load(Ordering::SeqCst) { // return current nonce - return Ok(self.nonce.load(Ordering::SeqCst).into()); + return Ok(self.nonce.load(Ordering::SeqCst).into()) } let _guard = self.init_guard.lock().await; @@ -51,7 +51,7 @@ where // do this again in case multiple tasks enter this codepath if self.initialized.load(Ordering::SeqCst) { // return current nonce - return Ok(self.nonce.load(Ordering::SeqCst).into()); + return Ok(self.nonce.load(Ordering::SeqCst).into()) } // initialize the nonce the first time the manager is called diff --git a/ethers-middleware/src/signer.rs b/ethers-middleware/src/signer.rs index f757dc01e..648d2039b 100644 --- a/ethers-middleware/src/signer.rs +++ b/ethers-middleware/src/signer.rs @@ -301,7 +301,7 @@ where .inner .send_transaction(tx, block) .await - .map_err(SignerMiddlewareError::MiddlewareError); + .map_err(SignerMiddlewareError::MiddlewareError) } // if we have a nonce manager set, we should try handling the result in diff --git a/ethers-middleware/src/timelag/mod.rs b/ethers-middleware/src/timelag/mod.rs index 1d1b786f1..258fc15ad 100644 --- a/ethers-middleware/src/timelag/mod.rs +++ b/ethers-middleware/src/timelag/mod.rs @@ -244,12 +244,12 @@ where .map_err(ethers_providers::MiddlewareError::from_err)?; if receipt.is_none() { - return Ok(None); + return Ok(None) } let receipt = receipt.expect("checked is_none"); if receipt.block_number.is_none() { - return Ok(Some(receipt)); + return Ok(Some(receipt)) } let number = receipt.block_number.expect("checked is_none"); diff --git a/ethers-providers/src/ext/ens.rs b/ethers-providers/src/ext/ens.rs index 2cdd04dde..f3b0e9de4 100644 --- a/ethers-providers/src/ext/ens.rs +++ b/ethers-providers/src/ext/ens.rs @@ -78,7 +78,7 @@ pub fn reverse_address(addr: Address) -> String { /// Returns the ENS namehash as specified in [EIP-137](https://eips.ethereum.org/EIPS/eip-137) pub fn namehash(name: &str) -> H256 { if name.is_empty() { - return H256::zero(); + return H256::zero() } // iterate in reverse diff --git a/ethers-providers/src/ext/erc.rs b/ethers-providers/src/ext/erc.rs index 4c7d132f7..538ffe712 100644 --- a/ethers-providers/src/ext/erc.rs +++ b/ethers-providers/src/ext/erc.rs @@ -35,7 +35,7 @@ impl FromStr for ERCNFT { split[1], ) } else { - return Err("Unsupported ERC link".to_string()); + return Err("Unsupported ERC link".to_string()) }; let token_split: Vec<&str> = inner_path.split('/').collect(); @@ -50,7 +50,7 @@ impl FromStr for ERCNFT { token_id_bytes, ) } else { - return Err("Unsupported ERC link path".to_string()); + return Err("Unsupported ERC link path".to_string()) }; Ok(ERCNFT { id: token_id, type_: token_type, contract: contract_addr }) } diff --git a/ethers-providers/src/rpc/provider.rs b/ethers-providers/src/rpc/provider.rs index 7dadbf2b7..68c6da4ce 100644 --- a/ethers-providers/src/rpc/provider.rs +++ b/ethers-providers/src/rpc/provider.rs @@ -803,7 +803,7 @@ impl Middleware for Provider

{ }; let data = self.call(&tx.into(), None).await?; if decode_bytes::

(ParamType::Address, data) != owner { - return Err(ProviderError::CustomError("Incorrect owner.".to_string())); + return Err(ProviderError::CustomError("Incorrect owner.".to_string())) } } erc::ERCNFTType::ERC1155 => { @@ -823,9 +823,7 @@ impl Middleware for Provider

{ }; let data = self.call(&tx.into(), None).await?; if decode_bytes::(ParamType::Uint(64), data) == 0 { - return Err(ProviderError::CustomError( - "Incorrect balance.".to_string(), - )); + return Err(ProviderError::CustomError("Incorrect balance.".to_string())) } } } @@ -1110,7 +1108,7 @@ impl Middleware for Provider

{ if fallback.is_err() { // if the older fallback also resulted in an error, we return the error from the // initial attempt - return err; + return err } fallback } @@ -1144,12 +1142,12 @@ impl Provider

{ // otherwise, decode_bytes panics if data.0.is_empty() { - return Err(ProviderError::EnsError(ens_name.to_string())); + return Err(ProviderError::EnsError(ens_name.to_string())) } let resolver_address: Address = decode_bytes(ParamType::Address, data); if resolver_address == Address::zero() { - return Err(ProviderError::EnsError(ens_name.to_string())); + return Err(ProviderError::EnsError(ens_name.to_string())) } if let ParamType::Address = param { @@ -1178,7 +1176,7 @@ impl Provider

{ if data.is_empty() { return Err(ProviderError::EnsError(format!( "`{ens_name}` resolver ({resolver_address:?}) is invalid." - ))); + ))) } let supports_selector = abi::decode(&[ParamType::Bool], data.as_ref()) @@ -1191,7 +1189,7 @@ impl Provider

{ ens_name, resolver_address, hex::encode(selector) - ))); + ))) } Ok(()) @@ -1480,10 +1478,10 @@ pub fn is_local_endpoint(endpoint: &str) -> bool { match host { Host::Domain(domain) => return domain.contains("localhost"), Host::Ipv4(ipv4) => { - return ipv4 == Ipv4Addr::LOCALHOST - || ipv4.is_link_local() - || ipv4.is_loopback() - || ipv4.is_private() + return ipv4 == Ipv4Addr::LOCALHOST || + ipv4.is_link_local() || + ipv4.is_loopback() || + ipv4.is_private() } Host::Ipv6(ipv6) => return ipv6.is_loopback(), } diff --git a/ethers-providers/src/rpc/pubsub.rs b/ethers-providers/src/rpc/pubsub.rs index 061a71542..a11579501 100644 --- a/ethers-providers/src/rpc/pubsub.rs +++ b/ethers-providers/src/rpc/pubsub.rs @@ -91,7 +91,7 @@ where fn poll_next(self: Pin<&mut Self>, ctx: &mut Context) -> Poll> { if !self.loaded_elements.is_empty() { let next_element = self.get_mut().loaded_elements.pop_front(); - return Poll::Ready(next_element); + return Poll::Ready(next_element) } let mut this = self.project(); @@ -101,11 +101,11 @@ where Ok(res) => Poll::Ready(Some(res)), Err(err) => { error!("failed to deserialize item {:?}", err); - continue; + continue } }, None => Poll::Ready(None), - }; + } } } } diff --git a/ethers-providers/src/rpc/transports/common.rs b/ethers-providers/src/rpc/transports/common.rs index 965693ab1..072cf7d63 100644 --- a/ethers-providers/src/rpc/transports/common.rs +++ b/ethers-providers/src/rpc/transports/common.rs @@ -144,22 +144,19 @@ impl<'de: 'a, 'a> Deserialize<'de> for Response<'a> { match key { "jsonrpc" => { if jsonrpc { - return Err(de::Error::duplicate_field("jsonrpc")); + return Err(de::Error::duplicate_field("jsonrpc")) } let value = map.next_value()?; if value != "2.0" { - return Err(de::Error::invalid_value( - Unexpected::Str(value), - &"2.0", - )); + return Err(de::Error::invalid_value(Unexpected::Str(value), &"2.0")) } jsonrpc = true; } "id" => { if id.is_some() { - return Err(de::Error::duplicate_field("id")); + return Err(de::Error::duplicate_field("id")) } let value: u64 = map.next_value()?; @@ -167,7 +164,7 @@ impl<'de: 'a, 'a> Deserialize<'de> for Response<'a> { } "result" => { if result.is_some() { - return Err(de::Error::duplicate_field("result")); + return Err(de::Error::duplicate_field("result")) } let value: &RawValue = map.next_value()?; @@ -175,7 +172,7 @@ impl<'de: 'a, 'a> Deserialize<'de> for Response<'a> { } "error" => { if error.is_some() { - return Err(de::Error::duplicate_field("error")); + return Err(de::Error::duplicate_field("error")) } let value: JsonRpcError = map.next_value()?; @@ -183,7 +180,7 @@ impl<'de: 'a, 'a> Deserialize<'de> for Response<'a> { } "method" => { if method.is_some() { - return Err(de::Error::duplicate_field("method")); + return Err(de::Error::duplicate_field("method")) } let value: &str = map.next_value()?; @@ -191,7 +188,7 @@ impl<'de: 'a, 'a> Deserialize<'de> for Response<'a> { } "params" => { if params.is_some() { - return Err(de::Error::duplicate_field("params")); + return Err(de::Error::duplicate_field("params")) } let value: Params = map.next_value()?; @@ -208,7 +205,7 @@ impl<'de: 'a, 'a> Deserialize<'de> for Response<'a> { // jsonrpc version must be present in all responses if !jsonrpc { - return Err(de::Error::missing_field("jsonrpc")); + return Err(de::Error::missing_field("jsonrpc")) } match (id, result, error, method, params) { diff --git a/ethers-providers/src/rpc/transports/http.rs b/ethers-providers/src/rpc/transports/http.rs index 2fa745d9e..6198bf2fe 100644 --- a/ethers-providers/src/rpc/transports/http.rs +++ b/ethers-providers/src/rpc/transports/http.rs @@ -104,7 +104,7 @@ impl JsonRpcClient for Provider { err: serde::de::Error::custom("unexpected notification over HTTP transport"), text: String::from_utf8_lossy(&body).to_string(), }; - return Err(err); + return Err(err) } Err(err) => { return Err(ClientError::SerdeJson { diff --git a/ethers-providers/src/rpc/transports/ipc.rs b/ethers-providers/src/rpc/transports/ipc.rs index 2db0b2e54..2ead47299 100644 --- a/ethers-providers/src/rpc/transports/ipc.rs +++ b/ethers-providers/src/rpc/transports/ipc.rs @@ -351,7 +351,7 @@ impl Shared { let read = reader.read_buf(&mut buf).await?; if read == 0 { // eof, socket was closed - return Err(IpcError::ServerExit); + return Err(IpcError::ServerExit) } // parse the received bytes into 0-n jsonrpc messages @@ -427,7 +427,7 @@ impl Shared { Some(tx) => tx, None => { tracing::warn!(%id, "no pending request exists for the response ID"); - return; + return } }; @@ -448,7 +448,7 @@ impl Shared { id = ?params.subscription, "no subscription exists for the notification ID" ); - return; + return } }; diff --git a/ethers-providers/src/rpc/transports/legacy_ws.rs b/ethers-providers/src/rpc/transports/legacy_ws.rs index 104c25b67..a150868a6 100644 --- a/ethers-providers/src/rpc/transports/legacy_ws.rs +++ b/ethers-providers/src/rpc/transports/legacy_ws.rs @@ -258,13 +258,13 @@ where loop { if self.is_done() { debug!("work complete"); - break; + break } if let Err(e) = self.tick().await { error!("Received a WebSocket error: {:?}", e); self.close_all_subscriptions(); - break; + break } } }; @@ -361,7 +361,7 @@ where // subscription channel was closed on the receiver end stream.remove(); } - return Err(to_client_error(err)); + return Err(to_client_error(err)) } } diff --git a/ethers-providers/src/rpc/transports/quorum.rs b/ethers-providers/src/rpc/transports/quorum.rs index 0447ca44f..127419fc8 100644 --- a/ethers-providers/src/rpc/transports/quorum.rs +++ b/ethers-providers/src/rpc/transports/quorum.rs @@ -188,16 +188,16 @@ impl QuorumProvider { v } else { // at this time no normalization is required for calls with zero parameters. - return; + return }; match method { - "eth_call" - | "eth_createAccessList" - | "eth_getStorageAt" - | "eth_getCode" - | "eth_getProof" - | "trace_call" - | "trace_block" => { + "eth_call" | + "eth_createAccessList" | + "eth_getStorageAt" | + "eth_getCode" | + "eth_getProof" | + "trace_call" | + "trace_block" => { // calls that include the block number in the params at the last index of json array if let Some(block) = params.as_array_mut().and_then(|arr| arr.last_mut()) { if Some("latest") == block.as_str() { @@ -303,13 +303,13 @@ impl<'a, T> Future for QuorumRequest<'a, T> { *weight += response_weight; if *weight >= this.inner.quorum_weight { // reached quorum with multiple responses - return Poll::Ready(Ok(val)); + return Poll::Ready(Ok(val)) } else { this.responses.push((val, response_weight)); } } else if response_weight >= this.inner.quorum_weight { // reached quorum with single response - return Poll::Ready(Ok(val)); + return Poll::Ready(Ok(val)) } else { this.responses.push((val, response_weight)); } @@ -536,14 +536,14 @@ impl Stream for QuorumStream { if *weight >= this.quorum_weight { // reached quorum with multiple notification this.benched.push(stream); - return Poll::Ready(Some(val)); + return Poll::Ready(Some(val)) } else { this.responses.push((val, response_weight)); } } else if response_weight >= this.quorum_weight { // reached quorum with single notification this.benched.push(stream); - return Poll::Ready(Some(val)); + return Poll::Ready(Some(val)) } else { this.responses.push((val, response_weight)); } @@ -558,7 +558,7 @@ impl Stream for QuorumStream { } if this.active.is_empty() && this.benched.is_empty() { - return Poll::Ready(None); + return Poll::Ready(None) } Poll::Pending } diff --git a/ethers-providers/src/rpc/transports/retry.rs b/ethers-providers/src/rpc/transports/retry.rs index 1065dcd64..ba283b311 100644 --- a/ethers-providers/src/rpc/transports/retry.rs +++ b/ethers-providers/src/rpc/transports/retry.rs @@ -76,7 +76,7 @@ where /// # Example /// /// ``` - /// + /// /// # async fn demo() { /// use ethers_providers::{Http, RetryClient, HttpRateLimitRetryPolicy}; /// use std::time::Duration; @@ -293,7 +293,7 @@ where match resp { Ok(ret) => { self.requests_enqueued.fetch_sub(1, Ordering::SeqCst); - return Ok(ret); + return Ok(ret) } Err(err_) => err = err_, } @@ -304,7 +304,7 @@ where rate_limit_retry_number += 1; if rate_limit_retry_number > self.rate_limit_retries { trace!("request timed out after {} retries", self.rate_limit_retries); - return Err(RetryClientError::TimeoutError); + return Err(RetryClientError::TimeoutError) } let current_queued_requests = self.requests_enqueued.load(Ordering::SeqCst) as u64; @@ -344,12 +344,12 @@ where if timeout_retries < self.timeout_retries && maybe_connectivity(&err) { timeout_retries += 1; trace!(err = ?err, "retrying due to spurious network"); - continue; + continue } trace!(err = ?err, "should not retry"); self.requests_enqueued.fetch_sub(1, Ordering::SeqCst); - return Err(RetryClientError::ProviderError(err)); + return Err(RetryClientError::ProviderError(err)) } } } @@ -369,17 +369,17 @@ impl RetryPolicy for HttpRateLimitRetryPolicy { let JsonRpcError { code, message, .. } = err; // alchemy throws it this way if *code == 429 { - return true; + return true } // This is an infura error code for `exceeded project rate limit` if *code == -32005 { - return true; + return true } // alternative alchemy error for specific IPs if *code == -32016 && message.contains("rate limit") { - return true; + return true } match message.as_str() { @@ -405,7 +405,7 @@ impl RetryPolicy for HttpRateLimitRetryPolicy { } if let Ok(resp) = serde_json::from_str::(text) { - return should_retry_json_rpc_error(&resp.error); + return should_retry_json_rpc_error(&resp.error) } false } @@ -421,10 +421,10 @@ impl RetryPolicy for HttpRateLimitRetryPolicy { let backoff_seconds = &data["rate"]["backoff_seconds"]; // infura rate limit error if let Some(seconds) = backoff_seconds.as_u64() { - return Some(Duration::from_secs(seconds)); + return Some(Duration::from_secs(seconds)) } if let Some(seconds) = backoff_seconds.as_f64() { - return Some(Duration::from_secs(seconds as u64 + 1)); + return Some(Duration::from_secs(seconds as u64 + 1)) } } @@ -462,19 +462,19 @@ fn compute_unit_offset_in_secs( fn maybe_connectivity(err: &ProviderError) -> bool { if let ProviderError::HTTPError(reqwest_err) = err { if reqwest_err.is_timeout() { - return true; + return true } #[cfg(not(target_arch = "wasm32"))] if reqwest_err.is_connect() { - return true; + return true } // Error HTTP codes (5xx) are considered connectivity issues and will prompt retry if let Some(status) = reqwest_err.status() { let code = status.as_u16(); if (500..600).contains(&code) { - return true; + return true } } } diff --git a/ethers-providers/src/rpc/transports/ws/backend.rs b/ethers-providers/src/rpc/transports/ws/backend.rs index e06992f60..6a4bef661 100644 --- a/ethers-providers/src/rpc/transports/ws/backend.rs +++ b/ethers-providers/src/rpc/transports/ws/backend.rs @@ -88,7 +88,7 @@ impl WsBackend { trace!(%item, "Deserialized message"); let res = self.handler.unbounded_send(item); if res.is_err() { - return Err(WsClientError::DeadChannel); + return Err(WsClientError::DeadChannel) } } Err(e) => { diff --git a/ethers-providers/src/rpc/transports/ws/manager.rs b/ethers-providers/src/rpc/transports/ws/manager.rs index 46b2a466f..5f25ad175 100644 --- a/ethers-providers/src/rpc/transports/ws/manager.rs +++ b/ethers-providers/src/rpc/transports/ws/manager.rs @@ -77,7 +77,7 @@ impl SubscriptionManager { channel, }; // reuse the RPC ID. this is somewhat dirty. - return unsub_request.serialize_raw(id).ok(); + return unsub_request.serialize_raw(id).ok() } tracing::trace!("No current server id"); } @@ -96,7 +96,7 @@ impl SubscriptionManager { server_id = format!("0x{server_id:x}"), "No aliased subscription found" ); - return; + return } let id = id_opt.unwrap(); @@ -236,7 +236,7 @@ impl RequestManager { async fn reconnect(&mut self) -> Result<(), WsClientError> { if self.reconnects == 0 { - return Err(WsClientError::TooManyReconnects); + return Err(WsClientError::TooManyReconnects) } self.reconnects -= 1; diff --git a/ethers-providers/src/rpc/transports/ws/types.rs b/ethers-providers/src/rpc/transports/ws/types.rs index 055395860..5dbcc3ab3 100644 --- a/ethers-providers/src/rpc/transports/ws/types.rs +++ b/ethers-providers/src/rpc/transports/ws/types.rs @@ -67,7 +67,7 @@ impl<'de> Deserialize<'de> for PubSubItem { match key { "jsonrpc" => { if jsonrpc { - return Err(de::Error::duplicate_field("jsonrpc")); + return Err(de::Error::duplicate_field("jsonrpc")) } let value = map.next_value()?; @@ -75,14 +75,14 @@ impl<'de> Deserialize<'de> for PubSubItem { return Err(de::Error::invalid_value( de::Unexpected::Str(value), &"2.0", - )); + )) } jsonrpc = true; } "id" => { if id.is_some() { - return Err(de::Error::duplicate_field("id")); + return Err(de::Error::duplicate_field("id")) } let value: u64 = map.next_value()?; @@ -90,7 +90,7 @@ impl<'de> Deserialize<'de> for PubSubItem { } "result" => { if result.is_some() { - return Err(de::Error::duplicate_field("result")); + return Err(de::Error::duplicate_field("result")) } let value: Box = map.next_value()?; @@ -98,7 +98,7 @@ impl<'de> Deserialize<'de> for PubSubItem { } "error" => { if error.is_some() { - return Err(de::Error::duplicate_field("error")); + return Err(de::Error::duplicate_field("error")) } let value: JsonRpcError = map.next_value()?; @@ -106,7 +106,7 @@ impl<'de> Deserialize<'de> for PubSubItem { } "method" => { if method.is_some() { - return Err(de::Error::duplicate_field("method")); + return Err(de::Error::duplicate_field("method")) } let value: String = map.next_value()?; @@ -114,7 +114,7 @@ impl<'de> Deserialize<'de> for PubSubItem { } "params" => { if params.is_some() { - return Err(de::Error::duplicate_field("params")); + return Err(de::Error::duplicate_field("params")) } let value: Notification = map.next_value()?; @@ -131,7 +131,7 @@ impl<'de> Deserialize<'de> for PubSubItem { // jsonrpc version must be present in all responses if !jsonrpc { - return Err(de::Error::missing_field("jsonrpc")); + return Err(de::Error::missing_field("jsonrpc")) } match (id, result, error, method, params) { diff --git a/ethers-providers/src/stream/tx_stream.rs b/ethers-providers/src/stream/tx_stream.rs index 3067088be..3444df59f 100644 --- a/ethers-providers/src/stream/tx_stream.rs +++ b/ethers-providers/src/stream/tx_stream.rs @@ -101,7 +101,7 @@ where if let Some(tx) = this.buffered.pop_front() { this.push_tx(tx); } else { - break; + break } } @@ -117,7 +117,7 @@ where } Poll::Ready(None) => { this.stream_done = true; - break; + break } _ => break, } @@ -126,12 +126,12 @@ where // poll running futures if let tx @ Poll::Ready(Some(_)) = this.pending.poll_next_unpin(cx) { - return tx; + return tx } if this.stream_done && this.pending.is_empty() { // all done - return Poll::Ready(None); + return Poll::Ready(None) } Poll::Pending @@ -233,7 +233,7 @@ mod tests { sent.iter().map(|tx| tx.transaction_hash).collect::>(); assert_eq!(sent_txs, watch_received.iter().map(|tx| tx.hash).collect()); assert_eq!(sent_txs, sub_received.iter().map(|tx| tx.hash).collect()); - break; + break } } } diff --git a/ethers-providers/src/stream/watcher.rs b/ethers-providers/src/stream/watcher.rs index 9ea5e893c..8c37ec26f 100644 --- a/ethers-providers/src/stream/watcher.rs +++ b/ethers-providers/src/stream/watcher.rs @@ -105,7 +105,7 @@ where // for new logs FilterWatcherState::NextItem(iter) => { if let item @ Some(_) = iter.next() { - return Poll::Ready(item); + return Poll::Ready(item) } FilterWatcherState::WaitForInterval } diff --git a/ethers-providers/src/toolbox/log_query.rs b/ethers-providers/src/toolbox/log_query.rs index b74551e18..f71ab536a 100644 --- a/ethers-providers/src/toolbox/log_query.rs +++ b/ethers-providers/src/toolbox/log_query.rs @@ -136,7 +136,7 @@ where // no more pages to load, and everything is consumed // can safely assume this will always be set in this state if from_block > self.last_block.unwrap() { - return Poll::Ready(None); + return Poll::Ready(None) } // load next page self.from_block = Some(to_block + 1); diff --git a/ethers-providers/src/toolbox/pending_escalator.rs b/ethers-providers/src/toolbox/pending_escalator.rs index f8473d650..b77135257 100644 --- a/ethers-providers/src/toolbox/pending_escalator.rs +++ b/ethers-providers/src/toolbox/pending_escalator.rs @@ -193,7 +193,7 @@ where let fut = this.provider.send_raw_transaction(next_to_broadcast); *this.state = BroadcastingNew(fut); cx.waker().wake_by_ref(); - return Poll::Pending; + return Poll::Pending } } check_all_receipts!(cx, this); diff --git a/ethers-providers/src/toolbox/pending_transaction.rs b/ethers-providers/src/toolbox/pending_transaction.rs index 0eb607152..cbe2e0a08 100644 --- a/ethers-providers/src/toolbox/pending_transaction.rs +++ b/ethers-providers/src/toolbox/pending_transaction.rs @@ -183,7 +183,7 @@ impl<'a, P: JsonRpcClient> Future for PendingTransaction<'a, P> { if *this.retries_remaining == 0 { tracing::debug!("Dropped from mempool, pending tx {:?}", *this.tx_hash); *this.state = PendingTxState::Completed; - return Poll::Ready(Ok(None)); + return Poll::Ready(Ok(None)) } *this.retries_remaining -= 1; @@ -242,7 +242,7 @@ impl<'a, P: JsonRpcClient> Future for PendingTransaction<'a, P> { } else { let receipt = receipt.take(); *this.state = PendingTxState::Completed; - return Poll::Ready(Ok(receipt)); + return Poll::Ready(Ok(receipt)) } } PendingTxState::PausedGettingBlockNumber(receipt) => { @@ -273,7 +273,7 @@ impl<'a, P: JsonRpcClient> Future for PendingTransaction<'a, P> { if current_block > inclusion_block + *this.confirmations - 1 { let receipt = Some(receipt); *this.state = PendingTxState::Completed; - return Poll::Ready(Ok(receipt)); + return Poll::Ready(Ok(receipt)) } else { tracing::trace!(tx_hash = ?this.tx_hash, "confirmations {}/{}", current_block - inclusion_block + 1, this.confirmations); *this.state = PendingTxState::PausedGettingBlockNumber(Some(receipt)); diff --git a/ethers-signers/src/ledger/app.rs b/ethers-signers/src/ledger/app.rs index 6b7927bda..2f4125eb2 100644 --- a/ethers-signers/src/ledger/app.rs +++ b/ethers-signers/src/ledger/app.rs @@ -125,7 +125,7 @@ impl LedgerEthereum { let answer = block_on(transport.exchange(&command))?; let result = answer.data().ok_or(LedgerError::UnexpectedNullResponse)?; if result.len() < 4 { - return Err(LedgerError::ShortResponse { got: result.len(), at_least: 4 }); + return Err(LedgerError::ShortResponse { got: result.len(), at_least: 4 }) } let version = format!("{}.{}.{}", result[1], result[2], result[3]); tracing::debug!(version, "Retrieved version from device"); @@ -190,7 +190,7 @@ impl LedgerEthereum { // Enforce app version is greater than EIP712_MIN_VERSION if !req.matches(&version) { - return Err(LedgerError::UnsupportedAppVersion(EIP712_MIN_VERSION.to_string())); + return Err(LedgerError::UnsupportedAppVersion(EIP712_MIN_VERSION.to_string())) } let domain_separator = @@ -214,7 +214,7 @@ impl LedgerEthereum { payload: &Vec, ) -> Result { if payload.is_empty() { - return Err(LedgerError::EmptyPayload); + return Err(LedgerError::EmptyPayload) } let transport = self.transport.lock().await; let mut command = APDUCommand { @@ -244,7 +244,7 @@ impl LedgerEthereum { let data = answer.as_ref().expect("just assigned").data(); if data.is_none() { - return Err(LedgerError::UnexpectedNullResponse); + return Err(LedgerError::UnexpectedNullResponse) } tracing::debug!( response = hex::encode(data.expect("just checked")), @@ -258,7 +258,7 @@ impl LedgerEthereum { let answer = answer.expect("payload is non-empty, therefore loop ran"); let result = answer.data().expect("check in loop"); if result.len() < 65 { - return Err(LedgerError::ShortResponse { got: result.len(), at_least: 65 }); + return Err(LedgerError::ShortResponse { got: result.len(), at_least: 65 }) } let v = result[0] as u64; let r = U256::from_big_endian(&result[1..33]); diff --git a/ethers-signers/src/trezor/app.rs b/ethers-signers/src/trezor/app.rs index b2113f5ea..e8fb1e297 100644 --- a/ethers-signers/src/trezor/app.rs +++ b/ethers-signers/src/trezor/app.rs @@ -88,7 +88,7 @@ impl TrezorEthereum { let req = semver::VersionReq::parse(min_version)?; // Enforce firmware version is greater than "min_version" if !req.matches(&version) { - return Err(TrezorError::UnsupportedFirmwareVersion(min_version.to_string())); + return Err(TrezorError::UnsupportedFirmwareVersion(min_version.to_string())) } Ok(()) diff --git a/ethers-signers/src/wallet/private_key.rs b/ethers-signers/src/wallet/private_key.rs index 0cb5f30fe..e90578502 100644 --- a/ethers-signers/src/wallet/private_key.rs +++ b/ethers-signers/src/wallet/private_key.rs @@ -101,9 +101,9 @@ impl Wallet { impl PartialEq for Wallet { fn eq(&self, other: &Self) -> bool { - self.signer.to_bytes().eq(&other.signer.to_bytes()) - && self.address == other.address - && self.chain_id == other.chain_id + self.signer.to_bytes().eq(&other.signer.to_bytes()) && + self.address == other.address && + self.chain_id == other.chain_id } } @@ -134,7 +134,7 @@ impl FromStr for Wallet { let src = hex::decode(src)?; if src.len() != 32 { - return Err(WalletError::HexError(hex::FromHexError::InvalidStringLength)); + return Err(WalletError::HexError(hex::FromHexError::InvalidStringLength)) } let sk = SigningKey::from_bytes(src.as_slice().into())?; diff --git a/ethers-solc/src/artifact_output/configurable.rs b/ethers-solc/src/artifact_output/configurable.rs index 03ddd5786..0c87731d0 100644 --- a/ethers-solc/src/artifact_output/configurable.rs +++ b/ethers-solc/src/artifact_output/configurable.rs @@ -152,7 +152,7 @@ pub struct ConfigurableArtifacts { /// _always_ be done using a public constructor or update syntax: /// /// ```rust - /// + /// /// use ethers_solc::{ExtraOutputFiles, ConfigurableArtifacts}; /// let config = ConfigurableArtifacts { /// additional_files: ExtraOutputFiles { metadata: true, ..Default::default() }, @@ -395,7 +395,7 @@ pub struct ExtraOutputValues { /// _always_ be done using a public constructor or update syntax: /// /// ```rust - /// + /// /// use ethers_solc::ExtraOutputValues; /// let config = ExtraOutputValues { /// ir: true, @@ -516,7 +516,7 @@ pub struct ExtraOutputFiles { /// _always_ be done using a public constructor or update syntax: /// /// ```rust - /// + /// /// use ethers_solc::ExtraOutputFiles; /// let config = ExtraOutputFiles { /// metadata: true, @@ -584,8 +584,8 @@ impl ExtraOutputFiles { EvmOutputSelection::ByteCode(BytecodeOutputSelection::SourceMap) => { config.source_map = true; } - EvmOutputSelection::DeployedByteCode(DeployedBytecodeOutputSelection::All) - | EvmOutputSelection::DeployedByteCode( + EvmOutputSelection::DeployedByteCode(DeployedBytecodeOutputSelection::All) | + EvmOutputSelection::DeployedByteCode( DeployedBytecodeOutputSelection::Object, ) => { config.deployed_bytecode = true; diff --git a/ethers-solc/src/artifact_output/mod.rs b/ethers-solc/src/artifact_output/mod.rs index 1a30fd9be..5f7b2bc3d 100644 --- a/ethers-solc/src/artifact_output/mod.rs +++ b/ethers-solc/src/artifact_output/mod.rs @@ -670,7 +670,7 @@ pub trait ArtifactOutput { let out_path = artifacts_folder.join(&candidate); if !already_taken.contains(&out_path) { trace!("found alternative output file={:?} for {:?}", out_path, contract_file); - return out_path; + return out_path } current_parent = current_parent.and_then(|f| f.parent()); } @@ -700,7 +700,7 @@ pub trait ArtifactOutput { .collect(); if !already_taken.contains(&candidate) { trace!("found alternative output file={:?} for {:?}", candidate, contract_file); - return candidate; + return candidate } num += 1; @@ -841,8 +841,8 @@ pub trait ArtifactOutput { // we keep the top most conflicting file unchanged let is_top_most = contracts.iter().enumerate().filter(|(i, _)| *i != idx).all(|(_, c)| { - Path::new(file).components().count() - < Path::new(c.file).components().count() + Path::new(file).components().count() < + Path::new(c.file).components().count() }); if !is_top_most { // we resolve the conflicting by finding a new unique, alternative path @@ -886,10 +886,10 @@ pub trait ArtifactOutput { // source units // there's also no need to create a standalone artifact for source files that // don't contain an ast - if source.source_file.contains_contract_definition() - || source.source_file.ast.is_none() + if source.source_file.contains_contract_definition() || + source.source_file.ast.is_none() { - continue; + continue } // we use file and file stem diff --git a/ethers-solc/src/artifacts/bytecode.rs b/ethers-solc/src/artifacts/bytecode.rs index eaac67025..635aba3c0 100644 --- a/ethers-solc/src/artifacts/bytecode.rs +++ b/ethers-solc/src/artifacts/bytecode.rs @@ -71,7 +71,7 @@ impl CompactBytecode { address: Address, ) -> bool { if !self.object.is_unlinked() { - return true; + return true } let file = file.as_ref(); @@ -84,7 +84,7 @@ impl CompactBytecode { self.link_references.insert(key, contracts); } if self.link_references.is_empty() { - return self.object.resolve().is_some(); + return self.object.resolve().is_some() } } false @@ -156,7 +156,7 @@ impl Bytecode { address: Address, ) -> bool { if !self.object.is_unlinked() { - return true; + return true } let file = file.as_ref(); @@ -169,7 +169,7 @@ impl Bytecode { self.link_references.insert(key, contracts); } if self.link_references.is_empty() { - return self.object.resolve().is_some(); + return self.object.resolve().is_some() } } false @@ -184,7 +184,7 @@ impl Bytecode { { for (file, lib, addr) in libs.into_iter() { if self.link(file, lib, addr) { - return true; + return true } } false @@ -198,7 +198,7 @@ impl Bytecode { { for (name, addr) in libs.into_iter() { if self.link_fully_qualified(name, addr) { - return true; + return true } } false @@ -339,8 +339,8 @@ impl BytecodeObject { pub fn contains_fully_qualified_placeholder(&self, name: impl AsRef) -> bool { if let BytecodeObject::Unlinked(unlinked) = self { let name = name.as_ref(); - unlinked.contains(&utils::library_hash_placeholder(name)) - || unlinked.contains(&utils::library_fully_qualified_placeholder(name)) + unlinked.contains(&utils::library_hash_placeholder(name)) || + unlinked.contains(&utils::library_fully_qualified_placeholder(name)) } else { false } diff --git a/ethers-solc/src/artifacts/contract.rs b/ethers-solc/src/artifacts/contract.rs index 9e0921a73..d0a51fe2a 100644 --- a/ethers-solc/src/artifacts/contract.rs +++ b/ethers-solc/src/artifacts/contract.rs @@ -236,7 +236,7 @@ impl TryFrom for ContractBytecodeSome { fn try_from(value: ContractBytecode) -> Result { if value.abi.is_none() || value.bytecode.is_none() || value.deployed_bytecode.is_none() { - return Err(value); + return Err(value) } Ok(value.unwrap()) } @@ -258,7 +258,7 @@ impl TryFrom for CompactContractSome { fn try_from(value: CompactContract) -> Result { if value.abi.is_none() || value.bin.is_none() || value.bin_runtime.is_none() { - return Err(value); + return Err(value) } Ok(value.unwrap()) } @@ -448,7 +448,7 @@ impl<'a> TryFrom> for CompactContractRefSome<'a> { fn try_from(value: CompactContractRef<'a>) -> Result { if value.abi.is_none() || value.bin.is_none() || value.bin_runtime.is_none() { - return Err(value); + return Err(value) } Ok(value.unwrap()) } diff --git a/ethers-solc/src/artifacts/mod.rs b/ethers-solc/src/artifacts/mod.rs index 304924a7b..835cf777c 100644 --- a/ethers-solc/src/artifacts/mod.rs +++ b/ethers-solc/src/artifacts/mod.rs @@ -567,7 +567,7 @@ impl Libraries { if items.next().is_some() { return Err(SolcError::msg(format!( "failed to parse, too many arguments passed: {lib}" - ))); + ))) } libraries .entry(file.into()) @@ -700,15 +700,15 @@ pub struct OptimizerDetails { impl OptimizerDetails { /// Returns true if no settings are set. pub fn is_empty(&self) -> bool { - self.peephole.is_none() - && self.inliner.is_none() - && self.jumpdest_remover.is_none() - && self.order_literals.is_none() - && self.deduplicate.is_none() - && self.cse.is_none() - && self.constant_optimizer.is_none() - && self.yul.is_none() - && self.yul_details.as_ref().map(|yul| yul.is_empty()).unwrap_or(true) + self.peephole.is_none() && + self.inliner.is_none() && + self.jumpdest_remover.is_none() && + self.order_literals.is_none() && + self.deduplicate.is_none() && + self.cse.is_none() && + self.constant_optimizer.is_none() && + self.yul.is_none() && + self.yul_details.as_ref().map(|yul| yul.is_empty()).unwrap_or(true) } } @@ -1905,7 +1905,7 @@ impl fmt::Display for Error { let msg = self.formatted_message.as_ref().unwrap_or(&self.message); self.fmt_severity(f)?; f.write_str(": ")?; - return f.write_str(msg); + return f.write_str(msg) } // Error (XXXX): Error Message @@ -2075,7 +2075,7 @@ fn fmt_framed_location( if let Some((space_or_line_number, rest)) = line.split_once('|') { // if the potential frame is not just whitespace or numbers, don't color it if !space_or_line_number.chars().all(|c| c.is_whitespace() || c.is_numeric()) { - return f.write_str(line); + return f.write_str(line) } styled(f, Error::frame_style(), |f| { @@ -2192,7 +2192,7 @@ impl SourceFile { pub fn contains_contract_definition(&self) -> bool { if let Some(ref ast) = self.ast { // contract definitions are only allowed at the source-unit level - return ast.nodes.iter().any(|node| node.node_type == NodeType::ContractDefinition); + return ast.nodes.iter().any(|node| node.node_type == NodeType::ContractDefinition) // abstract contract, interfaces: ContractDefinition } diff --git a/ethers-solc/src/artifacts/output_selection.rs b/ethers-solc/src/artifacts/output_selection.rs index b1b835073..769b4d4bb 100644 --- a/ethers-solc/src/artifacts/output_selection.rs +++ b/ethers-solc/src/artifacts/output_selection.rs @@ -482,11 +482,11 @@ impl FromStr for DeployedBytecodeOutputSelection { "evm.deployedBytecode.functionDebugData" => { Ok(DeployedBytecodeOutputSelection::FunctionDebugData) } - "deployed-code" - | "deployed-bin" - | "runtime-code" - | "runtime-bin" - | "evm.deployedBytecode.object" => Ok(DeployedBytecodeOutputSelection::Object), + "deployed-code" | + "deployed-bin" | + "runtime-code" | + "runtime-bin" | + "evm.deployedBytecode.object" => Ok(DeployedBytecodeOutputSelection::Object), "evm.deployedBytecode.opcodes" => Ok(DeployedBytecodeOutputSelection::Opcodes), "evm.deployedBytecode.sourceMap" => Ok(DeployedBytecodeOutputSelection::SourceMap), "evm.deployedBytecode.linkReferences" => { diff --git a/ethers-solc/src/artifacts/serde_helpers.rs b/ethers-solc/src/artifacts/serde_helpers.rs index 2bbbe3c11..c24c263be 100644 --- a/ethers-solc/src/artifacts/serde_helpers.rs +++ b/ethers-solc/src/artifacts/serde_helpers.rs @@ -63,7 +63,7 @@ pub mod json_string_opt { { if let Some(s) = Option::::deserialize(deserializer)? { if s.is_empty() { - return Ok(None); + return Ok(None) } let value = serde_json::Value::String(s); serde_json::from_value(value).map_err(de::Error::custom).map(Some) @@ -100,10 +100,10 @@ pub mod empty_json_object_opt { { let json = serde_json::Value::deserialize(deserializer)?; if json.is_null() { - return Ok(None); + return Ok(None) } if json.as_object().map(|obj| obj.is_empty()).unwrap_or_default() { - return Ok(None); + return Ok(None) } serde_json::from_value(json).map_err(de::Error::custom).map(Some) } diff --git a/ethers-solc/src/cache.rs b/ethers-solc/src/cache.rs index 2d99a0324..b0586712c 100644 --- a/ethers-solc/src/cache.rs +++ b/ethers-solc/src/cache.rs @@ -332,13 +332,13 @@ impl SolFilesCache { if entry.artifacts.is_empty() { // keep entries that didn't emit any artifacts in the first place, such as a // solidity file that only includes error definitions - return true; + return true } if let Some(versions) = files.remove(file.as_path()) { entry.retain_versions(versions); } else { - return false; + return false } !entry.artifacts.is_empty() }); @@ -721,8 +721,8 @@ impl<'a, T: ArtifactOutput> ArtifactsCacheInner<'a, T> { version: &Version, ) -> FilteredSourceInfo { let idx = self.edges.node_id(&file); - if !self.is_dirty(&file, version) - && self.edges.imports(&file).iter().all(|file| !self.is_dirty(file, version)) + if !self.is_dirty(&file, version) && + self.edges.imports(&file).iter().all(|file| !self.is_dirty(file, version)) { FilteredSourceInfo { file, source, idx, dirty: false } } else { @@ -736,11 +736,11 @@ impl<'a, T: ArtifactOutput> ArtifactsCacheInner<'a, T> { if let Some(entry) = self.cache.entry(file) { if entry.content_hash.as_bytes() != hash.as_bytes() { tracing::trace!("changed content hash for source file \"{}\"", file.display()); - return true; + return true } if self.project.solc_config != entry.solc_config { tracing::trace!("changed solc config for source file \"{}\"", file.display()); - return true; + return true } // only check artifact's existence if the file generated artifacts. @@ -753,7 +753,7 @@ impl<'a, T: ArtifactOutput> ArtifactsCacheInner<'a, T> { file.display(), version ); - return true; + return true } if entry.artifacts_for_version(version).any(|artifact_path| { @@ -763,11 +763,11 @@ impl<'a, T: ArtifactOutput> ArtifactsCacheInner<'a, T> { } missing_artifact }) { - return true; + return true } } // all things match, can be reused - return false; + return false } tracing::trace!("Missing cache entry for {}", file.display()); } else { @@ -812,7 +812,7 @@ impl<'a, T: ArtifactOutput> ArtifactsCache<'a, T> { if let Ok(cache) = SolFilesCache::read_joined(&project.paths) { if cache.paths == paths { // unchanged project paths - return cache; + return cache } } } diff --git a/ethers-solc/src/compile/mod.rs b/ethers-solc/src/compile/mod.rs index 99eda0528..b513e8e7a 100644 --- a/ethers-solc/src/compile/mod.rs +++ b/ethers-solc/src/compile/mod.rs @@ -164,7 +164,7 @@ pub struct Solc { impl Default for Solc { fn default() -> Self { if let Ok(solc) = std::env::var("SOLC_PATH") { - return Solc::new(solc); + return Solc::new(solc) } #[cfg(not(target_arch = "wasm32"))] { @@ -172,7 +172,7 @@ impl Default for Solc { .and_then(|vers| Solc::find_svm_installed_version(vers.to_string()).ok()) .flatten() { - return solc; + return solc } } @@ -302,7 +302,7 @@ impl Solc { .join(format!("solc-{version}")); if !solc.is_file() { - return Ok(None); + return Ok(None) } Ok(Some(Solc::new(solc))) } @@ -472,7 +472,7 @@ impl Solc { if !RELEASES.2 { // we skip checksum verification because the underlying request to fetch release info // failed so we have nothing to compare against - return Ok(()); + return Ok(()) } use sha2::Digest; diff --git a/ethers-solc/src/compile/output/info.rs b/ethers-solc/src/compile/output/info.rs index 58a895a2a..1d2be6d61 100644 --- a/ethers-solc/src/compile/output/info.rs +++ b/ethers-solc/src/compile/output/info.rs @@ -63,7 +63,7 @@ impl FromStr for ContractInfo { let path = iter.next().map(str::to_string); if name.ends_with(".sol") || name.contains('/') { - return Err(err()); + return Err(err()) } Ok(Self { path, name }) diff --git a/ethers-solc/src/compile/output/mod.rs b/ethers-solc/src/compile/output/mod.rs index 373dca405..3f9d29fce 100644 --- a/ethers-solc/src/compile/output/mod.rs +++ b/ethers-solc/src/compile/output/mod.rs @@ -282,7 +282,7 @@ impl ProjectCompileOutput { let contract_path = path.as_ref(); let contract_name = contract.as_ref(); if let artifact @ Some(_) = self.compiled_artifacts.find(contract_path, contract_name) { - return artifact; + return artifact } self.cached_artifacts.find(contract_path, contract_name) } @@ -291,7 +291,7 @@ impl ProjectCompileOutput { pub fn find_first(&self, contract_name: impl AsRef) -> Option<&T::Artifact> { let contract_name = contract_name.as_ref(); if let artifact @ Some(_) = self.compiled_artifacts.find_first(contract_name) { - return artifact; + return artifact } self.cached_artifacts.find_first(contract_name) } @@ -316,7 +316,7 @@ impl ProjectCompileOutput { let contract_path = path.as_ref(); let contract_name = contract.as_ref(); if let artifact @ Some(_) = self.compiled_artifacts.remove(contract_path, contract_name) { - return artifact; + return artifact } self.cached_artifacts.remove(contract_path, contract_name) } @@ -336,7 +336,7 @@ impl ProjectCompileOutput { pub fn remove_first(&mut self, contract_name: impl AsRef) -> Option { let contract_name = contract_name.as_ref(); if let artifact @ Some(_) = self.compiled_artifacts.remove_first(contract_name) { - return artifact; + return artifact } self.cached_artifacts.remove_first(contract_name) } @@ -439,9 +439,9 @@ impl AggregatedCompilerOutput { self.errors.iter().any(|err| { if compiler_severity_filter.ge(&err.severity) { if compiler_severity_filter.is_warning() { - return self.has_warning(ignored_error_codes); + return self.has_warning(ignored_error_codes) } - return true; + return true } false }) @@ -510,7 +510,7 @@ impl AggregatedCompilerOutput { /// file name pub fn write_build_infos(&self, build_info_dir: impl AsRef) -> Result<(), SolcIoError> { if self.build_infos.is_empty() { - return Ok(()); + return Ok(()) } let build_info_dir = build_info_dir.as_ref(); std::fs::create_dir_all(build_info_dir) @@ -741,7 +741,7 @@ impl<'a> OutputDiagnostics<'a> { /// Returns true if the contract is a expected to be a test fn is_test>(&self, contract_path: T) -> bool { if contract_path.as_ref().ends_with(".t.sol") { - return true; + return true } self.compiler_output.find_first(&contract_path).map_or(false, |contract| { diff --git a/ethers-solc/src/compile/project.rs b/ethers-solc/src/compile/project.rs index 5b3e0b7a6..1ea58ef09 100644 --- a/ethers-solc/src/compile/project.rs +++ b/ethers-solc/src/compile/project.rs @@ -506,7 +506,7 @@ fn compile_sequential( if filtered_sources.is_empty() { // nothing to compile trace!("skip solc {} {} for empty sources set", solc.as_ref().display(), version); - continue; + continue } trace!( "compiling {} sources with solc \"{}\" {:?}", @@ -538,7 +538,7 @@ fn compile_sequential( version, input.language ); - continue; + continue } let input = input .settings(opt_settings.clone()) @@ -591,7 +591,7 @@ fn compile_parallel( if filtered_sources.is_empty() { // nothing to compile trace!("skip solc {} {} for empty sources set", solc.as_ref().display(), version); - continue; + continue } let dirty_files: Vec = filtered_sources.dirty_files().cloned().collect(); @@ -617,7 +617,7 @@ fn compile_parallel( version, input.language ); - continue; + continue } let job = input diff --git a/ethers-solc/src/config.rs b/ethers-solc/src/config.rs index d7b5c4ab9..e400e231f 100644 --- a/ethers-solc/src/config.rs +++ b/ethers-solc/src/config.rs @@ -191,19 +191,19 @@ impl ProjectPathsConfig { let file = file.as_ref(); for lib in &self.libraries { - if lib.is_relative() - && file.is_absolute() - && file.starts_with(&self.root) - && file.starts_with(self.root.join(lib)) - || file.is_relative() - && lib.is_absolute() - && lib.starts_with(&self.root) - && self.root.join(file).starts_with(lib) + if lib.is_relative() && + file.is_absolute() && + file.starts_with(&self.root) && + file.starts_with(self.root.join(lib)) || + file.is_relative() && + lib.is_absolute() && + lib.starts_with(&self.root) && + self.root.join(file).starts_with(lib) { - return Some(lib); + return Some(lib) } if file.starts_with(lib) { - return Some(lib); + return Some(lib) } } @@ -247,14 +247,14 @@ impl ProjectPathsConfig { { // track the path for this absolute import inside a nested library include_paths.insert(include_path); - return Ok(import); + return Ok(import) } } // also try to resolve absolute imports from the project paths for path in [&self.root, &self.sources, &self.tests, &self.scripts] { if cwd.starts_with(path) { if let Ok(import) = utils::canonicalize(path.join(import)) { - return Ok(import); + return Ok(import) } } } @@ -336,7 +336,7 @@ impl ProjectPathsConfig { // (`/=.../contracts`) and the stripped import also starts with `contracts` if let Ok(adjusted_import) = stripped_import.strip_prefix("contracts/") { if r.path.ends_with("contracts/") && !lib_path.exists() { - return Path::new(&r.path).join(adjusted_import); + return Path::new(&r.path).join(adjusted_import) } } lib_path @@ -416,7 +416,7 @@ impl ProjectPathsConfig { if imported.contains(target_index) { // short circuit nodes that were already imported, if both A.sol and B.sol import C.sol - return Ok(String::new()); + return Ok(String::new()) } imported.insert(*target_index); @@ -437,7 +437,7 @@ impl ProjectPathsConfig { let mut replace_offset = 0; for cap in name_regex.captures_iter(&content.clone()) { if cap.name("ignore").is_some() { - continue; + continue } if let Some(name_match) = vec!["n1", "n2", "n3"].iter().find_map(|name| cap.name(name)) @@ -866,7 +866,7 @@ impl AllowedLibPaths { pub fn args(&self) -> Option<[String; 2]> { let args = self.to_string(); if args.is_empty() { - return None; + return None } Some(["--allow-paths".to_string(), args]) } diff --git a/ethers-solc/src/lib.rs b/ethers-solc/src/lib.rs index c4c541190..10185c91d 100644 --- a/ethers-solc/src/lib.rs +++ b/ethers-solc/src/lib.rs @@ -271,7 +271,7 @@ impl Project { #[cfg(all(feature = "svm-solc", not(target_arch = "wasm32")))] if self.auto_detect { tracing::trace!("using solc auto detection to compile sources"); - return self.svm_compile(sources); + return self.svm_compile(sources) } self.compile_with_version(&self.solc, sources) @@ -348,7 +348,7 @@ impl Project { #[cfg(all(feature = "svm-solc", not(target_arch = "wasm32")))] if self.auto_detect { - return project::ProjectCompiler::with_sources(self, sources)?.compile(); + return project::ProjectCompiler::with_sources(self, sources)?.compile() } let solc = self.configure_solc(self.solc.clone()); @@ -397,7 +397,7 @@ impl Project { if self.auto_detect { return project::ProjectCompiler::with_sources(self, sources)? .with_sparse_output(filter) - .compile(); + .compile() } project::ProjectCompiler::with_sources_and_solc(self, sources, self.solc.clone())? diff --git a/ethers-solc/src/remappings.rs b/ethers-solc/src/remappings.rs index 595c0b0a3..bc403bb85 100644 --- a/ethers-solc/src/remappings.rs +++ b/ethers-solc/src/remappings.rs @@ -83,10 +83,10 @@ impl FromStr for Remapping { .split_once('=') .ok_or_else(|| RemappingError::InvalidRemapping(remapping.to_string()))?; if name.trim().is_empty() { - return Err(RemappingError::EmptyRemappingKey(remapping.to_string())); + return Err(RemappingError::EmptyRemappingKey(remapping.to_string())) } if path.trim().is_empty() { - return Err(RemappingError::EmptyRemappingValue(remapping.to_string())); + return Err(RemappingError::EmptyRemappingValue(remapping.to_string())) } Ok(Remapping { name: name.to_string(), path: path.to_string() }) } @@ -179,9 +179,9 @@ impl Remapping { fn insert_prioritized(mappings: &mut HashMap, key: String, path: PathBuf) { match mappings.entry(key) { Entry::Occupied(mut e) => { - if e.get().components().count() > path.components().count() - || (path.ends_with(DAPPTOOLS_CONTRACTS_DIR) - && !e.get().ends_with(DAPPTOOLS_CONTRACTS_DIR)) + if e.get().components().count() > path.components().count() || + (path.ends_with(DAPPTOOLS_CONTRACTS_DIR) && + !e.get().ends_with(DAPPTOOLS_CONTRACTS_DIR)) { e.insert(path); } @@ -353,7 +353,7 @@ impl RelativeRemappingPathBuf { /// path has a root. pub fn relative(&self) -> PathBuf { if self.original().has_root() { - return self.original().into(); + return self.original().into() } self.parent .as_ref() @@ -506,11 +506,11 @@ impl Candidate { // if the window start and the source dir are the same directory we can end early if // we wrongfully detect something like: `/src/lib/` - if current_level > 0 - && source_dir == window_start - && (is_source_dir(&source_dir) || is_lib_dir(&source_dir)) + if current_level > 0 && + source_dir == window_start && + (is_source_dir(&source_dir) || is_lib_dir(&source_dir)) { - return; + return } candidates.push(Candidate { window_start, source_dir, window_level: current_level }); } @@ -588,9 +588,9 @@ fn find_remapping_candidates( let entry: walkdir::DirEntry = entry; // found a solidity file directly the current dir - if !is_candidate - && entry.file_type().is_file() - && entry.path().extension() == Some("sol".as_ref()) + if !is_candidate && + entry.file_type().is_file() && + entry.path().extension() == Some("sol".as_ref()) { is_candidate = true; } else if entry.file_type().is_dir() { @@ -605,11 +605,11 @@ fn find_remapping_candidates( if entry.path_is_symlink() { if let Ok(target) = utils::canonicalize(entry.path()) { // the symlink points to a parent dir of the current window - if open.components().count() > target.components().count() - && utils::common_ancestor(open, &target).is_some() + if open.components().count() > target.components().count() && + utils::common_ancestor(open, &target).is_some() { // short-circuiting - return Vec::new(); + return Vec::new() } } } @@ -649,12 +649,12 @@ fn find_remapping_candidates( // need to find the actual next window in the event `open` is a lib dir let window_start = next_nested_window(open, current_dir); // finally, we need to merge, adjust candidates from the same level and opening window - if is_candidate - || candidates + if is_candidate || + candidates .iter() .filter(|c| c.window_level == current_level && c.window_start == window_start) - .count() - > 1 + .count() > + 1 { Candidate::merge_on_same_level( &mut candidates, @@ -672,8 +672,8 @@ fn find_remapping_candidates( let distance = dir_distance(&candidate.window_start, &candidate.source_dir); if distance > 1 && candidate.source_dir_ends_with_js_source() { candidate.source_dir = window_start; - } else if !is_source_dir(&candidate.source_dir) - && candidate.source_dir != candidate.window_start + } else if !is_source_dir(&candidate.source_dir) && + candidate.source_dir != candidate.window_start { candidate.source_dir = last_nested_source_dir(open, &candidate.source_dir); } @@ -686,7 +686,7 @@ fn find_remapping_candidates( /// `dir_distance("root/a", "root/a/b/c") == 2` fn dir_distance(root: &Path, current: &Path) -> usize { if root == current { - return 0; + return 0 } if let Ok(rem) = current.strip_prefix(root) { rem.components().count() @@ -700,14 +700,14 @@ fn dir_distance(root: &Path, current: &Path) -> usize { /// window opener is found fn next_nested_window(root: &Path, current: &Path) -> PathBuf { if !is_lib_dir(root) || root == current { - return root.to_path_buf(); + return root.to_path_buf() } if let Ok(rem) = current.strip_prefix(root) { let mut p = root.to_path_buf(); for c in rem.components() { let next = p.join(c); if !is_lib_dir(&next) || !next.ends_with(JS_CONTRACTS_DIR) { - return next; + return next } p = next } @@ -718,15 +718,15 @@ fn next_nested_window(root: &Path, current: &Path) -> PathBuf { /// Finds the last valid source directory in the window (root -> dir) fn last_nested_source_dir(root: &Path, dir: &Path) -> PathBuf { if is_source_dir(dir) { - return dir.to_path_buf(); + return dir.to_path_buf() } let mut p = dir; while let Some(parent) = p.parent() { if parent == root { - return root.to_path_buf(); + return root.to_path_buf() } if is_source_dir(parent) { - return parent.to_path_buf(); + return parent.to_path_buf() } p = parent; } diff --git a/ethers-solc/src/report/mod.rs b/ethers-solc/src/report/mod.rs index dc83be3b3..99cd60f9e 100644 --- a/ethers-solc/src/report/mod.rs +++ b/ethers-solc/src/report/mod.rs @@ -220,7 +220,7 @@ pub(crate) fn unresolved_imports(imports: &[(&Path, &Path)], remappings: &[Remap fn get_global() -> Option<&'static Report> { if GLOBAL_REPORTER_STATE.load(Ordering::SeqCst) != SET { - return None; + return None } unsafe { // This is safe given the invariant that setting the global reporter @@ -240,7 +240,7 @@ where if SCOPED_COUNT.load(Ordering::Acquire) == 0 { // fast path if no scoped reporter has been set; use the global // default. - return if let Some(glob) = get_global() { f(glob) } else { f(&Report::none()) }; + return if let Some(glob) = get_global() { f(glob) } else { f(&Report::none()) } } get_default_scoped(f) @@ -391,7 +391,7 @@ impl Reporter for BasicStdoutReporter { fn on_unresolved_imports(&self, imports: &[(&Path, &Path)], remappings: &[Remapping]) { if imports.is_empty() { - return; + return } println!("{}", format_unresolved_imports(imports, remappings)) } diff --git a/ethers-solc/src/resolver/mod.rs b/ethers-solc/src/resolver/mod.rs index 094748f17..16f7d1d61 100644 --- a/ethers-solc/src/resolver/mod.rs +++ b/ethers-solc/src/resolver/mod.rs @@ -376,8 +376,8 @@ impl Graph { add_node(&mut unresolved, &mut index, &mut resolved_imports, import) .map_err(|err| { match err { - err @ SolcError::ResolveCaseSensitiveFileName { .. } - | err @ SolcError::Resolve(_) => { + err @ SolcError::ResolveCaseSensitiveFileName { .. } | + err @ SolcError::Resolve(_) => { // make the error more helpful by providing additional // context SolcError::FailedResolveImport( @@ -466,7 +466,7 @@ impl Graph { // keep track of processed dependencies, if the dep was already in the set we have // processed it already if !processed_sources.insert(dep) { - continue; + continue } // library import @@ -547,7 +547,7 @@ impl Graph { } if candidates.is_empty() { // nothing to filter anymore - return; + return } } } @@ -668,7 +668,7 @@ impl Graph { mut sets: Vec<&HashSet<&'a crate::SolcVersion>>, ) -> Vec<&'a crate::SolcVersion> { if sets.is_empty() { - return Vec::new(); + return Vec::new() } let mut result = sets.pop().cloned().expect("not empty; qed."); @@ -706,7 +706,7 @@ impl Graph { "resolved solc version compatible with all sources \"{}\"", exact_version ); - return HashMap::from([(exact_version, all_nodes)]); + return HashMap::from([(exact_version, all_nodes)]) } // no version satisfies all nodes @@ -799,7 +799,7 @@ impl VersionedSources { if self.offline { return Err(SolcError::msg(format!( "missing solc \"{version}\" installation in offline mode" - ))); + ))) } else { // install missing solc Solc::blocking_install(version.as_ref())? @@ -922,7 +922,7 @@ impl Node { Err(SourceVersionError::NoMatchingVersionOffline(req)) } else { Err(SourceVersionError::NoMatchingVersion(req)) - }; + } } Ok(()) diff --git a/ethers-solc/src/resolver/tree.rs b/ethers-solc/src/resolver/tree.rs index e140c3ab1..96f58a785 100644 --- a/ethers-solc/src/resolver/tree.rs +++ b/ethers-solc/src/resolver/tree.rs @@ -111,7 +111,7 @@ fn print_node( writeln!(out, "{}{star}", graph.display_node(node_index))?; if !new_node || in_cycle { - return Ok(()); + return Ok(()) } write_stack.push(node_index); @@ -145,7 +145,7 @@ fn print_imports( ) -> io::Result<()> { let imports = graph.imported_nodes(node_index); if imports.is_empty() { - return Ok(()); + return Ok(()) } let mut iter = imports.iter().peekable(); diff --git a/ethers-solc/src/sourcemap.rs b/ethers-solc/src/sourcemap.rs index 1be14c13f..f9b758443 100644 --- a/ethers-solc/src/sourcemap.rs +++ b/ethers-solc/src/sourcemap.rs @@ -79,13 +79,13 @@ impl<'input> TokenStream<'input> { loop { if let Some((_, ch)) = self.chars.peek().cloned() { if !ch.is_ascii_digit() { - break; + break } self.chars.next(); end += 1; } else { end = self.input.len(); - break; + break } } Some(Ok((Token::Number(&self.input[start..end]), start))) @@ -201,13 +201,13 @@ struct SourceElementBuilder { impl fmt::Display for SourceElementBuilder { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - if self.offset.is_none() - && self.length.is_none() - && self.index.is_none() - && self.jump.is_none() - && self.modifier_depth.is_none() + if self.offset.is_none() && + self.length.is_none() && + self.index.is_none() && + self.jump.is_none() && + self.modifier_depth.is_none() { - return Ok(()); + return Ok(()) } if let Some(s) = self.offset { @@ -217,12 +217,12 @@ impl fmt::Display for SourceElementBuilder { s.fmt(f)?; } } - if self.length.is_none() - && self.index.is_none() - && self.jump.is_none() - && self.modifier_depth.is_none() + if self.length.is_none() && + self.index.is_none() && + self.jump.is_none() && + self.modifier_depth.is_none() { - return Ok(()); + return Ok(()) } f.write_char(':')?; @@ -234,7 +234,7 @@ impl fmt::Display for SourceElementBuilder { } } if self.index.is_none() && self.jump.is_none() && self.modifier_depth.is_none() { - return Ok(()); + return Ok(()) } f.write_char(':')?; @@ -243,7 +243,7 @@ impl fmt::Display for SourceElementBuilder { s.fmt(f)?; } if self.jump.is_none() && self.modifier_depth.is_none() { - return Ok(()); + return Ok(()) } f.write_char(':')?; @@ -251,7 +251,7 @@ impl fmt::Display for SourceElementBuilder { s.fmt(f)?; } if self.modifier_depth.is_none() { - return Ok(()); + return Ok(()) } f.write_char(':')?; @@ -291,7 +291,7 @@ impl SourceElementBuilder { fn set_jmp(&mut self, jmp: Jump, i: usize) -> Option { if self.jump.is_some() { - return Some(SyntaxError::new(format!("Jump already set: {i}"))); + return Some(SyntaxError::new(format!("Jump already set: {i}"))) } self.jump = Some(jmp); None @@ -299,7 +299,7 @@ impl SourceElementBuilder { fn set_offset(&mut self, offset: usize, i: usize) -> Option { if self.offset.is_some() { - return Some(SyntaxError::new(format!("Offset already set: {i}"))); + return Some(SyntaxError::new(format!("Offset already set: {i}"))) } self.offset = Some(offset); None @@ -307,7 +307,7 @@ impl SourceElementBuilder { fn set_length(&mut self, length: usize, i: usize) -> Option { if self.length.is_some() { - return Some(SyntaxError::new(format!("Length already set: {i}"))); + return Some(SyntaxError::new(format!("Length already set: {i}"))) } self.length = Some(length); None @@ -315,7 +315,7 @@ impl SourceElementBuilder { fn set_index(&mut self, index: Option, i: usize) -> Option { if self.index.is_some() { - return Some(SyntaxError::new(format!("Index already set: {i}"))); + return Some(SyntaxError::new(format!("Index already set: {i}"))) } self.index = Some(index); None @@ -323,7 +323,7 @@ impl SourceElementBuilder { fn set_modifier(&mut self, modifier_depth: usize, i: usize) -> Option { if self.modifier_depth.is_some() { - return Some(SyntaxError::new(format!("Modifier depth already set: {i}"))); + return Some(SyntaxError::new(format!("Modifier depth already set: {i}"))) } self.modifier_depth = Some(modifier_depth); None @@ -376,7 +376,7 @@ macro_rules! parse_number { macro_rules! bail_opt { ($opt:stmt) => { if let Some(err) = { $opt } { - return Some(Err(err)); + return Some(Err(err)) } }; } @@ -435,10 +435,10 @@ impl<'input> Iterator for Parser<'input> { Some(Err(err)) => return Some(Err(err)), None => { if self.done { - return None; + return None } self.done = true; - break; + break } } } diff --git a/ethers-solc/src/utils.rs b/ethers-solc/src/utils.rs index a01d2eea8..24e45fa47 100644 --- a/ethers-solc/src/utils.rs +++ b/ethers-solc/src/utils.rs @@ -205,7 +205,7 @@ pub fn resolve_library(libs: &[impl AsRef], source: impl AsRef) -> O let contract = lib.join(source); if contract.exists() { // contract exists in / - return Some(contract); + return Some(contract) } // check for //src/name.sol let contract = lib @@ -213,7 +213,7 @@ pub fn resolve_library(libs: &[impl AsRef], source: impl AsRef) -> O .join("src") .join(source.strip_prefix(first_dir).expect("is first component")); if contract.exists() { - return Some(contract); + return Some(contract) } } None @@ -247,7 +247,7 @@ pub fn resolve_absolute_library( let mut parent = cwd.parent()?; while parent != root { if let Ok(import) = canonicalize(parent.join(import)) { - return Some((parent.to_path_buf(), import)); + return Some((parent.to_path_buf(), import)) } parent = parent.parent()?; } @@ -328,7 +328,7 @@ where if let Some(r) = common_ancestor(ret, path.as_ref()) { ret = r; } else { - return None; + return None } } Some(ret) @@ -359,7 +359,7 @@ pub fn common_ancestor(a: impl AsRef, b: impl AsRef) -> Option, fave: &str, alt: &st if !p.exists() { let alt = root.join(alt); if alt.exists() { - return alt; + return alt } } p @@ -396,10 +396,10 @@ pub(crate) fn find_case_sensitive_existing_file(non_existing: &Path) -> Option

Result<()> { eprint!(": {e}"); } eprintln!(); - return Ok(()); + return Ok(()) } Ok(true) => {} } diff --git a/examples/transactions/examples/remove_liquidity.rs b/examples/transactions/examples/remove_liquidity.rs index 036120901..587f64362 100644 --- a/examples/transactions/examples/remove_liquidity.rs +++ b/examples/transactions/examples/remove_liquidity.rs @@ -59,8 +59,8 @@ async fn example() -> Result<()> { println!("Reserves (token A, Token B): ({reserve0}, {reserve1})"); let price = - if reserve0 > reserve1 { 1000 * reserve0 / reserve1 } else { 1000 * reserve1 / reserve0 } - / 1000; + if reserve0 > reserve1 { 1000 * reserve0 / reserve1 } else { 1000 * reserve1 / reserve0 } / + 1000; println!("token0 / token1 price = {price}"); let liquidity = 100.into(); From ee33f3decd99151d202e02126e9ed354e5dc5896 Mon Sep 17 00:00:00 2001 From: Dave Belvedere Date: Wed, 10 May 2023 00:06:29 +1000 Subject: [PATCH 3/7] Fix clippy issues --- ethers-providers/src/rpc/transports/retry.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ethers-providers/src/rpc/transports/retry.rs b/ethers-providers/src/rpc/transports/retry.rs index ba283b311..454e59be3 100644 --- a/ethers-providers/src/rpc/transports/retry.rs +++ b/ethers-providers/src/rpc/transports/retry.rs @@ -561,7 +561,7 @@ mod tests { let err: JsonRpcError = serde_json::from_str(s).unwrap(); let err = ClientError::JsonRpcError(err); - let should_retry = HttpRateLimitRetryPolicy::default().should_retry(&err); + let should_retry = HttpRateLimitRetryPolicy.should_retry(&err); assert!(should_retry); } @@ -574,7 +574,7 @@ mod tests { text: s.to_string(), }; - let should_retry = HttpRateLimitRetryPolicy::default().should_retry(&err); + let should_retry = HttpRateLimitRetryPolicy.should_retry(&err); assert!(should_retry); } } From 3d90bea2099bb399097c138d1a32871778984696 Mon Sep 17 00:00:00 2001 From: Dave Belvedere Date: Wed, 10 May 2023 00:18:50 +1000 Subject: [PATCH 4/7] Test clippy --- ethers-contract/tests/it/abigen.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ethers-contract/tests/it/abigen.rs b/ethers-contract/tests/it/abigen.rs index 7a1cd79ba..7c6f79ddb 100644 --- a/ethers-contract/tests/it/abigen.rs +++ b/ethers-contract/tests/it/abigen.rs @@ -667,7 +667,7 @@ fn can_generate_seaport_1_0() { assert_eq!(hex::encode(FulfillAdvancedOrderCall::selector()), "e7acab24"); assert_codec::(); - let err = SeaportErrors::BadContractSignature(BadContractSignature::default()); + let err = SeaportErrors::BadContractSignature(BadContractSignature); let encoded = err.clone().encode(); assert_eq!(err, SeaportErrors::decode(encoded.clone()).unwrap()); From ac268a7176aae10388d05733baf1c17316e1e04a Mon Sep 17 00:00:00 2001 From: Dave Belvedere Date: Wed, 10 May 2023 00:22:23 +1000 Subject: [PATCH 5/7] Address review comments --- ethers/Cargo.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/ethers/Cargo.toml b/ethers/Cargo.toml index 015dad636..9e11adb36 100644 --- a/ethers/Cargo.toml +++ b/ethers/Cargo.toml @@ -72,6 +72,7 @@ solc-tests = ["ethers-solc?/tests"] # Deprecated solc-sha2-asm = [] +eip712 = [] [dependencies] ethers-addressbook.workspace = true From 8575d7164281b67023217db3a82974a40d7df093 Mon Sep 17 00:00:00 2001 From: Dave Belvedere Date: Wed, 10 May 2023 10:48:57 +1000 Subject: [PATCH 6/7] Address review comments --- ethers-contract/Cargo.toml | 3 +++ ethers-core/Cargo.toml | 3 +++ ethers-core/README.md | 4 ++++ ethers-core/src/types/signature.rs | 28 +++++++++++++--------------- 4 files changed, 23 insertions(+), 15 deletions(-) diff --git a/ethers-contract/Cargo.toml b/ethers-contract/Cargo.toml index d5acc5832..c6ff98d5c 100644 --- a/ethers-contract/Cargo.toml +++ b/ethers-contract/Cargo.toml @@ -58,3 +58,6 @@ legacy = [] rustls = ["ethers-contract-abigen/rustls"] openssl = ["ethers-contract-abigen/openssl"] + +# Deprecated +eip712 = [] \ No newline at end of file diff --git a/ethers-core/Cargo.toml b/ethers-core/Cargo.toml index 909304f5f..8350c38cb 100644 --- a/ethers-core/Cargo.toml +++ b/ethers-core/Cargo.toml @@ -70,3 +70,6 @@ rand.workspace = true celo = ["legacy"] # celo support extends the transaction format with extra fields legacy = [] macros = ["syn", "cargo_metadata", "once_cell"] + +# Deprecated +eip712 = [] \ No newline at end of file diff --git a/ethers-core/README.md b/ethers-core/README.md index 645043192..d202258bd 100644 --- a/ethers-core/README.md +++ b/ethers-core/README.md @@ -10,6 +10,10 @@ other utilities for interacting with the Ethereum ecosystem For more information, please refer to the [book](https://gakonst.com/ethers-rs). +## Feature flags + +- `eip712`: Does nothing. + ## ABI This crate re-exports the [`ethabi`](https://docs.rs/ethabi) crate's functions diff --git a/ethers-core/src/types/signature.rs b/ethers-core/src/types/signature.rs index 0ec05e7e6..f66748eaf 100644 --- a/ethers-core/src/types/signature.rs +++ b/ethers-core/src/types/signature.rs @@ -69,21 +69,6 @@ impl fmt::Display for Signature { } } -impl Signature { - /// Recovers the ethereum address which was used to sign a given EIP712 - /// typed data payload. - /// - /// Recovery signature data uses 'Electrum' notation, this means the `v` - /// value is expected to be either `27` or `28`. - pub fn recover_typed_data(&self, payload: T) -> Result - where - T: super::transaction::eip712::Eip712, - { - let encoded = payload.encode_eip712().map_err(|_| SignatureError::RecoveryError)?; - self.recover(encoded) - } -} - impl Signature { /// Verifies that signature on `message` was produced by `address` pub fn verify(&self, message: M, address: A) -> Result<(), SignatureError> @@ -129,6 +114,19 @@ impl Signature { Ok(Address::from_slice(&hash[12..])) } + /// Recovers the ethereum address which was used to sign a given EIP712 + /// typed data payload. + /// + /// Recovery signature data uses 'Electrum' notation, this means the `v` + /// value is expected to be either `27` or `28`. + pub fn recover_typed_data(&self, payload: T) -> Result + where + T: super::transaction::eip712::Eip712, + { + let encoded = payload.encode_eip712().map_err(|_| SignatureError::RecoveryError)?; + self.recover(encoded) + } + /// Retrieves the recovery signature. fn as_signature(&self) -> Result<(RecoverableSignature, RecoveryId), SignatureError> { let recovery_id = self.recovery_id()?; From 59d948976850e124dbd41c4521f49159253ad40c Mon Sep 17 00:00:00 2001 From: Dave Belvedere Date: Wed, 10 May 2023 10:51:25 +1000 Subject: [PATCH 7/7] fmt --- ethers-core/src/types/signature.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ethers-core/src/types/signature.rs b/ethers-core/src/types/signature.rs index f66748eaf..6b0959e1c 100644 --- a/ethers-core/src/types/signature.rs +++ b/ethers-core/src/types/signature.rs @@ -120,8 +120,8 @@ impl Signature { /// Recovery signature data uses 'Electrum' notation, this means the `v` /// value is expected to be either `27` or `28`. pub fn recover_typed_data(&self, payload: T) -> Result - where - T: super::transaction::eip712::Eip712, + where + T: super::transaction::eip712::Eip712, { let encoded = payload.encode_eip712().map_err(|_| SignatureError::RecoveryError)?; self.recover(encoded)