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