diff --git a/crates/json-rpc/src/common.rs b/crates/json-rpc/src/common.rs index fe3aa30d078c..4aca16fa6b55 100644 --- a/crates/json-rpc/src/common.rs +++ b/crates/json-rpc/src/common.rs @@ -159,12 +159,7 @@ mod test { fn it_serializes_and_deserializes() { let cases = [ (TestCase { id: Id::Number(1) }, r#"{"id":1}"#), - ( - TestCase { - id: Id::String("foo".to_string()), - }, - r#"{"id":"foo"}"#, - ), + (TestCase { id: Id::String("foo".to_string()) }, r#"{"id":"foo"}"#), (TestCase { id: Id::None }, r#"{"id":null}"#), ]; for (case, expected) in cases { diff --git a/crates/json-rpc/src/lib.rs b/crates/json-rpc/src/lib.rs index dd92328d3ed8..746a2c6f470c 100644 --- a/crates/json-rpc/src/lib.rs +++ b/crates/json-rpc/src/lib.rs @@ -17,14 +17,13 @@ //! actual data being passed to and from the RPC. We can achieve partial //! (de)serialization by making them generic over a `serde_json::RawValue`. //! -//! - For [`Request`] - [`PartiallySerializedRequest`] is a -//! `Request`. It represents a `Request` whose parameters have -//! been serialized. [`SerializedRequest`], on the other hand is a request -//! that has been totally serialized. For client-development purposes, its -//! [`Id`] and method have been preserved. -//! - For [`Response`] - [`BorrowedResponse`] is a `Response<&RawValue>`. It -//! represents a Response whose [`Id`] and return status (success or failure) -//! have been deserialized, but whose payload has not. +//! - For [`Request`] - [`PartiallySerializedRequest`] is a `Request`. It represents a +//! `Request` whose parameters have been serialized. [`SerializedRequest`], on the other hand is a +//! request that has been totally serialized. For client-development purposes, its [`Id`] and +//! method have been preserved. +//! - For [`Response`] - [`BorrowedResponse`] is a `Response<&RawValue>`. It represents a Response +//! whose [`Id`] and return status (success or failure) have been deserialized, but whose payload +//! has not. //! //! Allowing partial serialization lets us include many unlike [`Request`] //! objects in collections (e.g. in a batch request). This is useful for diff --git a/crates/json-rpc/src/packet.rs b/crates/json-rpc/src/packet.rs index bf5a67fc8688..e440ecc84ed2 100644 --- a/crates/json-rpc/src/packet.rs +++ b/crates/json-rpc/src/packet.rs @@ -1,10 +1,11 @@ use crate::{Id, Response, SerializedRequest}; -use serde::de::{self, Deserializer, MapAccess, SeqAccess, Visitor}; -use serde::{ser::SerializeSeq, Deserialize, Serialize}; +use serde::{ + de::{self, Deserializer, MapAccess, SeqAccess, Visitor}, + ser::SerializeSeq, + Deserialize, Serialize, +}; use serde_json::value::RawValue; -use std::collections::HashSet; -use std::fmt; -use std::marker::PhantomData; +use std::{collections::HashSet, fmt, marker::PhantomData}; /// A [`RequestPacket`] is a [`SerializedRequest`] or a batch of serialized /// request. @@ -193,9 +194,7 @@ where } } - deserializer.deserialize_any(ResponsePacketVisitor { - marker: PhantomData, - }) + deserializer.deserialize_any(ResponsePacketVisitor { marker: PhantomData }) } } diff --git a/crates/json-rpc/src/request.rs b/crates/json-rpc/src/request.rs index 63f4f4b03546..e34bbb235eb3 100644 --- a/crates/json-rpc/src/request.rs +++ b/crates/json-rpc/src/request.rs @@ -58,10 +58,7 @@ where /// Serialize the request, including the request parameters. pub fn serialize(self) -> serde_json::Result { let request = serde_json::to_string(&self)?; - Ok(SerializedRequest { - meta: self.meta, - request: RawValue::from_string(request)?, - }) + Ok(SerializedRequest { meta: self.meta, request: RawValue::from_string(request)? }) } } diff --git a/crates/json-rpc/src/response/error.rs b/crates/json-rpc/src/response/error.rs index e856b4a91502..d71097892a71 100644 --- a/crates/json-rpc/src/response/error.rs +++ b/crates/json-rpc/src/response/error.rs @@ -151,14 +151,10 @@ where /// # Returns /// /// - `None` if the error has no `data` field. - /// - `Some(Ok(data))` if the error has a `data` field that can be - /// deserialized. - /// - `Some(Err(err))` if the error has a `data` field that can't be - /// deserialized. + /// - `Some(Ok(data))` if the error has a `data` field that can be deserialized. + /// - `Some(Err(err))` if the error has a `data` field that can't be deserialized. pub fn try_data_as>(&'a self) -> Option> { - self.data - .as_ref() - .map(|data| serde_json::from_str(data.borrow().get())) + self.data.as_ref().map(|data| serde_json::from_str(data.borrow().get())) } /// Attempt to deserialize the data field. @@ -166,15 +162,12 @@ where /// # Returns /// /// - `Ok(ErrorPayload)` if the data field can be deserialized - /// - `Err(self)` if the data field can't be deserialized, or if there - /// is no data field. + /// - `Err(self)` if the data field can't be deserialized, or if there is no data field. pub fn deser_data(self) -> Result, Self> { match self.try_data_as::() { - Some(Ok(data)) => Ok(ErrorPayload { - code: self.code, - message: self.message, - data: Some(data), - }), + Some(Ok(data)) => { + Ok(ErrorPayload { code: self.code, message: self.message, data: Some(data) }) + } _ => Err(self), } } diff --git a/crates/json-rpc/src/response/mod.rs b/crates/json-rpc/src/response/mod.rs index 583c9b47795a..ed84dc689ad8 100644 --- a/crates/json-rpc/src/response/mod.rs +++ b/crates/json-rpc/src/response/mod.rs @@ -39,10 +39,7 @@ impl BorrowedResponse<'_> { /// Convert this borrowed response to an owned response by copying the data /// from the deserializer (if necessary). pub fn into_owned(self) -> Response { - Response { - id: self.id.clone(), - payload: self.payload.into_owned(), - } + Response { id: self.id.clone(), payload: self.payload.into_owned() } } } @@ -74,19 +71,13 @@ where /// /// # Returns /// - /// - `Ok(Response)` if the payload is a success and can be - /// deserialized as T, or if the payload is an error. + /// - `Ok(Response)` if the payload is a success and can be deserialized as T, or if + /// the payload is an error. /// - `Err(self)` if the payload is a success and can't be deserialized. pub fn deser_success(self) -> Result, Self> { match self.payload.deserialize_success() { - Ok(payload) => Ok(Response { - id: self.id, - payload, - }), - Err(payload) => Err(Response { - id: self.id, - payload, - }), + Ok(payload) => Ok(Response { id: self.id, payload }), + Err(payload) => Err(Response { id: self.id, payload }), } } } @@ -107,19 +98,13 @@ where /// /// # Returns /// - /// - `Ok(Response)` if the payload is an error and can be - /// deserialized as `T`, or if the payload is a success. + /// - `Ok(Response)` if the payload is an error and can be deserialized as `T`, or + /// if the payload is a success. /// - `Err(self)` if the payload is an error and can't be deserialized. pub fn deser_err(self) -> Result, Self> { match self.payload.deserialize_error() { - Ok(payload) => Ok(Response { - id: self.id, - payload, - }), - Err(payload) => Err(Response { - id: self.id, - payload, - }), + Ok(payload) => Ok(Response { id: self.id, payload }), + Err(payload) => Err(Response { id: self.id, payload }), } } } @@ -221,18 +206,16 @@ where let id = id.unwrap_or(Id::None); match (result, error) { - (Some(result), None) => Ok(Response { - id, - payload: ResponsePayload::Success(result), - }), - (None, Some(error)) => Ok(Response { - id, - payload: ResponsePayload::Failure(error), - }), + (Some(result), None) => { + Ok(Response { id, payload: ResponsePayload::Success(result) }) + } + (None, Some(error)) => { + Ok(Response { id, payload: ResponsePayload::Failure(error) }) + } (None, None) => Err(serde::de::Error::missing_field("result or error")), - (Some(_), Some(_)) => Err(serde::de::Error::custom( - "result and error are mutually exclusive", - )), + (Some(_), Some(_)) => { + Err(serde::de::Error::custom("result and error are mutually exclusive")) + } } } } @@ -252,10 +235,7 @@ mod test { }"#; let response: super::Response = serde_json::from_str(response).unwrap(); assert_eq!(response.id, super::Id::Number(1)); - assert!(matches!( - response.payload, - super::ResponsePayload::Success(_) - )); + assert!(matches!(response.payload, super::ResponsePayload::Success(_))); } #[test] @@ -270,10 +250,7 @@ mod test { }"#; let response: super::Response = serde_json::from_str(response).unwrap(); assert_eq!(response.id, super::Id::None); - assert!(matches!( - response.payload, - super::ResponsePayload::Failure(_) - )); + assert!(matches!(response.payload, super::ResponsePayload::Failure(_))); } #[test] @@ -290,10 +267,7 @@ mod test { }"#; let response: super::Response = serde_json::from_str(response).unwrap(); assert_eq!(response.id, super::Id::None); - assert!(matches!( - response.payload, - super::ResponsePayload::Success(_) - )); + assert!(matches!(response.payload, super::ResponsePayload::Success(_))); } } diff --git a/crates/json-rpc/src/response/payload.rs b/crates/json-rpc/src/response/payload.rs index b047bf3d649f..71d75b184cb2 100644 --- a/crates/json-rpc/src/response/payload.rs +++ b/crates/json-rpc/src/response/payload.rs @@ -81,19 +81,18 @@ where /// # Returns /// - `None` if the payload is an error /// - `Some(Ok(T))` if the payload is a success and can be deserialized - /// - `Some(Err(serde_json::Error))` if the payload is a success and can't - /// be deserialized as `T` + /// - `Some(Err(serde_json::Error))` if the payload is a success and can't be deserialized as + /// `T` pub fn try_success_as>(&'a self) -> Option> { - self.as_success() - .map(|payload| serde_json::from_str(payload.as_ref().get())) + self.as_success().map(|payload| serde_json::from_str(payload.as_ref().get())) } /// Deserialize a Success payload, if possible, transforming this type. /// /// # Returns /// - /// - `Ok(ResponsePayload)` if the payload is an error, or if the - /// payload is a success and can be deserialized as `T` + /// - `Ok(ResponsePayload)` if the payload is an error, or if the payload is a success and + /// can be deserialized as `T` /// - `Err(self)` if the payload is a success and can't be deserialized pub fn deserialize_success( self, @@ -120,8 +119,7 @@ where /// # Returns /// - `None` if the payload is a success /// - `Some(Ok(T))` if the payload is an error and can be deserialized - /// - `Some(Err(serde_json::Error))` if the payload is an error and can't - /// be deserialized as `T` + /// - `Some(Err(serde_json::Error))` if the payload is an error and can't be deserialized as `T` pub fn try_error_as>(&'a self) -> Option> { self.as_error().and_then(|error| error.try_data_as::()) } @@ -130,8 +128,8 @@ where /// /// # Returns /// - /// - `Ok(ResponsePayload)` if the payload is an error, or if - /// the payload is an error and can be deserialized as `T`. + /// - `Ok(ResponsePayload)` if the payload is an error, or if the payload is an + /// error and can be deserialized as `T`. /// - `Err(self)` if the payload is an error and can't be deserialized. pub fn deserialize_error( self, diff --git a/crates/json-rpc/src/result.rs b/crates/json-rpc/src/result.rs index 6efbbf67a240..8ee5498335a5 100644 --- a/crates/json-rpc/src/result.rs +++ b/crates/json-rpc/src/result.rs @@ -192,10 +192,9 @@ where /// /// # Returns /// - `None` if the response is not `Success`. - /// - `Some(Ok(Resp))` if the response is `Success` and the - /// `result` field can be deserialized. - /// - `Some(Err(err))` if the response is `Success` and the `result` field - /// can't be deserialized. + /// - `Some(Ok(Resp))` if the response is `Success` and the `result` field can be deserialized. + /// - `Some(Err(err))` if the response is `Success` and the `result` field can't be + /// deserialized. pub fn try_success_as<'a, Resp: Deserialize<'a>>(&'a self) -> Option> { match self { Self::Success(val) => Some(serde_json::from_str(val.borrow().get())), @@ -245,10 +244,9 @@ where /// /// # Returns /// - `None` if the response is not `Failure` - /// - `Some(Ok(ErrorPayload))` if the response is `Failure` and the - /// `data` field can be deserialized. - /// - `Some(Err(err))` if the response is `Failure` and the `data` field - /// can't be deserialized. + /// - `Some(Ok(ErrorPayload))` if the response is `Failure` and the `data` field can be + /// deserialized. + /// - `Some(Err(err))` if the response is `Failure` and the `data` field can't be deserialized. pub fn try_failure_as<'a, ErrData: Deserialize<'a>>( &'a self, ) -> Option> { @@ -263,10 +261,9 @@ where pub fn deserialize_failure(self) -> Result, Self> { match self { RpcResult::Success(ok) => Ok(RpcResult::Success(ok)), - RpcResult::Failure(err_resp) => err_resp - .deser_data::() - .map(RpcResult::Failure) - .map_err(RpcResult::Failure), + RpcResult::Failure(err_resp) => { + err_resp.deser_data::().map(RpcResult::Failure).map_err(RpcResult::Failure) + } RpcResult::Err(err) => Ok(RpcResult::Err(err)), } } @@ -296,11 +293,7 @@ where data: Some(data), })), Some(Err(e)) => { - let text = err_resp - .data - .as_ref() - .map(|d| d.borrow().get()) - .unwrap_or(""); + let text = err_resp.data.as_ref().map(|d| d.borrow().get()).unwrap_or(""); Err(f(e, text)) } }, diff --git a/crates/providers/src/builder.rs b/crates/providers/src/builder.rs index b05a7c96ca35..b1b486a632e9 100644 --- a/crates/providers/src/builder.rs +++ b/crates/providers/src/builder.rs @@ -22,11 +22,7 @@ pub struct Stack { impl Stack { /// Create a new `Stack`. pub fn new(inner: Inner, outer: Outer) -> Self { - Stack { - inner, - outer, - _pd: std::marker::PhantomData, - } + Stack { inner, outer, _pd: std::marker::PhantomData } } } @@ -92,11 +88,7 @@ impl ProviderBuilder { /// builder.network::() /// ``` pub fn network(self) -> ProviderBuilder { - ProviderBuilder { - layer: self.layer, - transport: self.transport, - network: PhantomData, - } + ProviderBuilder { layer: self.layer, transport: self.transport, network: PhantomData } } /// Finish the layer stack by providing a root [`RpcClient`], outputting diff --git a/crates/providers/src/lib.rs b/crates/providers/src/lib.rs index 96b6cbd9c647..9e8c5d35aac9 100644 --- a/crates/providers/src/lib.rs +++ b/crates/providers/src/lib.rs @@ -59,10 +59,7 @@ where T: Transport, { fn from(client: RpcClient) -> Self { - Self { - network: PhantomData, - client, - } + Self { network: PhantomData, client } } } diff --git a/crates/providers/src/provider.rs b/crates/providers/src/provider.rs index 20dc8bee7f59..b373441755ca 100644 --- a/crates/providers/src/provider.rs +++ b/crates/providers/src/provider.rs @@ -58,9 +58,7 @@ impl Provider { where Self: Sync, { - self.inner - .prepare("eth_blockNumber", Cow::<()>::Owned(())) - .await + self.inner.prepare("eth_blockNumber", Cow::<()>::Owned(())).await } /// Gets the balance of the account at the specified tag, which defaults to latest. @@ -93,10 +91,7 @@ impl Provider { Self: Sync, { self.inner - .prepare( - "eth_getBlockByHash", - Cow::<(BlockHash, bool)>::Owned((hash, full)), - ) + .prepare("eth_getBlockByHash", Cow::<(BlockHash, bool)>::Owned((hash, full))) .await } @@ -122,9 +117,7 @@ impl Provider { where Self: Sync, { - self.inner - .prepare("eth_chainId", Cow::<()>::Owned(())) - .await + self.inner.prepare("eth_chainId", Cow::<()>::Owned(())).await } /// Gets the bytecode located at the corresponding [Address]. pub async fn get_code_at + Send + Sync>( @@ -136,10 +129,7 @@ impl Provider { Self: Sync, { self.inner - .prepare( - "eth_getCode", - Cow::<(Address, BlockId)>::Owned((address, tag.into())), - ) + .prepare("eth_getCode", Cow::<(Address, BlockId)>::Owned((address, tag.into()))) .await } @@ -169,19 +159,16 @@ impl Provider { where Self: Sync, { - self.inner - .prepare("eth_getLogs", Cow::>::Owned(vec![filter])) - .await + self.inner.prepare("eth_getLogs", Cow::>::Owned(vec![filter])).await } - /// Gets the accounts in the remote node. This is usually empty unless you're using a local node. + /// Gets the accounts in the remote node. This is usually empty unless you're using a local + /// node. pub async fn get_accounts(&self) -> RpcResult, Box, TransportError> where Self: Sync, { - self.inner - .prepare("eth_accounts", Cow::<()>::Owned(())) - .await + self.inner.prepare("eth_accounts", Cow::<()>::Owned(())).await } /// Gets the current gas price. @@ -189,9 +176,7 @@ impl Provider { where Self: Sync, { - self.inner - .prepare("eth_gasPrice", Cow::<()>::Owned(())) - .await + self.inner.prepare("eth_gasPrice", Cow::<()>::Owned(())).await } /// Gets a [TransactionReceipt] if it exists, by its [TxHash]. @@ -202,12 +187,7 @@ impl Provider { where Self: Sync, { - self.inner - .prepare( - "eth_getTransactionReceipt", - Cow::>::Owned(vec![hash]), - ) - .await + self.inner.prepare("eth_getTransactionReceipt", Cow::>::Owned(vec![hash])).await } /// Returns a collection of historical gas information [FeeHistory] which @@ -241,12 +221,7 @@ impl Provider { where Self: Sync, { - self.inner - .prepare( - "eth_getBlockReceipts", - Cow::::Owned(block), - ) - .await + self.inner.prepare("eth_getBlockReceipts", Cow::::Owned(block)).await } /// Gets an uncle block through the tag [BlockId] and index [U64]. @@ -284,9 +259,7 @@ impl Provider { where Self: Sync, { - self.inner - .prepare("eth_syncing", Cow::<()>::Owned(())) - .await + self.inner.prepare("eth_syncing", Cow::<()>::Owned(())).await } /// Execute a smart contract call with [TransactionRequest] without publishing a transaction. @@ -335,9 +308,7 @@ impl Provider { where Self: Sync, { - self.inner - .prepare("eth_sendRawTransaction", Cow::::Owned(tx)) - .await + self.inner.prepare("eth_sendRawTransaction", Cow::::Owned(tx)).await } /// Estimates the EIP1559 `maxFeePerGas` and `maxPriorityFeePerGas` fields. @@ -350,9 +321,7 @@ impl Provider { where Self: Sync, { - let base_fee_per_gas = match self - .get_block_by_number(BlockNumberOrTag::Latest, false) - .await + let base_fee_per_gas = match self.get_block_by_number(BlockNumberOrTag::Latest, false).await { RpcResult::Success(Some(block)) => match block.header.base_fee_per_gas { Some(base_fee_per_gas) => base_fee_per_gas, @@ -403,10 +372,7 @@ impl Provider { Self: Sync, { self.inner - .prepare( - "anvil_setCode", - Cow::<(Address, &'static str)>::Owned((address, code)), - ) + .prepare("anvil_setCode", Cow::<(Address, &'static str)>::Owned((address, code))) .await } @@ -487,17 +453,9 @@ mod providers_test { let provider = Provider::new(&anvil.endpoint()).unwrap(); let num = 0; let tag: BlockNumberOrTag = num.into(); - let block = provider - .get_block_by_number(tag, true) - .await - .unwrap() - .unwrap(); + let block = provider.get_block_by_number(tag, true).await.unwrap().unwrap(); let hash = block.header.hash.unwrap(); - let block = provider - .get_block_by_hash(hash, true) - .await - .unwrap() - .unwrap(); + let block = provider.get_block_by_hash(hash, true).await.unwrap().unwrap(); assert_eq!(block.header.hash.unwrap(), hash); } @@ -507,11 +465,7 @@ mod providers_test { let provider = Provider::new(&anvil.endpoint()).unwrap(); let num = 0; let tag: BlockNumberOrTag = num.into(); - let block = provider - .get_block_by_number(tag, true) - .await - .unwrap() - .unwrap(); + let block = provider.get_block_by_number(tag, true).await.unwrap().unwrap(); assert_eq!(block.header.number.unwrap(), U256::from(num)); } @@ -521,11 +475,7 @@ mod providers_test { let provider = Provider::new(&anvil.endpoint()).unwrap(); let num = 0; let tag: BlockNumberOrTag = num.into(); - let block = provider - .get_block_by_number(tag, true) - .await - .unwrap() - .unwrap(); + let block = provider.get_block_by_number(tag, true).await.unwrap().unwrap(); assert_eq!(block.header.number.unwrap(), U256::from(num)); } diff --git a/crates/providers/src/utils.rs b/crates/providers/src/utils.rs index e19a8d1d3a2f..50fbdbdc1475 100644 --- a/crates/providers/src/utils.rs +++ b/crates/providers/src/utils.rs @@ -19,11 +19,7 @@ pub const EIP1559_FEE_ESTIMATION_THRESHOLD_MAX_CHANGE: i64 = 200; pub type EstimatorFunction = fn(U256, Vec>) -> (U256, U256); fn estimate_priority_fee(rewards: Vec>) -> U256 { - let mut rewards: Vec = rewards - .iter() - .map(|r| r[0]) - .filter(|r| *r > U256::ZERO) - .collect(); + let mut rewards: Vec = rewards.iter().map(|r| r[0]).filter(|r| *r > U256::ZERO).collect(); if rewards.is_empty() { return U256::ZERO; } @@ -51,10 +47,7 @@ fn estimate_priority_fee(rewards: Vec>) -> U256 { // Fetch the max of the percentage change, and that element's index. let max_change = percentage_change.iter().max().unwrap(); - let max_change_index = percentage_change - .iter() - .position(|&c| c == *max_change) - .unwrap(); + let max_change_index = percentage_change.iter().position(|&c| c == *max_change).unwrap(); // If we encountered a big change in fees at a certain position, then consider only // the values >= it. diff --git a/crates/pubsub/src/frontend.rs b/crates/pubsub/src/frontend.rs index 56c17977057f..6d0bf7a18750 100644 --- a/crates/pubsub/src/frontend.rs +++ b/crates/pubsub/src/frontend.rs @@ -28,9 +28,7 @@ impl PubSubFrontend { id: U256, ) -> Result>, TransportError> { let (tx, rx) = oneshot::channel(); - self.tx - .send(PubSubInstruction::GetSub(id, tx)) - .map_err(|_| TransportError::BackendGone)?; + self.tx.send(PubSubInstruction::GetSub(id, tx)).map_err(|_| TransportError::BackendGone)?; rx.await.map_err(|_| TransportError::BackendGone) } diff --git a/crates/pubsub/src/handle.rs b/crates/pubsub/src/handle.rs index 1ce8422101a6..c6454a708659 100644 --- a/crates/pubsub/src/handle.rs +++ b/crates/pubsub/src/handle.rs @@ -33,12 +33,7 @@ impl ConnectionHandle { let (error_tx, error_rx) = oneshot::channel(); let (shutdown_tx, shutdown_rx) = oneshot::channel(); - let handle = Self { - to_socket, - from_socket, - error: error_rx, - shutdown: shutdown_tx, - }; + let handle = Self { to_socket, from_socket, error: error_rx, shutdown: shutdown_tx }; let interface = ConnectionInterface { from_frontend, to_frontend, diff --git a/crates/pubsub/src/managers/active_sub.rs b/crates/pubsub/src/managers/active_sub.rs index 5d82465e6c88..642cbd893208 100644 --- a/crates/pubsub/src/managers/active_sub.rs +++ b/crates/pubsub/src/managers/active_sub.rs @@ -59,14 +59,7 @@ impl ActiveSubscription { pub(crate) fn new(request: SerializedRequest) -> (Self, broadcast::Receiver>) { let local_id = request.params_hash(); let (tx, rx) = broadcast::channel(16); - ( - Self { - request, - local_id, - tx, - }, - rx, - ) + (Self { request, local_id, tx }, rx) } /// Serialize the request as a boxed [`RawValue`]. diff --git a/crates/pubsub/src/managers/in_flight.rs b/crates/pubsub/src/managers/in_flight.rs index e08ffe91133a..9ab992d4ae38 100644 --- a/crates/pubsub/src/managers/in_flight.rs +++ b/crates/pubsub/src/managers/in_flight.rs @@ -17,15 +17,10 @@ pub(crate) struct InFlight { impl std::fmt::Debug for InFlight { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let channel_desc = format!( - "Channel status: {}", - if self.tx.is_closed() { "closed" } else { "ok" } - ); + let channel_desc = + format!("Channel status: {}", if self.tx.is_closed() { "closed" } else { "ok" }); - f.debug_struct("InFlight") - .field("req", &self.request) - .field("tx", &channel_desc) - .finish() + f.debug_struct("InFlight").field("req", &self.request).field("tx", &channel_desc).finish() } } diff --git a/crates/pubsub/src/service.rs b/crates/pubsub/src/service.rs index cf267feaa55c..e1eba120236d 100644 --- a/crates/pubsub/src/service.rs +++ b/crates/pubsub/src/service.rs @@ -65,10 +65,7 @@ where async fn reconnect(&mut self) -> Result<(), TransportError> { tracing::info!("Reconnecting pubsub service backend."); - let mut old_handle = self - .get_new_backend() - .await - .map_err(TransportError::custom)?; + let mut old_handle = self.get_new_backend().await.map_err(TransportError::custom)?; tracing::debug!("Draining old backend to_handle"); @@ -106,11 +103,7 @@ where /// Dispatch a request to the socket. fn dispatch_request(&mut self, brv: Box) -> Result<(), TransportError> { - self.handle - .to_socket - .send(brv) - .map(drop) - .map_err(|_| TransportError::BackendGone) + self.handle.to_socket.send(brv).map(drop).map_err(|_| TransportError::BackendGone) } /// Service a request. @@ -147,10 +140,7 @@ where fn service_unsubscribe(&mut self, local_id: U256) -> Result<(), TransportError> { let local_id = local_id.into(); let req = Request { - meta: RequestMeta { - id: Id::None, - method: "eth_unsubscribe", - }, + meta: RequestMeta { id: Id::None, method: "eth_unsubscribe" }, params: [local_id], }; let brv = req.serialize().expect("no ser error").take_request(); @@ -202,10 +192,8 @@ where // We send back a success response with the new subscription ID. // We don't care if the channel is dead. - let _ = in_flight.tx.send(Ok(Response { - id, - payload: ResponsePayload::Success(ser_alias), - })); + let _ = + in_flight.tx.send(Ok(Response { id, payload: ResponsePayload::Success(ser_alias) })); Ok(()) } diff --git a/crates/rpc-client/src/batch.rs b/crates/rpc-client/src/batch.rs index 043288943acf..b539bfe2f363 100644 --- a/crates/rpc-client/src/batch.rs +++ b/crates/rpc-client/src/batch.rs @@ -46,10 +46,7 @@ impl From, Box, Transp fn from( rx: oneshot::Receiver, Box, TransportError>>, ) -> Self { - Self { - rx, - _resp: PhantomData, - } + Self { rx, _resp: PhantomData } } } @@ -168,11 +165,7 @@ where mut self: Pin<&mut Self>, cx: &mut task::Context<'_>, ) -> Poll<::Output> { - let CallStateProj::Prepared { - transport, - requests, - channels, - } = self.as_mut().project() + let CallStateProj::Prepared { transport, requests, channels } = self.as_mut().project() else { unreachable!("Called poll_prepared in incorrect state") }; diff --git a/crates/rpc-client/src/builder.rs b/crates/rpc-client/src/builder.rs index 6a37c28d81a6..f6870ee6fe4b 100644 --- a/crates/rpc-client/src/builder.rs +++ b/crates/rpc-client/src/builder.rs @@ -22,9 +22,7 @@ pub struct ClientBuilder { impl Default for ClientBuilder { fn default() -> Self { - Self { - builder: ServiceBuilder::new(), - } + Self { builder: ServiceBuilder::new() } } } @@ -34,9 +32,7 @@ impl ClientBuilder { /// This is a wrapper around [`tower::ServiceBuilder::layer`]. Layers that /// are added first will be called with the request first. pub fn layer(self, layer: M) -> ClientBuilder> { - ClientBuilder { - builder: self.builder.layer(layer), - } + ClientBuilder { builder: self.builder.layer(layer) } } /// Create a new [`RpcClient`] with the given transport and the configured diff --git a/crates/rpc-client/src/call.rs b/crates/rpc-client/src/call.rs index d7a34ffbe0e4..6de6b7cbeded 100644 --- a/crates/rpc-client/src/call.rs +++ b/crates/rpc-client/src/call.rs @@ -55,11 +55,7 @@ where ) -> task::Poll<::Output> { trace!("Polling prepared"); let fut = { - let CallStateProj::Prepared { - connection, - request, - } = self.as_mut().project() - else { + let CallStateProj::Prepared { connection, request } = self.as_mut().project() else { unreachable!("Called poll_prepared in incorrect state") }; @@ -67,10 +63,7 @@ where self.set(CallState::Complete); return Ready(RpcResult::Err(e)); } - let request = request - .take() - .expect("No request. This is a bug.") - .serialize(); + let request = request.take().expect("No request. This is a bug.").serialize(); match request { Ok(request) => connection.call(request.into()), @@ -163,13 +156,7 @@ where { #[doc(hidden)] pub fn new(req: Request, connection: Conn) -> Self { - Self { - state: CallState::Prepared { - request: Some(req), - connection, - }, - _pd: PhantomData, - } + Self { state: CallState::Prepared { request: Some(req), connection }, _pd: PhantomData } } /// Get a mutable reference to the params of the request. @@ -178,10 +165,7 @@ where /// prepared. pub fn params(&mut self) -> &mut Params { if let CallState::Prepared { request, .. } = &mut self.state { - &mut request - .as_mut() - .expect("No params in prepared. This is a bug") - .params + &mut request.as_mut().expect("No params in prepared. This is a bug").params } else { panic!("Cannot get params after request has been sent"); } diff --git a/crates/rpc-client/src/client.rs b/crates/rpc-client/src/client.rs index 0ea2709b00be..f17b832f96dd 100644 --- a/crates/rpc-client/src/client.rs +++ b/crates/rpc-client/src/client.rs @@ -33,20 +33,14 @@ pub struct RpcClient { impl RpcClient { /// Create a new [`ClientBuilder`]. pub fn builder() -> ClientBuilder { - ClientBuilder { - builder: ServiceBuilder::new(), - } + ClientBuilder { builder: ServiceBuilder::new() } } } impl RpcClient { /// Create a new [`RpcClient`] with the given transport. pub const fn new(t: T, is_local: bool) -> Self { - Self { - transport: t, - is_local, - id: AtomicU64::new(0), - } + Self { transport: t, is_local, id: AtomicU64::new(0) } } /// Connect to a transport via a [`TransportConnect`] implementor. @@ -68,13 +62,7 @@ impl RpcClient { method: &'static str, params: Cow<'a, Params>, ) -> Request> { - Request { - meta: RequestMeta { - method, - id: self.next_id(), - }, - params, - } + Request { meta: RequestMeta { method, id: self.next_id() }, params } } /// `true` if the client believes the transport is local. @@ -139,11 +127,7 @@ where /// `RpcClient` you can put both into a `Vec>`. #[inline] pub fn boxed(self) -> RpcClient { - RpcClient { - transport: self.transport.boxed(), - is_local: self.is_local, - id: self.id, - } + RpcClient { transport: self.transport.boxed(), is_local: self.is_local, id: self.id } } } diff --git a/crates/rpc-client/tests/it/ws.rs b/crates/rpc-client/tests/it/ws.rs index d35c48969166..9d06aaf940fd 100644 --- a/crates/rpc-client/tests/it/ws.rs +++ b/crates/rpc-client/tests/it/ws.rs @@ -7,10 +7,7 @@ use std::borrow::Cow; async fn it_makes_a_request() { let infura = std::env::var("WS_PROVIDER_URL").unwrap(); - let connector = WsConnect { - url: infura.parse().unwrap(), - auth: None, - }; + let connector = WsConnect { url: infura.parse().unwrap(), auth: None }; let client = ClientBuilder::default().pubsub(connector).await.unwrap(); diff --git a/crates/rpc-types/src/eth/block.rs b/crates/rpc-types/src/eth/block.rs index a9c16aaba158..aedde7d0086e 100644 --- a/crates/rpc-types/src/eth/block.rs +++ b/crates/rpc-types/src/eth/block.rs @@ -181,10 +181,7 @@ pub struct Header { #[serde(rename = "excessBlobGas", skip_serializing_if = "Option::is_none")] pub excess_blob_gas: Option, /// Parent beacon block root - #[serde( - rename = "parentBeaconBlockRoot", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "parentBeaconBlockRoot", skip_serializing_if = "Option::is_none")] pub parent_beacon_block_root: Option, } @@ -206,10 +203,7 @@ pub struct RpcBlockHash { impl RpcBlockHash { /// Returns an [RpcBlockHash] from a [B256]. pub const fn from_hash(block_hash: B256, require_canonical: Option) -> Self { - RpcBlockHash { - block_hash, - require_canonical, - } + RpcBlockHash { block_hash, require_canonical } } } @@ -429,19 +423,13 @@ impl From for BlockId { impl From for BlockId { fn from(block_hash: B256) -> Self { - BlockId::Hash(RpcBlockHash { - block_hash, - require_canonical: None, - }) + BlockId::Hash(RpcBlockHash { block_hash, require_canonical: None }) } } impl From<(B256, Option)> for BlockId { fn from(hash_can: (B256, Option)) -> Self { - BlockId::Hash(RpcBlockHash { - block_hash: hash_can.0, - require_canonical: hash_can.1, - }) + BlockId::Hash(RpcBlockHash { block_hash: hash_can.0, require_canonical: hash_can.1 }) } } @@ -451,10 +439,7 @@ impl Serialize for BlockId { S: Serializer, { match *self { - BlockId::Hash(RpcBlockHash { - ref block_hash, - ref require_canonical, - }) => { + BlockId::Hash(RpcBlockHash { ref block_hash, ref require_canonical }) => { let mut s = serializer.serialize_struct("BlockIdEip1898", 1)?; s.serialize_field("blockHash", block_hash)?; if let Some(require_canonical) = require_canonical { @@ -488,14 +473,10 @@ impl<'de> Deserialize<'de> for BlockId { // Since there is no way to clearly distinguish between a DATA parameter and a QUANTITY parameter. A str is therefor deserialized into a Block Number: // However, since the hex string should be a QUANTITY, we can safely assume that if the len is 66 bytes, it is in fact a hash, ref if v.len() == 66 { - Ok(BlockId::Hash( - v.parse::().map_err(serde::de::Error::custom)?.into(), - )) + Ok(BlockId::Hash(v.parse::().map_err(serde::de::Error::custom)?.into())) } else { // quantity hex string or tag - Ok(BlockId::Number( - v.parse().map_err(serde::de::Error::custom)?, - )) + Ok(BlockId::Number(v.parse().map_err(serde::de::Error::custom)?)) } } @@ -545,10 +526,7 @@ impl<'de> Deserialize<'de> for BlockId { if let Some(number) = number { Ok(BlockId::Number(number)) } else if let Some(block_hash) = block_hash { - Ok(BlockId::Hash(RpcBlockHash { - block_hash, - require_canonical, - })) + Ok(BlockId::Hash(RpcBlockHash { block_hash, require_canonical })) } else { Err(serde::de::Error::custom( "Expected `blockNumber` or `blockHash` with `requireCanonical` optionally", @@ -575,10 +553,7 @@ pub type ForkBlock = BlockNumHash; impl std::fmt::Debug for BlockNumHash { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_tuple("") - .field(&self.number) - .field(&self.hash) - .finish() + f.debug_tuple("").field(&self.number).field(&self.hash).finish() } } @@ -604,19 +579,13 @@ impl BlockNumHash { impl From<(BlockNumber, BlockHash)> for BlockNumHash { fn from(val: (BlockNumber, BlockHash)) -> Self { - BlockNumHash { - number: val.0, - hash: val.1, - } + BlockNumHash { number: val.0, hash: val.1 } } } impl From<(BlockHash, BlockNumber)> for BlockNumHash { fn from(val: (BlockHash, BlockNumber)) -> Self { - BlockNumHash { - hash: val.0, - number: val.1, - } + BlockNumHash { hash: val.0, number: val.1 } } } @@ -728,10 +697,7 @@ pub type RichBlock = Rich; impl From for RichBlock { fn from(block: Block) -> Self { - Rich { - inner: block, - extra_info: Default::default(), - } + Rich { inner: block, extra_info: Default::default() } } } @@ -740,10 +706,7 @@ pub type RichHeader = Rich
; impl From
for RichHeader { fn from(header: Header) -> Self { - Rich { - inner: header, - extra_info: Default::default(), - } + Rich { inner: header, extra_info: Default::default() } } } @@ -783,9 +746,7 @@ impl Serialize for Rich { value.extend(extras); value.serialize(serializer) } else { - Err(S::Error::custom( - "Unserializable structures: expected objects", - )) + Err(S::Error::custom("Unserializable structures: expected objects")) } } } @@ -799,11 +760,7 @@ pub struct BlockOverrides { /// For `eth_callMany` this will be the block number of the first simulated block. Each /// following block increments its block number by 1 // Note: geth uses `number`, erigon uses `blockNumber` - #[serde( - default, - skip_serializing_if = "Option::is_none", - alias = "blockNumber" - )] + #[serde(default, skip_serializing_if = "Option::is_none", alias = "blockNumber")] pub number: Option, /// Overrides the difficulty of the block. #[serde(default, skip_serializing_if = "Option::is_none")] diff --git a/crates/rpc-types/src/eth/call.rs b/crates/rpc-types/src/eth/call.rs index 416ecdda194c..2c41dcf28257 100644 --- a/crates/rpc-types/src/eth/call.rs +++ b/crates/rpc-types/src/eth/call.rs @@ -136,10 +136,7 @@ impl CallRequest { /// Returns true if the request has a `blobVersionedHashes` field but it is empty. #[inline] pub fn has_empty_blob_hashes(&self) -> bool { - self.blob_versioned_hashes - .as_ref() - .map(|blobs| blobs.is_empty()) - .unwrap_or(false) + self.blob_versioned_hashes.as_ref().map(|blobs| blobs.is_empty()).unwrap_or(false) } } @@ -202,10 +199,7 @@ impl CallInput { impl From for CallInput { fn from(input: Bytes) -> Self { - Self { - input: Some(input), - data: None, - } + Self { input: Some(input), data: None } } } diff --git a/crates/rpc-types/src/eth/filter.rs b/crates/rpc-types/src/eth/filter.rs index 4f9325b903a4..1c625acc95d1 100644 --- a/crates/rpc-types/src/eth/filter.rs +++ b/crates/rpc-types/src/eth/filter.rs @@ -92,11 +92,7 @@ impl FilterSet { impl + Eq + Hash> FilterSet { /// Returns a list of Bloom (BloomFilter) corresponding to the filter's values pub fn to_bloom_filter(&self) -> BloomFilter { - self.0 - .iter() - .map(|a| BloomInput::Raw(a.as_ref()).into()) - .collect::>() - .into() + self.0.iter().map(|a| BloomInput::Raw(a.as_ref()).into()).collect::>().into() } } @@ -110,9 +106,7 @@ impl FilterSet { let mut values = self.0.iter().cloned().collect::>(); match values.len() { 0 => None, - 1 => Some(ValueOrArray::Value( - values.pop().expect("values length is one"), - )), + 1 => Some(ValueOrArray::Value(values.pop().expect("values length is one"))), _ => Some(ValueOrArray::Array(values)), } } @@ -163,10 +157,9 @@ impl FilterBlockOption { /// Returns the range (`fromBlock`, `toBlock`) if this is a range filter. pub fn as_range(&self) -> (Option<&BlockNumberOrTag>, Option<&BlockNumberOrTag>) { match self { - FilterBlockOption::Range { - from_block, - to_block, - } => (from_block.as_ref(), to_block.as_ref()), + FilterBlockOption::Range { from_block, to_block } => { + (from_block.as_ref(), to_block.as_ref()) + } FilterBlockOption::AtBlockHash(_) => (None, None), } } @@ -175,10 +168,7 @@ impl FilterBlockOption { impl From for FilterBlockOption { fn from(block: BlockNumberOrTag) -> Self { let block = Some(block); - FilterBlockOption::Range { - from_block: block, - to_block: block, - } + FilterBlockOption::Range { from_block: block, to_block: block } } } @@ -198,30 +188,21 @@ impl> From> for FilterBlockOption { fn from(r: Range) -> Self { let from_block = Some(r.start.into()); let to_block = Some(r.end.into()); - FilterBlockOption::Range { - from_block, - to_block, - } + FilterBlockOption::Range { from_block, to_block } } } impl> From> for FilterBlockOption { fn from(r: RangeTo) -> Self { let to_block = Some(r.end.into()); - FilterBlockOption::Range { - from_block: Some(BlockNumberOrTag::Earliest), - to_block, - } + FilterBlockOption::Range { from_block: Some(BlockNumberOrTag::Earliest), to_block } } } impl> From> for FilterBlockOption { fn from(r: RangeFrom) -> Self { let from_block = Some(r.start.into()); - FilterBlockOption::Range { - from_block, - to_block: Some(BlockNumberOrTag::Latest), - } + FilterBlockOption::Range { from_block, to_block: Some(BlockNumberOrTag::Latest) } } } @@ -233,10 +214,7 @@ impl From for FilterBlockOption { impl Default for FilterBlockOption { fn default() -> Self { - FilterBlockOption::Range { - from_block: None, - to_block: None, - } + FilterBlockOption::Range { from_block: None, to_block: None } } } @@ -244,31 +222,19 @@ impl FilterBlockOption { /// Sets the block number this range filter should start at. #[must_use] pub fn set_from_block(&self, block: BlockNumberOrTag) -> Self { - let to_block = if let FilterBlockOption::Range { to_block, .. } = self { - *to_block - } else { - None - }; + let to_block = + if let FilterBlockOption::Range { to_block, .. } = self { *to_block } else { None }; - FilterBlockOption::Range { - from_block: Some(block), - to_block, - } + FilterBlockOption::Range { from_block: Some(block), to_block } } /// Sets the block number this range filter should end at. #[must_use] pub fn set_to_block(&self, block: BlockNumberOrTag) -> Self { - let from_block = if let FilterBlockOption::Range { from_block, .. } = self { - *from_block - } else { - None - }; + let from_block = + if let FilterBlockOption::Range { from_block, .. } = self { *from_block } else { None }; - FilterBlockOption::Range { - from_block, - to_block: Some(block), - } + FilterBlockOption::Range { from_block, to_block: Some(block) } } /// Pins the block hash this filter should target. @@ -400,7 +366,8 @@ impl Filter { /// # use alloy_primitives::Address; /// # use alloy_rpc_types::Filter; /// # fn main() { - /// let filter = Filter::new().address("0xAc4b3DacB91461209Ae9d41EC517c2B9Cb1B7DAF".parse::
().unwrap()); + /// let filter = Filter::new() + /// .address("0xAc4b3DacB91461209Ae9d41EC517c2B9Cb1B7DAF".parse::
().unwrap()); /// # } /// ``` /// @@ -411,7 +378,10 @@ impl Filter { /// # use alloy_primitives::Address; /// # use alloy_rpc_types::Filter; /// # fn main() { - /// let addresses = vec!["0xAc4b3DacB91461209Ae9d41EC517c2B9Cb1B7DAF".parse::
().unwrap(),"0x8ad599c3A0ff1De082011EFDDc58f1908eb6e6D8".parse::
().unwrap()]; + /// let addresses = vec![ + /// "0xAc4b3DacB91461209Ae9d41EC517c2B9Cb1B7DAF".parse::
().unwrap(), + /// "0x8ad599c3A0ff1De082011EFDDc58f1908eb6e6D8".parse::
().unwrap(), + /// ]; /// let filter = Filter::new().address(addresses); /// # } /// ``` @@ -431,10 +401,7 @@ impl Filter { /// Hashes all event signatures and sets them as array to event_signature(topic0) #[must_use] pub fn events(self, events: impl IntoIterator>) -> Self { - let events = events - .into_iter() - .map(|e| keccak256(e.as_ref())) - .collect::>(); + let events = events.into_iter().map(|e| keccak256(e.as_ref())).collect::>(); self.event_signature(events) } @@ -486,9 +453,7 @@ impl Filter { /// Returns the numeric value of the `fromBlock` field pub fn get_from_block(&self) -> Option { - self.block_option - .get_from_block() - .and_then(|b| b.as_number()) + self.block_option.get_from_block().and_then(|b| b.as_number()) } /// Returns the numeric value of the `fromBlock` field @@ -512,10 +477,7 @@ impl Serialize for Filter { { let mut s = serializer.serialize_struct("Filter", 5)?; match self.block_option { - FilterBlockOption::Range { - from_block, - to_block, - } => { + FilterBlockOption::Range { from_block, to_block } => { if let Some(ref from_block) = from_block { s.serialize_field("fromBlock", from_block)?; } @@ -654,17 +616,10 @@ impl<'de> Deserialize<'de> for Filter { let block_option = if let Some(block_hash) = block_hash { FilterBlockOption::AtBlockHash(block_hash) } else { - FilterBlockOption::Range { - from_block, - to_block, - } + FilterBlockOption::Range { from_block, to_block } }; - Ok(Filter { - block_option, - address, - topics, - }) + Ok(Filter { block_option, address, topics }) } } @@ -756,9 +711,7 @@ impl FilteredParams { /// for matching pub fn new(filter: Option) -> Self { if let Some(filter) = filter { - FilteredParams { - filter: Some(filter), - } + FilteredParams { filter: Some(filter) } } else { Default::default() } @@ -839,10 +792,7 @@ impl FilteredParams { /// Returns `true` if the filter matches the given log. pub fn filter_address(&self, log: &Log) -> bool { - self.filter - .as_ref() - .map(|f| f.address.matches(&log.address)) - .unwrap_or(true) + self.filter.as_ref().map(|f| f.address.matches(&log.address)).unwrap_or(true) } /// Returns `true` if the log matches the filter's topics @@ -1066,16 +1016,12 @@ mod tests { value: ValueOrArray, } - let item = Item { - value: ValueOrArray::Value(U256::from(1u64)), - }; + let item = Item { value: ValueOrArray::Value(U256::from(1u64)) }; let json = serde_json::to_value(item.clone()).unwrap(); let deserialized: Item = serde_json::from_value(json).unwrap(); assert_eq!(item, deserialized); - let item = Item { - value: ValueOrArray::Array(vec![U256::from(1u64), U256::ZERO]), - }; + let item = Item { value: ValueOrArray::Array(vec![U256::from(1u64), U256::ZERO]) }; let json = serde_json::to_value(item.clone()).unwrap(); let deserialized: Item = serde_json::from_value(json).unwrap(); assert_eq!(item, deserialized); @@ -1125,38 +1071,23 @@ mod tests { // 3 let ser = serialize(&filter.clone().topic3(t3)); - assert_eq!( - ser, - json!({ "address" : addr, "topics": [t0, null, null, t3_padded]}) - ); + assert_eq!(ser, json!({ "address" : addr, "topics": [t0, null, null, t3_padded]})); // 1 & 2 let ser = serialize(&filter.clone().topic1(t1).topic2(t2)); - assert_eq!( - ser, - json!({ "address" : addr, "topics": [t0, t1_padded, t2]}) - ); + assert_eq!(ser, json!({ "address" : addr, "topics": [t0, t1_padded, t2]})); // 1 & 3 let ser = serialize(&filter.clone().topic1(t1).topic3(t3)); - assert_eq!( - ser, - json!({ "address" : addr, "topics": [t0, t1_padded, null, t3_padded]}) - ); + assert_eq!(ser, json!({ "address" : addr, "topics": [t0, t1_padded, null, t3_padded]})); // 2 & 3 let ser = serialize(&filter.clone().topic2(t2).topic3(t3)); - assert_eq!( - ser, - json!({ "address" : addr, "topics": [t0, null, t2, t3_padded]}) - ); + assert_eq!(ser, json!({ "address" : addr, "topics": [t0, null, t2, t3_padded]})); // 1 & 2 & 3 let ser = serialize(&filter.topic1(t1).topic2(t2).topic3(t3)); - assert_eq!( - ser, - json!({ "address" : addr, "topics": [t0, t1_padded, t2, t3_padded]}) - ); + assert_eq!(ser, json!({ "address" : addr, "topics": [t0, t1_padded, t2, t3_padded]})); } #[test] diff --git a/crates/rpc-types/src/eth/state.rs b/crates/rpc-types/src/eth/state.rs index c69a09139926..f88d68479fbe 100644 --- a/crates/rpc-types/src/eth/state.rs +++ b/crates/rpc-types/src/eth/state.rs @@ -44,9 +44,8 @@ mod tests { } }"#; let state_override: StateOverride = serde_json::from_str(s).unwrap(); - let acc = state_override - .get(&address!("0000000000000000000000000000000000000124")) - .unwrap(); + let acc = + state_override.get(&address!("0000000000000000000000000000000000000124")).unwrap(); assert!(acc.code.is_some()); } #[test] @@ -63,9 +62,8 @@ mod tests { } }"#; let state_override: StateOverride = serde_json::from_str(s).unwrap(); - let acc = state_override - .get(&address!("1b5212AF6b76113afD94cD2B5a78a73B7d7A8222")) - .unwrap(); + let acc = + state_override.get(&address!("1b5212AF6b76113afD94cD2B5a78a73B7d7A8222")).unwrap(); assert!(acc.state_diff.is_some()); } } diff --git a/crates/rpc-types/src/eth/transaction/access_list.rs b/crates/rpc-types/src/eth/transaction/access_list.rs index bf2c95e92c67..c4a7e8d1abee 100644 --- a/crates/rpc-types/src/eth/transaction/access_list.rs +++ b/crates/rpc-types/src/eth/transaction/access_list.rs @@ -19,9 +19,7 @@ pub struct AccessList(pub Vec); impl AccessList { /// Converts the list into a vec, expected by revm pub fn flattened(&self) -> Vec<(Address, Vec)> { - self.flatten() - .map(|(addr, keys)| (addr, keys.to_vec())) - .collect() + self.flatten().map(|(addr, keys)| (addr, keys.to_vec())).collect() } /// Consumes the type and converts the list into a vec, expected by revm @@ -31,16 +29,12 @@ impl AccessList { /// Consumes the type and returns an iterator over the list's addresses and storage keys. pub fn into_flatten(self) -> impl Iterator)> { - self.0 - .into_iter() - .map(|item| (item.address, item.storage_keys)) + self.0.into_iter().map(|item| (item.address, item.storage_keys)) } /// Returns an iterator over the list's addresses and storage keys. pub fn flatten(&self) -> impl Iterator + '_ { - self.0 - .iter() - .map(|item| (item.address, item.storage_keys.as_slice())) + self.0.iter().map(|item| (item.address, item.storage_keys.as_slice())) } } @@ -61,14 +55,8 @@ mod tests { #[test] fn access_list_serde() { let list = AccessList(vec![ - AccessListItem { - address: Address::ZERO, - storage_keys: vec![U256::ZERO], - }, - AccessListItem { - address: Address::ZERO, - storage_keys: vec![U256::ZERO], - }, + AccessListItem { address: Address::ZERO, storage_keys: vec![U256::ZERO] }, + AccessListItem { address: Address::ZERO, storage_keys: vec![U256::ZERO] }, ]); let json = serde_json::to_string(&list).unwrap(); let list2 = serde_json::from_str::(&json).unwrap(); @@ -79,14 +67,8 @@ mod tests { fn access_list_with_gas_used() { let list = AccessListWithGasUsed { access_list: AccessList(vec![ - AccessListItem { - address: Address::ZERO, - storage_keys: vec![U256::ZERO], - }, - AccessListItem { - address: Address::ZERO, - storage_keys: vec![U256::ZERO], - }, + AccessListItem { address: Address::ZERO, storage_keys: vec![U256::ZERO] }, + AccessListItem { address: Address::ZERO, storage_keys: vec![U256::ZERO] }, ]), gas_used: U256::from(100), }; diff --git a/crates/rpc-types/src/eth/transaction/request.rs b/crates/rpc-types/src/eth/transaction/request.rs index d9aadd69f125..716c3960b299 100644 --- a/crates/rpc-types/src/eth/transaction/request.rs +++ b/crates/rpc-types/src/eth/transaction/request.rs @@ -80,8 +80,8 @@ impl TransactionRequest { })) } // EIP2930 - (_, None, Some(access_list)) => Some(TypedTransactionRequest::EIP2930( - EIP2930TransactionRequest { + (_, None, Some(access_list)) => { + Some(TypedTransactionRequest::EIP2930(EIP2930TransactionRequest { nonce: nonce.unwrap_or_default(), gas_price: gas_price.unwrap_or_default(), gas_limit: gas.unwrap_or_default(), @@ -93,27 +93,25 @@ impl TransactionRequest { }, chain_id: 0, access_list, - }, - )), + })) + } // EIP1559 (None, Some(_), access_list) | (None, None, access_list @ None) => { // Empty fields fall back to the canonical transaction schema. - Some(TypedTransactionRequest::EIP1559( - EIP1559TransactionRequest { - nonce: nonce.unwrap_or_default(), - max_fee_per_gas: max_fee_per_gas.unwrap_or_default(), - max_priority_fee_per_gas: max_priority_fee_per_gas.unwrap_or_default(), - gas_limit: gas.unwrap_or_default(), - value: value.unwrap_or_default(), - input: data.unwrap_or_default(), - kind: match to { - Some(to) => TransactionKind::Call(to), - None => TransactionKind::Create, - }, - chain_id: 0, - access_list: access_list.unwrap_or_default(), + Some(TypedTransactionRequest::EIP1559(EIP1559TransactionRequest { + nonce: nonce.unwrap_or_default(), + max_fee_per_gas: max_fee_per_gas.unwrap_or_default(), + max_priority_fee_per_gas: max_priority_fee_per_gas.unwrap_or_default(), + gas_limit: gas.unwrap_or_default(), + value: value.unwrap_or_default(), + input: data.unwrap_or_default(), + kind: match to { + Some(to) => TransactionKind::Call(to), + None => TransactionKind::Create, }, - )) + chain_id: 0, + access_list: access_list.unwrap_or_default(), + })) } _ => None, diff --git a/crates/rpc-types/src/eth/transaction/signature.rs b/crates/rpc-types/src/eth/transaction/signature.rs index 4878433cd2ca..d447e3427f69 100644 --- a/crates/rpc-types/src/eth/transaction/signature.rs +++ b/crates/rpc-types/src/eth/transaction/signature.rs @@ -28,11 +28,7 @@ pub struct Signature { /// This will be serialized as "0x0" if false, and "0x1" if true. #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct Parity( - #[serde( - serialize_with = "serialize_parity", - deserialize_with = "deserialize_parity" - )] - pub bool, + #[serde(serialize_with = "serialize_parity", deserialize_with = "deserialize_parity")] pub bool, ); fn serialize_parity(parity: &bool, serializer: S) -> Result diff --git a/crates/transport-http/src/hyper.rs b/crates/transport-http/src/hyper.rs index 94c5bee0ad70..cd59684b403f 100644 --- a/crates/transport-http/src/hyper.rs +++ b/crates/transport-http/src/hyper.rs @@ -23,16 +23,11 @@ where .body(hyper::Body::from(ser.get().to_owned())) .expect("request parts are valid"); - let resp = this - .client - .request(req) - .await - .map_err(TransportError::custom)?; + let resp = this.client.request(req).await.map_err(TransportError::custom)?; // unpack json from the response body - let body = hyper::body::to_bytes(resp.into_body()) - .await - .map_err(TransportError::custom)?; + let body = + hyper::body::to_bytes(resp.into_body()).await.map_err(TransportError::custom)?; // Deser a Box from the body. If deser fails, return the // body as a string in the error. If the body is not UTF8, this will diff --git a/crates/transport-http/src/lib.rs b/crates/transport-http/src/lib.rs index 3c030f57bbef..5b11dc41011d 100644 --- a/crates/transport-http/src/lib.rs +++ b/crates/transport-http/src/lib.rs @@ -47,10 +47,7 @@ impl Http { where T: Default, { - Self { - client: Default::default(), - url, - } + Self { client: Default::default(), url } } /// Create a new [`Http`] transport with a custom client. diff --git a/crates/transport-ws/src/native.rs b/crates/transport-ws/src/native.rs index f04a7e1ca2c6..8b8a7b5858db 100644 --- a/crates/transport-ws/src/native.rs +++ b/crates/transport-ws/src/native.rs @@ -30,9 +30,7 @@ impl IntoClientRequest for WsConnect { let mut auth_value = http::HeaderValue::from_str(&auth.to_string())?; auth_value.set_sensitive(true); - request - .headers_mut() - .insert(http::header::AUTHORIZATION, auth_value); + request.headers_mut().insert(http::header::AUTHORIZATION, auth_value); } request.into_client_request() @@ -49,9 +47,8 @@ impl PubSubConnect for WsConnect { Box::pin(async move { let req = request.map_err(TransportError::custom)?; - let (socket, _) = tokio_tungstenite::connect_async(req) - .await - .map_err(TransportError::custom)?; + let (socket, _) = + tokio_tungstenite::connect_async(req).await.map_err(TransportError::custom)?; let (handle, interface) = alloy_pubsub::ConnectionHandle::new(); let backend = WsBackend { socket, interface }; diff --git a/crates/transport-ws/src/wasm.rs b/crates/transport-ws/src/wasm.rs index 47fc366f5a48..9869d6d79e11 100644 --- a/crates/transport-ws/src/wasm.rs +++ b/crates/transport-ws/src/wasm.rs @@ -22,11 +22,8 @@ impl PubSubConnect for WsConnect { fn connect<'a: 'b, 'b>(&'a self) -> Pbf<'b, alloy_pubsub::ConnectionHandle, TransportError> { Box::pin(async move { - let socket = WsMeta::connect(&self.url, None) - .await - .map_err(TransportError::custom)? - .1 - .fuse(); + let socket = + WsMeta::connect(&self.url, None).await.map_err(TransportError::custom)?.1.fuse(); let (handle, interface) = alloy_pubsub::ConnectionHandle::new(); let backend = WsBackend { socket, interface }; @@ -52,9 +49,7 @@ impl WsBackend> { /// Send a message to the websocket. pub async fn send(&mut self, msg: Box) -> Result<(), WsErr> { - self.socket - .send(WsMessage::Text(msg.get().to_owned())) - .await + self.socket.send(WsMessage::Text(msg.get().to_owned())).await } /// Spawn this backend on a loop. diff --git a/crates/transport/src/boxed.rs b/crates/transport/src/boxed.rs index 5ba397664cc2..38257d58a69d 100644 --- a/crates/transport/src/boxed.rs +++ b/crates/transport/src/boxed.rs @@ -26,9 +26,7 @@ impl BoxTransport { where T: Transport + Clone + Send + Sync, { - Self { - inner: Box::new(inner), - } + Self { inner: Box::new(inner) } } } @@ -40,9 +38,7 @@ impl Debug for BoxTransport { impl Clone for BoxTransport { fn clone(&self) -> Self { - Self { - inner: self.inner.clone_box(), - } + Self { inner: self.inner.clone_box() } } } diff --git a/crates/transport/src/connect.rs b/crates/transport/src/connect.rs index 70689c5b88d3..48e795c972c5 100644 --- a/crates/transport/src/connect.rs +++ b/crates/transport/src/connect.rs @@ -9,8 +9,7 @@ use crate::{BoxTransport, Pbf, Transport, TransportError}; /// /// Users may want to implement transport-connect for the following reasons: /// - You want to customize a `reqwest::Client` before using it. -/// - You need to provide special authentication information to a remote -/// provider. +/// - You need to provide special authentication information to a remote provider. /// - You have implemented a custom [`Transport`]. /// - You require a specific websocket reconnection strategy. pub trait TransportConnect: Sized + Send + Sync + 'static { diff --git a/crates/transport/src/error.rs b/crates/transport/src/error.rs index c06e9a861678..e2740f8965f3 100644 --- a/crates/transport/src/error.rs +++ b/crates/transport/src/error.rs @@ -54,9 +54,6 @@ where T: AsRef, { fn from((err, text): (serde_json::Error, T)) -> Self { - Self::SerdeJson { - err, - text: Some(text.as_ref().to_string()), - } + Self::SerdeJson { err, text: Some(text.as_ref().to_string()) } } } diff --git a/crates/transport/src/utils.rs b/crates/transport/src/utils.rs index 299d844dcbed..06d3bd5a2ecf 100644 --- a/crates/transport/src/utils.rs +++ b/crates/transport/src/utils.rs @@ -12,8 +12,7 @@ use url::Url; pub fn guess_local_url(s: impl AsRef) -> bool { fn _guess_local_url(url: &str) -> bool { if let Ok(url) = url.parse::() { - url.host_str() - .map_or(true, |host| host == "localhost" || host == "127.0.0.1") + url.host_str().map_or(true, |host| host == "localhost" || host == "127.0.0.1") } else { false } diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 000000000000..3063df707a64 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,12 @@ +reorder_imports = true +use_field_init_shorthand = true +use_small_heuristics = "Max" + +# Nightly +max_width = 100 +comment_width = 100 +imports_granularity = "Crate" +wrap_comments = true +format_code_in_doc_comments = true +doc_comment_code_block_width = 100 +format_macro_matchers = true