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