Skip to main content

ethrpc_rs/
api.rs

1//! High-level [`Api`] wrapper with convenience methods for common calls.
2
3use serde::de::DeserializeOwned;
4use serde_json::Value;
5
6use crate::decode::ValueExt;
7use crate::error::Result;
8use crate::rpc::Handler;
9
10/// Wraps any [`Handler`] and provides convenience methods for common Ethereum
11/// RPC calls.
12pub struct Api<H: Handler> {
13    /// The underlying handler.
14    pub handler: H,
15}
16
17impl<H: Handler> Api<H> {
18    /// Wraps `handler` in an [`Api`].
19    pub fn new(handler: H) -> Api<H> {
20        Api { handler }
21    }
22
23    /// Performs a JSON-RPC call with positional arguments.
24    pub async fn call(&self, method: &str, params: Vec<Value>) -> Result<Value> {
25        self.handler.call(method, params).await
26    }
27
28    /// Performs a call and deserializes the result into `T` via serde.
29    pub async fn call_as<T: DeserializeOwned>(
30        &self,
31        method: &str,
32        params: Vec<Value>,
33    ) -> Result<T> {
34        Ok(serde_json::from_value(
35            self.handler.call(method, params).await?,
36        )?)
37    }
38
39    /// Returns the current block number from the connected node.
40    pub async fn block_number(&self) -> Result<u64> {
41        self.handler.call("eth_blockNumber", vec![]).await?.to_u64()
42    }
43
44    /// Returns the chain id of the connected network.
45    pub async fn chain_id(&self) -> Result<u64> {
46        self.handler.call("eth_chainId", vec![]).await?.to_u64()
47    }
48}