Skip to main content

reth_rpc_eth_api/
core.rs

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