1use std::{ops::Deref, sync::Arc};
2
3use serde::{Serialize, de::DeserializeOwned};
4use serde_json::Value;
5
6use crate::{
7 PendingRpcRequest, Result, RpcNamespace,
8 rpc::{BatchPolicy, HttpJsonRpcTransport},
9 subscriptions::{RpcSubscription, SubscriptionId, WebSocketJsonRpcTransport},
10};
11
12pub const ETHEREUM_RPC_METHODS: &[&str] = &[
14 "eth_accounts",
15 "eth_baseFee",
16 "eth_blobBaseFee",
17 "eth_blockNumber",
18 "eth_call",
19 "eth_callMany",
20 "eth_capabilities",
21 "eth_chainId",
22 "eth_createAccessList",
23 "eth_estimateGas",
24 "eth_feeHistory",
25 "eth_gasPrice",
26 "eth_getAccount",
27 "eth_getBalance",
28 "eth_getBlockByHash",
29 "eth_getBlockByNumber",
30 "eth_getBlockReceipts",
31 "eth_getBlockTransactionCountByHash",
32 "eth_getBlockTransactionCountByNumber",
33 "eth_getCode",
34 "eth_getFilterChanges",
35 "eth_getFilterLogs",
36 "eth_getLogs",
37 "eth_getProof",
38 "eth_getRawTransactionByHash",
39 "eth_getStorageAt",
40 "eth_getTransactionByBlockHashAndIndex",
41 "eth_getTransactionByBlockNumberAndIndex",
42 "eth_getTransactionByHash",
43 "eth_getTransactionBySenderAndNonce",
44 "eth_getTransactionCount",
45 "eth_getTransactionReceipt",
46 "eth_getUncleCountByBlockHash",
47 "eth_getUncleCountByBlockNumber",
48 "eth_maxPriorityFeePerGas",
49 "eth_newBlockFilter",
50 "eth_newFilter",
51 "eth_newPendingTransactionFilter",
52 "eth_sendRawTransaction",
53 "eth_signTransaction",
54 "eth_simulateV1",
55 "eth_submitWork",
56 "eth_syncing",
57 "eth_uninstallFilter",
58 "net_listening",
59 "net_peerCount",
60 "net_version",
61 "txpool_content",
62 "txpool_contentFrom",
63 "txpool_inspect",
64 "txpool_status",
65 "web3_clientVersion",
66 "web3_sha3",
67];
68
69pub const ETHEREUM_SUBSCRIPTION_METHODS: &[&str] = &["eth_subscribe", "eth_unsubscribe"];
71
72#[derive(Clone)]
74pub struct EthereumRpcClient {
75 namespace: RpcNamespace,
76}
77
78impl EthereumRpcClient {
79 pub(crate) const fn new(transport: Arc<HttpJsonRpcTransport>) -> Self {
80 Self {
81 namespace: RpcNamespace::new(transport, BatchPolicy::Any),
82 }
83 }
84}
85
86impl Deref for EthereumRpcClient {
87 type Target = RpcNamespace;
88
89 fn deref(&self) -> &Self::Target {
90 &self.namespace
91 }
92}
93
94macro_rules! ethereum_no_params {
95 ($(($name:ident, $wire:literal, $result:ty)),* $(,)?) => {
96 impl EthereumRpcClient {
97 $(
98 #[doc = concat!("Creates a pending `", $wire, "` request.")]
99 #[must_use]
100 pub fn $name(&self) -> PendingRpcRequest<$result> {
101 self.namespace.request($wire, Vec::<Value>::new()).expect("empty parameters serialize")
102 }
103 )*
104 }
105 };
106}
107
108macro_rules! ethereum_with_params {
109 ($(($name:ident, $wire:literal, $result:ty)),* $(,)?) => {
110 impl EthereumRpcClient {
111 $(
112 #[doc = concat!("Creates a pending `", $wire, "` request from positional parameters.")]
113 pub fn $name<P: Serialize>(&self, params: P) -> Result<PendingRpcRequest<$result>> {
114 self.namespace.request($wire, params)
115 }
116 )*
117 }
118 };
119}
120
121ethereum_no_params!(
122 (eth_accounts, "eth_accounts", Vec<String>),
123 (eth_base_fee, "eth_baseFee", String),
124 (eth_blob_base_fee, "eth_blobBaseFee", String),
125 (eth_block_number, "eth_blockNumber", String),
126 (eth_capabilities, "eth_capabilities", Value),
127 (eth_chain_id, "eth_chainId", String),
128 (eth_gas_price, "eth_gasPrice", String),
129 (eth_max_priority_fee_per_gas, "eth_maxPriorityFeePerGas", String),
130 (eth_new_block_filter, "eth_newBlockFilter", String),
131 (
132 eth_new_pending_transaction_filter,
133 "eth_newPendingTransactionFilter",
134 String
135 ),
136 (eth_syncing, "eth_syncing", Value),
137 (net_listening, "net_listening", bool),
138 (net_peer_count, "net_peerCount", String),
139 (net_version, "net_version", String),
140 (txpool_content, "txpool_content", Value),
141 (txpool_inspect, "txpool_inspect", Value),
142 (txpool_status, "txpool_status", Value),
143 (web3_client_version, "web3_clientVersion", String),
144);
145
146ethereum_with_params!(
147 (eth_call, "eth_call", String),
148 (eth_call_many, "eth_callMany", Value),
149 (eth_create_access_list, "eth_createAccessList", Value),
150 (eth_estimate_gas, "eth_estimateGas", String),
151 (eth_fee_history, "eth_feeHistory", Value),
152 (eth_get_account, "eth_getAccount", Value),
153 (eth_get_balance, "eth_getBalance", String),
154 (eth_get_block_by_hash, "eth_getBlockByHash", Option<Value>),
155 (eth_get_block_by_number, "eth_getBlockByNumber", Option<Value>),
156 (eth_get_block_receipts, "eth_getBlockReceipts", Option<Value>),
157 (
158 eth_get_block_transaction_count_by_hash,
159 "eth_getBlockTransactionCountByHash",
160 Option<String>
161 ),
162 (
163 eth_get_block_transaction_count_by_number,
164 "eth_getBlockTransactionCountByNumber",
165 Option<String>
166 ),
167 (eth_get_code, "eth_getCode", String),
168 (eth_get_filter_changes, "eth_getFilterChanges", Value),
169 (eth_get_filter_logs, "eth_getFilterLogs", Value),
170 (eth_get_logs, "eth_getLogs", Value),
171 (eth_get_proof, "eth_getProof", Value),
172 (
173 eth_get_raw_transaction_by_hash,
174 "eth_getRawTransactionByHash",
175 Option<String>
176 ),
177 (eth_get_storage_at, "eth_getStorageAt", String),
178 (
179 eth_get_transaction_by_block_hash_and_index,
180 "eth_getTransactionByBlockHashAndIndex",
181 Option<Value>
182 ),
183 (
184 eth_get_transaction_by_block_number_and_index,
185 "eth_getTransactionByBlockNumberAndIndex",
186 Option<Value>
187 ),
188 (
189 eth_get_transaction_by_hash,
190 "eth_getTransactionByHash",
191 Option<Value>
192 ),
193 (
194 eth_get_transaction_by_sender_and_nonce,
195 "eth_getTransactionBySenderAndNonce",
196 Option<Value>
197 ),
198 (eth_get_transaction_count, "eth_getTransactionCount", String),
199 (
200 eth_get_transaction_receipt,
201 "eth_getTransactionReceipt",
202 Option<Value>
203 ),
204 (
205 eth_get_uncle_count_by_block_hash,
206 "eth_getUncleCountByBlockHash",
207 String
208 ),
209 (
210 eth_get_uncle_count_by_block_number,
211 "eth_getUncleCountByBlockNumber",
212 String
213 ),
214 (eth_new_filter, "eth_newFilter", String),
215 (eth_send_raw_transaction, "eth_sendRawTransaction", String),
216 (eth_sign_transaction, "eth_signTransaction", String),
217 (eth_simulate_v1, "eth_simulateV1", Value),
218 (eth_submit_work, "eth_submitWork", bool),
219 (eth_uninstall_filter, "eth_uninstallFilter", bool),
220 (txpool_content_from, "txpool_contentFrom", Value),
221 (web3_sha3, "web3_sha3", String),
222);
223
224#[derive(Clone)]
226pub struct EthereumSubscriptions {
227 transport: Arc<WebSocketJsonRpcTransport>,
228}
229
230impl EthereumSubscriptions {
231 pub(crate) const fn new(transport: Arc<WebSocketJsonRpcTransport>) -> Self {
232 Self { transport }
233 }
234
235 #[must_use]
237 pub fn endpoint(&self) -> &str {
238 self.transport.endpoint()
239 }
240
241 pub async fn subscribe(
243 &self,
244 subscription: &str,
245 options: Vec<Value>,
246 ) -> Result<RpcSubscription> {
247 let mut params = vec![Value::String(subscription.to_owned())];
248 params.extend(options);
249 let receiver = self.transport.subscribe_notifications();
250 let id: String = self
251 .transport
252 .request("eth_subscribe", Value::Array(params), None)
253 .await?;
254 Ok(RpcSubscription::new(
255 SubscriptionId::String(id),
256 Arc::clone(&self.transport),
257 "eth_unsubscribe",
258 receiver,
259 ))
260 }
261
262 pub async fn raw<T: DeserializeOwned>(&self, method: &str, params: Value) -> Result<T> {
264 self.transport.request(method, params, None).await
265 }
266
267 pub async fn close(&self) {
269 self.transport.close().await;
270 }
271}
272
273#[derive(Clone)]
275pub struct EthereumClient {
276 pub rpc: EthereumRpcClient,
278 pub subscriptions: EthereumSubscriptions,
280}
281
282impl EthereumClient {
283 pub(crate) const fn new(
284 transport: Arc<HttpJsonRpcTransport>,
285 websocket: Arc<WebSocketJsonRpcTransport>,
286 ) -> Self {
287 Self {
288 rpc: EthereumRpcClient::new(transport),
289 subscriptions: EthereumSubscriptions::new(websocket),
290 }
291 }
292}