Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(provider): serialize no parameters as [] instead of null #1193

Merged
merged 5 commits into from
Aug 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions crates/provider/src/chain.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use alloy_network::{Ethereum, Network};
use alloy_primitives::{BlockNumber, U64};
use alloy_rpc_client::{PollerBuilder, WeakClient};
use alloy_rpc_client::{NoParams, PollerBuilder, WeakClient};
use alloy_rpc_types_eth::Block;
use alloy_transport::{RpcError, Transport};
use async_stream::stream;
Expand All @@ -19,7 +19,7 @@ const NO_BLOCK_NUMBER: BlockNumber = BlockNumber::MAX;

pub(crate) struct ChainStreamPoller<T, N = Ethereum> {
client: WeakClient<T>,
poll_task: PollerBuilder<T, (), U64>,
poll_task: PollerBuilder<T, NoParams, U64>,
next_yield: BlockNumber,
known_blocks: LruCache<BlockNumber, Block>,
_phantom: PhantomData<N>,
Expand All @@ -39,7 +39,7 @@ impl<T: Transport + Clone, N: Network> ChainStreamPoller<T, N> {
fn with_next_yield(client: WeakClient<T>, next_yield: BlockNumber) -> Self {
Self {
client: client.clone(),
poll_task: PollerBuilder::new(client, "eth_blockNumber", ()),
poll_task: PollerBuilder::new(client, "eth_blockNumber", []),
next_yield,
known_blocks: LruCache::new(BLOCK_CACHE_SIZE),
_phantom: PhantomData,
Expand Down
6 changes: 3 additions & 3 deletions crates/provider/src/ext/admin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,19 +64,19 @@ where
}

async fn peers(&self) -> TransportResult<Vec<PeerInfo>> {
self.client().request("admin_peers", ()).await
self.client().request_noparams("admin_peers").await
}

async fn node_info(&self) -> TransportResult<NodeInfo> {
self.client().request("admin_nodeInfo", ()).await
self.client().request_noparams("admin_nodeInfo").await
}

#[cfg(feature = "pubsub")]
async fn subscribe_peer_events(
&self,
) -> TransportResult<alloy_pubsub::Subscription<alloy_rpc_types_admin::PeerEvent>> {
self.root().pubsub_frontend()?;
let mut call = self.client().request("admin_peerEvents_subscribe", ());
let mut call = self.client().request_noparams("admin_peerEvents_subscribe");
call.set_is_subscription();
let id = call.await?;
self.root().get_subscription(id).await
Expand Down
14 changes: 7 additions & 7 deletions crates/provider/src/ext/anvil.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ where
}

async fn anvil_get_auto_mine(&self) -> TransportResult<bool> {
self.client().request("anvil_getAutomine", ()).await
self.client().request_noparams("anvil_getAutomine").await
}

async fn anvil_set_auto_mine(&self, enabled: bool) -> TransportResult<()> {
Expand All @@ -190,7 +190,7 @@ where
}

async fn anvil_drop_all_transactions(&self) -> TransportResult<()> {
self.client().request("anvil_dropAllTransactions", ()).await
self.client().request_noparams("anvil_dropAllTransactions").await
}

async fn anvil_reset(&self, forking: Option<Forking>) -> TransportResult<()> {
Expand Down Expand Up @@ -239,27 +239,27 @@ where
}

async fn anvil_dump_state(&self) -> TransportResult<Bytes> {
self.client().request("anvil_dumpState", ()).await
self.client().request_noparams("anvil_dumpState").await
}

async fn anvil_load_state(&self, buf: Bytes) -> TransportResult<bool> {
self.client().request("anvil_loadState", (buf,)).await
}

async fn anvil_node_info(&self) -> TransportResult<NodeInfo> {
self.client().request("anvil_nodeInfo", ()).await
self.client().request_noparams("anvil_nodeInfo").await
}

async fn anvil_metadata(&self) -> TransportResult<Metadata> {
self.client().request("anvil_metadata", ()).await
self.client().request_noparams("anvil_metadata").await
}

async fn anvil_remove_pool_transactions(&self, address: Address) -> TransportResult<()> {
self.client().request("anvil_removePoolTransactions", (address,)).await
}

async fn anvil_snapshot(&self) -> TransportResult<U256> {
self.client().request("evm_snapshot", ()).await
self.client().request_noparams("evm_snapshot").await
}

async fn anvil_revert(&self, id: U256) -> TransportResult<bool> {
Expand Down Expand Up @@ -287,7 +287,7 @@ where
}

async fn anvil_remove_block_timestamp_interval(&self) -> TransportResult<bool> {
self.client().request("anvil_removeBlockTimestampInterval", ()).await
self.client().request_noparams("anvil_removeBlockTimestampInterval").await
}

async fn evm_mine(&self, opts: Option<MineOptions>) -> TransportResult<String> {
Expand Down
2 changes: 1 addition & 1 deletion crates/provider/src/ext/debug.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ where
}

async fn debug_get_bad_blocks(&self) -> TransportResult<Vec<Block>> {
self.client().request("debug_getBadBlocks", ()).await
self.client().request_noparams("debug_getBadBlocks").await
}

async fn debug_trace_chain(
Expand Down
6 changes: 3 additions & 3 deletions crates/provider/src/ext/net.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,15 @@ where
P: Provider<T, N>,
{
async fn net_listening(&self) -> TransportResult<bool> {
self.client().request("net_listening", ()).await
self.client().request_noparams("net_listening").await
}

async fn net_peer_count(&self) -> TransportResult<u64> {
self.client().request("net_peerCount", ()).map_resp(crate::utils::convert_u64).await
self.client().request_noparams("net_peerCount").map_resp(crate::utils::convert_u64).await
}

async fn net_version(&self) -> TransportResult<u64> {
self.client().request("net_version", ()).map_resp(crate::utils::convert_u64).await
self.client().request_noparams("net_version").map_resp(crate::utils::convert_u64).await
}
}

Expand Down
2 changes: 1 addition & 1 deletion crates/provider/src/ext/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,6 @@ where
P: Provider<T, N>,
{
async fn rpc_modules(&self) -> TransportResult<RpcModules> {
self.client().request("rpc_modules", ()).await
self.client().request_noparams("rpc_modules").await
}
}
6 changes: 3 additions & 3 deletions crates/provider/src/ext/txpool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ where
N: Network,
{
async fn txpool_content(&self) -> TransportResult<TxpoolContent<N::TransactionResponse>> {
self.client().request("txpool_content", ()).await
self.client().request_noparams("txpool_content").await
}

async fn txpool_content_from(
Expand All @@ -65,11 +65,11 @@ where
}

async fn txpool_inspect(&self) -> TransportResult<TxpoolInspect> {
self.client().request("txpool_inspect", ()).await
self.client().request_noparams("txpool_inspect").await
}

async fn txpool_status(&self) -> TransportResult<TxpoolStatus> {
self.client().request("txpool_status", ()).await
self.client().request_noparams("txpool_status").await
}
}

Expand Down
36 changes: 19 additions & 17 deletions crates/provider/src/provider/trait.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use alloy_primitives::{
hex, Address, BlockHash, BlockNumber, Bytes, StorageKey, StorageValue, TxHash, B256, U128,
U256, U64,
};
use alloy_rpc_client::{ClientRef, PollerBuilder, RpcCall, WeakClient};
use alloy_rpc_client::{ClientRef, NoParams, PollerBuilder, RpcCall, WeakClient};
use alloy_rpc_types_eth::{
AccessListResult, BlockId, BlockNumberOrTag, EIP1186AccountProofResponse, FeeHistory, Filter,
FilterChanges, Log, SyncStatus,
Expand Down Expand Up @@ -101,17 +101,17 @@ pub trait Provider<T: Transport + Clone = BoxTransport, N: Network = Ethereum>:
/// Gets the accounts in the remote node. This is usually empty unless you're using a local
/// node.
async fn get_accounts(&self) -> TransportResult<Vec<Address>> {
self.client().request("eth_accounts", ()).await
self.client().request_noparams("eth_accounts").await
}

/// Returns the base fee per blob gas (blob gas price) in wei.
async fn get_blob_base_fee(&self) -> TransportResult<u128> {
self.client().request("eth_blobBaseFee", ()).await.map(|fee: U128| fee.to::<u128>())
self.client().request_noparams("eth_blobBaseFee").await.map(|fee: U128| fee.to::<u128>())
}

/// Get the last block number available.
fn get_block_number(&self) -> RpcCall<T, (), U64, BlockNumber> {
self.client().request("eth_blockNumber", ()).map_resp(crate::utils::convert_u64)
fn get_block_number(&self) -> RpcCall<T, NoParams, U64, BlockNumber> {
self.client().request_noparams("eth_blockNumber").map_resp(crate::utils::convert_u64)
}

/// Execute a smart contract call with a transaction request and state
Expand Down Expand Up @@ -159,8 +159,8 @@ pub trait Provider<T: Transport + Clone = BoxTransport, N: Network = Ethereum>:
}

/// Gets the chain ID.
fn get_chain_id(&self) -> RpcCall<T, (), U64, u64> {
self.client().request("eth_chainId", ()).map_resp(crate::utils::convert_u64)
fn get_chain_id(&self) -> RpcCall<T, NoParams, U64, u64> {
self.client().request_noparams("eth_chainId").map_resp(crate::utils::convert_u64)
}

/// Create an [EIP-2930] access list.
Expand Down Expand Up @@ -242,8 +242,8 @@ pub trait Provider<T: Transport + Clone = BoxTransport, N: Network = Ethereum>:
}

/// Gets the current gas price in wei.
fn get_gas_price(&self) -> RpcCall<T, (), U128, u128> {
self.client().request("eth_gasPrice", ()).map_resp(crate::utils::convert_u128)
fn get_gas_price(&self) -> RpcCall<T, NoParams, U128, u128> {
self.client().request_noparams("eth_gasPrice").map_resp(crate::utils::convert_u128)
}

/// Retrieves account information ([Account](alloy_consensus::Account)) for the given [Address]
Expand Down Expand Up @@ -583,7 +583,7 @@ pub trait Provider<T: Transport + Clone = BoxTransport, N: Network = Ethereum>:
/// Returns a suggestion for the current `maxPriorityFeePerGas` in wei.
async fn get_max_priority_fee_per_gas(&self) -> TransportResult<u128> {
self.client()
.request("eth_maxPriorityFeePerGas", ())
.request_noparams("eth_maxPriorityFeePerGas")
.await
.map(|fee: U128| fee.to::<u128>())
}
Expand All @@ -594,7 +594,7 @@ pub trait Provider<T: Transport + Clone = BoxTransport, N: Network = Ethereum>:
///
/// See also [`watch_blocks`](Self::watch_blocks) to configure a poller.
async fn new_block_filter(&self) -> TransportResult<U256> {
self.client().request("eth_newBlockFilter", ()).await
self.client().request_noparams("eth_newBlockFilter").await
}

/// Notify the provider that we are interested in logs that match the given filter.
Expand Down Expand Up @@ -870,13 +870,13 @@ pub trait Provider<T: Transport + Clone = BoxTransport, N: Network = Ethereum>:

/// Gets syncing info.
async fn syncing(&self) -> TransportResult<SyncStatus> {
self.client().request("eth_syncing", ()).await
self.client().request_noparams("eth_syncing").await
}

/// Gets the client version.
#[doc(alias = "web3_client_version")]
async fn get_client_version(&self) -> TransportResult<String> {
self.client().request("web3_clientVersion", ()).await
self.client().request_noparams("web3_clientVersion").await
}

/// Gets the `Keccak-256` hash of the given data.
Expand All @@ -886,8 +886,8 @@ pub trait Provider<T: Transport + Clone = BoxTransport, N: Network = Ethereum>:
}

/// Gets the network ID. Same as `eth_chainId`.
fn get_net_version(&self) -> RpcCall<T, (), U64, u64> {
self.client().request("net_version", ()).map_resp(crate::utils::convert_u64)
fn get_net_version(&self) -> RpcCall<T, NoParams, U64, u64> {
self.client().request_noparams("net_version").map_resp(crate::utils::convert_u64)
}

/* ---------------------------------------- raw calls --------------------------------------- */
Expand All @@ -899,9 +899,10 @@ pub trait Provider<T: Transport + Clone = BoxTransport, N: Network = Ethereum>:
/// ```no_run
/// # async fn example(provider: impl alloy_provider::Provider) -> Result<(), Box<dyn std::error::Error>> {
/// use alloy_rpc_types_eth::BlockNumberOrTag;
/// use alloy_rpc_client::NoParams;
///
/// // No parameters: `()`
/// let block_number = provider.raw_request("eth_blockNumber".into(), ()).await?;
/// let block_number = provider.raw_request("eth_blockNumber".into(), NoParams::default()).await?;
///
/// // One parameter: `(param,)` or `[param]`
/// let block = provider.raw_request("eth_getBlockByNumber".into(), (BlockNumberOrTag::Latest,)).await?;
Expand Down Expand Up @@ -1253,7 +1254,8 @@ mod tests {
async fn gets_block_number_with_raw_req() {
init_tracing();
let provider = ProviderBuilder::new().on_anvil();
let num: U64 = provider.raw_request("eth_blockNumber".into(), ()).await.unwrap();
let num: U64 =
provider.raw_request("eth_blockNumber".into(), NoParams::default()).await.unwrap();
assert_eq!(0, num.to::<u64>())
}

Expand Down
2 changes: 1 addition & 1 deletion crates/rpc-client/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ For example, to make a simple request:
let client: ReqwestClient = ClientBuilder::default().http(url);

// Prepare a request to the server.
let request = client.request("eth_blockNumber", ());
let request = client.request_noparams("eth_blockNumber");

// Poll the request to completion.
let block_number = request.await.unwrap();
Expand Down
13 changes: 13 additions & 0 deletions crates/rpc-client/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ pub type WeakClient<T> = Weak<RpcClientInner<T>>;
/// A borrowed [`RpcClient`].
pub type ClientRef<'a, T> = &'a RpcClientInner<T>;

/// Parameter type of a JSON-RPC request with no parameters.
pub type NoParams = [(); 0];

/// A JSON-RPC client.
///
/// [`RpcClient`] should never be instantiated directly. Instead, use
Expand Down Expand Up @@ -280,6 +283,16 @@ impl<T: Transport + Clone> RpcClientInner<T> {
RpcCall::new(request, self.transport.clone())
}

/// Prepares an [`RpcCall`] with no parameters.
///
/// See [`request`](Self::request) for more details.
pub fn request_noparams<Resp: RpcReturn>(
&self,
method: impl Into<Cow<'static, str>>,
) -> RpcCall<T, NoParams, Resp> {
self.request(method, [])
}

/// Type erase the service in the transport, allowing it to be used in a
/// generic context.
///
Expand Down
2 changes: 1 addition & 1 deletion crates/rpc-client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ mod call;
pub use call::RpcCall;

mod client;
pub use client::{ClientRef, RpcClient, RpcClientInner, WeakClient};
pub use client::{ClientRef, NoParams, RpcClient, RpcClientInner, WeakClient};

mod poller;
pub use poller::{PollChannel, PollerBuilder};
Expand Down
2 changes: 1 addition & 1 deletion crates/rpc-client/tests/it/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ async fn it_makes_a_request() {
let anvil = Anvil::new().spawn();
let url = anvil.endpoint();
let client = ClientBuilder::default().http(url.parse().unwrap());
let req: RpcCall<_, (), U64> = client.request("eth_blockNumber", ());
let req: RpcCall<_, _, U64> = client.request_noparams("eth_blockNumber");
let timeout = tokio::time::timeout(std::time::Duration::from_secs(2), req);
let res = timeout.await.unwrap().unwrap();
assert_eq!(res.to::<u64>(), 0);
Expand Down
2 changes: 1 addition & 1 deletion crates/rpc-client/tests/it/ipc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ async fn it_makes_a_request() {
let connect = IpcConnect::new(geth.ipc_endpoint());
let client = ClientBuilder::default().pubsub(connect).await.unwrap();

let req: RpcCall<_, (), U64> = client.request("eth_blockNumber", ());
let req: RpcCall<_, _, U64> = client.request_noparams("eth_blockNumber");
let timeout = tokio::time::timeout(std::time::Duration::from_secs(2), req);
let res = timeout.await.unwrap().unwrap();
assert!(res.to::<u64>() <= 3);
Expand Down
2 changes: 1 addition & 1 deletion crates/rpc-client/tests/it/ws.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ async fn it_makes_a_request() {
let url = anvil.ws_endpoint();
let connector = WsConnect { url: url.parse().unwrap(), auth: None };
let client = ClientBuilder::default().pubsub(connector).await.unwrap();
let req: RpcCall<_, (), U64> = client.request("eth_blockNumber", ());
let req: RpcCall<_, _, U64> = client.request_noparams("eth_blockNumber");
let timeout = tokio::time::timeout(std::time::Duration::from_secs(2), req);
let res = timeout.await.unwrap().unwrap();
assert_eq!(res.to::<u64>(), 0);
Expand Down