Skip to main content

reth_rpc/eth/
core.rs

1//! Implementation of the [`jsonrpsee`] generated [`EthApiServer`](crate::EthApi) trait
2//! Handles RPC requests for the `eth_` namespace.
3
4use std::{sync::Arc, time::Duration};
5
6use crate::{eth::helpers::types::EthRpcConverter, EthApiBuilder};
7use alloy_consensus::BlockHeader;
8use alloy_eips::BlockNumberOrTag;
9use alloy_network::Ethereum;
10use alloy_primitives::{Bytes, U256};
11use alloy_rpc_client::RpcClient;
12use derive_more::Deref;
13use reth_chainspec::{ChainSpec, ChainSpecProvider};
14use reth_evm_ethereum::EthEvmConfig;
15use reth_network_api::noop::NoopNetwork;
16use reth_node_api::{FullNodeComponents, FullNodeTypes};
17use reth_rpc_convert::{RpcConvert, RpcConverter};
18use reth_rpc_eth_api::{
19    helpers::{pending_block::PendingEnvBuilder, spec::SignersForRpc, SpawnBlocking},
20    node::{RpcNodeCoreAdapter, RpcNodeCoreExt},
21    EthApiTypes, RpcNodeCore,
22};
23use reth_rpc_eth_types::{
24    builder::config::PendingBlockKind, receipt::EthReceiptConverter, EthApiError, EthStateCache,
25    FeeHistoryCache, GasCap, GasPriceOracle, PendingBlock,
26};
27use reth_storage_api::{noop::NoopProvider, BlockReaderIdExt, ProviderHeader};
28use reth_tasks::{
29    pool::{BlockingTaskGuard, BlockingTaskPool},
30    Runtime,
31};
32use reth_transaction_pool::{
33    blobstore::BlobSidecarConverter, noop::NoopTransactionPool, AddedTransactionOutcome,
34    BatchTxProcessor, BatchTxRequest, TransactionPool,
35};
36use tokio::sync::{broadcast, mpsc, Mutex, Semaphore};
37
38const DEFAULT_BROADCAST_CAPACITY: usize = 2000;
39
40/// Helper type alias for [`RpcConverter`] with components from the given [`FullNodeComponents`].
41pub type EthRpcConverterFor<N, NetworkT = Ethereum> = RpcConverter<
42    NetworkT,
43    <N as FullNodeComponents>::Evm,
44    EthReceiptConverter<<<N as FullNodeTypes>::Provider as ChainSpecProvider>::ChainSpec>,
45>;
46
47/// Helper type alias for [`EthApi`] with components from the given [`FullNodeComponents`].
48pub type EthApiFor<N, NetworkT = Ethereum> = EthApi<N, EthRpcConverterFor<N, NetworkT>>;
49
50/// Helper type alias for [`EthApi`] with components from the given [`FullNodeComponents`].
51pub type EthApiBuilderFor<N, NetworkT = Ethereum> =
52    EthApiBuilder<N, EthRpcConverterFor<N, NetworkT>>;
53
54/// `Eth` API implementation.
55///
56/// This type provides the functionality for handling `eth_` related requests.
57/// These are implemented two-fold: Core functionality is implemented as
58/// [`EthApiSpec`](reth_rpc_eth_api::helpers::EthApiSpec) trait. Additionally, the required server
59/// implementations (e.g. [`EthApiServer`](reth_rpc_eth_api::EthApiServer)) are implemented
60/// separately in submodules. The rpc handler implementation can then delegate to the main impls.
61/// This way [`EthApi`] is not limited to [`jsonrpsee`] and can be used standalone or in other
62/// network handlers (for example ipc).
63///
64/// ## Trait requirements
65///
66/// While this type requires various unrestricted generic components, trait bounds are enforced when
67/// additional traits are implemented for this type.
68#[derive(Deref)]
69pub struct EthApi<N: RpcNodeCore, Rpc: RpcConvert> {
70    /// All nested fields bundled together.
71    #[deref]
72    pub(super) inner: Arc<EthApiInner<N, Rpc>>,
73}
74
75impl<N, Rpc> Clone for EthApi<N, Rpc>
76where
77    N: RpcNodeCore,
78    Rpc: RpcConvert,
79{
80    fn clone(&self) -> Self {
81        Self { inner: self.inner.clone() }
82    }
83}
84
85impl
86    EthApi<
87        RpcNodeCoreAdapter<NoopProvider, NoopTransactionPool, NoopNetwork, EthEvmConfig>,
88        EthRpcConverter<ChainSpec>,
89    >
90{
91    /// Convenience fn to obtain a new [`EthApiBuilder`] instance with mandatory components.
92    ///
93    /// Creating an [`EthApi`] requires a few mandatory components:
94    ///  - provider: The type responsible for fetching requested data from disk.
95    ///  - transaction pool: To interact with the pool, submitting new transactions (e.g.
96    ///    `eth_sendRawTransactions`).
97    ///  - network: required to handle requests related to network state (e.g. `eth_syncing`).
98    ///  - evm config: Knows how create a new EVM instance to transact,estimate,call,trace.
99    ///
100    /// # Create an instance with noop ethereum implementations
101    ///
102    /// ```no_run
103    /// use alloy_network::Ethereum;
104    /// use reth_evm_ethereum::EthEvmConfig;
105    /// use reth_network_api::noop::NoopNetwork;
106    /// use reth_provider::noop::NoopProvider;
107    /// use reth_rpc::EthApi;
108    /// use reth_transaction_pool::noop::NoopTransactionPool;
109    /// let eth_api = EthApi::builder(
110    ///     NoopProvider::default(),
111    ///     NoopTransactionPool::default(),
112    ///     NoopNetwork::default(),
113    ///     EthEvmConfig::mainnet(),
114    /// )
115    /// .build();
116    /// ```
117    #[expect(clippy::type_complexity)]
118    pub fn builder<Provider, Pool, Network, EvmConfig, ChainSpec>(
119        provider: Provider,
120        pool: Pool,
121        network: Network,
122        evm_config: EvmConfig,
123    ) -> EthApiBuilder<
124        RpcNodeCoreAdapter<Provider, Pool, Network, EvmConfig>,
125        RpcConverter<Ethereum, EvmConfig, EthReceiptConverter<ChainSpec>>,
126    >
127    where
128        RpcNodeCoreAdapter<Provider, Pool, Network, EvmConfig>:
129            RpcNodeCore<Provider: ChainSpecProvider<ChainSpec = ChainSpec>, Evm = EvmConfig>,
130    {
131        EthApiBuilder::new(provider, pool, network, evm_config)
132    }
133}
134
135impl<N, Rpc> EthApiTypes for EthApi<N, Rpc>
136where
137    N: RpcNodeCore,
138    Rpc: RpcConvert<Error = EthApiError>,
139{
140    type Error = EthApiError;
141    type NetworkTypes = Rpc::Network;
142    type RpcConvert = Rpc;
143
144    fn converter(&self) -> &Self::RpcConvert {
145        &self.converter
146    }
147}
148
149impl<N, Rpc> RpcNodeCore for EthApi<N, Rpc>
150where
151    N: RpcNodeCore,
152    Rpc: RpcConvert,
153{
154    type Primitives = N::Primitives;
155    type Provider = N::Provider;
156    type Pool = N::Pool;
157    type Evm = N::Evm;
158    type Network = N::Network;
159
160    fn pool(&self) -> &Self::Pool {
161        self.inner.pool()
162    }
163
164    fn evm_config(&self) -> &Self::Evm {
165        self.inner.evm_config()
166    }
167
168    fn network(&self) -> &Self::Network {
169        self.inner.network()
170    }
171
172    fn provider(&self) -> &Self::Provider {
173        self.inner.provider()
174    }
175}
176
177impl<N, Rpc> RpcNodeCoreExt for EthApi<N, Rpc>
178where
179    N: RpcNodeCore,
180    Rpc: RpcConvert,
181{
182    #[inline]
183    fn cache(&self) -> &EthStateCache<N::Primitives> {
184        self.inner.cache()
185    }
186}
187
188impl<N, Rpc> std::fmt::Debug for EthApi<N, Rpc>
189where
190    N: RpcNodeCore,
191    Rpc: RpcConvert,
192{
193    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
194        f.debug_struct("EthApi").finish_non_exhaustive()
195    }
196}
197
198impl<N, Rpc> SpawnBlocking for EthApi<N, Rpc>
199where
200    N: RpcNodeCore,
201    Rpc: RpcConvert<Error = EthApiError>,
202{
203    #[inline]
204    fn io_task_spawner(&self) -> &Runtime {
205        self.inner.task_spawner()
206    }
207
208    #[inline]
209    fn tracing_task_pool(&self) -> &BlockingTaskPool {
210        self.inner.blocking_task_pool()
211    }
212
213    #[inline]
214    fn tracing_task_guard(&self) -> &BlockingTaskGuard {
215        self.inner.blocking_task_guard()
216    }
217
218    #[inline]
219    fn blocking_io_task_guard(&self) -> &std::sync::Arc<tokio::sync::Semaphore> {
220        self.inner.blocking_io_request_semaphore()
221    }
222}
223
224/// Container type `EthApi`
225#[expect(missing_debug_implementations)]
226pub struct EthApiInner<N: RpcNodeCore, Rpc: RpcConvert> {
227    /// The components of the node.
228    components: N,
229    /// All configured Signers
230    signers: SignersForRpc<N::Provider, Rpc::Network>,
231    /// The async cache frontend for eth related data
232    eth_cache: EthStateCache<N::Primitives>,
233    /// The async gas oracle frontend for gas price suggestions
234    gas_oracle: GasPriceOracle<N::Provider>,
235    /// Maximum gas limit for `eth_call` and call tracing RPC methods.
236    gas_cap: u64,
237    /// Maximum number of blocks for `eth_simulateV1`.
238    max_simulate_blocks: u64,
239    /// The maximum number of blocks into the past for generating state proofs.
240    eth_proof_window: u64,
241    /// The block number at which the node started
242    starting_block: U256,
243    /// The type that can spawn tasks which would otherwise block.
244    task_spawner: Runtime,
245    /// Cached pending block if any
246    pending_block: Mutex<Option<PendingBlock<N::Primitives>>>,
247    /// A pool dedicated to CPU heavy blocking tasks.
248    blocking_task_pool: BlockingTaskPool,
249    /// Cache for block fees history
250    fee_history_cache: FeeHistoryCache<ProviderHeader<N::Provider>>,
251
252    /// Guard for getproof calls
253    blocking_task_guard: BlockingTaskGuard,
254
255    /// Semaphore to limit concurrent blocking IO requests (`eth_call`, `eth_estimateGas`, etc.)
256    blocking_io_request_semaphore: Arc<Semaphore>,
257
258    /// Transaction broadcast channel
259    raw_tx_sender: broadcast::Sender<Bytes>,
260
261    /// Raw transaction forwarder
262    raw_tx_forwarder: Option<RpcClient>,
263
264    /// Converter for RPC types.
265    converter: Rpc,
266
267    /// Builder for pending block environment.
268    next_env_builder: Box<dyn PendingEnvBuilder<N::Evm>>,
269
270    /// Transaction batch sender for batching tx insertions
271    tx_batch_sender:
272        mpsc::UnboundedSender<BatchTxRequest<<N::Pool as TransactionPool>::Transaction>>,
273
274    /// Configuration for pending block construction.
275    pending_block_kind: PendingBlockKind,
276
277    /// Timeout duration for `send_raw_transaction_sync` RPC method.
278    send_raw_transaction_sync_timeout: Duration,
279
280    /// Blob sidecar converter
281    blob_sidecar_converter: BlobSidecarConverter,
282
283    /// Maximum memory the EVM can allocate per RPC request.
284    evm_memory_limit: u64,
285
286    /// Whether to force upcasting EIP-4844 blob sidecars to EIP-7594 format when Osaka is active.
287    force_blob_sidecar_upcasting: bool,
288}
289
290impl<N, Rpc> EthApiInner<N, Rpc>
291where
292    N: RpcNodeCore,
293    Rpc: RpcConvert,
294{
295    /// Creates a new, shareable instance using the default tokio task spawner.
296    #[expect(clippy::too_many_arguments)]
297    pub fn new(
298        components: N,
299        eth_cache: EthStateCache<N::Primitives>,
300        gas_oracle: GasPriceOracle<N::Provider>,
301        gas_cap: impl Into<GasCap>,
302        max_simulate_blocks: u64,
303        eth_proof_window: u64,
304        blocking_task_pool: BlockingTaskPool,
305        fee_history_cache: FeeHistoryCache<ProviderHeader<N::Provider>>,
306        task_spawner: Runtime,
307        proof_permits: usize,
308        converter: Rpc,
309        next_env: impl PendingEnvBuilder<N::Evm>,
310        max_batch_size: usize,
311        max_blocking_io_requests: usize,
312        pending_block_kind: PendingBlockKind,
313        raw_tx_forwarder: Option<RpcClient>,
314        send_raw_transaction_sync_timeout: Duration,
315        evm_memory_limit: u64,
316        force_blob_sidecar_upcasting: bool,
317    ) -> Self {
318        let signers = parking_lot::RwLock::new(Default::default());
319        // get the block number of the latest block
320        let starting_block = U256::from(
321            components
322                .provider()
323                .header_by_number_or_tag(BlockNumberOrTag::Latest)
324                .ok()
325                .flatten()
326                .map(|header| header.number())
327                .unwrap_or_default(),
328        );
329
330        let (raw_tx_sender, _) = broadcast::channel(DEFAULT_BROADCAST_CAPACITY);
331
332        // Create tx pool insertion batcher
333        let (processor, tx_batch_sender) =
334            BatchTxProcessor::new(components.pool().clone(), max_batch_size);
335        task_spawner.spawn_critical_task("tx-batcher", processor);
336
337        Self {
338            components,
339            signers,
340            eth_cache,
341            gas_oracle,
342            gas_cap: gas_cap.into().into(),
343            max_simulate_blocks,
344            eth_proof_window,
345            starting_block,
346            task_spawner,
347            pending_block: Default::default(),
348            blocking_task_pool,
349            fee_history_cache,
350            blocking_task_guard: BlockingTaskGuard::new(proof_permits),
351            blocking_io_request_semaphore: Arc::new(Semaphore::new(max_blocking_io_requests)),
352            raw_tx_sender,
353            raw_tx_forwarder,
354            converter,
355            next_env_builder: Box::new(next_env),
356            tx_batch_sender,
357            pending_block_kind,
358            send_raw_transaction_sync_timeout,
359            blob_sidecar_converter: BlobSidecarConverter::new(),
360            evm_memory_limit,
361            force_blob_sidecar_upcasting,
362        }
363    }
364}
365
366impl<N, Rpc> EthApiInner<N, Rpc>
367where
368    N: RpcNodeCore,
369    Rpc: RpcConvert,
370{
371    /// Returns a handle to data on disk.
372    #[inline]
373    pub fn provider(&self) -> &N::Provider {
374        self.components.provider()
375    }
376
377    /// Returns a handle to the transaction response builder.
378    #[inline]
379    pub const fn converter(&self) -> &Rpc {
380        &self.converter
381    }
382
383    /// Returns a handle to data in memory.
384    #[inline]
385    pub const fn cache(&self) -> &EthStateCache<N::Primitives> {
386        &self.eth_cache
387    }
388
389    /// Returns a handle to the pending block.
390    #[inline]
391    pub const fn pending_block(&self) -> &Mutex<Option<PendingBlock<N::Primitives>>> {
392        &self.pending_block
393    }
394
395    /// Returns a type that knows how to build a [`reth_evm::ConfigureEvm::NextBlockEnvCtx`] for a
396    /// pending block.
397    #[inline]
398    pub const fn pending_env_builder(&self) -> &dyn PendingEnvBuilder<N::Evm> {
399        &*self.next_env_builder
400    }
401
402    /// Returns a handle to the task spawner.
403    #[inline]
404    pub const fn task_spawner(&self) -> &Runtime {
405        &self.task_spawner
406    }
407
408    /// Returns a handle to the blocking thread pool.
409    ///
410    /// This is intended for tasks that are CPU bound.
411    #[inline]
412    pub const fn blocking_task_pool(&self) -> &BlockingTaskPool {
413        &self.blocking_task_pool
414    }
415
416    /// Returns a handle to the EVM config.
417    #[inline]
418    pub fn evm_config(&self) -> &N::Evm {
419        self.components.evm_config()
420    }
421
422    /// Returns a handle to the transaction pool.
423    #[inline]
424    pub fn pool(&self) -> &N::Pool {
425        self.components.pool()
426    }
427
428    /// Returns the gas cap.
429    #[inline]
430    pub const fn gas_cap(&self) -> u64 {
431        self.gas_cap
432    }
433
434    /// Returns the `max_simulate_blocks`.
435    #[inline]
436    pub const fn max_simulate_blocks(&self) -> u64 {
437        self.max_simulate_blocks
438    }
439
440    /// Returns a handle to the gas oracle.
441    #[inline]
442    pub const fn gas_oracle(&self) -> &GasPriceOracle<N::Provider> {
443        &self.gas_oracle
444    }
445
446    /// Returns a handle to the fee history cache.
447    #[inline]
448    pub const fn fee_history_cache(&self) -> &FeeHistoryCache<ProviderHeader<N::Provider>> {
449        &self.fee_history_cache
450    }
451
452    /// Returns a handle to the signers.
453    #[inline]
454    pub const fn signers(&self) -> &SignersForRpc<N::Provider, Rpc::Network> {
455        &self.signers
456    }
457
458    /// Returns the starting block.
459    #[inline]
460    pub const fn starting_block(&self) -> U256 {
461        self.starting_block
462    }
463
464    /// Returns the inner `Network`
465    #[inline]
466    pub fn network(&self) -> &N::Network {
467        self.components.network()
468    }
469
470    /// The maximum number of blocks into the past for generating state proofs.
471    #[inline]
472    pub const fn eth_proof_window(&self) -> u64 {
473        self.eth_proof_window
474    }
475
476    /// Returns reference to [`BlockingTaskGuard`].
477    #[inline]
478    pub const fn blocking_task_guard(&self) -> &BlockingTaskGuard {
479        &self.blocking_task_guard
480    }
481
482    /// Returns [`broadcast::Receiver`] of new raw transactions
483    #[inline]
484    pub fn subscribe_to_raw_transactions(&self) -> broadcast::Receiver<Bytes> {
485        self.raw_tx_sender.subscribe()
486    }
487
488    /// Broadcasts raw transaction if there are active subscribers.
489    #[inline]
490    pub fn broadcast_raw_transaction(&self, raw_tx: Bytes) {
491        let _ = self.raw_tx_sender.send(raw_tx);
492    }
493
494    /// Returns the transaction batch sender
495    #[inline]
496    pub const fn tx_batch_sender(
497        &self,
498    ) -> &mpsc::UnboundedSender<BatchTxRequest<<N::Pool as TransactionPool>::Transaction>> {
499        &self.tx_batch_sender
500    }
501
502    /// Adds an _unvalidated_ transaction into the pool via the transaction batch sender.
503    #[inline]
504    pub async fn add_pool_transaction(
505        &self,
506        origin: reth_transaction_pool::TransactionOrigin,
507        transaction: <N::Pool as TransactionPool>::Transaction,
508    ) -> Result<AddedTransactionOutcome, EthApiError> {
509        let (response_tx, response_rx) = tokio::sync::oneshot::channel();
510        let request = reth_transaction_pool::BatchTxRequest::new(origin, transaction, response_tx);
511
512        self.tx_batch_sender()
513            .send(request)
514            .map_err(|_| reth_rpc_eth_types::EthApiError::BatchTxSendError)?;
515
516        Ok(response_rx.await??)
517    }
518
519    /// Returns the pending block kind
520    #[inline]
521    pub const fn pending_block_kind(&self) -> PendingBlockKind {
522        self.pending_block_kind
523    }
524
525    /// Returns a handle to the raw transaction forwarder.
526    #[inline]
527    pub const fn raw_tx_forwarder(&self) -> Option<&RpcClient> {
528        self.raw_tx_forwarder.as_ref()
529    }
530
531    /// Returns the timeout duration for `send_raw_transaction_sync` RPC method.
532    #[inline]
533    pub const fn send_raw_transaction_sync_timeout(&self) -> Duration {
534        self.send_raw_transaction_sync_timeout
535    }
536
537    /// Returns a handle to the blob sidecar converter.
538    #[inline]
539    pub const fn blob_sidecar_converter(&self) -> &BlobSidecarConverter {
540        &self.blob_sidecar_converter
541    }
542
543    /// Returns the EVM memory limit.
544    #[inline]
545    pub const fn evm_memory_limit(&self) -> u64 {
546        self.evm_memory_limit
547    }
548
549    /// Returns a reference to the blocking IO request semaphore.
550    #[inline]
551    pub const fn blocking_io_request_semaphore(&self) -> &Arc<Semaphore> {
552        &self.blocking_io_request_semaphore
553    }
554
555    /// Returns whether to force upcasting EIP-4844 blob sidecars to EIP-7594 format.
556    #[inline]
557    pub const fn force_blob_sidecar_upcasting(&self) -> bool {
558        self.force_blob_sidecar_upcasting
559    }
560}
561
562#[cfg(test)]
563mod tests {
564    use crate::{eth::helpers::types::EthRpcConverter, EthApi, EthApiBuilder};
565    use alloy_consensus::{Block, BlockBody, Header};
566    use alloy_eips::BlockNumberOrTag;
567    use alloy_primitives::{Signature, B256, U64};
568    use alloy_rpc_types::FeeHistory;
569    use alloy_rpc_types_eth::{Bundle, TransactionRequest};
570    use jsonrpsee_types::error::INVALID_PARAMS_CODE;
571    use rand::Rng;
572    use reth_chain_state::CanonStateSubscriptions;
573    use reth_chainspec::{ChainSpec, ChainSpecProvider, EthChainSpec};
574    use reth_ethereum_primitives::TransactionSigned;
575    use reth_evm_ethereum::EthEvmConfig;
576    use reth_network_api::noop::NoopNetwork;
577    use reth_provider::{
578        test_utils::{MockEthProvider, NoopProvider},
579        StageCheckpointReader,
580    };
581    use reth_rpc_eth_api::{node::RpcNodeCoreAdapter, EthApiServer};
582    use reth_storage_api::{BalProvider, BlockReader, BlockReaderIdExt, StateProviderFactory};
583    use reth_testing_utils::generators;
584    use reth_transaction_pool::test_utils::{testing_pool, TestPool};
585
586    type FakeEthApi<P = MockEthProvider> = EthApi<
587        RpcNodeCoreAdapter<P, TestPool, NoopNetwork, EthEvmConfig>,
588        EthRpcConverter<ChainSpec>,
589    >;
590
591    fn build_test_eth_api<
592        P: BlockReaderIdExt<
593                Block = reth_ethereum_primitives::Block,
594                Receipt = reth_ethereum_primitives::Receipt,
595                Header = alloy_consensus::Header,
596                Transaction = reth_ethereum_primitives::TransactionSigned,
597            > + BlockReader
598            + ChainSpecProvider<ChainSpec = ChainSpec>
599            + StateProviderFactory
600            + CanonStateSubscriptions<Primitives = reth_ethereum_primitives::EthPrimitives>
601            + StageCheckpointReader
602            + BalProvider
603            + Unpin
604            + Clone
605            + 'static,
606    >(
607        provider: P,
608    ) -> FakeEthApi<P> {
609        EthApiBuilder::new(
610            provider.clone(),
611            testing_pool(),
612            NoopNetwork::default(),
613            EthEvmConfig::new(provider.chain_spec()),
614        )
615        .build()
616    }
617
618    // Function to prepare the EthApi with mock data
619    fn prepare_eth_api(
620        newest_block: u64,
621        mut oldest_block: Option<B256>,
622        block_count: u64,
623        mock_provider: MockEthProvider,
624    ) -> (FakeEthApi, Vec<u128>, Vec<f64>) {
625        let mut rng = generators::rng();
626
627        // Build mock data
628        let mut gas_used_ratios = Vec::with_capacity(block_count as usize);
629        let mut base_fees_per_gas = Vec::with_capacity(block_count as usize);
630        let mut last_header = None;
631        let mut parent_hash = B256::default();
632
633        for i in (0..block_count).rev() {
634            let hash = rng.random();
635            // Note: Generates saner values to avoid invalid overflows later
636            let gas_limit = rng.random::<u32>() as u64;
637            let base_fee_per_gas: Option<u64> =
638                rng.random::<bool>().then(|| rng.random::<u32>() as u64);
639            let gas_used = rng.random::<u32>() as u64;
640
641            let header = Header {
642                number: newest_block - i,
643                gas_limit,
644                gas_used,
645                base_fee_per_gas,
646                parent_hash,
647                ..Default::default()
648            };
649            last_header = Some(header.clone());
650            parent_hash = hash;
651
652            const TOTAL_TRANSACTIONS: usize = 100;
653            let mut transactions = Vec::with_capacity(TOTAL_TRANSACTIONS);
654            for _ in 0..TOTAL_TRANSACTIONS {
655                let random_fee: u128 = rng.random();
656
657                if let Some(base_fee_per_gas) = header.base_fee_per_gas {
658                    let transaction = TransactionSigned::new_unhashed(
659                        reth_ethereum_primitives::Transaction::Eip1559(
660                            alloy_consensus::TxEip1559 {
661                                max_priority_fee_per_gas: random_fee,
662                                max_fee_per_gas: random_fee + base_fee_per_gas as u128,
663                                ..Default::default()
664                            },
665                        ),
666                        Signature::test_signature(),
667                    );
668
669                    transactions.push(transaction);
670                } else {
671                    let transaction = TransactionSigned::new_unhashed(
672                        reth_ethereum_primitives::Transaction::Legacy(Default::default()),
673                        Signature::test_signature(),
674                    );
675
676                    transactions.push(transaction);
677                }
678            }
679
680            mock_provider.add_block(
681                hash,
682                Block {
683                    header: header.clone(),
684                    body: BlockBody { transactions, ..Default::default() },
685                },
686            );
687            mock_provider.add_header(hash, header);
688
689            oldest_block.get_or_insert(hash);
690            gas_used_ratios.push(gas_used as f64 / gas_limit as f64);
691            base_fees_per_gas.push(base_fee_per_gas.map(|fee| fee as u128).unwrap_or_default());
692        }
693
694        // Add final base fee (for the next block outside of the request)
695        let last_header = last_header.unwrap();
696        let spec = mock_provider.chain_spec();
697        base_fees_per_gas.push(
698            spec.next_block_base_fee(&last_header, last_header.timestamp).unwrap_or_default()
699                as u128,
700        );
701
702        let eth_api = build_test_eth_api(mock_provider);
703
704        (eth_api, base_fees_per_gas, gas_used_ratios)
705    }
706
707    /// Invalid block range
708    #[tokio::test]
709    async fn test_fee_history_empty() {
710        let response = <EthApi<_, _> as EthApiServer<_, _, _, _, _, _>>::fee_history(
711            &build_test_eth_api(NoopProvider::default()),
712            U64::from(1),
713            BlockNumberOrTag::Latest,
714            None,
715        )
716        .await;
717        assert!(response.is_err());
718        let error_object = response.unwrap_err();
719        assert_eq!(error_object.code(), INVALID_PARAMS_CODE);
720    }
721
722    #[tokio::test]
723    /// Invalid block range (request is before genesis)
724    async fn test_fee_history_invalid_block_range_before_genesis() {
725        let block_count = 10;
726        let newest_block = 1337;
727        let oldest_block = None;
728
729        let (eth_api, _, _) =
730            prepare_eth_api(newest_block, oldest_block, block_count, MockEthProvider::default());
731
732        let response = <EthApi<_, _> as EthApiServer<_, _, _, _, _, _>>::fee_history(
733            &eth_api,
734            U64::from(newest_block + 1),
735            newest_block.into(),
736            Some(vec![10.0]),
737        )
738        .await;
739
740        assert!(response.is_err());
741        let error_object = response.unwrap_err();
742        assert_eq!(error_object.code(), INVALID_PARAMS_CODE);
743    }
744
745    #[tokio::test]
746    /// Invalid block range (request is in the future)
747    async fn test_fee_history_invalid_block_range_in_future() {
748        let block_count = 10;
749        let newest_block = 1337;
750        let oldest_block = None;
751
752        let (eth_api, _, _) =
753            prepare_eth_api(newest_block, oldest_block, block_count, MockEthProvider::default());
754
755        let response = <EthApi<_, _> as EthApiServer<_, _, _, _, _, _>>::fee_history(
756            &eth_api,
757            U64::from(1),
758            (newest_block + 1000).into(),
759            Some(vec![10.0]),
760        )
761        .await;
762
763        assert!(response.is_err());
764        let error_object = response.unwrap_err();
765        assert_eq!(error_object.code(), INVALID_PARAMS_CODE);
766    }
767
768    #[tokio::test]
769    async fn test_call_many_maps_provider_block_lookup_error_with_eth_api_conversion() {
770        let eth_api = build_test_eth_api(MockEthProvider::default());
771        let bundles = vec![Bundle {
772            transactions: vec![TransactionRequest::default()],
773            block_override: None,
774        }];
775
776        let response = <EthApi<_, _> as EthApiServer<_, _, _, _, _, _>>::call_many(
777            &eth_api, bundles, None, None,
778        )
779        .await;
780
781        let err = response.expect_err("call_many should fail when latest block lookup errors");
782        let message = err.message().to_ascii_lowercase();
783        assert!(
784            message.contains("block not found"),
785            "best block lookup should map via EthApiError::from(ProviderError): {message}"
786        );
787        assert!(
788            !message.contains("best block does not exist"),
789            "provider implementation detail should not leak from converted error: {message}"
790        );
791    }
792
793    #[tokio::test]
794    async fn test_call_many_keeps_header_not_found_when_block_hash_absent() {
795        let eth_api = build_test_eth_api(NoopProvider::default());
796        let bundles = vec![Bundle {
797            transactions: vec![TransactionRequest::default()],
798            block_override: None,
799        }];
800
801        let response = <EthApi<_, _> as EthApiServer<_, _, _, _, _, _>>::call_many(
802            &eth_api, bundles, None, None,
803        )
804        .await;
805
806        let err =
807            response.expect_err("call_many should fail when latest block hash is unavailable");
808        let message = err.message().to_ascii_lowercase();
809        assert!(
810            message.contains("block not found"),
811            "missing block hash should still map to block-not-found: {message}"
812        );
813    }
814
815    #[tokio::test]
816    /// Requesting no block should result in a default response
817    async fn test_fee_history_no_block_requested() {
818        let block_count = 10;
819        let newest_block = 1337;
820        let oldest_block = None;
821
822        let (eth_api, _, _) =
823            prepare_eth_api(newest_block, oldest_block, block_count, MockEthProvider::default());
824
825        let response = <EthApi<_, _> as EthApiServer<_, _, _, _, _, _>>::fee_history(
826            &eth_api,
827            U64::from(0),
828            newest_block.into(),
829            None,
830        )
831        .await
832        .unwrap();
833        assert_eq!(
834            response,
835            FeeHistory::default(),
836            "none: requesting no block should yield a default response"
837        );
838    }
839
840    #[tokio::test]
841    /// Requesting a single block should return 1 block (+ base fee for the next block over)
842    async fn test_fee_history_single_block() {
843        let block_count = 10;
844        let newest_block = 1337;
845        let oldest_block = None;
846
847        let (eth_api, base_fees_per_gas, gas_used_ratios) =
848            prepare_eth_api(newest_block, oldest_block, block_count, MockEthProvider::default());
849
850        let fee_history =
851            eth_api.fee_history(U64::from(1), newest_block.into(), None).await.unwrap();
852        assert_eq!(
853            fee_history.base_fee_per_gas,
854            &base_fees_per_gas[base_fees_per_gas.len() - 2..],
855            "one: base fee per gas is incorrect"
856        );
857        assert_eq!(
858            fee_history.base_fee_per_gas.len(),
859            2,
860            "one: should return base fee of the next block as well"
861        );
862        assert_eq!(
863            &fee_history.gas_used_ratio,
864            &gas_used_ratios[gas_used_ratios.len() - 1..],
865            "one: gas used ratio is incorrect"
866        );
867        assert_eq!(fee_history.oldest_block, newest_block, "one: oldest block is incorrect");
868        assert!(
869            fee_history.reward.is_none(),
870            "one: no percentiles were requested, so there should be no rewards result"
871        );
872    }
873
874    /// Requesting all blocks should be ok
875    #[tokio::test]
876    async fn test_fee_history_all_blocks() {
877        let block_count = 10;
878        let newest_block = 1337;
879        let oldest_block = None;
880
881        let (eth_api, base_fees_per_gas, gas_used_ratios) =
882            prepare_eth_api(newest_block, oldest_block, block_count, MockEthProvider::default());
883
884        let fee_history =
885            eth_api.fee_history(U64::from(block_count), newest_block.into(), None).await.unwrap();
886
887        assert_eq!(
888            &fee_history.base_fee_per_gas, &base_fees_per_gas,
889            "all: base fee per gas is incorrect"
890        );
891        assert_eq!(
892            fee_history.base_fee_per_gas.len() as u64,
893            block_count + 1,
894            "all: should return base fee of the next block as well"
895        );
896        assert_eq!(
897            &fee_history.gas_used_ratio, &gas_used_ratios,
898            "all: gas used ratio is incorrect"
899        );
900        assert_eq!(
901            fee_history.oldest_block,
902            newest_block - block_count + 1,
903            "all: oldest block is incorrect"
904        );
905        assert!(
906            fee_history.reward.is_none(),
907            "all: no percentiles were requested, so there should be no rewards result"
908        );
909    }
910}