1use 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
40pub type EthRpcConverterFor<N, NetworkT = Ethereum> = RpcConverter<
42 NetworkT,
43 <N as FullNodeComponents>::Evm,
44 EthReceiptConverter<<<N as FullNodeTypes>::Provider as ChainSpecProvider>::ChainSpec>,
45>;
46
47pub type EthApiFor<N, NetworkT = Ethereum> = EthApi<N, EthRpcConverterFor<N, NetworkT>>;
49
50pub type EthApiBuilderFor<N, NetworkT = Ethereum> =
52 EthApiBuilder<N, EthRpcConverterFor<N, NetworkT>>;
53
54#[derive(Deref)]
69pub struct EthApi<N: RpcNodeCore, Rpc: RpcConvert> {
70 #[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 #[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#[expect(missing_debug_implementations)]
226pub struct EthApiInner<N: RpcNodeCore, Rpc: RpcConvert> {
227 components: N,
229 signers: SignersForRpc<N::Provider, Rpc::Network>,
231 eth_cache: EthStateCache<N::Primitives>,
233 gas_oracle: GasPriceOracle<N::Provider>,
235 gas_cap: u64,
237 max_simulate_blocks: u64,
239 eth_proof_window: u64,
241 starting_block: U256,
243 task_spawner: Runtime,
245 pending_block: Mutex<Option<PendingBlock<N::Primitives>>>,
247 blocking_task_pool: BlockingTaskPool,
249 fee_history_cache: FeeHistoryCache<ProviderHeader<N::Provider>>,
251
252 blocking_task_guard: BlockingTaskGuard,
254
255 blocking_io_request_semaphore: Arc<Semaphore>,
257
258 raw_tx_sender: broadcast::Sender<Bytes>,
260
261 raw_tx_forwarder: Option<RpcClient>,
263
264 converter: Rpc,
266
267 next_env_builder: Box<dyn PendingEnvBuilder<N::Evm>>,
269
270 tx_batch_sender:
272 mpsc::UnboundedSender<BatchTxRequest<<N::Pool as TransactionPool>::Transaction>>,
273
274 pending_block_kind: PendingBlockKind,
276
277 send_raw_transaction_sync_timeout: Duration,
279
280 blob_sidecar_converter: BlobSidecarConverter,
282
283 evm_memory_limit: u64,
285
286 force_blob_sidecar_upcasting: bool,
288}
289
290impl<N, Rpc> EthApiInner<N, Rpc>
291where
292 N: RpcNodeCore,
293 Rpc: RpcConvert,
294{
295 #[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 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 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 #[inline]
373 pub fn provider(&self) -> &N::Provider {
374 self.components.provider()
375 }
376
377 #[inline]
379 pub const fn converter(&self) -> &Rpc {
380 &self.converter
381 }
382
383 #[inline]
385 pub const fn cache(&self) -> &EthStateCache<N::Primitives> {
386 &self.eth_cache
387 }
388
389 #[inline]
391 pub const fn pending_block(&self) -> &Mutex<Option<PendingBlock<N::Primitives>>> {
392 &self.pending_block
393 }
394
395 #[inline]
398 pub const fn pending_env_builder(&self) -> &dyn PendingEnvBuilder<N::Evm> {
399 &*self.next_env_builder
400 }
401
402 #[inline]
404 pub const fn task_spawner(&self) -> &Runtime {
405 &self.task_spawner
406 }
407
408 #[inline]
412 pub const fn blocking_task_pool(&self) -> &BlockingTaskPool {
413 &self.blocking_task_pool
414 }
415
416 #[inline]
418 pub fn evm_config(&self) -> &N::Evm {
419 self.components.evm_config()
420 }
421
422 #[inline]
424 pub fn pool(&self) -> &N::Pool {
425 self.components.pool()
426 }
427
428 #[inline]
430 pub const fn gas_cap(&self) -> u64 {
431 self.gas_cap
432 }
433
434 #[inline]
436 pub const fn max_simulate_blocks(&self) -> u64 {
437 self.max_simulate_blocks
438 }
439
440 #[inline]
442 pub const fn gas_oracle(&self) -> &GasPriceOracle<N::Provider> {
443 &self.gas_oracle
444 }
445
446 #[inline]
448 pub const fn fee_history_cache(&self) -> &FeeHistoryCache<ProviderHeader<N::Provider>> {
449 &self.fee_history_cache
450 }
451
452 #[inline]
454 pub const fn signers(&self) -> &SignersForRpc<N::Provider, Rpc::Network> {
455 &self.signers
456 }
457
458 #[inline]
460 pub const fn starting_block(&self) -> U256 {
461 self.starting_block
462 }
463
464 #[inline]
466 pub fn network(&self) -> &N::Network {
467 self.components.network()
468 }
469
470 #[inline]
472 pub const fn eth_proof_window(&self) -> u64 {
473 self.eth_proof_window
474 }
475
476 #[inline]
478 pub const fn blocking_task_guard(&self) -> &BlockingTaskGuard {
479 &self.blocking_task_guard
480 }
481
482 #[inline]
484 pub fn subscribe_to_raw_transactions(&self) -> broadcast::Receiver<Bytes> {
485 self.raw_tx_sender.subscribe()
486 }
487
488 #[inline]
490 pub fn broadcast_raw_transaction(&self, raw_tx: Bytes) {
491 let _ = self.raw_tx_sender.send(raw_tx);
492 }
493
494 #[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 #[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 #[inline]
521 pub const fn pending_block_kind(&self) -> PendingBlockKind {
522 self.pending_block_kind
523 }
524
525 #[inline]
527 pub const fn raw_tx_forwarder(&self) -> Option<&RpcClient> {
528 self.raw_tx_forwarder.as_ref()
529 }
530
531 #[inline]
533 pub const fn send_raw_transaction_sync_timeout(&self) -> Duration {
534 self.send_raw_transaction_sync_timeout
535 }
536
537 #[inline]
539 pub const fn blob_sidecar_converter(&self) -> &BlobSidecarConverter {
540 &self.blob_sidecar_converter
541 }
542
543 #[inline]
545 pub const fn evm_memory_limit(&self) -> u64 {
546 self.evm_memory_limit
547 }
548
549 #[inline]
551 pub const fn blocking_io_request_semaphore(&self) -> &Arc<Semaphore> {
552 &self.blocking_io_request_semaphore
553 }
554
555 #[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 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 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 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 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 #[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 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 ð_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 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 ð_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 ð_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 ð_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 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 ð_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 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 #[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}