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