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