From 6e9edef8d890ba218b7d87059a5fa4f2212dcf17 Mon Sep 17 00:00:00 2001 From: aniket-prajapati Date: Tue, 16 Jul 2024 10:41:00 +0530 Subject: [PATCH 1/2] chore: more clippy lints --- Cargo.toml | 75 +++++++++ starknet-accounts/Cargo.toml | 3 + starknet-accounts/src/account/declaration.rs | 32 ++-- starknet-accounts/src/account/execution.rs | 20 +-- starknet-accounts/src/account/mod.rs | 45 +++--- starknet-accounts/src/factory/argent.rs | 1 + starknet-accounts/src/factory/mod.rs | 64 ++++---- .../src/factory/open_zeppelin.rs | 1 + starknet-accounts/src/single_owner.rs | 8 +- .../tests/single_owner_account.rs | 1 + starknet-contract/Cargo.toml | 3 + starknet-contract/src/factory.rs | 35 +++-- .../tests/contract_deployment.rs | 2 + starknet-core/Cargo.toml | 3 + starknet-core/src/chain_id.rs | 4 +- starknet-core/src/serde/byte_array.rs | 2 +- starknet-core/src/serde/num_hex.rs | 2 +- .../src/serde/unsigned_field_element.rs | 9 +- starknet-core/src/types/codegen.rs | 5 +- starknet-core/src/types/contract/legacy.rs | 22 ++- starknet-core/src/types/contract/mod.rs | 40 ++--- starknet-core/src/types/conversions.rs | 30 ++-- starknet-core/src/types/eth_address.rs | 6 +- starknet-core/src/types/execution_result.rs | 10 +- starknet-core/src/types/hash_256.rs | 10 +- starknet-core/src/types/mod.rs | 142 +++++++++--------- starknet-core/src/types/msg.rs | 8 +- starknet-core/src/types/receipt_block.rs | 24 +-- starknet-core/src/types/serde_impls.rs | 24 ++- starknet-core/src/types/u256.rs | 51 ++++--- starknet-core/src/utils.rs | 12 +- starknet-crypto-codegen/Cargo.toml | 3 + starknet-crypto/Cargo.toml | 3 + starknet-crypto/src/ecdsa.rs | 6 +- starknet-crypto/src/lib.rs | 1 + starknet-crypto/src/pedersen_hash.rs | 2 +- starknet-crypto/src/poseidon_hash.rs | 19 ++- starknet-crypto/src/rfc6979.rs | 4 +- starknet-curve/Cargo.toml | 3 + starknet-macros/Cargo.toml | 3 + starknet-macros/src/lib.rs | 2 +- starknet-providers/Cargo.toml | 3 + starknet-providers/src/any.rs | 2 +- starknet-providers/src/jsonrpc/mod.rs | 56 +++---- .../src/jsonrpc/transports/http.rs | 6 +- starknet-providers/src/provider.rs | 4 +- starknet-providers/src/sequencer/mod.rs | 40 +++-- .../src/sequencer/models/contract.rs | 2 +- .../src/sequencer/models/conversions.rs | 7 +- .../src/sequencer/models/serde_impls.rs | 6 +- .../src/sequencer/models/transaction.rs | 14 +- starknet-providers/src/sequencer/provider.rs | 5 +- starknet-providers/tests/jsonrpc.rs | 1 + starknet-signers/Cargo.toml | 3 + starknet-signers/src/key_pair.rs | 8 +- 55 files changed, 499 insertions(+), 398 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index b3c0f9cc..cb1a68f6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -54,3 +54,78 @@ no_unknown_fields = [ "starknet-core/no_unknown_fields", "starknet-providers/no_unknown_fields", ] + +[workspace.lints] +rust.missing_debug_implementations = "warn" +rust.missing_docs = "allow" +rust.unreachable_pub = "allow" +rust.unused_must_use = "deny" +rust.rust_2018_idioms = { level = "deny", priority = -1 } +rustdoc.all = "warn" + +[workspace.lints.clippy] +# These are some of clippy's nursery (i.e., experimental) lints that we like. +# By default, nursery lints are allowed. Some of the lints below have made good +# suggestions which we fixed. The others didn't have any findings, so we can +# assume they don't have that many false positives. Let's enable them to +# prevent future problems. +branches_sharing_code = "warn" +clear_with_drain = "warn" +derive_partial_eq_without_eq = "warn" +empty_line_after_outer_attr = "warn" +equatable_if_let = "warn" +imprecise_flops = "warn" +iter_on_empty_collections = "warn" +iter_with_drain = "warn" +large_stack_frames = "warn" +manual_clamp = "warn" +mutex_integer = "warn" +needless_pass_by_ref_mut = "warn" +nonstandard_macro_braces = "warn" +or_fun_call = "warn" +path_buf_push_overwrite = "warn" +read_zero_byte_vec = "warn" +redundant_clone = "warn" +suboptimal_flops = "warn" +suspicious_operation_groupings = "warn" +trailing_empty_array = "warn" +trait_duplication_in_bounds = "warn" +transmute_undefined_repr = "warn" +trivial_regex = "warn" +tuple_array_conversions = "warn" +uninhabited_references = "warn" +unused_peekable = "warn" +unused_rounding = "warn" +useless_let_if_seq = "warn" +use_self = "warn" +missing_const_for_fn = "warn" +empty_line_after_doc_comments = "warn" +iter_on_single_items = "warn" +match_same_arms = "warn" +doc_markdown = "warn" +unnecessary_struct_initialization = "warn" +string_lit_as_bytes = "warn" +explicit_into_iter_loop = "warn" +explicit_iter_loop = "warn" +type_repetition_in_bounds = "allow" +manual_string_new = "warn" +naive_bytecount = "warn" +needless_bitwise_bool = "warn" +zero_sized_map_values = "warn" +single_char_pattern = "warn" +needless_continue = "warn" + +# These are nursery lints which have findings. Allow them for now. Some are not +# quite mature enough for use in our codebase and some we don't really want. +# Explicitly listing should make it easier to fix in the future. +as_ptr_cast_mut = "allow" +cognitive_complexity = "allow" +collection_is_never_read = "allow" +debug_assert_with_mut_call = "allow" +fallible_impl_from = "allow" +future_not_send = "allow" +needless_collect = "allow" +non_send_fields_in_send_ty = "allow" +redundant_pub_crate = "allow" +significant_drop_in_scrutinee = "allow" +significant_drop_tightening = "allow" diff --git a/starknet-accounts/Cargo.toml b/starknet-accounts/Cargo.toml index 6ad3ad82..442a53fe 100644 --- a/starknet-accounts/Cargo.toml +++ b/starknet-accounts/Cargo.toml @@ -27,3 +27,6 @@ serde = { version = "1.0.160", features = ["derive"] } serde_json = "1.0.96" tokio = { version = "1.27.0", features = ["full"] } url = "2.3.1" + +[lints] +workspace = true diff --git a/starknet-accounts/src/account/declaration.rs b/starknet-accounts/src/account/declaration.rs index 360dc924..d8d2de4e 100644 --- a/starknet-accounts/src/account/declaration.rs +++ b/starknet-accounts/src/account/declaration.rs @@ -52,7 +52,7 @@ const QUERY_VERSION_THREE: Felt = Felt::from_raw([ ]); impl<'a, A> DeclarationV2<'a, A> { - pub fn new( + pub const fn new( contract_class: Arc, compiled_class_hash: Felt, account: &'a A, @@ -88,8 +88,8 @@ impl<'a, A> DeclarationV2<'a, A> { } } - /// Calling this function after manually specifying `nonce` and `max_fee` turns [DeclarationV2] - /// into [PreparedDeclarationV2]. Returns `Err` if either field is `None`. + /// Calling this function after manually specifying `nonce` and `max_fee` turns [`DeclarationV2`] + /// into [`PreparedDeclarationV2`]. Returns `Err` if either field is `None`. pub fn prepared(self) -> Result, NotPreparedError> { let nonce = self.nonce.ok_or(NotPreparedError)?; let max_fee = self.max_fee.ok_or(NotPreparedError)?; @@ -275,7 +275,7 @@ where } impl<'a, A> DeclarationV3<'a, A> { - pub fn new( + pub const fn new( contract_class: Arc, compiled_class_hash: Felt, account: &'a A, @@ -328,7 +328,7 @@ impl<'a, A> DeclarationV3<'a, A> { } /// Calling this function after manually specifying `nonce`, `gas` and `gas_price` turns - /// [DeclarationV3] into [PreparedDeclarationV3]. Returns `Err` if any field is `None`. + /// [`DeclarationV3`] into [`PreparedDeclarationV3`]. Returns `Err` if any field is `None`. pub fn prepared(self) -> Result, NotPreparedError> { let nonce = self.nonce.ok_or(NotPreparedError)?; let gas = self.gas.ok_or(NotPreparedError)?; @@ -570,7 +570,7 @@ where } impl<'a, A> LegacyDeclaration<'a, A> { - pub fn new(contract_class: Arc, account: &'a A) -> Self { + pub const fn new(contract_class: Arc, account: &'a A) -> Self { Self { account, contract_class, @@ -602,7 +602,7 @@ impl<'a, A> LegacyDeclaration<'a, A> { } /// Calling this function after manually specifying `nonce` and `max_fee` turns - /// [LegacyDeclaration] into [PreparedLegacyDeclaration]. Returns `Err` if either field is + /// [`LegacyDeclaration`] into [`PreparedLegacyDeclaration`]. Returns `Err` if either field is /// `None`. pub fn prepared(self) -> Result, NotPreparedError> { let nonce = self.nonce.ok_or(NotPreparedError)?; @@ -809,15 +809,15 @@ impl RawDeclarationV2 { &self.contract_class } - pub fn compiled_class_hash(&self) -> Felt { + pub const fn compiled_class_hash(&self) -> Felt { self.compiled_class_hash } - pub fn nonce(&self) -> Felt { + pub const fn nonce(&self) -> Felt { self.nonce } - pub fn max_fee(&self) -> Felt { + pub const fn max_fee(&self) -> Felt { self.max_fee } } @@ -880,19 +880,19 @@ impl RawDeclarationV3 { &self.contract_class } - pub fn compiled_class_hash(&self) -> Felt { + pub const fn compiled_class_hash(&self) -> Felt { self.compiled_class_hash } - pub fn nonce(&self) -> Felt { + pub const fn nonce(&self) -> Felt { self.nonce } - pub fn gas(&self) -> u64 { + pub const fn gas(&self) -> u64 { self.gas } - pub fn gas_price(&self) -> u128 { + pub const fn gas_price(&self) -> u128 { self.gas_price } } @@ -924,11 +924,11 @@ impl RawLegacyDeclaration { &self.contract_class } - pub fn nonce(&self) -> Felt { + pub const fn nonce(&self) -> Felt { self.nonce } - pub fn max_fee(&self) -> Felt { + pub const fn max_fee(&self) -> Felt { self.max_fee } } diff --git a/starknet-accounts/src/account/execution.rs b/starknet-accounts/src/account/execution.rs index 99757da0..3e529a45 100644 --- a/starknet-accounts/src/account/execution.rs +++ b/starknet-accounts/src/account/execution.rs @@ -41,7 +41,7 @@ const QUERY_VERSION_THREE: Felt = Felt::from_raw([ ]); impl<'a, A> ExecutionV1<'a, A> { - pub fn new(calls: Vec, account: &'a A) -> Self { + pub const fn new(calls: Vec, account: &'a A) -> Self { Self { account, calls, @@ -72,8 +72,8 @@ impl<'a, A> ExecutionV1<'a, A> { } } - /// Calling this function after manually specifying `nonce` and `max_fee` turns [ExecutionV1] into - /// [PreparedExecutionV1]. Returns `Err` if either field is `None`. + /// Calling this function after manually specifying `nonce` and `max_fee` turns [`ExecutionV1`] into + /// [`PreparedExecutionV1`]. Returns `Err` if either field is `None`. pub fn prepared(self) -> Result, NotPreparedError> { let nonce = self.nonce.ok_or(NotPreparedError)?; let max_fee = self.max_fee.ok_or(NotPreparedError)?; @@ -90,7 +90,7 @@ impl<'a, A> ExecutionV1<'a, A> { } impl<'a, A> ExecutionV3<'a, A> { - pub fn new(calls: Vec, account: &'a A) -> Self { + pub const fn new(calls: Vec, account: &'a A) -> Self { Self { account, calls, @@ -138,7 +138,7 @@ impl<'a, A> ExecutionV3<'a, A> { } /// Calling this function after manually specifying `nonce`, `gas` and `gas_price` turns - /// [ExecutionV3] into [PreparedExecutionV3]. Returns `Err` if any field is `None`. + /// [`ExecutionV3`] into [`PreparedExecutionV3`]. Returns `Err` if any field is `None`. pub fn prepared(self) -> Result, NotPreparedError> { let nonce = self.nonce.ok_or(NotPreparedError)?; let gas = self.gas.ok_or(NotPreparedError)?; @@ -583,11 +583,11 @@ impl RawExecutionV1 { &self.calls } - pub fn nonce(&self) -> Felt { + pub const fn nonce(&self) -> Felt { self.nonce } - pub fn max_fee(&self) -> Felt { + pub const fn max_fee(&self) -> Felt { self.max_fee } } @@ -667,15 +667,15 @@ impl RawExecutionV3 { &self.calls } - pub fn nonce(&self) -> Felt { + pub const fn nonce(&self) -> Felt { self.nonce } - pub fn gas(&self) -> u64 { + pub const fn gas(&self) -> u64 { self.gas } - pub fn gas_price(&self) -> u128 { + pub const fn gas_price(&self) -> u128 { self.gas_price } } diff --git a/starknet-accounts/src/account/mod.rs b/starknet-accounts/src/account/mod.rs index 94c9031c..5bb2db3e 100644 --- a/starknet-accounts/src/account/mod.rs +++ b/starknet-accounts/src/account/mod.rs @@ -63,16 +63,16 @@ pub trait Account: ExecutionEncoder + Sized { /// estimation/simulation purposes. fn is_signer_interactive(&self) -> bool; - fn execute_v1(&self, calls: Vec) -> ExecutionV1 { + fn execute_v1(&self, calls: Vec) -> ExecutionV1<'_, Self> { ExecutionV1::new(calls, self) } - fn execute_v3(&self, calls: Vec) -> ExecutionV3 { + fn execute_v3(&self, calls: Vec) -> ExecutionV3<'_, Self> { ExecutionV3::new(calls, self) } #[deprecated = "use version specific variants (`execute_v1` & `execute_v3`) instead"] - fn execute(&self, calls: Vec) -> ExecutionV1 { + fn execute(&self, calls: Vec) -> ExecutionV1<'_, Self> { self.execute_v1(calls) } @@ -80,7 +80,7 @@ pub trait Account: ExecutionEncoder + Sized { &self, contract_class: Arc, compiled_class_hash: Felt, - ) -> DeclarationV2 { + ) -> DeclarationV2<'_, Self> { DeclarationV2::new(contract_class, compiled_class_hash, self) } @@ -88,7 +88,7 @@ pub trait Account: ExecutionEncoder + Sized { &self, contract_class: Arc, compiled_class_hash: Felt, - ) -> DeclarationV3 { + ) -> DeclarationV3<'_, Self> { DeclarationV3::new(contract_class, compiled_class_hash, self) } @@ -97,11 +97,14 @@ pub trait Account: ExecutionEncoder + Sized { &self, contract_class: Arc, compiled_class_hash: Felt, - ) -> DeclarationV2 { + ) -> DeclarationV2<'_, Self> { self.declare_v2(contract_class, compiled_class_hash) } - fn declare_legacy(&self, contract_class: Arc) -> LegacyDeclaration { + fn declare_legacy( + &self, + contract_class: Arc, + ) -> LegacyDeclaration<'_, Self> { LegacyDeclaration::new(contract_class, self) } } @@ -135,7 +138,7 @@ pub trait ConnectedAccount: Account { /// Abstraction over `INVOKE` transactions from accounts for invoking contracts. This struct uses /// v1 `INVOKE` transactions under the hood, and hence pays transaction fees in ETH. To use v3 -/// transactions for STRK fee payment, use [ExecutionV3] instead. +/// transactions for STRK fee payment, use [`ExecutionV3`] instead. /// /// This is an intermediate type allowing users to optionally specify `nonce` and/or `max_fee`. #[must_use] @@ -150,7 +153,7 @@ pub struct ExecutionV1<'a, A> { /// Abstraction over `INVOKE` transactions from accounts for invoking contracts. This struct uses /// v3 `INVOKE` transactions under the hood, and hence pays transaction fees in STRK. To use v1 -/// transactions for ETH fee payment, use [ExecutionV1] instead. +/// transactions for ETH fee payment, use [`ExecutionV1`] instead. /// /// This is an intermediate type allowing users to optionally specify `nonce`, `gas`, and/or /// `gas_price`. @@ -168,7 +171,7 @@ pub struct ExecutionV3<'a, A> { /// Abstraction over `DECLARE` transactions from accounts for invoking contracts. This struct uses /// v2 `DECLARE` transactions under the hood, and hence pays transaction fees in ETH. To use v3 -/// transactions for STRK fee payment, use [DeclarationV3] instead. +/// transactions for STRK fee payment, use [`DeclarationV3`] instead. /// /// An intermediate type allowing users to optionally specify `nonce` and/or `max_fee`. #[must_use] @@ -184,7 +187,7 @@ pub struct DeclarationV2<'a, A> { /// Abstraction over `DECLARE` transactions from accounts for invoking contracts. This struct uses /// v3 `DECLARE` transactions under the hood, and hence pays transaction fees in STRK. To use v2 -/// transactions for ETH fee payment, use [DeclarationV2] instead. +/// transactions for ETH fee payment, use [`DeclarationV2`] instead. /// /// This is an intermediate type allowing users to optionally specify `nonce`, `gas`, and/or /// `gas_price`. @@ -212,7 +215,7 @@ pub struct LegacyDeclaration<'a, A> { fee_estimate_multiplier: f64, } -/// [ExecutionV1] but with `nonce` and `max_fee` already determined. +/// [`ExecutionV1`] but with `nonce` and `max_fee` already determined. #[derive(Debug)] pub struct RawExecutionV1 { calls: Vec, @@ -220,7 +223,7 @@ pub struct RawExecutionV1 { max_fee: Felt, } -/// [ExecutionV3] but with `nonce`, `gas` and `gas_price` already determined. +/// [`ExecutionV3`] but with `nonce`, `gas` and `gas_price` already determined. #[derive(Debug)] pub struct RawExecutionV3 { calls: Vec, @@ -229,7 +232,7 @@ pub struct RawExecutionV3 { gas_price: u128, } -/// [DeclarationV2] but with `nonce` and `max_fee` already determined. +/// [`DeclarationV2`] but with `nonce` and `max_fee` already determined. #[derive(Debug)] pub struct RawDeclarationV2 { contract_class: Arc, @@ -238,7 +241,7 @@ pub struct RawDeclarationV2 { max_fee: Felt, } -/// [DeclarationV3] but with `nonce`, `gas` and `gas_price` already determined. +/// [`DeclarationV3`] but with `nonce`, `gas` and `gas_price` already determined. #[derive(Debug)] pub struct RawDeclarationV3 { contract_class: Arc, @@ -248,7 +251,7 @@ pub struct RawDeclarationV3 { gas_price: u128, } -/// [LegacyDeclaration] but with `nonce` and `max_fee` already determined. +/// [`LegacyDeclaration`] but with `nonce` and `max_fee` already determined. #[derive(Debug)] pub struct RawLegacyDeclaration { contract_class: Arc, @@ -256,35 +259,35 @@ pub struct RawLegacyDeclaration { max_fee: Felt, } -/// [RawExecutionV1] but with an account associated. +/// [`RawExecutionV1`] but with an account associated. #[derive(Debug)] pub struct PreparedExecutionV1<'a, A> { account: &'a A, inner: RawExecutionV1, } -/// [RawExecutionV3] but with an account associated. +/// [`RawExecutionV3`] but with an account associated. #[derive(Debug)] pub struct PreparedExecutionV3<'a, A> { account: &'a A, inner: RawExecutionV3, } -/// [RawDeclarationV2] but with an account associated. +/// [`RawDeclarationV2`] but with an account associated. #[derive(Debug)] pub struct PreparedDeclarationV2<'a, A> { account: &'a A, inner: RawDeclarationV2, } -/// [RawDeclarationV3] but with an account associated. +/// [`RawDeclarationV3`] but with an account associated. #[derive(Debug)] pub struct PreparedDeclarationV3<'a, A> { account: &'a A, inner: RawDeclarationV3, } -/// [RawLegacyDeclaration] but with an account associated. +/// [`RawLegacyDeclaration`] but with an account associated. #[derive(Debug)] pub struct PreparedLegacyDeclaration<'a, A> { account: &'a A, diff --git a/starknet-accounts/src/factory/argent.rs b/starknet-accounts/src/factory/argent.rs index 5bfa0476..a8cf6482 100644 --- a/starknet-accounts/src/factory/argent.rs +++ b/starknet-accounts/src/factory/argent.rs @@ -8,6 +8,7 @@ use starknet_core::types::{BlockId, BlockTag, Felt}; use starknet_providers::Provider; use starknet_signers::Signer; +#[derive(Debug)] pub struct ArgentAccountFactory { class_hash: Felt, chain_id: Felt, diff --git a/starknet-accounts/src/factory/mod.rs b/starknet-accounts/src/factory/mod.rs index 1dc3b773..17f3d2a2 100644 --- a/starknet-accounts/src/factory/mod.rs +++ b/starknet-accounts/src/factory/mod.rs @@ -18,7 +18,7 @@ use std::error::Error; pub mod argent; pub mod open_zeppelin; -/// Cairo string for "deploy_account" +/// Cairo string for `deploy_account` const PREFIX_DEPLOY_ACCOUNT: Felt = Felt::from_raw([ 461298303000467581, 18446744073709551615, @@ -42,7 +42,7 @@ const QUERY_VERSION_THREE: Felt = Felt::from_raw([ 18446744073700081569, ]); -/// Cairo string for "STARKNET_CONTRACT_ADDRESS" +/// Cairo string for `STARKNET_CONTRACT_ADDRESS` const PREFIX_CONTRACT_ADDRESS: Felt = Felt::from_raw([ 533439743893157637, 8635008616843941496, @@ -98,23 +98,23 @@ pub trait AccountFactory: Sized { query_only: bool, ) -> Result, Self::SignError>; - fn deploy_v1(&self, salt: Felt) -> AccountDeploymentV1 { + fn deploy_v1(&self, salt: Felt) -> AccountDeploymentV1<'_, Self> { AccountDeploymentV1::new(salt, self) } - fn deploy_v3(&self, salt: Felt) -> AccountDeploymentV3 { + fn deploy_v3(&self, salt: Felt) -> AccountDeploymentV3<'_, Self> { AccountDeploymentV3::new(salt, self) } #[deprecated = "use version specific variants (`deploy_v1` & `deploy_v3`) instead"] - fn deploy(&self, salt: Felt) -> AccountDeploymentV1 { + fn deploy(&self, salt: Felt) -> AccountDeploymentV1<'_, Self> { self.deploy_v1(salt) } } /// Abstraction over `DEPLOY_ACCOUNT` transactions for account contract deployment. This struct uses /// v1 `DEPLOY_ACCOUNT` transactions under the hood, and hence pays transaction fees in ETH. To use -/// v3 transactions for STRK fee payment, use [AccountDeploymentV3] instead. +/// v3 transactions for STRK fee payment, use [`AccountDeploymentV3`] instead. /// /// An intermediate type allowing users to optionally specify `nonce` and/or `max_fee`. #[must_use] @@ -131,7 +131,7 @@ pub struct AccountDeploymentV1<'f, F> { /// Abstraction over `DEPLOY_ACCOUNT` transactions for account contract deployment. This struct uses /// v3 `DEPLOY_ACCOUNT` transactions under the hood, and hence pays transaction fees in STRK. To use -/// v1 transactions for ETH fee payment, use [AccountDeploymentV1] instead. +/// v1 transactions for ETH fee payment, use [`AccountDeploymentV1`] instead. /// /// This is an intermediate type allowing users to optionally specify `nonce`, `gas`, and/or /// `gas_price`. @@ -149,7 +149,7 @@ pub struct AccountDeploymentV3<'f, F> { gas_price_estimate_multiplier: f64, } -/// [AccountDeploymentV1] but with `nonce` and `max_fee` already determined. +/// [`AccountDeploymentV1`] but with `nonce` and `max_fee` already determined. #[derive(Debug, Clone)] pub struct RawAccountDeploymentV1 { salt: Felt, @@ -157,7 +157,7 @@ pub struct RawAccountDeploymentV1 { max_fee: Felt, } -/// [AccountDeploymentV3] but with `nonce`, `gas` and `gas_price` already determined. +/// [`AccountDeploymentV3`] but with `nonce`, `gas` and `gas_price` already determined. #[derive(Debug, Clone)] pub struct RawAccountDeploymentV3 { salt: Felt, @@ -166,14 +166,14 @@ pub struct RawAccountDeploymentV3 { gas_price: u128, } -/// [RawAccountDeploymentV1] but with a factory associated. +/// [`RawAccountDeploymentV1`] but with a factory associated. #[derive(Debug)] pub struct PreparedAccountDeploymentV1<'f, F> { factory: &'f F, inner: RawAccountDeploymentV1, } -/// [RawAccountDeploymentV3] but with a factory associated. +/// [`RawAccountDeploymentV3`] but with a factory associated. #[derive(Debug)] pub struct PreparedAccountDeploymentV3<'f, F> { factory: &'f F, @@ -191,7 +191,7 @@ pub enum AccountFactoryError { } impl<'f, F> AccountDeploymentV1<'f, F> { - pub fn new(salt: Felt, factory: &'f F) -> Self { + pub const fn new(salt: Felt, factory: &'f F) -> Self { Self { factory, salt, @@ -201,21 +201,21 @@ impl<'f, F> AccountDeploymentV1<'f, F> { } } - pub fn nonce(self, nonce: Felt) -> Self { + pub const fn nonce(self, nonce: Felt) -> Self { Self { nonce: Some(nonce), ..self } } - pub fn max_fee(self, max_fee: Felt) -> Self { + pub const fn max_fee(self, max_fee: Felt) -> Self { Self { max_fee: Some(max_fee), ..self } } - pub fn fee_estimate_multiplier(self, fee_estimate_multiplier: f64) -> Self { + pub const fn fee_estimate_multiplier(self, fee_estimate_multiplier: f64) -> Self { Self { fee_estimate_multiplier, ..self @@ -223,7 +223,7 @@ impl<'f, F> AccountDeploymentV1<'f, F> { } /// Calling this function after manually specifying `nonce` and `max_fee` turns - /// [AccountDeploymentV1] into [PreparedAccountDeploymentV1]. Returns `Err` if either field is + /// [`AccountDeploymentV1`] into [`PreparedAccountDeploymentV1`]. Returns `Err` if either field is /// `None`. pub fn prepared(self) -> Result, NotPreparedError> { let nonce = self.nonce.ok_or(NotPreparedError)?; @@ -241,7 +241,7 @@ impl<'f, F> AccountDeploymentV1<'f, F> { } impl<'f, F> AccountDeploymentV3<'f, F> { - pub fn new(salt: Felt, factory: &'f F) -> Self { + pub const fn new(salt: Felt, factory: &'f F) -> Self { Self { factory, salt, @@ -253,35 +253,35 @@ impl<'f, F> AccountDeploymentV3<'f, F> { } } - pub fn nonce(self, nonce: Felt) -> Self { + pub const fn nonce(self, nonce: Felt) -> Self { Self { nonce: Some(nonce), ..self } } - pub fn gas(self, gas: u64) -> Self { + pub const fn gas(self, gas: u64) -> Self { Self { gas: Some(gas), ..self } } - pub fn gas_price(self, gas_price: u128) -> Self { + pub const fn gas_price(self, gas_price: u128) -> Self { Self { gas_price: Some(gas_price), ..self } } - pub fn gas_estimate_multiplier(self, gas_estimate_multiplier: f64) -> Self { + pub const fn gas_estimate_multiplier(self, gas_estimate_multiplier: f64) -> Self { Self { gas_estimate_multiplier, ..self } } - pub fn gas_price_estimate_multiplier(self, gas_price_estimate_multiplier: f64) -> Self { + pub const fn gas_price_estimate_multiplier(self, gas_price_estimate_multiplier: f64) -> Self { Self { gas_price_estimate_multiplier, ..self @@ -289,7 +289,7 @@ impl<'f, F> AccountDeploymentV3<'f, F> { } /// Calling this function after manually specifying `nonce` and `max_fee` turns - /// [AccountDeploymentV3] into [PreparedAccountDeploymentV3]. Returns `Err` if either field is + /// [`AccountDeploymentV3`] into [`PreparedAccountDeploymentV3`]. Returns `Err` if either field is /// `None`. pub fn prepared(self) -> Result, NotPreparedError> { let nonce = self.nonce.ok_or(NotPreparedError)?; @@ -760,39 +760,39 @@ where } impl RawAccountDeploymentV1 { - pub fn salt(&self) -> Felt { + pub const fn salt(&self) -> Felt { self.salt } - pub fn nonce(&self) -> Felt { + pub const fn nonce(&self) -> Felt { self.nonce } - pub fn max_fee(&self) -> Felt { + pub const fn max_fee(&self) -> Felt { self.max_fee } } impl RawAccountDeploymentV3 { - pub fn salt(&self) -> Felt { + pub const fn salt(&self) -> Felt { self.salt } - pub fn nonce(&self) -> Felt { + pub const fn nonce(&self) -> Felt { self.nonce } - pub fn gas(&self) -> u64 { + pub const fn gas(&self) -> u64 { self.gas } - pub fn gas_price(&self) -> u128 { + pub const fn gas_price(&self) -> u128 { self.gas_price } } impl<'f, F> PreparedAccountDeploymentV1<'f, F> { - pub fn from_raw(raw_deployment: RawAccountDeploymentV1, factory: &'f F) -> Self { + pub const fn from_raw(raw_deployment: RawAccountDeploymentV1, factory: &'f F) -> Self { Self { factory, inner: raw_deployment, @@ -801,7 +801,7 @@ impl<'f, F> PreparedAccountDeploymentV1<'f, F> { } impl<'f, F> PreparedAccountDeploymentV3<'f, F> { - pub fn from_raw(raw_deployment: RawAccountDeploymentV3, factory: &'f F) -> Self { + pub const fn from_raw(raw_deployment: RawAccountDeploymentV3, factory: &'f F) -> Self { Self { factory, inner: raw_deployment, diff --git a/starknet-accounts/src/factory/open_zeppelin.rs b/starknet-accounts/src/factory/open_zeppelin.rs index 3b23b16e..8fa95022 100644 --- a/starknet-accounts/src/factory/open_zeppelin.rs +++ b/starknet-accounts/src/factory/open_zeppelin.rs @@ -8,6 +8,7 @@ use starknet_core::types::{BlockId, BlockTag, Felt}; use starknet_providers::Provider; use starknet_signers::Signer; +#[derive(Debug)] pub struct OpenZeppelinAccountFactory { class_hash: Felt, chain_id: Felt, diff --git a/starknet-accounts/src/single_owner.rs b/starknet-accounts/src/single_owner.rs index 0677a8d8..4fc44ede 100644 --- a/starknet-accounts/src/single_owner.rs +++ b/starknet-accounts/src/single_owner.rs @@ -54,7 +54,7 @@ where /// * `address`: Account contract address. /// * `chain_id`: Network chain ID. /// * `encoding`: How `__execute__` calldata should be encoded. - pub fn new( + pub const fn new( provider: P, signer: S, address: Felt, @@ -187,13 +187,13 @@ where match self.encoding { ExecutionEncoding::Legacy => { let mut concated_calldata: Vec = vec![]; - for call in calls.iter() { + for call in calls { execute_calldata.push(call.to); // to execute_calldata.push(call.selector); // selector execute_calldata.push(concated_calldata.len().into()); // data_offset execute_calldata.push(call.calldata.len().into()); // data_len - for item in call.calldata.iter() { + for item in &call.calldata { concated_calldata.push(*item); } } @@ -202,7 +202,7 @@ where execute_calldata.extend_from_slice(&concated_calldata); } ExecutionEncoding::New => { - for call in calls.iter() { + for call in calls { execute_calldata.push(call.to); // to execute_calldata.push(call.selector); // selector diff --git a/starknet-accounts/tests/single_owner_account.rs b/starknet-accounts/tests/single_owner_account.rs index c779c491..f836a7c4 100644 --- a/starknet-accounts/tests/single_owner_account.rs +++ b/starknet-accounts/tests/single_owner_account.rs @@ -31,6 +31,7 @@ fn create_sequencer_client() -> SequencerGatewayProvider { } fn create_jsonrpc_client() -> JsonRpcClient { + #[allow(clippy::or_fun_call)] let rpc_url = std::env::var("STARKNET_RPC") .unwrap_or("https://juno.rpc.sepolia.starknet.rs/rpc/v0_7".into()); JsonRpcClient::new(HttpTransport::new(url::Url::parse(&rpc_url).unwrap())) diff --git a/starknet-contract/Cargo.toml b/starknet-contract/Cargo.toml index 1c44ac28..f6a89f3c 100644 --- a/starknet-contract/Cargo.toml +++ b/starknet-contract/Cargo.toml @@ -27,3 +27,6 @@ rand = { version = "0.8.5", features=["std_rng"] } starknet-signers = { version = "0.9.0", path = "../starknet-signers" } tokio = { version = "1.27.0", features = ["full"] } url = "2.3.1" + +[lints] +workspace = true diff --git a/starknet-contract/src/factory.rs b/starknet-contract/src/factory.rs index 0cbd6065..299ff0f1 100644 --- a/starknet-contract/src/factory.rs +++ b/starknet-contract/src/factory.rs @@ -20,6 +20,7 @@ const SELECTOR_DEPLOYCONTRACT: Felt = Felt::from_raw([ 18249998464715511309, ]); +#[derive(Debug)] pub struct ContractFactory { class_hash: Felt, udc_address: Felt, @@ -28,8 +29,9 @@ pub struct ContractFactory { /// Abstraction over contract deployment via the UDC. This type uses `INVOKE` v1 transactions under /// the hood, and hence pays transaction fees in ETH. To use v3 transactions for STRK fee payment, -/// use [DeploymentV3] instead. +/// use [`DeploymentV3`] instead. #[must_use] +#[derive(Debug)] pub struct DeploymentV1<'f, A> { factory: &'f ContractFactory, constructor_calldata: Vec, @@ -43,8 +45,9 @@ pub struct DeploymentV1<'f, A> { /// Abstraction over contract deployment via the UDC. This type uses `INVOKE` v3 transactions under /// the hood, and hence pays transaction fees in STRK. To use v1 transactions for ETH fee payment, -/// use [DeploymentV1] instead. +/// use [`DeploymentV1`] instead. #[must_use] +#[derive(Debug)] pub struct DeploymentV3<'f, A> { factory: &'f ContractFactory, constructor_calldata: Vec, @@ -59,11 +62,11 @@ pub struct DeploymentV3<'f, A> { } impl ContractFactory { - pub fn new(class_hash: Felt, account: A) -> Self { + pub const fn new(class_hash: Felt, account: A) -> Self { Self::new_with_udc(class_hash, account, UDC_ADDRESS) } - pub fn new_with_udc(class_hash: Felt, account: A, udc_address: Felt) -> Self { + pub const fn new_with_udc(class_hash: Felt, account: A, udc_address: Felt) -> Self { Self { class_hash, udc_address, @@ -76,12 +79,12 @@ impl ContractFactory where A: Account, { - pub fn deploy_v1( + pub const fn deploy_v1( &self, constructor_calldata: Vec, salt: Felt, unique: bool, - ) -> DeploymentV1 { + ) -> DeploymentV1<'_, A> { DeploymentV1 { factory: self, constructor_calldata, @@ -93,12 +96,12 @@ where } } - pub fn deploy_v3( + pub const fn deploy_v3( &self, constructor_calldata: Vec, salt: Felt, unique: bool, - ) -> DeploymentV3 { + ) -> DeploymentV3<'_, A> { DeploymentV3 { factory: self, constructor_calldata, @@ -113,12 +116,12 @@ where } #[deprecated = "use version specific variants (`deploy_v1` & `deploy_v3`) instead"] - pub fn deploy( + pub const fn deploy( &self, constructor_calldata: Vec, salt: Felt, unique: bool, - ) -> DeploymentV1 { + ) -> DeploymentV1<'_, A> { self.deploy_v1(constructor_calldata, salt, unique) } } @@ -232,7 +235,7 @@ where A: ConnectedAccount + Sync, { pub async fn estimate_fee(&self) -> Result> { - let execution: ExecutionV1 = self.into(); + let execution: ExecutionV1<'_, A> = self.into(); execution.estimate_fee().await } @@ -241,12 +244,12 @@ where skip_validate: bool, skip_fee_charge: bool, ) -> Result> { - let execution: ExecutionV1 = self.into(); + let execution: ExecutionV1<'_, A> = self.into(); execution.simulate(skip_validate, skip_fee_charge).await } pub async fn send(&self) -> Result> { - let execution: ExecutionV1 = self.into(); + let execution: ExecutionV1<'_, A> = self.into(); execution.send().await } } @@ -256,7 +259,7 @@ where A: ConnectedAccount + Sync, { pub async fn estimate_fee(&self) -> Result> { - let execution: ExecutionV3 = self.into(); + let execution: ExecutionV3<'_, A> = self.into(); execution.estimate_fee().await } @@ -265,12 +268,12 @@ where skip_validate: bool, skip_fee_charge: bool, ) -> Result> { - let execution: ExecutionV3 = self.into(); + let execution: ExecutionV3<'_, A> = self.into(); execution.simulate(skip_validate, skip_fee_charge).await } pub async fn send(&self) -> Result> { - let execution: ExecutionV3 = self.into(); + let execution: ExecutionV3<'_, A> = self.into(); execution.send().await } } diff --git a/starknet-contract/tests/contract_deployment.rs b/starknet-contract/tests/contract_deployment.rs index 14ab3f26..a44f979e 100644 --- a/starknet-contract/tests/contract_deployment.rs +++ b/starknet-contract/tests/contract_deployment.rs @@ -16,6 +16,7 @@ const CHAIN_ID: Felt = Felt::from_raw([ #[tokio::test] async fn can_deploy_contract_to_alpha_sepolia_with_invoke_v1() { + #![allow(clippy::or_fun_call)] let rpc_url = std::env::var("STARKNET_RPC") .unwrap_or("https://pathfinder.rpc.sepolia.starknet.rs/rpc/v0_6".into()); let provider = JsonRpcClient::new(HttpTransport::new(Url::parse(&rpc_url).unwrap())); @@ -54,6 +55,7 @@ async fn can_deploy_contract_to_alpha_sepolia_with_invoke_v1() { #[tokio::test] async fn can_deploy_contract_to_alpha_sepolia_with_invoke_v3() { + #![allow(clippy::or_fun_call)] let rpc_url = std::env::var("STARKNET_RPC") .unwrap_or("https://pathfinder.rpc.sepolia.starknet.rs/rpc/v0_6".into()); let provider = JsonRpcClient::new(HttpTransport::new(Url::parse(&rpc_url).unwrap())); diff --git a/starknet-core/Cargo.toml b/starknet-core/Cargo.toml index a035ded2..363ca0c7 100644 --- a/starknet-core/Cargo.toml +++ b/starknet-core/Cargo.toml @@ -50,3 +50,6 @@ harness = false [[bench]] name = "sierra_class_hash" harness = false + +[lints] +workspace = true diff --git a/starknet-core/src/chain_id.rs b/starknet-core/src/chain_id.rs index cbb430fa..715dc437 100644 --- a/starknet-core/src/chain_id.rs +++ b/starknet-core/src/chain_id.rs @@ -45,9 +45,7 @@ mod test { ("SN_GOERLI", TESTNET), ("SN_GOERLI2", TESTNET2), ("SN_SEPOLIA", SEPOLIA), - ] - .into_iter() - { + ] { assert_eq!(cairo_short_string_to_felt(text).unwrap(), felt); } } diff --git a/starknet-core/src/serde/byte_array.rs b/starknet-core/src/serde/byte_array.rs index 9d171396..0d2bb46e 100644 --- a/starknet-core/src/serde/byte_array.rs +++ b/starknet-core/src/serde/byte_array.rs @@ -24,7 +24,7 @@ pub mod base64 { impl<'de> Visitor<'de> for Base64Visitor { type Value = Vec; - fn expecting(&self, formatter: &mut Formatter) -> alloc::fmt::Result { + fn expecting(&self, formatter: &mut Formatter<'_>) -> alloc::fmt::Result { write!(formatter, "string") } diff --git a/starknet-core/src/serde/num_hex.rs b/starknet-core/src/serde/num_hex.rs index 6268fb1e..f285a18a 100644 --- a/starknet-core/src/serde/num_hex.rs +++ b/starknet-core/src/serde/num_hex.rs @@ -30,7 +30,7 @@ pub mod u64 { impl<'de> Visitor<'de> for NumHexVisitor { type Value = u64; - fn expecting(&self, formatter: &mut Formatter) -> alloc::fmt::Result { + fn expecting(&self, formatter: &mut Formatter<'_>) -> alloc::fmt::Result { write!(formatter, "string, or an array of u8") } diff --git a/starknet-core/src/serde/unsigned_field_element.rs b/starknet-core/src/serde/unsigned_field_element.rs index f443797a..87f311cb 100644 --- a/starknet-core/src/serde/unsigned_field_element.rs +++ b/starknet-core/src/serde/unsigned_field_element.rs @@ -12,10 +12,13 @@ use starknet_types_core::felt::Felt; const PRIME: U256 = U256::from_be_hex("0800000000000011000000000000000000000000000000000000000000000001"); +#[derive(Debug)] pub struct UfeHex; +#[derive(Debug)] pub struct UfeHexOption; +#[derive(Debug)] pub struct UfePendingBlockHash; struct UfeHexVisitor; @@ -51,7 +54,7 @@ impl<'de> DeserializeAs<'de, Felt> for UfeHex { impl<'de> Visitor<'de> for UfeHexVisitor { type Value = Felt; - fn expecting(&self, formatter: &mut Formatter) -> alloc::fmt::Result { + fn expecting(&self, formatter: &mut Formatter<'_>) -> alloc::fmt::Result { write!(formatter, "a hex string, or an array of u8") } @@ -108,7 +111,7 @@ impl<'de> DeserializeAs<'de, Option> for UfeHexOption { impl<'de> Visitor<'de> for UfeHexOptionVisitor { type Value = Option; - fn expecting(&self, formatter: &mut Formatter) -> alloc::fmt::Result { + fn expecting(&self, formatter: &mut Formatter<'_>) -> alloc::fmt::Result { write!(formatter, "string") } @@ -176,7 +179,7 @@ impl<'de> DeserializeAs<'de, Option> for UfePendingBlockHash { impl<'de> Visitor<'de> for UfePendingBlockHashVisitor { type Value = Option; - fn expecting(&self, formatter: &mut Formatter) -> alloc::fmt::Result { + fn expecting(&self, formatter: &mut Formatter<'_>) -> alloc::fmt::Result { write!(formatter, "string") } diff --git a/starknet-core/src/types/codegen.rs b/starknet-core/src/types/codegen.rs index 46e11560..2d7e0d02 100644 --- a/starknet-core/src/types/codegen.rs +++ b/starknet-core/src/types/codegen.rs @@ -3,7 +3,7 @@ // https://github.com/xJonathanLEI/starknet-jsonrpc-codegen // Code generated with version: -// https://github.com/xJonathanLEI/starknet-jsonrpc-codegen#4118b48cc450a8ff558c2ac480aa12bf5efdd3bd +// https://github.com/xJonathanLEI/starknet-jsonrpc-codegen#fbd3aed2a08d6b29328e87ee0bbfb7e80f7051b0 // These types are ignored from code generation. Implement them manually: // - `RECEIPT_BLOCK` @@ -24,6 +24,9 @@ // - `TXN` // - `TXN_RECEIPT` +#![allow(clippy::doc_markdown)] +#![allow(clippy::missing_const_for_fn)] + use alloc::{format, string::*, vec::*}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; diff --git a/starknet-core/src/types/contract/legacy.rs b/starknet-core/src/types/contract/legacy.rs index 83294a82..3803a218 100644 --- a/starknet-core/src/types/contract/legacy.rs +++ b/starknet-core/src/types/contract/legacy.rs @@ -361,26 +361,26 @@ impl<'de> Deserialize<'de> for RawLegacyAbiEntry { let temp_value = serde_json::Value::deserialize(deserializer)?; match &temp_value["type"] { serde_json::Value::String(type_str) => match &type_str[..] { - "constructor" => Ok(RawLegacyAbiEntry::Constructor( + "constructor" => Ok(Self::Constructor( RawLegacyConstructor::deserialize(temp_value).map_err(|err| { DeError::custom(format!("invalid constructor variant: {err}")) })?, )), - "function" => Ok(RawLegacyAbiEntry::Function( + "function" => Ok(Self::Function( RawLegacyFunction::deserialize(temp_value).map_err(|err| { DeError::custom(format!("invalid function variant: {err}")) })?, )), - "struct" => Ok(RawLegacyAbiEntry::Struct( + "struct" => Ok(Self::Struct( RawLegacyStruct::deserialize(temp_value) .map_err(|err| DeError::custom(format!("invalid struct variant: {err}")))?, )), - "l1_handler" => Ok(RawLegacyAbiEntry::L1Handler( + "l1_handler" => Ok(Self::L1Handler( RawLegacyL1Handler::deserialize(temp_value).map_err(|err| { DeError::custom(format!("invalid l1_handler variant: {err}")) })?, )), - "event" => Ok(RawLegacyAbiEntry::Event( + "event" => Ok(Self::Event( RawLegacyEvent::deserialize(temp_value) .map_err(|err| DeError::custom(format!("invalid event variant: {err}")))?, )), @@ -402,7 +402,7 @@ impl LegacyContractClass { // Hashes external entry points elements.push({ let mut buffer = Vec::new(); - for entrypoint in self.entry_points_by_type.external.iter() { + for entrypoint in &self.entry_points_by_type.external { buffer.push(entrypoint.selector); buffer.push(entrypoint.offset.into()); } @@ -412,7 +412,7 @@ impl LegacyContractClass { // Hashes L1 handler entry points elements.push({ let mut buffer = Vec::new(); - for entrypoint in self.entry_points_by_type.l1_handler.iter() { + for entrypoint in &self.entry_points_by_type.l1_handler { buffer.push(entrypoint.selector); buffer.push(entrypoint.offset.into()); } @@ -422,7 +422,7 @@ impl LegacyContractClass { // Hashes constructor entry points elements.push({ let mut buffer = Vec::new(); - for entrypoint in self.entry_points_by_type.constructor.iter() { + for entrypoint in &self.entry_points_by_type.constructor { buffer.push(entrypoint.selector); buffer.push(entrypoint.offset.into()); } @@ -853,9 +853,7 @@ mod tests { include_str!( "../../../test-data/contracts/cairo0/artifacts/pre-0.11.0/event_example.txt" ), - ] - .into_iter() - { + ] { serde_json::from_str::(raw_artifact).unwrap(); } } @@ -893,7 +891,6 @@ mod tests { ), ), ] - .into_iter() { let artifact = serde_json::from_str::(raw_artifact).unwrap(); let computed_hash = artifact.class_hash().unwrap(); @@ -938,7 +935,6 @@ mod tests { ), ), ] - .into_iter() { let artifact = serde_json::from_str::(raw_artifact).unwrap(); let computed_hash = artifact.hinted_class_hash().unwrap(); diff --git a/starknet-core/src/types/contract/mod.rs b/starknet-core/src/types/contract/mod.rs index 24046f9b..ba1b17ba 100644 --- a/starknet-core/src/types/contract/mod.rs +++ b/starknet-core/src/types/contract/mod.rs @@ -16,7 +16,7 @@ use crate::{ /// Module containing types related to artifacts of contracts compiled with a Cairo 0.x compiler. pub mod legacy; -/// Cairo string for "CONTRACT_CLASS_V0.1.0" +/// Cairo string for `CONTRACT_CLASS_V0.1.0` const PREFIX_CONTRACT_CLASS_V0_1_0: Felt = Felt::from_raw([ 37302452645455172, 18446734822722598327, @@ -24,7 +24,7 @@ const PREFIX_CONTRACT_CLASS_V0_1_0: Felt = Felt::from_raw([ 5800711240972404213, ]); -/// Cairo string for "COMPILED_CLASS_V1" +/// Cairo string for `COMPILED_CLASS_V1` const PREFIX_COMPILED_CLASS_V1: Felt = Felt::from_raw([ 324306817650036332, 18446744073709549462, @@ -278,7 +278,7 @@ struct BytecodeSegmentedNode { /// Internal structure used for post-Sierra-1.5.0 CASM hash calculation. /// -/// Represents a child of [BytecodeSegmentedNode]. +/// Represents a child of [`BytecodeSegmentedNode`]. struct BytecodeSegment { segment_length: u64, #[allow(unused)] @@ -545,12 +545,12 @@ impl CompiledClass { ) -> Result { let mut hasher = PoseidonHasher::new(); - for entry in entrypoints.iter() { + for entry in entrypoints { hasher.update(entry.selector); hasher.update(entry.offset.into()); let mut builtin_hasher = PoseidonHasher::new(); - for builtin in entry.builtins.iter() { + for builtin in &entry.builtins { builtin_hasher.update(cairo_short_string_to_felt(builtin)?) } @@ -594,7 +594,7 @@ impl CompiledClass { let mut res = Vec::new(); let mut total_len = 0; - for item in bytecode_segment_lengths.iter() { + for item in bytecode_segment_lengths { let visited_pc_before = if !visited_pcs.is_empty() { Some(visited_pcs[visited_pcs.len() - 1]) } else { @@ -666,7 +666,7 @@ impl BytecodeLeaf { impl BytecodeSegmentedNode { fn hash(&self) -> Felt { let mut hasher = PoseidonHasher::new(); - for node in self.segments.iter() { + for node in &self.segments { hasher.update(node.segment_length.into()); hasher.update(node.inner_structure.hash()); } @@ -761,7 +761,7 @@ impl Serialize for TypedAbiEvent { } match self { - TypedAbiEvent::Struct(inner) => StructRef::serialize( + Self::Struct(inner) => StructRef::serialize( &StructRef { name: &inner.name, kind: "struct", @@ -769,7 +769,7 @@ impl Serialize for TypedAbiEvent { }, serializer, ), - TypedAbiEvent::Enum(inner) => EnumRef::serialize( + Self::Enum(inner) => EnumRef::serialize( &EnumRef { name: &inner.name, kind: "enum", @@ -790,7 +790,7 @@ impl Serialize for IntOrList { Self::Int(int) => serializer.serialize_u64(*int), Self::List(list) => { let mut seq = serializer.serialize_seq(Some(list.len()))?; - for item in list.iter() { + for item in list { seq.serialize_element(item)?; } seq.end() @@ -802,7 +802,7 @@ impl Serialize for IntOrList { impl<'de> Visitor<'de> for IntOrListVisitor { type Value = IntOrList; - fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result { + fn expecting(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(formatter, "number or list") } @@ -837,7 +837,7 @@ impl<'de> Deserialize<'de> for IntOrList { fn hash_sierra_entrypoints(entrypoints: &[SierraEntryPoint]) -> Felt { let mut hasher = PoseidonHasher::new(); - for entry in entrypoints.iter() { + for entry in entrypoints { hasher.update(entry.selector); hasher.update(entry.function_idx.into()); } @@ -864,9 +864,7 @@ mod tests { include_str!("../../../test-data/contracts/cairo2/artifacts/abi_types_sierra.txt"), include_str!("../../../test-data/contracts/cairo2/artifacts/erc20_sierra.txt"), include_str!("../../../test-data/contracts/cairo2.6/artifacts/erc20_sierra.txt"), - ] - .into_iter() - { + ] { match serde_json::from_str::(raw_artifact) { Ok(ContractArtifact::SierraClass(_)) => {} _ => panic!("Unexpected result"), @@ -883,9 +881,7 @@ mod tests { include_str!("../../../test-data/contracts/cairo2/artifacts/abi_types_compiled.txt"), include_str!("../../../test-data/contracts/cairo2/artifacts/erc20_compiled.txt"), include_str!("../../../test-data/contracts/cairo2.6/artifacts/erc20_compiled.txt"), - ] - .into_iter() - { + ] { match serde_json::from_str::(raw_artifact) { Ok(ContractArtifact::CompiledClass(_)) => {} _ => panic!("Unexpected result"), @@ -924,9 +920,7 @@ mod tests { include_str!("../../../test-data/contracts/cairo2/artifacts/abi_types_sierra.txt"), include_str!("../../../test-data/contracts/cairo2/artifacts/abi_types.hashes.json"), ), - ] - .into_iter() - { + ] { let sierra_class = serde_json::from_str::(raw_artifact).unwrap(); let computed_hash = sierra_class.class_hash().unwrap(); @@ -965,9 +959,7 @@ mod tests { include_str!("../../../test-data/contracts/cairo2.6/artifacts/erc20_compiled.txt"), include_str!("../../../test-data/contracts/cairo2.6/artifacts/erc20.hashes.json"), ), - ] - .into_iter() - { + ] { let compiled_class = serde_json::from_str::(raw_artifact).unwrap(); let computed_hash = compiled_class.class_hash().unwrap(); diff --git a/starknet-core/src/types/conversions.rs b/starknet-core/src/types/conversions.rs index 38e7aa5f..a4a9ba1d 100644 --- a/starknet-core/src/types/conversions.rs +++ b/starknet-core/src/types/conversions.rs @@ -10,33 +10,29 @@ impl From for RawLegacyAbiEntry { fn from(value: LegacyContractAbiEntry) -> Self { match value { LegacyContractAbiEntry::Function(inner) => match inner.r#type { - LegacyFunctionAbiType::Function => RawLegacyAbiEntry::Function(RawLegacyFunction { + LegacyFunctionAbiType::Function => Self::Function(RawLegacyFunction { inputs: inner.inputs, name: inner.name, outputs: inner.outputs, state_mutability: inner.state_mutability, }), - LegacyFunctionAbiType::L1Handler => { - RawLegacyAbiEntry::L1Handler(RawLegacyL1Handler { - inputs: inner.inputs, - name: inner.name, - outputs: inner.outputs, - }) - } - LegacyFunctionAbiType::Constructor => { - RawLegacyAbiEntry::Constructor(RawLegacyConstructor { - inputs: inner.inputs, - name: inner.name, - outputs: inner.outputs, - }) - } + LegacyFunctionAbiType::L1Handler => Self::L1Handler(RawLegacyL1Handler { + inputs: inner.inputs, + name: inner.name, + outputs: inner.outputs, + }), + LegacyFunctionAbiType::Constructor => Self::Constructor(RawLegacyConstructor { + inputs: inner.inputs, + name: inner.name, + outputs: inner.outputs, + }), }, - LegacyContractAbiEntry::Event(inner) => RawLegacyAbiEntry::Event(RawLegacyEvent { + LegacyContractAbiEntry::Event(inner) => Self::Event(RawLegacyEvent { data: inner.data, keys: inner.keys, name: inner.name, }), - LegacyContractAbiEntry::Struct(inner) => RawLegacyAbiEntry::Struct(RawLegacyStruct { + LegacyContractAbiEntry::Struct(inner) => Self::Struct(RawLegacyStruct { members: inner .members .into_iter() diff --git a/starknet-core/src/types/eth_address.rs b/starknet-core/src/types/eth_address.rs index dfc3028e..5bfa95bd 100644 --- a/starknet-core/src/types/eth_address.rs +++ b/starknet-core/src/types/eth_address.rs @@ -83,7 +83,7 @@ impl EthAddress { felt.try_into() } - pub fn as_bytes(&self) -> &[u8; 20] { + pub const fn as_bytes(&self) -> &[u8; 20] { &self.inner } } @@ -109,7 +109,7 @@ impl<'de> Deserialize<'de> for EthAddress { impl<'de> Visitor<'de> for EthAddressVisitor { type Value = EthAddress; - fn expecting(&self, formatter: &mut Formatter) -> alloc::fmt::Result { + fn expecting(&self, formatter: &mut Formatter<'_>) -> alloc::fmt::Result { write!(formatter, "string") } @@ -169,7 +169,7 @@ impl TryFrom<&Felt> for EthAddress { impl From for Felt { fn from(value: EthAddress) -> Self { // Safe to unwrap here as the value is never out of range - Felt::from_bytes_be_slice(&value.inner) + Self::from_bytes_be_slice(&value.inner) } } diff --git a/starknet-core/src/types/execution_result.rs b/starknet-core/src/types/execution_result.rs index 2a757531..b0d56a1c 100644 --- a/starknet-core/src/types/execution_result.rs +++ b/starknet-core/src/types/execution_result.rs @@ -12,10 +12,10 @@ pub enum ExecutionResult { } impl ExecutionResult { - pub fn status(&self) -> TransactionExecutionStatus { + pub const fn status(&self) -> TransactionExecutionStatus { match self { - ExecutionResult::Succeeded => TransactionExecutionStatus::Succeeded, - ExecutionResult::Reverted { .. } => TransactionExecutionStatus::Reverted, + Self::Succeeded => TransactionExecutionStatus::Succeeded, + Self::Reverted { .. } => TransactionExecutionStatus::Reverted, } } @@ -25,8 +25,8 @@ impl ExecutionResult { /// variant. pub fn revert_reason(&self) -> Option<&str> { match self { - ExecutionResult::Succeeded => None, - ExecutionResult::Reverted { reason } => Some(reason), + Self::Succeeded => None, + Self::Reverted { reason } => Some(reason), } } } diff --git a/starknet-core/src/types/hash_256.rs b/starknet-core/src/types/hash_256.rs index ec0bb839..b6ad9061 100644 --- a/starknet-core/src/types/hash_256.rs +++ b/starknet-core/src/types/hash_256.rs @@ -68,7 +68,7 @@ impl Hash256 { felt.into() } - pub fn as_bytes(&self) -> &[u8; HASH_256_BYTE_COUNT] { + pub const fn as_bytes(&self) -> &[u8; HASH_256_BYTE_COUNT] { &self.inner } } @@ -102,7 +102,7 @@ impl<'de> Deserialize<'de> for Hash256 { impl<'de> Visitor<'de> for Hash256Visitor { type Value = Hash256; - fn expecting(&self, formatter: &mut Formatter) -> alloc::fmt::Result { + fn expecting(&self, formatter: &mut Formatter<'_>) -> alloc::fmt::Result { write!(formatter, "string, or an array of u8") } @@ -186,7 +186,7 @@ impl TryFrom<&Hash256> for Felt { type Error = ToFieldElementError; fn try_from(value: &Hash256) -> Result { - Ok(Felt::from_bytes_be(&value.inner)) + Ok(Self::from_bytes_be(&value.inner)) } } @@ -212,7 +212,7 @@ mod tests { "25c5b1592b1743b62d7fabd4373d98219c2ff3750f49ec0608a8355fa3bb060f5", ]; - for item in test_data.into_iter() { + for item in test_data { match Hash256::from_hex(item) { Err(FromHexError::UnexpectedLength) => {} _ => panic!("Unexpected test result"), @@ -230,7 +230,7 @@ mod tests { "0x?5c5b1592b1743b62d7fabd4373d98219c2f63750f49ec0608a8355fa3bb060", ]; - for item in test_data.into_iter() { + for item in test_data { match Hash256::from_hex(item) { Err(FromHexError::InvalidHexString) => {} _ => panic!("Unexpected test result"), diff --git a/starknet-core/src/types/mod.rs b/starknet-core/src/types/mod.rs index 16614753..0d5321f8 100644 --- a/starknet-core/src/types/mod.rs +++ b/starknet-core/src/types/mod.rs @@ -336,7 +336,7 @@ pub enum ExecuteInvocation { mod errors { use core::fmt::{Display, Formatter, Result}; - #[derive(Debug, PartialEq)] + #[derive(Debug, PartialEq, Eq)] pub enum ParseMsgToL2Error { EmptyCalldata, FromAddressOutOfRange, @@ -366,15 +366,15 @@ pub use errors::ParseMsgToL2Error; impl MaybePendingBlockWithTxHashes { pub fn transactions(&self) -> &[Felt] { match self { - MaybePendingBlockWithTxHashes::Block(block) => &block.transactions, - MaybePendingBlockWithTxHashes::PendingBlock(block) => &block.transactions, + Self::Block(block) => &block.transactions, + Self::PendingBlock(block) => &block.transactions, } } - pub fn l1_gas_price(&self) -> &ResourcePrice { + pub const fn l1_gas_price(&self) -> &ResourcePrice { match self { - MaybePendingBlockWithTxHashes::Block(block) => &block.l1_gas_price, - MaybePendingBlockWithTxHashes::PendingBlock(block) => &block.l1_gas_price, + Self::Block(block) => &block.l1_gas_price, + Self::PendingBlock(block) => &block.l1_gas_price, } } } @@ -382,15 +382,15 @@ impl MaybePendingBlockWithTxHashes { impl MaybePendingBlockWithTxs { pub fn transactions(&self) -> &[Transaction] { match self { - MaybePendingBlockWithTxs::Block(block) => &block.transactions, - MaybePendingBlockWithTxs::PendingBlock(block) => &block.transactions, + Self::Block(block) => &block.transactions, + Self::PendingBlock(block) => &block.transactions, } } - pub fn l1_gas_price(&self) -> &ResourcePrice { + pub const fn l1_gas_price(&self) -> &ResourcePrice { match self { - MaybePendingBlockWithTxs::Block(block) => &block.l1_gas_price, - MaybePendingBlockWithTxs::PendingBlock(block) => &block.l1_gas_price, + Self::Block(block) => &block.l1_gas_price, + Self::PendingBlock(block) => &block.l1_gas_price, } } } @@ -398,100 +398,100 @@ impl MaybePendingBlockWithTxs { impl MaybePendingBlockWithReceipts { pub fn transactions(&self) -> &[TransactionWithReceipt] { match self { - MaybePendingBlockWithReceipts::Block(block) => &block.transactions, - MaybePendingBlockWithReceipts::PendingBlock(block) => &block.transactions, + Self::Block(block) => &block.transactions, + Self::PendingBlock(block) => &block.transactions, } } - pub fn l1_gas_price(&self) -> &ResourcePrice { + pub const fn l1_gas_price(&self) -> &ResourcePrice { match self { - MaybePendingBlockWithReceipts::Block(block) => &block.l1_gas_price, - MaybePendingBlockWithReceipts::PendingBlock(block) => &block.l1_gas_price, + Self::Block(block) => &block.l1_gas_price, + Self::PendingBlock(block) => &block.l1_gas_price, } } } impl TransactionStatus { - pub fn finality_status(&self) -> SequencerTransactionStatus { + pub const fn finality_status(&self) -> SequencerTransactionStatus { match self { - TransactionStatus::Received => SequencerTransactionStatus::Received, - TransactionStatus::Rejected => SequencerTransactionStatus::Rejected, - TransactionStatus::AcceptedOnL2(_) => SequencerTransactionStatus::AcceptedOnL2, - TransactionStatus::AcceptedOnL1(_) => SequencerTransactionStatus::AcceptedOnL1, + Self::Received => SequencerTransactionStatus::Received, + Self::Rejected => SequencerTransactionStatus::Rejected, + Self::AcceptedOnL2(_) => SequencerTransactionStatus::AcceptedOnL2, + Self::AcceptedOnL1(_) => SequencerTransactionStatus::AcceptedOnL1, } } } impl Transaction { - pub fn transaction_hash(&self) -> &Felt { + pub const fn transaction_hash(&self) -> &Felt { match self { - Transaction::Invoke(tx) => tx.transaction_hash(), - Transaction::L1Handler(tx) => &tx.transaction_hash, - Transaction::Declare(tx) => tx.transaction_hash(), - Transaction::Deploy(tx) => &tx.transaction_hash, - Transaction::DeployAccount(tx) => tx.transaction_hash(), + Self::Invoke(tx) => tx.transaction_hash(), + Self::L1Handler(tx) => &tx.transaction_hash, + Self::Declare(tx) => tx.transaction_hash(), + Self::Deploy(tx) => &tx.transaction_hash, + Self::DeployAccount(tx) => tx.transaction_hash(), } } } impl InvokeTransaction { - pub fn transaction_hash(&self) -> &Felt { + pub const fn transaction_hash(&self) -> &Felt { match self { - InvokeTransaction::V0(tx) => &tx.transaction_hash, - InvokeTransaction::V1(tx) => &tx.transaction_hash, - InvokeTransaction::V3(tx) => &tx.transaction_hash, + Self::V0(tx) => &tx.transaction_hash, + Self::V1(tx) => &tx.transaction_hash, + Self::V3(tx) => &tx.transaction_hash, } } } impl DeclareTransaction { - pub fn transaction_hash(&self) -> &Felt { + pub const fn transaction_hash(&self) -> &Felt { match self { - DeclareTransaction::V0(tx) => &tx.transaction_hash, - DeclareTransaction::V1(tx) => &tx.transaction_hash, - DeclareTransaction::V2(tx) => &tx.transaction_hash, - DeclareTransaction::V3(tx) => &tx.transaction_hash, + Self::V0(tx) => &tx.transaction_hash, + Self::V1(tx) => &tx.transaction_hash, + Self::V2(tx) => &tx.transaction_hash, + Self::V3(tx) => &tx.transaction_hash, } } } impl DeployAccountTransaction { - pub fn transaction_hash(&self) -> &Felt { + pub const fn transaction_hash(&self) -> &Felt { match self { - DeployAccountTransaction::V1(tx) => &tx.transaction_hash, - DeployAccountTransaction::V3(tx) => &tx.transaction_hash, + Self::V1(tx) => &tx.transaction_hash, + Self::V3(tx) => &tx.transaction_hash, } } } impl TransactionReceipt { - pub fn transaction_hash(&self) -> &Felt { + pub const fn transaction_hash(&self) -> &Felt { match self { - TransactionReceipt::Invoke(receipt) => &receipt.transaction_hash, - TransactionReceipt::L1Handler(receipt) => &receipt.transaction_hash, - TransactionReceipt::Declare(receipt) => &receipt.transaction_hash, - TransactionReceipt::Deploy(receipt) => &receipt.transaction_hash, - TransactionReceipt::DeployAccount(receipt) => &receipt.transaction_hash, + Self::Invoke(receipt) => &receipt.transaction_hash, + Self::L1Handler(receipt) => &receipt.transaction_hash, + Self::Declare(receipt) => &receipt.transaction_hash, + Self::Deploy(receipt) => &receipt.transaction_hash, + Self::DeployAccount(receipt) => &receipt.transaction_hash, } } - pub fn finality_status(&self) -> &TransactionFinalityStatus { + pub const fn finality_status(&self) -> &TransactionFinalityStatus { match self { - TransactionReceipt::Invoke(receipt) => &receipt.finality_status, - TransactionReceipt::L1Handler(receipt) => &receipt.finality_status, - TransactionReceipt::Declare(receipt) => &receipt.finality_status, - TransactionReceipt::Deploy(receipt) => &receipt.finality_status, - TransactionReceipt::DeployAccount(receipt) => &receipt.finality_status, + Self::Invoke(receipt) => &receipt.finality_status, + Self::L1Handler(receipt) => &receipt.finality_status, + Self::Declare(receipt) => &receipt.finality_status, + Self::Deploy(receipt) => &receipt.finality_status, + Self::DeployAccount(receipt) => &receipt.finality_status, } } - pub fn execution_result(&self) -> &ExecutionResult { + pub const fn execution_result(&self) -> &ExecutionResult { match self { - TransactionReceipt::Invoke(receipt) => &receipt.execution_result, - TransactionReceipt::L1Handler(receipt) => &receipt.execution_result, - TransactionReceipt::Declare(receipt) => &receipt.execution_result, - TransactionReceipt::Deploy(receipt) => &receipt.execution_result, - TransactionReceipt::DeployAccount(receipt) => &receipt.execution_result, + Self::Invoke(receipt) => &receipt.execution_result, + Self::L1Handler(receipt) => &receipt.execution_result, + Self::Declare(receipt) => &receipt.execution_result, + Self::Deploy(receipt) => &receipt.execution_result, + Self::DeployAccount(receipt) => &receipt.execution_result, } } } @@ -515,44 +515,44 @@ impl L1HandlerTransaction { } } -impl AsRef for BlockId { - fn as_ref(&self) -> &BlockId { +impl AsRef for BlockId { + fn as_ref(&self) -> &Self { self } } -impl AsRef for FunctionCall { - fn as_ref(&self) -> &FunctionCall { +impl AsRef for FunctionCall { + fn as_ref(&self) -> &Self { self } } -impl AsRef for MsgFromL1 { - fn as_ref(&self) -> &MsgFromL1 { +impl AsRef for MsgFromL1 { + fn as_ref(&self) -> &Self { self } } -impl AsRef for BroadcastedTransaction { - fn as_ref(&self) -> &BroadcastedTransaction { +impl AsRef for BroadcastedTransaction { + fn as_ref(&self) -> &Self { self } } -impl AsRef for BroadcastedInvokeTransaction { - fn as_ref(&self) -> &BroadcastedInvokeTransaction { +impl AsRef for BroadcastedInvokeTransaction { + fn as_ref(&self) -> &Self { self } } -impl AsRef for BroadcastedDeclareTransaction { - fn as_ref(&self) -> &BroadcastedDeclareTransaction { +impl AsRef for BroadcastedDeclareTransaction { + fn as_ref(&self) -> &Self { self } } -impl AsRef for BroadcastedDeployAccountTransaction { - fn as_ref(&self) -> &BroadcastedDeployAccountTransaction { +impl AsRef for BroadcastedDeployAccountTransaction { + fn as_ref(&self) -> &Self { self } } diff --git a/starknet-core/src/types/msg.rs b/starknet-core/src/types/msg.rs index e1f1ce04..c34919e9 100644 --- a/starknet-core/src/types/msg.rs +++ b/starknet-core/src/types/msg.rs @@ -17,7 +17,7 @@ pub struct MsgToL2 { impl MsgToL2 { /// Calculates the message hash based on the algorithm documented here: /// - /// https://docs.starknet.io/documentation/architecture_and_concepts/L1-L2_Communication/messaging-mechanism/ + /// pub fn hash(&self) -> Hash256 { let mut hasher = Keccak256::new(); @@ -40,7 +40,7 @@ impl MsgToL2 { hasher.update((self.payload.len() as u64).to_be_bytes()); // Payload - for item in self.payload.iter() { + for item in &self.payload { hasher.update(item.to_bytes_be()); } @@ -54,7 +54,7 @@ impl MsgToL2 { impl MsgToL1 { /// Calculates the message hash based on the algorithm documented here: /// - /// https://docs.starknet.io/documentation/architecture_and_concepts/Network_Architecture/messaging-mechanism/#structure_and_hashing_l2-l1 + /// pub fn hash(&self) -> Hash256 { let mut hasher = Keccak256::new(); @@ -69,7 +69,7 @@ impl MsgToL1 { hasher.update((self.payload.len() as u64).to_be_bytes()); // Payload - for item in self.payload.iter() { + for item in &self.payload { hasher.update(item.to_bytes_be()); } diff --git a/starknet-core/src/types/receipt_block.rs b/starknet-core/src/types/receipt_block.rs index 5c73d03d..a6216dfe 100644 --- a/starknet-core/src/types/receipt_block.rs +++ b/starknet-core/src/types/receipt_block.rs @@ -13,38 +13,38 @@ pub enum ReceiptBlock { impl ReceiptBlock { /// Returns `true` if and only if it's the `Pending` variant. - pub fn is_pending(&self) -> bool { + pub const fn is_pending(&self) -> bool { match self { - ReceiptBlock::Pending => true, - ReceiptBlock::Block { .. } => false, + Self::Pending => true, + Self::Block { .. } => false, } } /// Returns `true` if and only if it's the `Block` variant. - pub fn is_block(&self) -> bool { + pub const fn is_block(&self) -> bool { match self { - ReceiptBlock::Pending => false, - ReceiptBlock::Block { .. } => true, + Self::Pending => false, + Self::Block { .. } => true, } } /// Returns `None` if block is not `Block`. /// /// A more idiomatic way of accessing the block hash is to match the `Block` enum variant. - pub fn block_hash(&self) -> Option { + pub const fn block_hash(&self) -> Option { match self { - ReceiptBlock::Pending => None, - ReceiptBlock::Block { block_hash, .. } => Some(*block_hash), + Self::Pending => None, + Self::Block { block_hash, .. } => Some(*block_hash), } } /// Returns `None` if block is not `Block`. /// /// A more idiomatic way of accessing the block number is to match the `Block` enum variant. - pub fn block_number(&self) -> Option { + pub const fn block_number(&self) -> Option { match self { - ReceiptBlock::Pending => None, - ReceiptBlock::Block { block_number, .. } => Some(*block_number), + Self::Pending => None, + Self::Block { block_number, .. } => Some(*block_number), } } } diff --git a/starknet-core/src/types/serde_impls.rs b/starknet-core/src/types/serde_impls.rs index 95a5221f..925321c8 100644 --- a/starknet-core/src/types/serde_impls.rs +++ b/starknet-core/src/types/serde_impls.rs @@ -58,7 +58,7 @@ impl<'de> DeserializeAs<'de, u128> for NumAsHex { impl<'de> Visitor<'de> for NumAsHexVisitorU64 { type Value = u64; - fn expecting(&self, formatter: &mut Formatter) -> alloc::fmt::Result { + fn expecting(&self, formatter: &mut Formatter<'_>) -> alloc::fmt::Result { write!(formatter, "string or number") } @@ -98,7 +98,7 @@ impl<'de> Visitor<'de> for NumAsHexVisitorU64 { impl<'de> Visitor<'de> for NumAsHexVisitorU128 { type Value = u128; - fn expecting(&self, formatter: &mut Formatter) -> alloc::fmt::Result { + fn expecting(&self, formatter: &mut Formatter<'_>) -> alloc::fmt::Result { write!(formatter, "string or number") } @@ -128,8 +128,8 @@ impl Serialize for SyncStatusType { S: serde::Serializer, { match self { - SyncStatusType::NotSyncing => serializer.serialize_bool(false), - SyncStatusType::Syncing(sync_status) => SyncStatus::serialize(sync_status, serializer), + Self::NotSyncing => serializer.serialize_bool(false), + Self::Syncing(sync_status) => SyncStatus::serialize(sync_status, serializer), } } } @@ -145,7 +145,7 @@ impl<'de> Deserialize<'de> for SyncStatusType { false => Ok(Self::NotSyncing), }, - SyncStatusTypeDe::SyncStatus(value) => Ok(SyncStatusType::Syncing(value)), + SyncStatusTypeDe::SyncStatus(value) => Ok(Self::Syncing(value)), } } } @@ -233,19 +233,19 @@ mod transaction_status { S: Serializer, { let raw = match self { - TransactionStatus::Received => Raw { + Self::Received => Raw { finality_status: SequencerTransactionStatus::Received, execution_status: None, }, - TransactionStatus::Rejected => Raw { + Self::Rejected => Raw { finality_status: SequencerTransactionStatus::Rejected, execution_status: None, }, - TransactionStatus::AcceptedOnL2(exe) => Raw { + Self::AcceptedOnL2(exe) => Raw { finality_status: SequencerTransactionStatus::AcceptedOnL2, execution_status: Some(*exe), }, - TransactionStatus::AcceptedOnL1(exe) => Raw { + Self::AcceptedOnL1(exe) => Raw { finality_status: SequencerTransactionStatus::AcceptedOnL1, execution_status: Some(*exe), }, @@ -419,9 +419,7 @@ mod tests { (BlockId::Number(1234), "{\"block_number\":1234}"), (BlockId::Tag(BlockTag::Latest), "\"latest\""), (BlockId::Tag(BlockTag::Pending), "\"pending\""), - ] - .into_iter() - { + ] { assert_eq!(serde_json::to_string(&block_id).unwrap(), json); assert_eq!(serde_json::from_str::(json).unwrap(), block_id); } @@ -434,7 +432,7 @@ mod tests { #[derive(Debug, PartialEq, Eq, Deserialize)] struct Value(#[serde_as(as = "NumAsHex")] u64); - for (num, json) in [(Value(100), "\"0x64\""), (Value(100), "100")].into_iter() { + for (num, json) in [(Value(100), "\"0x64\""), (Value(100), "100")] { assert_eq!(serde_json::from_str::(json).unwrap(), num); } } diff --git a/starknet-core/src/types/u256.rs b/starknet-core/src/types/u256.rs index 7f731e3e..aa7b8da4 100644 --- a/starknet-core/src/types/u256.rs +++ b/starknet-core/src/types/u256.rs @@ -1,3 +1,4 @@ +#![allow(clippy::missing_const_for_fn)] use core::{fmt::Display, str}; use crypto_bigint::{ArrayEncoding, CheckedAdd, CheckedMul, CheckedSub, Zero}; @@ -46,72 +47,72 @@ impl U256 { } } -impl core::ops::Add for U256 { - type Output = U256; +impl core::ops::Add for U256 { + type Output = Self; - fn add(self, rhs: U256) -> Self::Output { + fn add(self, rhs: Self) -> Self::Output { Self(self.0.checked_add(&rhs.0).unwrap()) } } -impl core::ops::AddAssign for U256 { - fn add_assign(&mut self, rhs: U256) { +impl core::ops::AddAssign for U256 { + fn add_assign(&mut self, rhs: Self) { self.0 = self.0.checked_add(&rhs.0).unwrap() } } -impl core::ops::Sub for U256 { - type Output = U256; +impl core::ops::Sub for U256 { + type Output = Self; - fn sub(self, rhs: U256) -> Self::Output { + fn sub(self, rhs: Self) -> Self::Output { Self(self.0.checked_sub(&rhs.0).unwrap()) } } -impl core::ops::SubAssign for U256 { - fn sub_assign(&mut self, rhs: U256) { +impl core::ops::SubAssign for U256 { + fn sub_assign(&mut self, rhs: Self) { self.0 = self.0.checked_sub(&rhs.0).unwrap() } } -impl core::ops::Mul for U256 { - type Output = U256; +impl core::ops::Mul for U256 { + type Output = Self; - fn mul(self, rhs: U256) -> Self::Output { + fn mul(self, rhs: Self) -> Self::Output { Self(self.0.checked_mul(&rhs.0).unwrap()) } } -impl core::ops::MulAssign for U256 { - fn mul_assign(&mut self, rhs: U256) { +impl core::ops::MulAssign for U256 { + fn mul_assign(&mut self, rhs: Self) { self.0 = self.0.checked_mul(&rhs.0).unwrap() } } -impl core::ops::Div for U256 { - type Output = U256; +impl core::ops::Div for U256 { + type Output = Self; - fn div(self, rhs: U256) -> Self::Output { + fn div(self, rhs: Self) -> Self::Output { Self(self.0.checked_div(&rhs.0).unwrap()) } } -impl core::ops::DivAssign for U256 { - fn div_assign(&mut self, rhs: U256) { +impl core::ops::DivAssign for U256 { + fn div_assign(&mut self, rhs: Self) { self.0 = self.0.checked_div(&rhs.0).unwrap() } } -impl core::ops::Rem for U256 { - type Output = U256; +impl core::ops::Rem for U256 { + type Output = Self; - fn rem(self, rhs: U256) -> Self::Output { + fn rem(self, rhs: Self) -> Self::Output { Self(self.0.checked_rem(&rhs.0).unwrap()) } } -impl core::ops::RemAssign for U256 { - fn rem_assign(&mut self, rhs: U256) { +impl core::ops::RemAssign for U256 { + fn rem_assign(&mut self, rhs: Self) { self.0 = self.0.checked_rem(&rhs.0).unwrap() } } diff --git a/starknet-core/src/utils.rs b/starknet-core/src/utils.rs index c1fa8273..10bac139 100644 --- a/starknet-core/src/utils.rs +++ b/starknet-core/src/utils.rs @@ -126,7 +126,7 @@ pub fn get_storage_var_address(var_name: &str, args: &[Felt]) -> Result Result Result { if !str.is_ascii() { return Err(CairoShortStringToFeltError::NonAsciiCharacter); @@ -153,7 +153,7 @@ pub fn cairo_short_string_to_felt(str: &str) -> Result Result { if felt == &Felt::ZERO { return Ok(String::new()); @@ -165,7 +165,7 @@ pub fn parse_cairo_short_string(felt: &Felt) -> Result for Signature { #[cfg(feature = "signature-display")] impl core::fmt::Display for Signature { - fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!( f, "{}{}", @@ -57,7 +57,7 @@ impl core::fmt::Display for Signature { #[cfg(feature = "signature-display")] impl core::fmt::Display for ExtendedSignature { - fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!( f, "{}{}{:02x}", @@ -278,7 +278,7 @@ mod tests { serde_json::from_str(json_data).expect("Unable to parse the JSON"); // Iterating over each element in the JSON - for (private_key, expected_public_key) in key_map.into_iter() { + for (private_key, expected_public_key) in key_map { let private_key = if private_key.len() % 2 != 0 { format!("0{}", private_key.trim_start_matches("0x")) } else { diff --git a/starknet-crypto/src/lib.rs b/starknet-crypto/src/lib.rs index 16470b64..47b7db8b 100644 --- a/starknet-crypto/src/lib.rs +++ b/starknet-crypto/src/lib.rs @@ -1,6 +1,7 @@ #![cfg_attr(not(feature = "std"), no_std)] #![doc = include_str!("../README.md")] +#[allow(unused_extern_crates)] #[cfg(all(not(feature = "std"), any(test, feature = "alloc")))] extern crate alloc; diff --git a/starknet-crypto/src/pedersen_hash.rs b/starknet-crypto/src/pedersen_hash.rs index a59c5345..5080a826 100644 --- a/starknet-crypto/src/pedersen_hash.rs +++ b/starknet-crypto/src/pedersen_hash.rs @@ -37,7 +37,7 @@ mod tests { ), ]; - for (in1, in2, expected_hash) in test_data.into_iter() { + for (in1, in2, expected_hash) in test_data { let in1 = field_element_from_be_hex(in1); let in2 = field_element_from_be_hex(in2); let expected_hash = field_element_from_be_hex(expected_hash); diff --git a/starknet-crypto/src/poseidon_hash.rs b/starknet-crypto/src/poseidon_hash.rs index 4f3db345..ff96efbb 100644 --- a/starknet-crypto/src/poseidon_hash.rs +++ b/starknet-crypto/src/poseidon_hash.rs @@ -8,7 +8,7 @@ poseidon_consts!(); /// A hasher for Starknet Poseidon hash. /// -/// Using this hasher is the same as calling [poseidon_hash_many]. +/// Using this hasher is the same as calling [`poseidon_hash_many`]. #[derive(Debug, Default)] pub struct PoseidonHasher { state: [Felt; 3], @@ -16,7 +16,7 @@ pub struct PoseidonHasher { } impl PoseidonHasher { - /// Creates a new [PoseidonHasher]. + /// Creates a new [`PoseidonHasher`]. pub fn new() -> Self { Self::default() } @@ -61,7 +61,7 @@ pub fn poseidon_hash(x: Felt, y: Felt) -> Felt { state[0] } -/// Computes the Starknet Poseidon hash of a single [Felt]. +/// Computes the Starknet Poseidon hash of a single [`Felt`]. pub fn poseidon_hash_single(x: Felt) -> Felt { let mut state = [x, Felt::ZERO, Felt::ONE]; poseidon_permute_comp(&mut state); @@ -69,9 +69,9 @@ pub fn poseidon_hash_single(x: Felt) -> Felt { state[0] } -/// Computes the Starknet Poseidon hash of an arbitrary number of [Felt]s. +/// Computes the Starknet Poseidon hash of an arbitrary number of [`Felt`]s. /// -/// Using this function is the same as using [PoseidonHasher]. +/// Using this function is the same as using [`PoseidonHasher`]. pub fn poseidon_hash_many<'a, I: IntoIterator>(msgs: I) -> Felt { let mut state = [Felt::ZERO, Felt::ZERO, Felt::ZERO]; let mut iter = msgs.into_iter(); @@ -141,11 +141,10 @@ fn round_comp(state: &mut [Felt; 3], idx: usize, full: bool) { state[2] += POSEIDON_COMP_CONSTS[idx + 2]; state[0] = state[0] * state[0] * state[0]; state[1] = state[1] * state[1] * state[1]; - state[2] = state[2] * state[2] * state[2]; } else { state[2] += POSEIDON_COMP_CONSTS[idx]; - state[2] = state[2] * state[2] * state[2]; } + state[2] = state[2] * state[2] * state[2]; mix(state); } @@ -176,7 +175,7 @@ mod tests { ), ]; - for (x, y, hash) in test_data.into_iter() { + for (x, y, hash) in test_data { assert_eq!(poseidon_hash(x, y), hash); } } @@ -200,7 +199,7 @@ mod tests { ), ]; - for (x, hash) in test_data.into_iter() { + for (x, hash) in test_data { assert_eq!(poseidon_hash_single(x), hash); } } @@ -252,7 +251,7 @@ mod tests { ), ]; - for (input, hash) in test_data.into_iter() { + for (input, hash) in test_data { // Direct function call assert_eq!(poseidon_hash_many(&input), hash); diff --git a/starknet-crypto/src/rfc6979.rs b/starknet-crypto/src/rfc6979.rs index af2897a9..cd7ea7da 100644 --- a/starknet-crypto/src/rfc6979.rs +++ b/starknet-crypto/src/rfc6979.rs @@ -104,9 +104,9 @@ mod tests { } fn test_generate_k_from_json_str(json_str: &'static str) { - let test_vectors: Vec = serde_json::from_str(json_str).unwrap(); + let test_vectors: Vec> = serde_json::from_str(json_str).unwrap(); - for test_vector in test_vectors.iter() { + for test_vector in &test_vectors { let msg_hash = field_element_from_be_hex(test_vector.msg_hash); let priv_key = field_element_from_be_hex(test_vector.priv_key); let seed = field_element_from_be_hex(test_vector.seed); diff --git a/starknet-curve/Cargo.toml b/starknet-curve/Cargo.toml index 83c291ba..7c01748b 100644 --- a/starknet-curve/Cargo.toml +++ b/starknet-curve/Cargo.toml @@ -14,3 +14,6 @@ keywords = ["ethereum", "starknet", "web3", "no_std"] [dependencies] starknet-types-core = { version = "0.1.3", default-features = false, features = ["curve"] } + +[lints] +workspace = true diff --git a/starknet-macros/Cargo.toml b/starknet-macros/Cargo.toml index 82d6471c..e402e0fb 100644 --- a/starknet-macros/Cargo.toml +++ b/starknet-macros/Cargo.toml @@ -22,3 +22,6 @@ syn = "2.0.15" [features] default = [] use_imported_type = [] + +[lints] +workspace = true diff --git a/starknet-macros/src/lib.rs b/starknet-macros/src/lib.rs index ebeebe38..79d1aade 100644 --- a/starknet-macros/src/lib.rs +++ b/starknet-macros/src/lib.rs @@ -121,6 +121,6 @@ fn field_element_path() -> &'static str { } #[cfg(not(feature = "use_imported_type"))] -fn field_element_path() -> &'static str { +const fn field_element_path() -> &'static str { "::starknet::core::types::Felt" } diff --git a/starknet-providers/Cargo.toml b/starknet-providers/Cargo.toml index 48db0b55..15055413 100644 --- a/starknet-providers/Cargo.toml +++ b/starknet-providers/Cargo.toml @@ -39,3 +39,6 @@ default = [] no_unknown_fields = [ "starknet-core/no_unknown_fields" ] + +[lints] +workspace = true diff --git a/starknet-providers/src/any.rs b/starknet-providers/src/any.rs index 7bbd7f13..beff9c47 100644 --- a/starknet-providers/src/any.rs +++ b/starknet-providers/src/any.rs @@ -20,7 +20,7 @@ use crate::{ /// the [Provider] trait itself cannot be Box-ed due to the use of associated type. /// /// A recommended pattern is to make your business logic code (e.g. functions) generic over the -/// [Provider] trait, while using this [AnyProvider] type for bootstrapping your application. +/// [Provider] trait, while using this [`AnyProvider`] type for bootstrapping your application. /// /// NOTE: This type was introduced when [Provider] was not Box-able. It should be reviewed whether /// it's still needed anymore. diff --git a/starknet-providers/src/jsonrpc/mod.rs b/starknet-providers/src/jsonrpc/mod.rs index e57550cc..be9b9571 100644 --- a/starknet-providers/src/jsonrpc/mod.rs +++ b/starknet-providers/src/jsonrpc/mod.rs @@ -155,7 +155,7 @@ pub enum JsonRpcResponse { Error { id: u64, error: JsonRpcError }, } -/// Failures trying to parse a [JsonRpcError] into [StarknetError]. +/// Failures trying to parse a [`JsonRpcError`] into [`StarknetError`]. #[derive(Debug, thiserror::Error)] pub enum JsonRpcErrorConversionError { #[error("unknown error code")] @@ -175,7 +175,7 @@ struct Felt(#[serde_as(as = "UfeHex")] pub FeltPrimitive); struct FeltArray(#[serde_as(as = "Vec")] pub Vec); impl JsonRpcClient { - pub fn new(transport: T) -> Self { + pub const fn new(transport: T) -> Self { Self { transport } } } @@ -884,16 +884,16 @@ impl TryFrom<&JsonRpcError> for StarknetError { fn try_from(value: &JsonRpcError) -> Result { match value.code { - 1 => Ok(StarknetError::FailedToReceiveTransaction), - 20 => Ok(StarknetError::ContractNotFound), - 24 => Ok(StarknetError::BlockNotFound), - 27 => Ok(StarknetError::InvalidTransactionIndex), - 28 => Ok(StarknetError::ClassHashNotFound), - 29 => Ok(StarknetError::TransactionHashNotFound), - 31 => Ok(StarknetError::PageSizeTooBig), - 32 => Ok(StarknetError::NoBlocks), - 33 => Ok(StarknetError::InvalidContinuationToken), - 34 => Ok(StarknetError::TooManyKeysInFilter), + 1 => Ok(Self::FailedToReceiveTransaction), + 20 => Ok(Self::ContractNotFound), + 24 => Ok(Self::BlockNotFound), + 27 => Ok(Self::InvalidTransactionIndex), + 28 => Ok(Self::ClassHashNotFound), + 29 => Ok(Self::TransactionHashNotFound), + 31 => Ok(Self::PageSizeTooBig), + 32 => Ok(Self::NoBlocks), + 33 => Ok(Self::InvalidContinuationToken), + 34 => Ok(Self::TooManyKeysInFilter), 40 => { let data = ContractErrorData::deserialize( value @@ -902,7 +902,7 @@ impl TryFrom<&JsonRpcError> for StarknetError { .ok_or(JsonRpcErrorConversionError::MissingData)?, ) .map_err(|_| JsonRpcErrorConversionError::DataParsingFailure)?; - Ok(StarknetError::ContractError(data)) + Ok(Self::ContractError(data)) } 41 => { let data = TransactionExecutionErrorData::deserialize( @@ -912,12 +912,12 @@ impl TryFrom<&JsonRpcError> for StarknetError { .ok_or(JsonRpcErrorConversionError::MissingData)?, ) .map_err(|_| JsonRpcErrorConversionError::DataParsingFailure)?; - Ok(StarknetError::TransactionExecutionError(data)) + Ok(Self::TransactionExecutionError(data)) } - 51 => Ok(StarknetError::ClassAlreadyDeclared), - 52 => Ok(StarknetError::InvalidTransactionNonce), - 53 => Ok(StarknetError::InsufficientMaxFee), - 54 => Ok(StarknetError::InsufficientAccountBalance), + 51 => Ok(Self::ClassAlreadyDeclared), + 52 => Ok(Self::InvalidTransactionNonce), + 53 => Ok(Self::InsufficientMaxFee), + 54 => Ok(Self::InsufficientAccountBalance), 55 => { let data = String::deserialize( value @@ -926,15 +926,15 @@ impl TryFrom<&JsonRpcError> for StarknetError { .ok_or(JsonRpcErrorConversionError::MissingData)?, ) .map_err(|_| JsonRpcErrorConversionError::DataParsingFailure)?; - Ok(StarknetError::ValidationFailure(data)) + Ok(Self::ValidationFailure(data)) } - 56 => Ok(StarknetError::CompilationFailed), - 57 => Ok(StarknetError::ContractClassSizeIsTooLarge), - 58 => Ok(StarknetError::NonAccount), - 59 => Ok(StarknetError::DuplicateTx), - 60 => Ok(StarknetError::CompiledClassHashMismatch), - 61 => Ok(StarknetError::UnsupportedTxVersion), - 62 => Ok(StarknetError::UnsupportedContractClassVersion), + 56 => Ok(Self::CompilationFailed), + 57 => Ok(Self::ContractClassSizeIsTooLarge), + 58 => Ok(Self::NonAccount), + 59 => Ok(Self::DuplicateTx), + 60 => Ok(Self::CompiledClassHashMismatch), + 61 => Ok(Self::UnsupportedTxVersion), + 62 => Ok(Self::UnsupportedContractClassVersion), 63 => { let data = String::deserialize( value @@ -943,7 +943,7 @@ impl TryFrom<&JsonRpcError> for StarknetError { .ok_or(JsonRpcErrorConversionError::MissingData)?, ) .map_err(|_| JsonRpcErrorConversionError::DataParsingFailure)?; - Ok(StarknetError::UnexpectedError(data)) + Ok(Self::UnexpectedError(data)) } 10 => { let data = NoTraceAvailableErrorData::deserialize( @@ -953,7 +953,7 @@ impl TryFrom<&JsonRpcError> for StarknetError { .ok_or(JsonRpcErrorConversionError::MissingData)?, ) .map_err(|_| JsonRpcErrorConversionError::DataParsingFailure)?; - Ok(StarknetError::NoTraceAvailable(data)) + Ok(Self::NoTraceAvailable(data)) } _ => Err(JsonRpcErrorConversionError::UnknownCode), } diff --git a/starknet-providers/src/jsonrpc/transports/http.rs b/starknet-providers/src/jsonrpc/transports/http.rs index bd54d8b4..f50bb46a 100644 --- a/starknet-providers/src/jsonrpc/transports/http.rs +++ b/starknet-providers/src/jsonrpc/transports/http.rs @@ -40,8 +40,8 @@ impl HttpTransport { } } - /// Consumes the current [HttpTransport] instance and returns a new one with the header - /// appended. Same as calling [add_header]. + /// Consumes the current [`HttpTransport`] instance and returns a new one with the header + /// appended. Same as calling [`add_header`]. pub fn with_header(self, name: String, value: String) -> Self { let mut headers = self.headers; headers.push((name, value)); @@ -88,7 +88,7 @@ impl JsonRpcTransport for HttpTransport { .post(self.url.clone()) .body(request_body) .header("Content-Type", "application/json"); - for (name, value) in self.headers.iter() { + for (name, value) in &self.headers { request = request.header(name, value); } diff --git a/starknet-providers/src/provider.rs b/starknet-providers/src/provider.rs index 0ee4958a..1d0588da 100644 --- a/starknet-providers/src/provider.rs +++ b/starknet-providers/src/provider.rs @@ -302,10 +302,10 @@ pub trait Provider { /// Trait for implementation-specific error type. These errors are irrelevant in most cases, /// assuming that users typically care more about the specifics of RPC errors instead of the -/// underlying transport. Therefore, it makes little sense to bloat [ProviderError] with a generic +/// underlying transport. Therefore, it makes little sense to bloat [`ProviderError`] with a generic /// parameter just for these errors. Instead, they're erased to this trait object. /// -/// This trait is used instead of a plain [std::error::Error] to allow downcasting, in case access +/// This trait is used instead of a plain [`std::error::Error`] to allow downcasting, in case access /// to the specific error type is indeed desired. This is achieved with the `as_any()` method. pub trait ProviderImplError: Error + Debug + Send + Sync { fn as_any(&self) -> &dyn Any; diff --git a/starknet-providers/src/sequencer/mod.rs b/starknet-providers/src/sequencer/mod.rs index 4453a3ed..b12c91e8 100644 --- a/starknet-providers/src/sequencer/mod.rs +++ b/starknet-providers/src/sequencer/mod.rs @@ -37,7 +37,7 @@ pub enum GatewayClientError { /// JSON serialization/deserialization error #[error(transparent)] Serde(SerdeJsonError), - /// Sequencer error responses not parsable into [StarknetError] + /// Sequencer error responses not parsable into [`StarknetError`] #[error(transparent)] SequencerError(SequencerError), /// Method is not supported (only when using as [Provider]) @@ -139,8 +139,8 @@ impl SequencerGatewayProvider { ) } - /// Consumes the current [SequencerGatewayProvider] instance and returns a new one with the - /// header appended. Same as calling [add_header]. + /// Consumes the current [`SequencerGatewayProvider`] instance and returns a new one with the + /// header appended. Same as calling [`add_header`]. pub fn with_header(self, name: String, value: String) -> Self { let mut headers = self.headers; headers.push((name, value)); @@ -194,7 +194,7 @@ impl SequencerGatewayProvider { trace!("Sending GET request to sequencer API ({})", url); let mut request = self.client.get(url); - for (name, value) in self.headers.iter() { + for (name, value) in &self.headers { request = request.header(name, value); } @@ -228,7 +228,7 @@ impl SequencerGatewayProvider { .post(url) .header("Content-Type", "application/json") .body(request_body); - for (name, value) in self.headers.iter() { + for (name, value) in &self.headers { request = request.header(name, value); } @@ -475,29 +475,27 @@ impl From for ProviderError { fn from(value: SequencerError) -> Self { let matching_code = match value.code { ErrorCode::BlockNotFound => Some(StarknetError::BlockNotFound), - ErrorCode::EntryPointNotFoundInContract => None, - ErrorCode::InvalidProgram => None, - ErrorCode::TransactionFailed => { + ErrorCode::EntryPointNotFoundInContract + | ErrorCode::InvalidContractClass + | ErrorCode::DeprecatedEndpoint + | ErrorCode::MalformedRequest + | ErrorCode::InvalidProgram => None, + ErrorCode::TransactionFailed | ErrorCode::ValidateFailure => { Some(StarknetError::ValidationFailure(value.message.clone())) } - ErrorCode::TransactionNotFound => Some(StarknetError::ContractNotFound), - ErrorCode::UninitializedContract => Some(StarknetError::ContractNotFound), - ErrorCode::MalformedRequest => None, + ErrorCode::TransactionNotFound | ErrorCode::UninitializedContract => { + Some(StarknetError::ContractNotFound) + } ErrorCode::UndeclaredClass => Some(StarknetError::ClassHashNotFound), ErrorCode::InvalidTransactionNonce => Some(StarknetError::InvalidTransactionNonce), - ErrorCode::ValidateFailure => { - Some(StarknetError::ValidationFailure(value.message.clone())) - } ErrorCode::ClassAlreadyDeclared => Some(StarknetError::ClassAlreadyDeclared), ErrorCode::CompilationFailed => Some(StarknetError::CompilationFailed), ErrorCode::InvalidCompiledClassHash => Some(StarknetError::CompiledClassHashMismatch), ErrorCode::DuplicatedTransaction => Some(StarknetError::DuplicateTx), - ErrorCode::InvalidContractClass => None, - ErrorCode::DeprecatedEndpoint => None, }; match matching_code { - Some(code) => ProviderError::StarknetError(code), + Some(code) => Self::StarknetError(code), None => GatewayClientError::SequencerError(value).into(), } } @@ -539,10 +537,10 @@ where { let temp_value = serde_json::Value::deserialize(deserializer)?; if let Ok(value) = T::deserialize(&temp_value) { - return Ok(GatewayResponse::Data(value)); + return Ok(Self::Data(value)); } if let Ok(value) = SequencerError::deserialize(&temp_value) { - return Ok(GatewayResponse::SequencerError(value)); + return Ok(Self::SequencerError(value)); } Err(serde::de::Error::custom( "data did not match any variant of enum GatewayResponse", @@ -583,9 +581,7 @@ mod tests { for raw in [ include_str!("../../test-data/raw_gateway_responses/get_class_by_hash/1_cairo_0.txt"), include_str!("../../test-data/raw_gateway_responses/get_class_by_hash/3_cairo_1.txt"), - ] - .into_iter() - { + ] { serde_json::from_str::>(raw).unwrap(); } } diff --git a/starknet-providers/src/sequencer/models/contract.rs b/starknet-providers/src/sequencer/models/contract.rs index 04584d51..0ef6a2e6 100644 --- a/starknet-providers/src/sequencer/models/contract.rs +++ b/starknet-providers/src/sequencer/models/contract.rs @@ -91,7 +91,7 @@ impl CompressedSierraClass { let compressed_program = gzip_encoder.finish().map_err(DecompressProgramError::Io)?; - Ok(CompressedSierraClass { + Ok(Self { sierra_program: compressed_program, contract_class_version: flattened_class.contract_class_version.clone(), entry_points_by_type: flattened_class.entry_points_by_type.clone(), diff --git a/starknet-providers/src/sequencer/models/conversions.rs b/starknet-providers/src/sequencer/models/conversions.rs index 8e2c6efe..6af9f96a 100644 --- a/starknet-providers/src/sequencer/models/conversions.rs +++ b/starknet-providers/src/sequencer/models/conversions.rs @@ -604,8 +604,9 @@ impl TryFrom for core::TransactionFinalityStatus { fn try_from(value: TransactionFinalityStatus) -> Result { match value { - TransactionFinalityStatus::NotReceived => Err(ConversionError), - TransactionFinalityStatus::Received => Err(ConversionError), + TransactionFinalityStatus::NotReceived | TransactionFinalityStatus::Received => { + Err(ConversionError) + } TransactionFinalityStatus::AcceptedOnL2 => Ok(Self::AcceptedOnL2), TransactionFinalityStatus::AcceptedOnL1 => Ok(Self::AcceptedOnL1), } @@ -1209,7 +1210,7 @@ fn convert_execution_result( } } -fn convert_legacy_entry_point( +const fn convert_legacy_entry_point( value: core::LegacyContractEntryPoint, ) -> contract_legacy::RawLegacyEntryPoint { // WARNING: this causes pre-0.11.0 contract declaration to fail due to `offset` issue diff --git a/starknet-providers/src/sequencer/models/serde_impls.rs b/starknet-providers/src/sequencer/models/serde_impls.rs index f54d344f..fda5b8e7 100644 --- a/starknet-providers/src/sequencer/models/serde_impls.rs +++ b/starknet-providers/src/sequencer/models/serde_impls.rs @@ -20,7 +20,7 @@ pub(crate) mod u64_hex { impl<'de> Visitor<'de> for U64HexVisitor { type Value = u64; - fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "string") } @@ -56,7 +56,7 @@ pub(crate) mod u128_hex { impl<'de> Visitor<'de> for U128HexVisitor { type Value = u128; - fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "string") } @@ -95,7 +95,7 @@ pub(crate) mod u64_hex_opt { impl<'de> Visitor<'de> for U64HexOptVisitor { type Value = Option; - fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "null or string") } diff --git a/starknet-providers/src/sequencer/models/transaction.rs b/starknet-providers/src/sequencer/models/transaction.rs index 388ace7d..75aaa0b6 100644 --- a/starknet-providers/src/sequencer/models/transaction.rs +++ b/starknet-providers/src/sequencer/models/transaction.rs @@ -246,13 +246,13 @@ pub enum DataAvailabilityMode { struct DataAvailabilityModeVisitor; impl TransactionType { - pub fn transaction_hash(&self) -> Felt { + pub const fn transaction_hash(&self) -> Felt { match self { - TransactionType::Declare(inner) => inner.transaction_hash, - TransactionType::Deploy(inner) => inner.transaction_hash, - TransactionType::DeployAccount(inner) => inner.transaction_hash, - TransactionType::InvokeFunction(inner) => inner.transaction_hash, - TransactionType::L1Handler(inner) => inner.transaction_hash, + Self::Declare(inner) => inner.transaction_hash, + Self::Deploy(inner) => inner.transaction_hash, + Self::DeployAccount(inner) => inner.transaction_hash, + Self::InvokeFunction(inner) => inner.transaction_hash, + Self::L1Handler(inner) => inner.transaction_hash, } } } @@ -281,7 +281,7 @@ impl<'de> Deserialize<'de> for DataAvailabilityMode { impl<'de> Visitor<'de> for DataAvailabilityModeVisitor { type Value = DataAvailabilityMode; - fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "integer") } diff --git a/starknet-providers/src/sequencer/provider.rs b/starknet-providers/src/sequencer/provider.rs index b6b44bcd..313cda9c 100644 --- a/starknet-providers/src/sequencer/provider.rs +++ b/starknet-providers/src/sequencer/provider.rs @@ -113,7 +113,10 @@ impl Provider for SequencerGatewayProvider { .await?; // `NotReceived` is not a valid status for JSON-RPC. It's an error. - if let Some(TransactionFinalityStatus::NotReceived) = &status.finality_status { + if matches!( + &status.finality_status, + Some(TransactionFinalityStatus::NotReceived) + ) { return Err(ProviderError::StarknetError( StarknetError::TransactionHashNotFound, )); diff --git a/starknet-providers/tests/jsonrpc.rs b/starknet-providers/tests/jsonrpc.rs index bddd2ab4..6910ce49 100644 --- a/starknet-providers/tests/jsonrpc.rs +++ b/starknet-providers/tests/jsonrpc.rs @@ -17,6 +17,7 @@ use starknet_providers::{ use url::Url; fn create_jsonrpc_client() -> JsonRpcClient { + #[allow(clippy::or_fun_call)] let rpc_url = std::env::var("STARKNET_RPC") .unwrap_or("https://pathfinder.rpc.sepolia.starknet.rs/rpc/v0_7".into()); JsonRpcClient::new(HttpTransport::new(Url::parse(&rpc_url).unwrap())) diff --git a/starknet-signers/Cargo.toml b/starknet-signers/Cargo.toml index d0515adf..f608b25f 100644 --- a/starknet-signers/Cargo.toml +++ b/starknet-signers/Cargo.toml @@ -39,3 +39,6 @@ wasm-bindgen-test = "0.3.34" default = [] ledger = ["coins-bip32", "coins-ledger", "semver"] + +[lints] +workspace = true diff --git a/starknet-signers/src/key_pair.rs b/starknet-signers/src/key_pair.rs index 31a7cefe..65047f20 100644 --- a/starknet-signers/src/key_pair.rs +++ b/starknet-signers/src/key_pair.rs @@ -47,7 +47,7 @@ impl SigningKey { Self { secret_scalar } } - pub fn from_secret_scalar(secret_scalar: Felt) -> Self { + pub const fn from_secret_scalar(secret_scalar: Felt) -> Self { Self { secret_scalar } } @@ -92,7 +92,7 @@ impl SigningKey { Ok(()) } - pub fn secret_scalar(&self) -> Felt { + pub const fn secret_scalar(&self) -> Felt { self.secret_scalar } @@ -106,11 +106,11 @@ impl SigningKey { } impl VerifyingKey { - pub fn from_scalar(scalar: Felt) -> Self { + pub const fn from_scalar(scalar: Felt) -> Self { Self { scalar } } - pub fn scalar(&self) -> Felt { + pub const fn scalar(&self) -> Felt { self.scalar } From 9badd54eba53bcad3d26c4bdd5d58ded70272ed0 Mon Sep 17 00:00:00 2001 From: Jonathan LEI Date: Tue, 16 Jul 2024 13:54:30 +0800 Subject: [PATCH 2/2] chore: remove unnecessary `allow` --- starknet-accounts/tests/single_owner_account.rs | 3 +-- starknet-contract/tests/contract_deployment.rs | 6 ++---- starknet-core/src/types/u256.rs | 13 ++++++------- starknet-providers/tests/jsonrpc.rs | 3 +-- 4 files changed, 10 insertions(+), 15 deletions(-) diff --git a/starknet-accounts/tests/single_owner_account.rs b/starknet-accounts/tests/single_owner_account.rs index f836a7c4..46d895f4 100644 --- a/starknet-accounts/tests/single_owner_account.rs +++ b/starknet-accounts/tests/single_owner_account.rs @@ -31,9 +31,8 @@ fn create_sequencer_client() -> SequencerGatewayProvider { } fn create_jsonrpc_client() -> JsonRpcClient { - #[allow(clippy::or_fun_call)] let rpc_url = std::env::var("STARKNET_RPC") - .unwrap_or("https://juno.rpc.sepolia.starknet.rs/rpc/v0_7".into()); + .unwrap_or_else(|_| "https://juno.rpc.sepolia.starknet.rs/rpc/v0_7".into()); JsonRpcClient::new(HttpTransport::new(url::Url::parse(&rpc_url).unwrap())) } diff --git a/starknet-contract/tests/contract_deployment.rs b/starknet-contract/tests/contract_deployment.rs index a44f979e..eff7f2cc 100644 --- a/starknet-contract/tests/contract_deployment.rs +++ b/starknet-contract/tests/contract_deployment.rs @@ -16,9 +16,8 @@ const CHAIN_ID: Felt = Felt::from_raw([ #[tokio::test] async fn can_deploy_contract_to_alpha_sepolia_with_invoke_v1() { - #![allow(clippy::or_fun_call)] let rpc_url = std::env::var("STARKNET_RPC") - .unwrap_or("https://pathfinder.rpc.sepolia.starknet.rs/rpc/v0_6".into()); + .unwrap_or_else(|_| "https://pathfinder.rpc.sepolia.starknet.rs/rpc/v0_6".into()); let provider = JsonRpcClient::new(HttpTransport::new(Url::parse(&rpc_url).unwrap())); let signer = LocalWallet::from(SigningKey::from_secret_scalar( Felt::from_hex("00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").unwrap(), @@ -55,9 +54,8 @@ async fn can_deploy_contract_to_alpha_sepolia_with_invoke_v1() { #[tokio::test] async fn can_deploy_contract_to_alpha_sepolia_with_invoke_v3() { - #![allow(clippy::or_fun_call)] let rpc_url = std::env::var("STARKNET_RPC") - .unwrap_or("https://pathfinder.rpc.sepolia.starknet.rs/rpc/v0_6".into()); + .unwrap_or_else(|_| "https://pathfinder.rpc.sepolia.starknet.rs/rpc/v0_6".into()); let provider = JsonRpcClient::new(HttpTransport::new(Url::parse(&rpc_url).unwrap())); let signer = LocalWallet::from(SigningKey::from_secret_scalar( Felt::from_hex("00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").unwrap(), diff --git a/starknet-core/src/types/u256.rs b/starknet-core/src/types/u256.rs index aa7b8da4..f02b87c0 100644 --- a/starknet-core/src/types/u256.rs +++ b/starknet-core/src/types/u256.rs @@ -1,4 +1,3 @@ -#![allow(clippy::missing_const_for_fn)] use core::{fmt::Display, str}; use crypto_bigint::{ArrayEncoding, CheckedAdd, CheckedMul, CheckedSub, Zero}; @@ -13,7 +12,7 @@ pub struct U256(crypto_bigint::U256); impl U256 { #[cfg(target_pointer_width = "64")] - pub fn from_words(low: u128, high: u128) -> Self { + pub const fn from_words(low: u128, high: u128) -> Self { Self(crypto_bigint::U256::from_words([ low as u64, (low >> 64) as u64, @@ -23,7 +22,7 @@ impl U256 { } #[cfg(target_pointer_width = "32")] - pub fn from_words(low: u128, high: u128) -> Self { + pub const fn from_words(low: u128, high: u128) -> Self { Self(crypto_bigint::U256::from_words([ low as u32, (low >> 32) as u32, @@ -36,12 +35,12 @@ impl U256 { ])) } - pub fn low(&self) -> u128 { + pub const fn low(&self) -> u128 { let words = u256_to_u64_array(&self.0); words[0] as u128 + ((words[1] as u128) << 64) } - pub fn high(&self) -> u128 { + pub const fn high(&self) -> u128 { let words = u256_to_u64_array(&self.0); words[2] as u128 + ((words[3] as u128) << 64) } @@ -254,13 +253,13 @@ impl From for U256 { #[cfg(target_pointer_width = "64")] #[inline] -fn u256_to_u64_array(num: &crypto_bigint::U256) -> [u64; 4] { +const fn u256_to_u64_array(num: &crypto_bigint::U256) -> [u64; 4] { num.to_words() } #[cfg(target_pointer_width = "32")] #[inline] -fn u256_to_u64_array(num: &crypto_bigint::U256) -> [u64; 4] { +const fn u256_to_u64_array(num: &crypto_bigint::U256) -> [u64; 4] { unsafe { core::mem::transmute::<[u32; 8], [u64; 4]>(num.to_words()) } } diff --git a/starknet-providers/tests/jsonrpc.rs b/starknet-providers/tests/jsonrpc.rs index 6910ce49..dac0910a 100644 --- a/starknet-providers/tests/jsonrpc.rs +++ b/starknet-providers/tests/jsonrpc.rs @@ -17,9 +17,8 @@ use starknet_providers::{ use url::Url; fn create_jsonrpc_client() -> JsonRpcClient { - #[allow(clippy::or_fun_call)] let rpc_url = std::env::var("STARKNET_RPC") - .unwrap_or("https://pathfinder.rpc.sepolia.starknet.rs/rpc/v0_7".into()); + .unwrap_or_else(|_| "https://pathfinder.rpc.sepolia.starknet.rs/rpc/v0_7".into()); JsonRpcClient::new(HttpTransport::new(Url::parse(&rpc_url).unwrap())) }