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