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::{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            + Unpin
603            + Clone
604            + 'static,
605    >(
606        provider: P,
607    ) -> FakeEthApi<P> {
608        EthApiBuilder::new(
609            provider.clone(),
610            testing_pool(),
611            NoopNetwork::default(),
612            EthEvmConfig::new(provider.chain_spec()),
613        )
614        .build()
615    }
616
617    // Function to prepare the EthApi with mock data
618    fn prepare_eth_api(
619        newest_block: u64,
620        mut oldest_block: Option<B256>,
621        block_count: u64,
622        mock_provider: MockEthProvider,
623    ) -> (FakeEthApi, Vec<u128>, Vec<f64>) {
624        let mut rng = generators::rng();
625
626        // Build mock data
627        let mut gas_used_ratios = Vec::with_capacity(block_count as usize);
628        let mut base_fees_per_gas = Vec::with_capacity(block_count as usize);
629        let mut last_header = None;
630        let mut parent_hash = B256::default();
631
632        for i in (0..block_count).rev() {
633            let hash = rng.random();
634            // Note: Generates saner values to avoid invalid overflows later
635            let gas_limit = rng.random::<u32>() as u64;
636            let base_fee_per_gas: Option<u64> =
637                rng.random::<bool>().then(|| rng.random::<u32>() as u64);
638            let gas_used = rng.random::<u32>() as u64;
639
640            let header = Header {
641                number: newest_block - i,
642                gas_limit,
643                gas_used,
644                base_fee_per_gas,
645                parent_hash,
646                ..Default::default()
647            };
648            last_header = Some(header.clone());
649            parent_hash = hash;
650
651            const TOTAL_TRANSACTIONS: usize = 100;
652            let mut transactions = Vec::with_capacity(TOTAL_TRANSACTIONS);
653            for _ in 0..TOTAL_TRANSACTIONS {
654                let random_fee: u128 = rng.random();
655
656                if let Some(base_fee_per_gas) = header.base_fee_per_gas {
657                    let transaction = TransactionSigned::new_unhashed(
658                        reth_ethereum_primitives::Transaction::Eip1559(
659                            alloy_consensus::TxEip1559 {
660                                max_priority_fee_per_gas: random_fee,
661                                max_fee_per_gas: random_fee + base_fee_per_gas as u128,
662                                ..Default::default()
663                            },
664                        ),
665                        Signature::test_signature(),
666                    );
667
668                    transactions.push(transaction);
669                } else {
670                    let transaction = TransactionSigned::new_unhashed(
671                        reth_ethereum_primitives::Transaction::Legacy(Default::default()),
672                        Signature::test_signature(),
673                    );
674
675                    transactions.push(transaction);
676                }
677            }
678
679            mock_provider.add_block(
680                hash,
681                Block {
682                    header: header.clone(),
683                    body: BlockBody { transactions, ..Default::default() },
684                },
685            );
686            mock_provider.add_header(hash, header);
687
688            oldest_block.get_or_insert(hash);
689            gas_used_ratios.push(gas_used as f64 / gas_limit as f64);
690            base_fees_per_gas.push(base_fee_per_gas.map(|fee| fee as u128).unwrap_or_default());
691        }
692
693        // Add final base fee (for the next block outside of the request)
694        let last_header = last_header.unwrap();
695        let spec = mock_provider.chain_spec();
696        base_fees_per_gas.push(
697            spec.next_block_base_fee(&last_header, last_header.timestamp).unwrap_or_default()
698                as u128,
699        );
700
701        let eth_api = build_test_eth_api(mock_provider);
702
703        (eth_api, base_fees_per_gas, gas_used_ratios)
704    }
705
706    /// Invalid block range
707    #[tokio::test]
708    async fn test_fee_history_empty() {
709        let response = <EthApi<_, _> as EthApiServer<_, _, _, _, _, _>>::fee_history(
710            &build_test_eth_api(NoopProvider::default()),
711            U64::from(1),
712            BlockNumberOrTag::Latest,
713            None,
714        )
715        .await;
716        assert!(response.is_err());
717        let error_object = response.unwrap_err();
718        assert_eq!(error_object.code(), INVALID_PARAMS_CODE);
719    }
720
721    #[tokio::test]
722    /// Invalid block range (request is before genesis)
723    async fn test_fee_history_invalid_block_range_before_genesis() {
724        let block_count = 10;
725        let newest_block = 1337;
726        let oldest_block = None;
727
728        let (eth_api, _, _) =
729            prepare_eth_api(newest_block, oldest_block, block_count, MockEthProvider::default());
730
731        let response = <EthApi<_, _> as EthApiServer<_, _, _, _, _, _>>::fee_history(
732            &eth_api,
733            U64::from(newest_block + 1),
734            newest_block.into(),
735            Some(vec![10.0]),
736        )
737        .await;
738
739        assert!(response.is_err());
740        let error_object = response.unwrap_err();
741        assert_eq!(error_object.code(), INVALID_PARAMS_CODE);
742    }
743
744    #[tokio::test]
745    /// Invalid block range (request is in the future)
746    async fn test_fee_history_invalid_block_range_in_future() {
747        let block_count = 10;
748        let newest_block = 1337;
749        let oldest_block = None;
750
751        let (eth_api, _, _) =
752            prepare_eth_api(newest_block, oldest_block, block_count, MockEthProvider::default());
753
754        let response = <EthApi<_, _> as EthApiServer<_, _, _, _, _, _>>::fee_history(
755            &eth_api,
756            U64::from(1),
757            (newest_block + 1000).into(),
758            Some(vec![10.0]),
759        )
760        .await;
761
762        assert!(response.is_err());
763        let error_object = response.unwrap_err();
764        assert_eq!(error_object.code(), INVALID_PARAMS_CODE);
765    }
766
767    #[tokio::test]
768    async fn test_call_many_maps_provider_block_lookup_error_with_eth_api_conversion() {
769        let eth_api = build_test_eth_api(MockEthProvider::default());
770        let bundles = vec![Bundle {
771            transactions: vec![TransactionRequest::default()],
772            block_override: None,
773        }];
774
775        let response = <EthApi<_, _> as EthApiServer<_, _, _, _, _, _>>::call_many(
776            &eth_api, bundles, None, None,
777        )
778        .await;
779
780        let err = response.expect_err("call_many should fail when latest block lookup errors");
781        let message = err.message().to_ascii_lowercase();
782        assert!(
783            message.contains("block not found"),
784            "best block lookup should map via EthApiError::from(ProviderError): {message}"
785        );
786        assert!(
787            !message.contains("best block does not exist"),
788            "provider implementation detail should not leak from converted error: {message}"
789        );
790    }
791
792    #[tokio::test]
793    async fn test_call_many_keeps_header_not_found_when_block_hash_absent() {
794        let eth_api = build_test_eth_api(NoopProvider::default());
795        let bundles = vec![Bundle {
796            transactions: vec![TransactionRequest::default()],
797            block_override: None,
798        }];
799
800        let response = <EthApi<_, _> as EthApiServer<_, _, _, _, _, _>>::call_many(
801            &eth_api, bundles, None, None,
802        )
803        .await;
804
805        let err =
806            response.expect_err("call_many should fail when latest block hash is unavailable");
807        let message = err.message().to_ascii_lowercase();
808        assert!(
809            message.contains("block not found"),
810            "missing block hash should still map to block-not-found: {message}"
811        );
812    }
813
814    #[tokio::test]
815    /// Requesting no block should result in a default response
816    async fn test_fee_history_no_block_requested() {
817        let block_count = 10;
818        let newest_block = 1337;
819        let oldest_block = None;
820
821        let (eth_api, _, _) =
822            prepare_eth_api(newest_block, oldest_block, block_count, MockEthProvider::default());
823
824        let response = <EthApi<_, _> as EthApiServer<_, _, _, _, _, _>>::fee_history(
825            &eth_api,
826            U64::from(0),
827            newest_block.into(),
828            None,
829        )
830        .await
831        .unwrap();
832        assert_eq!(
833            response,
834            FeeHistory::default(),
835            "none: requesting no block should yield a default response"
836        );
837    }
838
839    #[tokio::test]
840    /// Requesting a single block should return 1 block (+ base fee for the next block over)
841    async fn test_fee_history_single_block() {
842        let block_count = 10;
843        let newest_block = 1337;
844        let oldest_block = None;
845
846        let (eth_api, base_fees_per_gas, gas_used_ratios) =
847            prepare_eth_api(newest_block, oldest_block, block_count, MockEthProvider::default());
848
849        let fee_history =
850            eth_api.fee_history(U64::from(1), newest_block.into(), None).await.unwrap();
851        assert_eq!(
852            fee_history.base_fee_per_gas,
853            &base_fees_per_gas[base_fees_per_gas.len() - 2..],
854            "one: base fee per gas is incorrect"
855        );
856        assert_eq!(
857            fee_history.base_fee_per_gas.len(),
858            2,
859            "one: should return base fee of the next block as well"
860        );
861        assert_eq!(
862            &fee_history.gas_used_ratio,
863            &gas_used_ratios[gas_used_ratios.len() - 1..],
864            "one: gas used ratio is incorrect"
865        );
866        assert_eq!(fee_history.oldest_block, newest_block, "one: oldest block is incorrect");
867        assert!(
868            fee_history.reward.is_none(),
869            "one: no percentiles were requested, so there should be no rewards result"
870        );
871    }
872
873    /// Requesting all blocks should be ok
874    #[tokio::test]
875    async fn test_fee_history_all_blocks() {
876        let block_count = 10;
877        let newest_block = 1337;
878        let oldest_block = None;
879
880        let (eth_api, base_fees_per_gas, gas_used_ratios) =
881            prepare_eth_api(newest_block, oldest_block, block_count, MockEthProvider::default());
882
883        let fee_history =
884            eth_api.fee_history(U64::from(block_count), newest_block.into(), None).await.unwrap();
885
886        assert_eq!(
887            &fee_history.base_fee_per_gas, &base_fees_per_gas,
888            "all: base fee per gas is incorrect"
889        );
890        assert_eq!(
891            fee_history.base_fee_per_gas.len() as u64,
892            block_count + 1,
893            "all: should return base fee of the next block as well"
894        );
895        assert_eq!(
896            &fee_history.gas_used_ratio, &gas_used_ratios,
897            "all: gas used ratio is incorrect"
898        );
899        assert_eq!(
900            fee_history.oldest_block,
901            newest_block - block_count + 1,
902            "all: oldest block is incorrect"
903        );
904        assert!(
905            fee_history.reward.is_none(),
906            "all: no percentiles were requested, so there should be no rewards result"
907        );
908    }
909}