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