Skip to main content

reth_rpc_eth_api/
core.rs

1//! Implementation of the [`jsonrpsee`] generated [`EthApiServer`] trait. Handles RPC requests for
2//! the `eth_` namespace.
3use crate::{
4    helpers::{EthApiSpec, EthBlocks, EthCall, EthFees, EthState, EthTransactions, FullEthApi},
5    RpcBlock, RpcHeader, RpcReceipt, RpcTransaction,
6};
7use alloy_dyn_abi::TypedData;
8use alloy_eips::{eip2930::AccessListResult, BlockId, BlockNumberOrTag};
9use alloy_json_rpc::RpcObject;
10use alloy_primitives::{Address, Bytes, B256, B64, U256, U64};
11use alloy_rpc_types_eth::{
12    simulate::{SimulatePayload, SimulatedBlock},
13    state::{EvmOverrides, StateOverride},
14    BlockOverrides, Bundle, EIP1186AccountProofResponse, EthCallResponse, FeeHistory, Index,
15    StateContext, SyncStatus, Work,
16};
17use alloy_serde::JsonStorageKey;
18use jsonrpsee::{core::RpcResult, proc_macros::rpc};
19use reth_primitives_traits::TxTy;
20use reth_rpc_convert::RpcTxReq;
21use reth_rpc_eth_types::{EthApiError, EthCapabilities, FillTransaction};
22use reth_rpc_server_types::{result::internal_rpc_err, ToRpcResult};
23use serde_json::Value;
24use std::collections::HashMap;
25use tracing::trace;
26
27/// Helper trait, unifies functionality that must be supported to implement all RPC methods for
28/// server.
29pub trait FullEthApiServer:
30    EthApiServer<
31        RpcTxReq<Self::NetworkTypes>,
32        RpcTransaction<Self::NetworkTypes>,
33        RpcBlock<Self::NetworkTypes>,
34        RpcReceipt<Self::NetworkTypes>,
35        RpcHeader<Self::NetworkTypes>,
36        TxTy<Self::Primitives>,
37    > + FullEthApi
38    + Clone
39{
40}
41
42impl<T> FullEthApiServer for T where
43    T: EthApiServer<
44            RpcTxReq<T::NetworkTypes>,
45            RpcTransaction<T::NetworkTypes>,
46            RpcBlock<T::NetworkTypes>,
47            RpcReceipt<T::NetworkTypes>,
48            RpcHeader<T::NetworkTypes>,
49            TxTy<T::Primitives>,
50        > + FullEthApi
51        + Clone
52{
53}
54
55/// Eth rpc interface: <https://ethereum.github.io/execution-apis/api-documentation>
56#[cfg_attr(not(feature = "client"), rpc(server, namespace = "eth"))]
57#[cfg_attr(feature = "client", rpc(server, client, namespace = "eth"))]
58pub trait EthApi<
59    TxReq: RpcObject,
60    T: RpcObject,
61    B: RpcObject,
62    R: RpcObject,
63    H: RpcObject,
64    RawTx: RpcObject,
65>
66{
67    /// Returns the protocol version encoded as a string.
68    #[method(name = "protocolVersion")]
69    async fn protocol_version(&self) -> RpcResult<U64>;
70
71    /// Returns an object with data about the sync status or false.
72    #[method(name = "syncing")]
73    fn syncing(&self) -> RpcResult<SyncStatus>;
74
75    /// Returns the client coinbase address.
76    #[method(name = "coinbase")]
77    async fn author(&self) -> RpcResult<Address>;
78
79    /// Returns a list of addresses owned by client.
80    #[method(name = "accounts")]
81    fn accounts(&self) -> RpcResult<Vec<Address>>;
82
83    /// Returns the number of most recent block.
84    #[method(name = "blockNumber")]
85    fn block_number(&self) -> RpcResult<U256>;
86
87    /// Returns the chain ID of the current network.
88    #[method(name = "chainId")]
89    async fn chain_id(&self) -> RpcResult<Option<U64>>;
90
91    /// Returns effective routing capabilities for this node.
92    ///
93    /// See the `eth_capabilities` execution API proposal:
94    /// <https://github.com/ethereum/execution-apis/pull/755>.
95    #[method(name = "capabilities")]
96    fn capabilities(&self) -> RpcResult<EthCapabilities>;
97
98    /// Returns information about a block by hash.
99    #[method(name = "getBlockByHash")]
100    async fn block_by_hash(&self, hash: B256, full: bool) -> RpcResult<Option<B>>;
101
102    /// Returns information about a block by number.
103    #[method(name = "getBlockByNumber")]
104    async fn block_by_number(&self, number: BlockNumberOrTag, full: bool) -> RpcResult<Option<B>>;
105
106    /// Returns the number of transactions in a block from a block matching the given block hash.
107    #[method(name = "getBlockTransactionCountByHash")]
108    async fn block_transaction_count_by_hash(&self, hash: B256) -> RpcResult<Option<U256>>;
109
110    /// Returns the number of transactions in a block matching the given block number.
111    #[method(name = "getBlockTransactionCountByNumber")]
112    async fn block_transaction_count_by_number(
113        &self,
114        number: BlockNumberOrTag,
115    ) -> RpcResult<Option<U256>>;
116
117    /// Returns the number of uncles in a block from a block matching the given block hash.
118    #[method(name = "getUncleCountByBlockHash")]
119    async fn block_uncles_count_by_hash(&self, hash: B256) -> RpcResult<Option<U256>>;
120
121    /// Returns the number of uncles in a block with given block number.
122    #[method(name = "getUncleCountByBlockNumber")]
123    async fn block_uncles_count_by_number(
124        &self,
125        number: BlockNumberOrTag,
126    ) -> RpcResult<Option<U256>>;
127
128    /// Returns all transaction receipts for a given block.
129    #[method(name = "getBlockReceipts")]
130    async fn block_receipts(&self, block_id: BlockId) -> RpcResult<Option<Vec<R>>>;
131
132    /// Returns an uncle block of the given block and index.
133    #[method(name = "getUncleByBlockHashAndIndex")]
134    async fn uncle_by_block_hash_and_index(&self, hash: B256, index: Index)
135        -> RpcResult<Option<B>>;
136
137    /// Returns an uncle block of the given block and index.
138    #[method(name = "getUncleByBlockNumberAndIndex")]
139    async fn uncle_by_block_number_and_index(
140        &self,
141        number: BlockNumberOrTag,
142        index: Index,
143    ) -> RpcResult<Option<B>>;
144
145    /// Returns the EIP-2718 encoded transaction if it exists.
146    ///
147    /// If this is an EIP-4844 transaction that is in the pool, it will include the sidecar.
148    #[method(name = "getRawTransactionByHash")]
149    async fn raw_transaction_by_hash(&self, hash: B256) -> RpcResult<Option<Bytes>>;
150
151    /// Returns the information about a transaction requested by transaction hash.
152    #[method(name = "getTransactionByHash")]
153    async fn transaction_by_hash(&self, hash: B256) -> RpcResult<Option<T>>;
154
155    /// Returns information about a raw transaction by block hash and transaction index position.
156    #[method(name = "getRawTransactionByBlockHashAndIndex")]
157    async fn raw_transaction_by_block_hash_and_index(
158        &self,
159        hash: B256,
160        index: Index,
161    ) -> RpcResult<Option<Bytes>>;
162
163    /// Returns information about a transaction by block hash and transaction index position.
164    #[method(name = "getTransactionByBlockHashAndIndex")]
165    async fn transaction_by_block_hash_and_index(
166        &self,
167        hash: B256,
168        index: Index,
169    ) -> RpcResult<Option<T>>;
170
171    /// Returns information about a raw transaction by block number and transaction index
172    /// position.
173    #[method(name = "getRawTransactionByBlockNumberAndIndex")]
174    async fn raw_transaction_by_block_number_and_index(
175        &self,
176        number: BlockNumberOrTag,
177        index: Index,
178    ) -> RpcResult<Option<Bytes>>;
179
180    /// Returns information about a transaction by block number and transaction index position.
181    #[method(name = "getTransactionByBlockNumberAndIndex")]
182    async fn transaction_by_block_number_and_index(
183        &self,
184        number: BlockNumberOrTag,
185        index: Index,
186    ) -> RpcResult<Option<T>>;
187
188    /// Returns information about a transaction by sender and nonce.
189    #[method(name = "getTransactionBySenderAndNonce")]
190    async fn transaction_by_sender_and_nonce(
191        &self,
192        address: Address,
193        nonce: U64,
194    ) -> RpcResult<Option<T>>;
195
196    /// Returns all transactions in the local pending pool.
197    #[method(name = "pendingTransactions")]
198    fn pending_transactions(&self) -> RpcResult<Vec<T>>;
199
200    /// Returns the receipt of a transaction by transaction hash.
201    #[method(name = "getTransactionReceipt")]
202    async fn transaction_receipt(&self, hash: B256) -> RpcResult<Option<R>>;
203
204    /// Returns the balance of the account of given address.
205    #[method(name = "getBalance")]
206    async fn balance(&self, address: Address, block_number: Option<BlockId>) -> RpcResult<U256>;
207
208    /// Returns the value from a storage position at a given address
209    #[method(name = "getStorageAt")]
210    async fn storage_at(
211        &self,
212        address: Address,
213        index: JsonStorageKey,
214        block_number: Option<BlockId>,
215    ) -> RpcResult<B256>;
216
217    /// Returns values from multiple storage positions across multiple addresses.
218    #[method(name = "getStorageValues")]
219    async fn storage_values(
220        &self,
221        requests: HashMap<Address, Vec<JsonStorageKey>>,
222        block_number: Option<BlockId>,
223    ) -> RpcResult<HashMap<Address, Vec<B256>>>;
224
225    /// Returns the number of transactions sent from an address at given block number.
226    #[method(name = "getTransactionCount")]
227    async fn transaction_count(
228        &self,
229        address: Address,
230        block_number: Option<BlockId>,
231    ) -> RpcResult<U256>;
232
233    /// Returns code at a given address at given block number.
234    #[method(name = "getCode")]
235    async fn get_code(&self, address: Address, block_number: Option<BlockId>) -> RpcResult<Bytes>;
236
237    /// Returns the block's header at given number.
238    #[method(name = "getHeaderByNumber")]
239    async fn header_by_number(&self, hash: BlockNumberOrTag) -> RpcResult<Option<H>>;
240
241    /// Returns the block's header at given hash.
242    #[method(name = "getHeaderByHash")]
243    async fn header_by_hash(&self, hash: B256) -> RpcResult<Option<H>>;
244
245    /// `eth_simulateV1` executes an arbitrary number of transactions on top of the requested state.
246    /// The transactions are packed into individual blocks. Overrides can be provided.
247    #[method(name = "simulateV1")]
248    async fn simulate_v1(
249        &self,
250        opts: SimulatePayload<TxReq>,
251        block_number: Option<BlockId>,
252    ) -> RpcResult<Vec<SimulatedBlock<B>>>;
253
254    /// Executes a new message call immediately without creating a transaction on the block chain.
255    #[method(name = "call")]
256    async fn call(
257        &self,
258        request: TxReq,
259        block_number: Option<BlockId>,
260        state_overrides: Option<StateOverride>,
261        block_overrides: Option<Box<BlockOverrides>>,
262    ) -> RpcResult<Bytes>;
263
264    /// Fills the defaults on a given unsigned transaction.
265    #[method(name = "fillTransaction")]
266    async fn fill_transaction(&self, request: TxReq) -> RpcResult<FillTransaction<RawTx>>;
267
268    /// Simulate arbitrary number of transactions at an arbitrary blockchain index, with the
269    /// optionality of state overrides
270    #[method(name = "callMany")]
271    async fn call_many(
272        &self,
273        bundles: Vec<Bundle<TxReq>>,
274        state_context: Option<StateContext>,
275        state_override: Option<StateOverride>,
276    ) -> RpcResult<Vec<Vec<EthCallResponse>>>;
277
278    /// Generates an access list for a transaction.
279    ///
280    /// This method creates an [EIP2930](https://eips.ethereum.org/EIPS/eip-2930) type accessList based on a given Transaction.
281    ///
282    /// An access list contains all storage slots and addresses touched by the transaction, except
283    /// for the sender account and the chain's precompiles.
284    ///
285    /// It returns list of addresses and storage keys used by the transaction, plus the gas
286    /// consumed when the access list is added. That is, it gives you the list of addresses and
287    /// storage keys that will be used by that transaction, plus the gas consumed if the access
288    /// list is included. Like `eth_estimateGas`, this is an estimation; the list could change
289    /// when the transaction is actually mined. Adding an accessList to your transaction does
290    /// not necessary result in lower gas usage compared to a transaction without an access
291    /// list.
292    #[method(name = "createAccessList")]
293    async fn create_access_list(
294        &self,
295        request: TxReq,
296        block_number: Option<BlockId>,
297        state_override: Option<StateOverride>,
298    ) -> RpcResult<AccessListResult>;
299
300    /// Generates and returns an estimate of how much gas is necessary to allow the transaction to
301    /// complete.
302    #[method(name = "estimateGas")]
303    async fn estimate_gas(
304        &self,
305        request: TxReq,
306        block_number: Option<BlockId>,
307        state_override: Option<StateOverride>,
308        block_overrides: Option<Box<BlockOverrides>>,
309    ) -> RpcResult<U256>;
310
311    /// Returns the current price per gas in wei.
312    #[method(name = "gasPrice")]
313    async fn gas_price(&self) -> RpcResult<U256>;
314
315    /// Returns the account details by specifying an address and a block number/tag
316    #[method(name = "getAccount")]
317    async fn get_account(
318        &self,
319        address: Address,
320        block: BlockId,
321    ) -> RpcResult<Option<alloy_rpc_types_eth::Account>>;
322
323    /// Introduced in EIP-1559, returns suggestion for the priority for dynamic fee transactions.
324    #[method(name = "maxPriorityFeePerGas")]
325    async fn max_priority_fee_per_gas(&self) -> RpcResult<U256>;
326
327    /// Returns the base fee for the next block, or `null` before London activation.
328    #[method(name = "baseFee")]
329    async fn base_fee(&self) -> RpcResult<Option<U256>>;
330
331    /// Introduced in EIP-4844, returns the current blob base fee in wei.
332    #[method(name = "blobBaseFee")]
333    async fn blob_base_fee(&self) -> RpcResult<U256>;
334
335    /// Returns the Transaction fee history
336    ///
337    /// Introduced in EIP-1559 for getting information on the appropriate priority fee to use.
338    ///
339    /// Returns transaction base fee per gas and effective priority fee per gas for the
340    /// requested/supported block range. The returned Fee history for the returned block range
341    /// can be a subsection of the requested range if not all blocks are available.
342    #[method(name = "feeHistory")]
343    async fn fee_history(
344        &self,
345        block_count: U64,
346        newest_block: BlockNumberOrTag,
347        reward_percentiles: Option<Vec<f64>>,
348    ) -> RpcResult<FeeHistory>;
349
350    /// Returns whether the client is actively mining new blocks.
351    #[method(name = "mining")]
352    async fn is_mining(&self) -> RpcResult<bool>;
353
354    /// Returns the number of hashes per second that the node is mining with.
355    #[method(name = "hashrate")]
356    async fn hashrate(&self) -> RpcResult<U256>;
357
358    /// Returns the hash of the current block, the seedHash, and the boundary condition to be met
359    /// (“target”)
360    #[method(name = "getWork")]
361    async fn get_work(&self) -> RpcResult<Work>;
362
363    /// Used for submitting mining hashrate.
364    ///
365    /// Can be used for remote miners to submit their hash rate.
366    /// It accepts the miner hash rate and an identifier which must be unique between nodes.
367    /// Returns `true` if the block was successfully submitted, `false` otherwise.
368    #[method(name = "submitHashrate")]
369    async fn submit_hashrate(&self, hashrate: U256, id: B256) -> RpcResult<bool>;
370
371    /// Used for submitting a proof-of-work solution.
372    #[method(name = "submitWork")]
373    async fn submit_work(&self, nonce: B64, pow_hash: B256, mix_digest: B256) -> RpcResult<bool>;
374
375    /// Sends transaction; will block waiting for signer to return the
376    /// transaction hash.
377    #[method(name = "sendTransaction")]
378    async fn send_transaction(&self, request: TxReq) -> RpcResult<B256>;
379
380    /// Sends signed transaction, returning its hash.
381    #[method(name = "sendRawTransaction")]
382    async fn send_raw_transaction(&self, bytes: Bytes) -> RpcResult<B256>;
383
384    /// Sends a signed transaction and awaits the transaction receipt.
385    ///
386    /// This will return a timeout error if the transaction isn't included within some time period.
387    #[method(name = "sendRawTransactionSync")]
388    async fn send_raw_transaction_sync(
389        &self,
390        bytes: Bytes,
391        timeout_ms: Option<u64>,
392    ) -> RpcResult<R>;
393
394    /// Returns an Ethereum specific signature with: sign(keccak256("\x19Ethereum Signed Message:\n"
395    /// + len(message) + message))).
396    #[method(name = "sign")]
397    async fn sign(&self, address: Address, message: Bytes) -> RpcResult<Bytes>;
398
399    /// Signs a transaction that can be submitted to the network at a later time using with
400    /// `sendRawTransaction.`
401    #[method(name = "signTransaction")]
402    async fn sign_transaction(&self, transaction: TxReq) -> RpcResult<Bytes>;
403
404    /// Signs data via [EIP-712](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md).
405    #[method(name = "signTypedData")]
406    async fn sign_typed_data(&self, address: Address, data: TypedData) -> RpcResult<Bytes>;
407
408    /// Returns the account and storage values of the specified account including the Merkle-proof.
409    /// This call can be used to verify that the data you are pulling from is not tampered with.
410    #[method(name = "getProof")]
411    async fn get_proof(
412        &self,
413        address: Address,
414        keys: Vec<JsonStorageKey>,
415        block_number: Option<BlockId>,
416    ) -> RpcResult<EIP1186AccountProofResponse>;
417
418    /// Returns the account's balance, nonce, and code.
419    ///
420    /// This is similar to `eth_getAccount` but does not return the storage root.
421    #[method(name = "getAccountInfo")]
422    async fn get_account_info(
423        &self,
424        address: Address,
425        block: BlockId,
426    ) -> RpcResult<alloy_rpc_types_eth::AccountInfo>;
427
428    /// Returns the EIP-7928 block access list for a block by hash.
429    #[method(name = "getBlockAccessListByBlockHash")]
430    async fn block_access_list_by_block_hash(&self, hash: B256) -> RpcResult<Option<Value>>;
431
432    /// Returns the EIP-7928 block access list for a block by number.
433    #[method(name = "getBlockAccessListByBlockNumber")]
434    async fn block_access_list_by_block_number(
435        &self,
436        number: BlockNumberOrTag,
437    ) -> RpcResult<Option<Value>>;
438
439    /// Returns the EIP-7928 block access list for a given block id.
440    #[method(name = "getBlockAccessList")]
441    async fn block_access_list(&self, block_id: BlockId) -> RpcResult<Option<Value>>;
442
443    /// Returns the EIP-7928 block access list bytes for a block by number.
444    #[method(name = "getBlockAccessListRaw")]
445    async fn block_access_list_raw(&self, block: BlockId) -> RpcResult<Option<Bytes>>;
446}
447
448#[async_trait::async_trait]
449impl<T>
450    EthApiServer<
451        RpcTxReq<T::NetworkTypes>,
452        RpcTransaction<T::NetworkTypes>,
453        RpcBlock<T::NetworkTypes>,
454        RpcReceipt<T::NetworkTypes>,
455        RpcHeader<T::NetworkTypes>,
456        TxTy<T::Primitives>,
457    > for T
458where
459    T: FullEthApi,
460    jsonrpsee_types::error::ErrorObject<'static>: From<T::Error>,
461{
462    /// Handler for: `eth_protocolVersion`
463    async fn protocol_version(&self) -> RpcResult<U64> {
464        trace!(target: "rpc::eth", "Serving eth_protocolVersion");
465        EthApiSpec::protocol_version(self).await.to_rpc_result()
466    }
467
468    /// Handler for: `eth_syncing`
469    fn syncing(&self) -> RpcResult<SyncStatus> {
470        trace!(target: "rpc::eth", "Serving eth_syncing");
471        EthApiSpec::sync_status(self).to_rpc_result()
472    }
473
474    /// Handler for: `eth_coinbase`
475    async fn author(&self) -> RpcResult<Address> {
476        Err(internal_rpc_err("unimplemented"))
477    }
478
479    /// Handler for: `eth_accounts`
480    fn accounts(&self) -> RpcResult<Vec<Address>> {
481        trace!(target: "rpc::eth", "Serving eth_accounts");
482        Ok(EthTransactions::accounts(self))
483    }
484
485    /// Handler for: `eth_blockNumber`
486    fn block_number(&self) -> RpcResult<U256> {
487        trace!(target: "rpc::eth", "Serving eth_blockNumber");
488        Ok(U256::from(
489            EthApiSpec::chain_info(self).with_message("failed to read chain info")?.best_number,
490        ))
491    }
492
493    /// Handler for: `eth_chainId`
494    async fn chain_id(&self) -> RpcResult<Option<U64>> {
495        trace!(target: "rpc::eth", "Serving eth_chainId");
496        Ok(Some(EthApiSpec::chain_id(self)))
497    }
498
499    /// Handler for: `eth_capabilities`
500    fn capabilities(&self) -> RpcResult<EthCapabilities> {
501        trace!(target: "rpc::eth", "Serving eth_capabilities");
502        EthApiSpec::capabilities(self).to_rpc_result()
503    }
504
505    /// Handler for: `eth_getBlockByHash`
506    async fn block_by_hash(
507        &self,
508        hash: B256,
509        full: bool,
510    ) -> RpcResult<Option<RpcBlock<T::NetworkTypes>>> {
511        trace!(target: "rpc::eth", ?hash, ?full, "Serving eth_getBlockByHash");
512        Ok(EthBlocks::rpc_block(self, hash.into(), full).await?)
513    }
514
515    /// Handler for: `eth_getBlockByNumber`
516    async fn block_by_number(
517        &self,
518        number: BlockNumberOrTag,
519        full: bool,
520    ) -> RpcResult<Option<RpcBlock<T::NetworkTypes>>> {
521        trace!(target: "rpc::eth", ?number, ?full, "Serving eth_getBlockByNumber");
522        Ok(EthBlocks::rpc_block(self, number.into(), full).await?)
523    }
524
525    /// Handler for: `eth_getBlockTransactionCountByHash`
526    async fn block_transaction_count_by_hash(&self, hash: B256) -> RpcResult<Option<U256>> {
527        trace!(target: "rpc::eth", ?hash, "Serving eth_getBlockTransactionCountByHash");
528        Ok(EthBlocks::block_transaction_count(self, hash.into()).await?.map(U256::from))
529    }
530
531    /// Handler for: `eth_getBlockTransactionCountByNumber`
532    async fn block_transaction_count_by_number(
533        &self,
534        number: BlockNumberOrTag,
535    ) -> RpcResult<Option<U256>> {
536        trace!(target: "rpc::eth", ?number, "Serving eth_getBlockTransactionCountByNumber");
537        Ok(EthBlocks::block_transaction_count(self, number.into()).await?.map(U256::from))
538    }
539
540    /// Handler for: `eth_getUncleCountByBlockHash`
541    async fn block_uncles_count_by_hash(&self, hash: B256) -> RpcResult<Option<U256>> {
542        trace!(target: "rpc::eth", ?hash, "Serving eth_getUncleCountByBlockHash");
543
544        if let Some(block) = self.block_by_hash(hash, false).await? {
545            Ok(Some(U256::from(block.uncles.len())))
546        } else {
547            Ok(None)
548        }
549    }
550
551    /// Handler for: `eth_getUncleCountByBlockNumber`
552    async fn block_uncles_count_by_number(
553        &self,
554        number: BlockNumberOrTag,
555    ) -> RpcResult<Option<U256>> {
556        trace!(target: "rpc::eth", ?number, "Serving eth_getUncleCountByBlockNumber");
557
558        if let Some(block) = self.block_by_number(number, false).await? {
559            Ok(Some(U256::from(block.uncles.len())))
560        } else {
561            Ok(None)
562        }
563    }
564
565    /// Handler for: `eth_getBlockReceipts`
566    async fn block_receipts(
567        &self,
568        block_id: BlockId,
569    ) -> RpcResult<Option<Vec<RpcReceipt<T::NetworkTypes>>>> {
570        trace!(target: "rpc::eth", ?block_id, "Serving eth_getBlockReceipts");
571        Ok(EthBlocks::block_receipts(self, block_id).await?)
572    }
573
574    /// Handler for: `eth_getUncleByBlockHashAndIndex`
575    async fn uncle_by_block_hash_and_index(
576        &self,
577        hash: B256,
578        index: Index,
579    ) -> RpcResult<Option<RpcBlock<T::NetworkTypes>>> {
580        trace!(target: "rpc::eth", ?hash, ?index, "Serving eth_getUncleByBlockHashAndIndex");
581        Ok(EthBlocks::ommer_by_block_and_index(self, hash.into(), index).await?)
582    }
583
584    /// Handler for: `eth_getUncleByBlockNumberAndIndex`
585    async fn uncle_by_block_number_and_index(
586        &self,
587        number: BlockNumberOrTag,
588        index: Index,
589    ) -> RpcResult<Option<RpcBlock<T::NetworkTypes>>> {
590        trace!(target: "rpc::eth", ?number, ?index, "Serving eth_getUncleByBlockNumberAndIndex");
591        Ok(EthBlocks::ommer_by_block_and_index(self, number.into(), index).await?)
592    }
593
594    /// Handler for: `eth_getRawTransactionByHash`
595    async fn raw_transaction_by_hash(&self, hash: B256) -> RpcResult<Option<Bytes>> {
596        trace!(target: "rpc::eth", ?hash, "Serving eth_getRawTransactionByHash");
597        Ok(EthTransactions::raw_transaction_by_hash(self, hash).await?)
598    }
599
600    /// Handler for: `eth_getTransactionByHash`
601    async fn transaction_by_hash(
602        &self,
603        hash: B256,
604    ) -> RpcResult<Option<RpcTransaction<T::NetworkTypes>>> {
605        trace!(target: "rpc::eth", ?hash, "Serving eth_getTransactionByHash");
606        Ok(EthTransactions::transaction_by_hash(self, hash)
607            .await?
608            .map(|tx| tx.into_transaction(self.converter()))
609            .transpose()
610            .map_err(T::Error::from)?)
611    }
612
613    /// Handler for: `eth_getRawTransactionByBlockHashAndIndex`
614    async fn raw_transaction_by_block_hash_and_index(
615        &self,
616        hash: B256,
617        index: Index,
618    ) -> RpcResult<Option<Bytes>> {
619        trace!(target: "rpc::eth", ?hash, ?index, "Serving eth_getRawTransactionByBlockHashAndIndex");
620        Ok(EthTransactions::raw_transaction_by_block_and_tx_index(self, hash.into(), index.into())
621            .await?)
622    }
623
624    /// Handler for: `eth_getTransactionByBlockHashAndIndex`
625    async fn transaction_by_block_hash_and_index(
626        &self,
627        hash: B256,
628        index: Index,
629    ) -> RpcResult<Option<RpcTransaction<T::NetworkTypes>>> {
630        trace!(target: "rpc::eth", ?hash, ?index, "Serving eth_getTransactionByBlockHashAndIndex");
631        Ok(EthTransactions::transaction_by_block_and_tx_index(self, hash.into(), index.into())
632            .await?)
633    }
634
635    /// Handler for: `eth_getRawTransactionByBlockNumberAndIndex`
636    async fn raw_transaction_by_block_number_and_index(
637        &self,
638        number: BlockNumberOrTag,
639        index: Index,
640    ) -> RpcResult<Option<Bytes>> {
641        trace!(target: "rpc::eth", ?number, ?index, "Serving eth_getRawTransactionByBlockNumberAndIndex");
642        Ok(EthTransactions::raw_transaction_by_block_and_tx_index(
643            self,
644            number.into(),
645            index.into(),
646        )
647        .await?)
648    }
649
650    /// Handler for: `eth_getTransactionByBlockNumberAndIndex`
651    async fn transaction_by_block_number_and_index(
652        &self,
653        number: BlockNumberOrTag,
654        index: Index,
655    ) -> RpcResult<Option<RpcTransaction<T::NetworkTypes>>> {
656        trace!(target: "rpc::eth", ?number, ?index, "Serving eth_getTransactionByBlockNumberAndIndex");
657        Ok(EthTransactions::transaction_by_block_and_tx_index(self, number.into(), index.into())
658            .await?)
659    }
660
661    /// Handler for: `eth_getTransactionBySenderAndNonce`
662    async fn transaction_by_sender_and_nonce(
663        &self,
664        sender: Address,
665        nonce: U64,
666    ) -> RpcResult<Option<RpcTransaction<T::NetworkTypes>>> {
667        trace!(target: "rpc::eth", ?sender, ?nonce, "Serving eth_getTransactionBySenderAndNonce");
668        Ok(EthTransactions::get_transaction_by_sender_and_nonce(self, sender, nonce.to(), true)
669            .await?)
670    }
671
672    /// Handler for: `eth_pendingTransactions`
673    fn pending_transactions(&self) -> RpcResult<Vec<RpcTransaction<T::NetworkTypes>>> {
674        trace!(target: "rpc::eth", "Serving eth_pendingTransactions");
675        Ok(EthTransactions::pending_transactions(self)?)
676    }
677
678    /// Handler for: `eth_getTransactionReceipt`
679    async fn transaction_receipt(
680        &self,
681        hash: B256,
682    ) -> RpcResult<Option<RpcReceipt<T::NetworkTypes>>> {
683        trace!(target: "rpc::eth", ?hash, "Serving eth_getTransactionReceipt");
684        Ok(EthTransactions::transaction_receipt(self, hash).await?)
685    }
686
687    /// Handler for: `eth_getBalance`
688    async fn balance(&self, address: Address, block_number: Option<BlockId>) -> RpcResult<U256> {
689        trace!(target: "rpc::eth", ?address, ?block_number, "Serving eth_getBalance");
690        Ok(EthState::balance(self, address, block_number).await?)
691    }
692
693    /// Handler for: `eth_getStorageAt`
694    async fn storage_at(
695        &self,
696        address: Address,
697        index: JsonStorageKey,
698        block_number: Option<BlockId>,
699    ) -> RpcResult<B256> {
700        trace!(target: "rpc::eth", ?address, ?block_number, "Serving eth_getStorageAt");
701        Ok(EthState::storage_at(self, address, index, block_number).await?)
702    }
703
704    /// Handler for: `eth_getStorageValues`
705    async fn storage_values(
706        &self,
707        requests: HashMap<Address, Vec<JsonStorageKey>>,
708        block_number: Option<BlockId>,
709    ) -> RpcResult<HashMap<Address, Vec<B256>>> {
710        trace!(target: "rpc::eth", ?block_number, "Serving eth_getStorageValues");
711        Ok(EthState::storage_values(self, requests, block_number).await?)
712    }
713
714    /// Handler for: `eth_getTransactionCount`
715    async fn transaction_count(
716        &self,
717        address: Address,
718        block_number: Option<BlockId>,
719    ) -> RpcResult<U256> {
720        trace!(target: "rpc::eth", ?address, ?block_number, "Serving eth_getTransactionCount");
721        Ok(EthState::transaction_count(self, address, block_number).await?)
722    }
723
724    /// Handler for: `eth_getCode`
725    async fn get_code(&self, address: Address, block_number: Option<BlockId>) -> RpcResult<Bytes> {
726        trace!(target: "rpc::eth", ?address, ?block_number, "Serving eth_getCode");
727        Ok(EthState::get_code(self, address, block_number).await?)
728    }
729
730    /// Handler for: `eth_getHeaderByNumber`
731    async fn header_by_number(
732        &self,
733        block_number: BlockNumberOrTag,
734    ) -> RpcResult<Option<RpcHeader<T::NetworkTypes>>> {
735        trace!(target: "rpc::eth", ?block_number, "Serving eth_getHeaderByNumber");
736        Ok(EthBlocks::rpc_block_header(self, block_number.into()).await?)
737    }
738
739    /// Handler for: `eth_getHeaderByHash`
740    async fn header_by_hash(&self, hash: B256) -> RpcResult<Option<RpcHeader<T::NetworkTypes>>> {
741        trace!(target: "rpc::eth", ?hash, "Serving eth_getHeaderByHash");
742        Ok(EthBlocks::rpc_block_header(self, hash.into()).await?)
743    }
744
745    /// Handler for: `eth_simulateV1`
746    async fn simulate_v1(
747        &self,
748        payload: SimulatePayload<RpcTxReq<T::NetworkTypes>>,
749        block_number: Option<BlockId>,
750    ) -> RpcResult<Vec<SimulatedBlock<RpcBlock<T::NetworkTypes>>>> {
751        trace!(target: "rpc::eth", ?block_number, "Serving eth_simulateV1");
752        let _permit = self.tracing_task_guard().clone().acquire_owned().await;
753        Ok(EthCall::simulate_v1(self, payload, block_number).await?)
754    }
755
756    /// Handler for: `eth_call`
757    async fn call(
758        &self,
759        request: RpcTxReq<T::NetworkTypes>,
760        block_number: Option<BlockId>,
761        state_overrides: Option<StateOverride>,
762        block_overrides: Option<Box<BlockOverrides>>,
763    ) -> RpcResult<Bytes> {
764        trace!(target: "rpc::eth", ?request, ?block_number, ?state_overrides, ?block_overrides, "Serving eth_call");
765        Ok(EthCall::call(
766            self,
767            request,
768            block_number,
769            EvmOverrides::new(state_overrides, block_overrides),
770        )
771        .await?)
772    }
773
774    /// Handler for: `eth_fillTransaction`
775    async fn fill_transaction(
776        &self,
777        request: RpcTxReq<T::NetworkTypes>,
778    ) -> RpcResult<FillTransaction<TxTy<T::Primitives>>> {
779        trace!(target: "rpc::eth", ?request, "Serving eth_fillTransaction");
780        Ok(EthTransactions::fill_transaction(self, request).await?)
781    }
782
783    /// Handler for: `eth_callMany`
784    async fn call_many(
785        &self,
786        bundles: Vec<Bundle<RpcTxReq<T::NetworkTypes>>>,
787        state_context: Option<StateContext>,
788        state_override: Option<StateOverride>,
789    ) -> RpcResult<Vec<Vec<EthCallResponse>>> {
790        trace!(target: "rpc::eth", ?bundles, ?state_context, ?state_override, "Serving eth_callMany");
791        Ok(EthCall::call_many(self, bundles, state_context, state_override).await?)
792    }
793
794    /// Handler for: `eth_createAccessList`
795    async fn create_access_list(
796        &self,
797        request: RpcTxReq<T::NetworkTypes>,
798        block_number: Option<BlockId>,
799        state_override: Option<StateOverride>,
800    ) -> RpcResult<AccessListResult> {
801        trace!(target: "rpc::eth", ?request, ?block_number, ?state_override, "Serving eth_createAccessList");
802        Ok(EthCall::create_access_list_at(self, request, block_number, state_override).await?)
803    }
804
805    /// Handler for: `eth_estimateGas`
806    async fn estimate_gas(
807        &self,
808        request: RpcTxReq<T::NetworkTypes>,
809        block_number: Option<BlockId>,
810        state_override: Option<StateOverride>,
811        block_overrides: Option<Box<BlockOverrides>>,
812    ) -> RpcResult<U256> {
813        trace!(target: "rpc::eth", ?request, ?block_number, "Serving eth_estimateGas");
814        Ok(EthCall::estimate_gas_at(
815            self,
816            request,
817            block_number.unwrap_or_default(),
818            EvmOverrides::new(state_override, block_overrides),
819        )
820        .await?)
821    }
822
823    /// Handler for: `eth_gasPrice`
824    async fn gas_price(&self) -> RpcResult<U256> {
825        trace!(target: "rpc::eth", "Serving eth_gasPrice");
826        Ok(EthFees::gas_price(self).await?)
827    }
828
829    /// Handler for: `eth_getAccount`
830    async fn get_account(
831        &self,
832        address: Address,
833        block: BlockId,
834    ) -> RpcResult<Option<alloy_rpc_types_eth::Account>> {
835        trace!(target: "rpc::eth", "Serving eth_getAccount");
836        Ok(EthState::get_account(self, address, block).await?)
837    }
838
839    /// Handler for: `eth_maxPriorityFeePerGas`
840    async fn max_priority_fee_per_gas(&self) -> RpcResult<U256> {
841        trace!(target: "rpc::eth", "Serving eth_maxPriorityFeePerGas");
842        Ok(EthFees::suggested_priority_fee(self).await?)
843    }
844
845    /// Handler for: `eth_blobBaseFee`
846    async fn blob_base_fee(&self) -> RpcResult<U256> {
847        trace!(target: "rpc::eth", "Serving eth_blobBaseFee");
848        Ok(EthFees::blob_base_fee(self).await?)
849    }
850
851    /// Handler for: `eth_baseFee`
852    async fn base_fee(&self) -> RpcResult<Option<U256>> {
853        trace!(target: "rpc::eth", "Serving eth_baseFee");
854        Ok(EthFees::base_fee(self).await?)
855    }
856
857    // FeeHistory is calculated based on lazy evaluation of fees for historical blocks, and further
858    // caching of it in the LRU cache.
859    // When new RPC call is executed, the cache gets locked, we check it for the historical fees
860    // according to the requested block range, and fill any cache misses (in both RPC response
861    // and cache itself) with the actual data queried from the database.
862    // To minimize the number of database seeks required to query the missing data, we calculate the
863    // first non-cached block number and last non-cached block number. After that, we query this
864    // range of consecutive blocks from the database.
865    /// Handler for: `eth_feeHistory`
866    async fn fee_history(
867        &self,
868        block_count: U64,
869        newest_block: BlockNumberOrTag,
870        reward_percentiles: Option<Vec<f64>>,
871    ) -> RpcResult<FeeHistory> {
872        trace!(target: "rpc::eth", ?block_count, ?newest_block, ?reward_percentiles, "Serving eth_feeHistory");
873        Ok(EthFees::fee_history(self, block_count.to(), newest_block, reward_percentiles).await?)
874    }
875
876    /// Handler for: `eth_mining`
877    async fn is_mining(&self) -> RpcResult<bool> {
878        Err(internal_rpc_err("unimplemented"))
879    }
880
881    /// Handler for: `eth_hashrate`
882    async fn hashrate(&self) -> RpcResult<U256> {
883        Ok(U256::ZERO)
884    }
885
886    /// Handler for: `eth_getWork`
887    async fn get_work(&self) -> RpcResult<Work> {
888        Err(internal_rpc_err("unimplemented"))
889    }
890
891    /// Handler for: `eth_submitHashrate`
892    async fn submit_hashrate(&self, _hashrate: U256, _id: B256) -> RpcResult<bool> {
893        Ok(false)
894    }
895
896    /// Handler for: `eth_submitWork`
897    async fn submit_work(
898        &self,
899        _nonce: B64,
900        _pow_hash: B256,
901        _mix_digest: B256,
902    ) -> RpcResult<bool> {
903        Err(internal_rpc_err("unimplemented"))
904    }
905
906    /// Handler for: `eth_sendTransaction`
907    async fn send_transaction(&self, request: RpcTxReq<T::NetworkTypes>) -> RpcResult<B256> {
908        trace!(target: "rpc::eth", ?request, "Serving eth_sendTransaction");
909        Ok(EthTransactions::send_transaction_request(self, request).await?)
910    }
911
912    /// Handler for: `eth_sendRawTransaction`
913    async fn send_raw_transaction(&self, tx: Bytes) -> RpcResult<B256> {
914        trace!(target: "rpc::eth", ?tx, "Serving eth_sendRawTransaction");
915        Ok(EthTransactions::send_raw_transaction(self, tx).await?)
916    }
917
918    /// Handler for: `eth_sendRawTransactionSync`
919    async fn send_raw_transaction_sync(
920        &self,
921        tx: Bytes,
922        timeout_ms: Option<u64>,
923    ) -> RpcResult<RpcReceipt<T::NetworkTypes>> {
924        trace!(target: "rpc::eth", ?tx, ?timeout_ms, "Serving eth_sendRawTransactionSync");
925        Ok(EthTransactions::send_raw_transaction_sync(self, tx, timeout_ms).await?)
926    }
927
928    /// Handler for: `eth_sign`
929    async fn sign(&self, address: Address, message: Bytes) -> RpcResult<Bytes> {
930        trace!(target: "rpc::eth", ?address, ?message, "Serving eth_sign");
931        Ok(EthTransactions::sign(self, address, message).await?)
932    }
933
934    /// Handler for: `eth_signTransaction`
935    async fn sign_transaction(&self, request: RpcTxReq<T::NetworkTypes>) -> RpcResult<Bytes> {
936        trace!(target: "rpc::eth", ?request, "Serving eth_signTransaction");
937        Ok(EthTransactions::sign_transaction(self, request).await?)
938    }
939
940    /// Handler for: `eth_signTypedData`
941    async fn sign_typed_data(&self, address: Address, data: TypedData) -> RpcResult<Bytes> {
942        trace!(target: "rpc::eth", ?address, ?data, "Serving eth_signTypedData");
943        Ok(EthTransactions::sign_typed_data(self, &data, address)?)
944    }
945
946    /// Handler for: `eth_getProof`
947    async fn get_proof(
948        &self,
949        address: Address,
950        keys: Vec<JsonStorageKey>,
951        block_number: Option<BlockId>,
952    ) -> RpcResult<EIP1186AccountProofResponse> {
953        trace!(target: "rpc::eth", ?address, ?keys, ?block_number, "Serving eth_getProof");
954        Ok(EthState::get_proof(self, address, keys, block_number)?.await?)
955    }
956
957    /// Handler for: `eth_getAccountInfo`
958    async fn get_account_info(
959        &self,
960        address: Address,
961        block: BlockId,
962    ) -> RpcResult<alloy_rpc_types_eth::AccountInfo> {
963        trace!(target: "rpc::eth", "Serving eth_getAccountInfo");
964        Ok(EthState::get_account_info(self, address, block).await?)
965    }
966
967    /// Handler for: `eth_getBlockAccessListByBlockHash`
968    async fn block_access_list_by_block_hash(&self, block_hash: B256) -> RpcResult<Option<Value>> {
969        trace!(target: "rpc::eth", ?block_hash, "Serving eth_getBlockAccessListByBlockHash");
970
971        let bal = self.get_block_access_list(block_hash.into()).await?;
972        let json = serde_json::to_value(&bal)
973            .map_err(|e| EthApiError::Internal(reth_errors::RethError::msg(e.to_string())))?;
974
975        Ok(Some(json))
976    }
977
978    /// Handler for: `eth_getBlockAccessListByBlockNumber`
979    async fn block_access_list_by_block_number(
980        &self,
981        number: BlockNumberOrTag,
982    ) -> RpcResult<Option<Value>> {
983        trace!(target: "rpc::eth", ?number, "Serving eth_getBlockAccessListByBlockNumber");
984
985        let bal = self.get_block_access_list(number.into()).await?;
986        let json = serde_json::to_value(&bal)
987            .map_err(|e| EthApiError::Internal(reth_errors::RethError::msg(e.to_string())))?;
988
989        Ok(Some(json))
990    }
991
992    /// Handler for: `eth_getBlockAccessList`
993    async fn block_access_list(&self, block_id: BlockId) -> RpcResult<Option<Value>> {
994        trace!(target: "rpc::eth", ?block_id, "Serving eth_getBlockAccessList");
995
996        let bal = self.get_block_access_list(block_id).await?;
997        let json = serde_json::to_value(&bal)
998            .map_err(|e| EthApiError::Internal(reth_errors::RethError::msg(e.to_string())))?;
999
1000        Ok(Some(json))
1001    }
1002
1003    /// Handler for: `eth_getBlockAccessListRaw`
1004    async fn block_access_list_raw(&self, block: BlockId) -> RpcResult<Option<Bytes>> {
1005        trace!(target: "rpc::eth", ?block, "Serving eth_getBlockAccessListRaw");
1006
1007        Ok(self.get_raw_block_access_list(block).await?)
1008    }
1009}