Skip to content

Commit

Permalink
Fix clippy warnings (#597)
Browse files Browse the repository at this point in the history
* removed unneeded unit return type

* borrowed a reference that immediately got dereferenced by the compiler

* deleted unnecessary closure for substituting value for `Option::None`

* replace match block with `matches!` macro instead

* use unwrap_or_else instead to avoid potentially side effects

* no need to use question mark here becuase execution of the body will end up there anyway

* borrowed a reference that immediately got dereferenced by the compiler

* borrowed a reference that immediately got dereferenced by the compiler

* when replacing a value of type `T` with `T::default()` std::mem::take is a better option

* use the map function instead of implenting it manually

* use `.is_empty()` instead of checking the length is bigger then 0

* use `.is_some()` and `is_none()` instead of creating an unused variable

* implementing the `From` Trait and we will get the `Into` for free

* add `Default`

* declare it as u64 instead of cast it to u64

* deleted unnecessary clone

* use `assert!` for booleans comparisons

Co-authored-by: Tomasz Drwięga <tomusdrw@users.noreply.github.com>
  • Loading branch information
niclaslind and tomusdrw authored Feb 5, 2022
1 parent b6f10b3 commit 190c21d
Show file tree
Hide file tree
Showing 12 changed files with 44 additions and 51 deletions.
13 changes: 5 additions & 8 deletions src/api/accounts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ mod accounts_signing {
let message_hash = self.hash_message(message);

let signature = key
.sign(&message_hash.as_bytes(), None)
.sign(message_hash.as_bytes(), None)
.expect("hash is non-zero 32-bytes; qed");
let v = signature
.v
Expand Down Expand Up @@ -179,7 +179,7 @@ mod accounts_signing {
};
let (signature, recovery_id) = recovery
.as_signature()
.ok_or_else(|| error::Error::Recovery(signing::RecoveryError::InvalidSignature))?;
.ok_or(error::Error::Recovery(signing::RecoveryError::InvalidSignature))?;
let address = signing::recover(message_hash.as_bytes(), &signature, recovery_id)?;
Ok(address)
}
Expand Down Expand Up @@ -278,13 +278,13 @@ mod accounts_signing {
stream
}

fn rlp_append_signature(&self, stream: &mut RlpStream, signature: &Signature) -> () {
fn rlp_append_signature(&self, stream: &mut RlpStream, signature: &Signature) {
stream.append(&signature.v);
stream.append(&U256::from_big_endian(signature.r.as_bytes()));
stream.append(&U256::from_big_endian(signature.s.as_bytes()));
}

fn rlp_append_access_list(&self, stream: &mut RlpStream) -> () {
fn rlp_append_access_list(&self, stream: &mut RlpStream) {
stream.begin_list(self.access_list.len());
for access in self.access_list.iter() {
stream.begin_list(2);
Expand Down Expand Up @@ -323,10 +323,7 @@ mod accounts_signing {

/// Sign and return a raw signed transaction.
pub fn sign(self, sign: impl signing::Key, chain_id: u64) -> SignedTransaction {
let adjust_v_value = match self.transaction_type.map(|t| t.as_u64()) {
Some(LEGACY_TX_ID) | None => true,
_ => false,
};
let adjust_v_value = matches!(self.transaction_type.map(|t| t.as_u64()), Some(LEGACY_TX_ID) | None);

let encoded = self.encode(chain_id, None);

Expand Down
2 changes: 1 addition & 1 deletion src/api/parity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ mod tests {
ParityPendingTransactionFilter::builder()
.from(Address::from_low_u64_be(0x32))
.gas(U64::from(100_000))
.gas_price(FilterCondition::GreaterThan(U64::from(100_000_000_000 as u64)))
.gas_price(FilterCondition::GreaterThan(U64::from(100_000_000_000_u64)))
.build()
=> "parity_pendingTransactions",
vec![r#"1"#, r#"{"from":{"eq":"0x0000000000000000000000000000000000000032"},"gas":{"eq":"0x186a0"},"gas_price":{"gt":"0x174876e800"}}"#]
Expand Down
4 changes: 2 additions & 2 deletions src/contract/deploy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,9 +130,9 @@ impl<T: Transport> Builder<T> {
let tx = TransactionParameters {
nonce: tx.nonce,
to: tx.to,
gas: tx.gas.unwrap_or(1_000_000.into()),
gas: tx.gas.unwrap_or_else(|| 1_000_000.into()),
gas_price: tx.gas_price,
value: tx.value.unwrap_or(0.into()),
value: tx.value.unwrap_or_else(|| 0.into()),
data: tx
.data
.expect("Tried to deploy a contract but transaction data wasn't set"),
Expand Down
4 changes: 1 addition & 3 deletions src/contract/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -319,9 +319,7 @@ impl<T: Transport> Contract<T> {
data: l.data.0,
})?;

Ok(R::from_tokens(
log.params.into_iter().map(|x| x.value).collect::<Vec<_>>(),
)?)
R::from_tokens(log.params.into_iter().map(|x| x.value).collect::<Vec<_>>())
})
.collect::<Result<Vec<R>>>()
}
Expand Down
8 changes: 4 additions & 4 deletions src/signing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,13 +94,13 @@ mod feature_gated {
type Target = SecretKey;

fn deref(&self) -> &Self::Target {
&self.key
self.key
}
}

impl<T: Deref<Target = SecretKey>> Key for T {
fn sign(&self, message: &[u8], chain_id: Option<u64>) -> Result<Signature, SigningError> {
let message = Message::from_slice(&message).map_err(|_| SigningError::InvalidMessage)?;
let message = Message::from_slice(message).map_err(|_| SigningError::InvalidMessage)?;
let (recovery_id, signature) = CONTEXT.sign_ecdsa_recoverable(&message, self).serialize_compact();

let standard_v = recovery_id.to_i32() as u64;
Expand All @@ -118,7 +118,7 @@ mod feature_gated {
}

fn sign_message(&self, message: &[u8]) -> Result<Signature, SigningError> {
let message = Message::from_slice(&message).map_err(|_| SigningError::InvalidMessage)?;
let message = Message::from_slice(message).map_err(|_| SigningError::InvalidMessage)?;
let (recovery_id, signature) = CONTEXT.sign_ecdsa_recoverable(&message, self).serialize_compact();

let v = recovery_id.to_i32() as u64;
Expand All @@ -140,7 +140,7 @@ mod feature_gated {
let message = Message::from_slice(message).map_err(|_| RecoveryError::InvalidMessage)?;
let recovery_id = RecoveryId::from_i32(recovery_id).map_err(|_| RecoveryError::InvalidSignature)?;
let signature =
RecoverableSignature::from_compact(&signature, recovery_id).map_err(|_| RecoveryError::InvalidSignature)?;
RecoverableSignature::from_compact(signature, recovery_id).map_err(|_| RecoveryError::InvalidSignature)?;
let public_key = CONTEXT
.recover_ecdsa(&message, &signature)
.map_err(|_| RecoveryError::InvalidSignature)?;
Expand Down
4 changes: 2 additions & 2 deletions src/transports/batch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use futures::{
Future, FutureExt,
};
use parking_lot::Mutex;
use std::{collections::BTreeMap, mem, pin::Pin, sync::Arc};
use std::{collections::BTreeMap, pin::Pin, sync::Arc};

type Pending = oneshot::Sender<error::Result<rpc::Value>>;
type PendingRequests = Arc<Mutex<BTreeMap<RequestId, Pending>>>;
Expand Down Expand Up @@ -38,7 +38,7 @@ where

/// Sends all requests as a batch.
pub fn submit_batch(&self) -> impl Future<Output = error::Result<Vec<error::Result<rpc::Value>>>> {
let batch = mem::replace(&mut *self.batch.lock(), vec![]);
let batch = std::mem::take(&mut *self.batch.lock());
let ids = batch.iter().map(|&(id, _)| id).collect::<Vec<_>>();

let batch = self.transport.send_batch(batch);
Expand Down
6 changes: 3 additions & 3 deletions src/transports/ipc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -173,17 +173,17 @@ async fn run_server(unix_stream: UnixStream, messages_rx: UnboundedReceiverStrea
let mut read_buffer = vec![];
let mut closed = false;

while !closed || pending_response_txs.len() > 0 {
while !closed || !pending_response_txs.is_empty() {
tokio::select! {
message = messages_rx.next() => match message {
None => closed = true,
Some(TransportMessage::Subscribe(id, tx)) => {
if let Some(_) = subscription_txs.insert(id.clone(), tx) {
if subscription_txs.insert(id.clone(), tx).is_some() {
log::warn!("Replacing a subscription with id {:?}", id);
}
},
Some(TransportMessage::Unsubscribe(id)) => {
if let None = subscription_txs.remove(&id) {
if subscription_txs.remove(&id).is_none() {
log::warn!("Unsubscribing not subscribed id {:?}", id);
}
},
Expand Down
12 changes: 5 additions & 7 deletions src/transports/ws.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,14 +161,12 @@ impl WsServerTask {
.to_vec()
});

let headers = if let Some(ref head) = maybe_encoded {
Some([soketto::handshake::client::Header {
let headers = maybe_encoded.as_ref().map(|head| {
[soketto::handshake::client::Header {
name: "Authorization",
value: &head,
}])
} else {
None
};
value: head,
}]
});

if let Some(ref head) = headers {
client.set_headers(head);
Expand Down
2 changes: 1 addition & 1 deletion src/types/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,7 @@ mod tests {
}
);

let block: Block<()> = serde_json::from_value(json.clone()).unwrap();
let block: Block<()> = serde_json::from_value(json).unwrap();
assert_eq!(block.base_fee_per_gas, Some(U256::from(7)));
}

Expand Down
10 changes: 5 additions & 5 deletions src/types/log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ mod tests {
log_type: None,
removed: Some(true),
};
assert_eq!(true, log.is_removed());
assert!(log.is_removed());
}

#[test]
Expand All @@ -228,7 +228,7 @@ mod tests {
log_type: None,
removed: Some(false),
};
assert_eq!(false, log.is_removed());
assert!(!log.is_removed());
}

#[test]
Expand All @@ -246,7 +246,7 @@ mod tests {
log_type: Some("removed".into()),
removed: None,
};
assert_eq!(true, log.is_removed());
assert!(log.is_removed());
}

#[test]
Expand All @@ -264,7 +264,7 @@ mod tests {
log_type: Some("mined".into()),
removed: None,
};
assert_eq!(false, log.is_removed());
assert!(!log.is_removed());
}

#[test]
Expand All @@ -282,7 +282,7 @@ mod tests {
log_type: None,
removed: None,
};
assert_eq!(false, log.is_removed());
assert!(!log.is_removed());
}

#[test]
Expand Down
22 changes: 11 additions & 11 deletions src/types/signed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,19 +107,19 @@ impl From<CallRequest> for TransactionParameters {
}
}

impl Into<CallRequest> for TransactionParameters {
fn into(self) -> CallRequest {
impl From<TransactionParameters> for CallRequest {
fn from(val: TransactionParameters) -> Self {
CallRequest {
from: None,
to: self.to,
gas: Some(self.gas),
gas_price: self.gas_price,
value: Some(self.value),
data: Some(self.data),
transaction_type: self.transaction_type,
access_list: self.access_list,
max_fee_per_gas: self.max_fee_per_gas,
max_priority_fee_per_gas: self.max_priority_fee_per_gas,
to: val.to,
gas: Some(val.gas),
gas_price: val.gas_price,
value: Some(val.value),
data: Some(val.data),
transaction_type: val.transaction_type,
access_list: val.access_list,
max_fee_per_gas: val.max_fee_per_gas,
max_priority_fee_per_gas: val.max_priority_fee_per_gas,
}
}
}
Expand Down
8 changes: 4 additions & 4 deletions src/types/transaction_request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ impl CallRequest {
}

/// Call Request Builder
#[derive(Clone, Debug)]
#[derive(Clone, Debug, Default)]
pub struct CallRequestBuilder {
call_request: CallRequest,
}
Expand Down Expand Up @@ -165,7 +165,7 @@ impl TransactionRequest {
}

/// Transaction Request Builder
#[derive(Clone, Debug)]
#[derive(Clone, Debug, Default)]
pub struct TransactionRequestBuilder {
transaction_request: TransactionRequest,
}
Expand Down Expand Up @@ -296,7 +296,7 @@ mod tests {
"value": "0x4c4b40",
"data": "0x010203"
}"#;
let deserialized: CallRequest = serde_json::from_str(&serialized).unwrap();
let deserialized: CallRequest = serde_json::from_str(serialized).unwrap();

assert_eq!(deserialized.from, None);
assert_eq!(deserialized.to, Some(Address::from_low_u64_be(5)));
Expand Down Expand Up @@ -353,7 +353,7 @@ mod tests {
"block": 5
}
}"#;
let deserialized: TransactionRequest = serde_json::from_str(&serialized).unwrap();
let deserialized: TransactionRequest = serde_json::from_str(serialized).unwrap();

assert_eq!(deserialized.from, Address::from_low_u64_be(5));
assert_eq!(deserialized.to, None);
Expand Down

0 comments on commit 190c21d

Please sign in to comment.