Skip to main content

reth_rpc/eth/
builder.rs

1//! `EthApiBuilder` implementation
2
3use crate::{eth::core::EthApiInner, EthApi};
4use alloy_network::Ethereum;
5use reth_chain_state::CanonStateSubscriptions;
6use reth_chainspec::ChainSpecProvider;
7use reth_evm::SenderRecoveryCache;
8use reth_primitives_traits::HeaderTy;
9use reth_rpc_convert::{RpcConvert, RpcConverter};
10use reth_rpc_eth_api::{
11    helpers::pending_block::PendingEnvBuilder, node::RpcNodeCoreAdapter, RpcNodeCore,
12};
13use reth_rpc_eth_types::{
14    builder::config::PendingBlockKind, fee_history::fee_history_cache_new_blocks_task,
15    receipt::EthReceiptConverter, EthApiSettings, EthStateCache, EthStateCacheConfig,
16    FeeHistoryCache, FeeHistoryCacheConfig, ForwardConfig, GasCap, GasPriceOracle,
17    GasPriceOracleConfig,
18};
19use reth_rpc_server_types::constants::{
20    DEFAULT_ETH_PROOF_WINDOW, DEFAULT_MAX_BLOCKING_IO_REQUEST, DEFAULT_MAX_SIMULATE_BLOCKS,
21    DEFAULT_PROOF_PERMITS,
22};
23use reth_tasks::{pool::BlockingTaskPool, Runtime};
24use std::{sync::Arc, time::Duration};
25
26/// A helper to build the `EthApi` handler instance.
27///
28/// This builder type contains all settings to create an [`EthApiInner`] or an [`EthApi`] instance
29/// directly.
30#[derive(Debug)]
31pub struct EthApiBuilder<N: RpcNodeCore, Rpc, NextEnv = ()> {
32    components: N,
33    rpc_converter: Rpc,
34    gas_cap: GasCap,
35    max_simulate_blocks: u64,
36    max_trace_bytes: Option<usize>,
37    max_response_size: Option<usize>,
38    compute_state_root_for_eth_simulate: bool,
39    eth_proof_window: u64,
40    fee_history_cache_config: FeeHistoryCacheConfig,
41    proof_permits: usize,
42    eth_state_cache_config: EthStateCacheConfig,
43    eth_cache: Option<EthStateCache<N::Primitives>>,
44    gas_oracle_config: GasPriceOracleConfig,
45    gas_oracle: Option<GasPriceOracle<N::Provider>>,
46    blocking_task_pool: Option<BlockingTaskPool>,
47    /// Runtime used to spawn tasks. Defaults to [`Runtime::test`] when not configured.
48    task_spawner: Option<Runtime>,
49    next_env: NextEnv,
50    max_batch_size: usize,
51    max_blocking_io_requests: usize,
52    pending_block_kind: PendingBlockKind,
53    raw_tx_forwarder: ForwardConfig,
54    sender_recovery_cache: Option<SenderRecoveryCache>,
55    send_raw_transaction_sync_timeout: Duration,
56    evm_memory_limit: u64,
57    force_blob_sidecar_upcasting: bool,
58}
59
60impl<Provider, Pool, Network, EvmConfig, ChainSpec>
61    EthApiBuilder<
62        RpcNodeCoreAdapter<Provider, Pool, Network, EvmConfig>,
63        RpcConverter<Ethereum, EvmConfig, EthReceiptConverter<ChainSpec>>,
64    >
65where
66    RpcNodeCoreAdapter<Provider, Pool, Network, EvmConfig>:
67        RpcNodeCore<Provider: ChainSpecProvider<ChainSpec = ChainSpec>, Evm = EvmConfig>,
68{
69    /// Creates a new `EthApiBuilder` instance.
70    pub fn new(provider: Provider, pool: Pool, network: Network, evm_config: EvmConfig) -> Self {
71        Self::new_with_components(RpcNodeCoreAdapter::new(provider, pool, network, evm_config))
72    }
73}
74
75impl<N: RpcNodeCore, Rpc, NextEnv> EthApiBuilder<N, Rpc, NextEnv> {
76    /// Apply a function to the builder
77    pub fn apply<F>(self, f: F) -> Self
78    where
79        F: FnOnce(Self) -> Self,
80    {
81        f(self)
82    }
83
84    /// Converts the RPC converter type of this builder
85    pub fn map_converter<F, R>(self, f: F) -> EthApiBuilder<N, R, NextEnv>
86    where
87        F: FnOnce(Rpc) -> R,
88    {
89        let Self {
90            components,
91            rpc_converter,
92            gas_cap,
93            max_simulate_blocks,
94            max_trace_bytes,
95            max_response_size,
96            compute_state_root_for_eth_simulate,
97            eth_proof_window,
98            fee_history_cache_config,
99            proof_permits,
100            eth_state_cache_config,
101            eth_cache,
102            gas_oracle_config,
103            gas_oracle,
104            blocking_task_pool,
105            task_spawner,
106            next_env,
107            max_batch_size,
108            max_blocking_io_requests,
109            pending_block_kind,
110            raw_tx_forwarder,
111            sender_recovery_cache,
112            send_raw_transaction_sync_timeout,
113            evm_memory_limit,
114            force_blob_sidecar_upcasting,
115        } = self;
116        EthApiBuilder {
117            components,
118            rpc_converter: f(rpc_converter),
119            gas_cap,
120            max_simulate_blocks,
121            max_trace_bytes,
122            max_response_size,
123            compute_state_root_for_eth_simulate,
124            eth_proof_window,
125            fee_history_cache_config,
126            proof_permits,
127            eth_state_cache_config,
128            eth_cache,
129            gas_oracle_config,
130            gas_oracle,
131            blocking_task_pool,
132            task_spawner,
133            next_env,
134            max_batch_size,
135            max_blocking_io_requests,
136            pending_block_kind,
137            raw_tx_forwarder,
138            sender_recovery_cache,
139            send_raw_transaction_sync_timeout,
140            evm_memory_limit,
141            force_blob_sidecar_upcasting,
142        }
143    }
144}
145
146impl<N, ChainSpec> EthApiBuilder<N, RpcConverter<Ethereum, N::Evm, EthReceiptConverter<ChainSpec>>>
147where
148    N: RpcNodeCore<Provider: ChainSpecProvider<ChainSpec = ChainSpec>>,
149{
150    /// Creates a new `EthApiBuilder` instance with the provided components.
151    pub fn new_with_components(components: N) -> Self {
152        let rpc_converter =
153            RpcConverter::new(EthReceiptConverter::new(components.provider().chain_spec()));
154        Self {
155            components,
156            rpc_converter,
157            eth_cache: None,
158            gas_oracle: None,
159            gas_cap: GasCap::default(),
160            max_simulate_blocks: DEFAULT_MAX_SIMULATE_BLOCKS,
161            max_trace_bytes: None,
162            max_response_size: None,
163            compute_state_root_for_eth_simulate: false,
164            eth_proof_window: DEFAULT_ETH_PROOF_WINDOW,
165            blocking_task_pool: None,
166            fee_history_cache_config: FeeHistoryCacheConfig::default(),
167            proof_permits: DEFAULT_PROOF_PERMITS,
168            task_spawner: None,
169            gas_oracle_config: Default::default(),
170            eth_state_cache_config: Default::default(),
171            next_env: Default::default(),
172            max_batch_size: 1,
173            max_blocking_io_requests: DEFAULT_MAX_BLOCKING_IO_REQUEST,
174            pending_block_kind: PendingBlockKind::Full,
175            raw_tx_forwarder: ForwardConfig::default(),
176            sender_recovery_cache: None,
177            send_raw_transaction_sync_timeout: Duration::from_secs(30),
178            evm_memory_limit: 100 * 1024 * 1024,
179            force_blob_sidecar_upcasting: false,
180        }
181    }
182}
183
184impl<N, Rpc, NextEnv> EthApiBuilder<N, Rpc, NextEnv>
185where
186    N: RpcNodeCore,
187{
188    /// Configures the task spawner used to spawn additional tasks.
189    pub fn task_spawner(mut self, spawner: Runtime) -> Self {
190        self.task_spawner = Some(spawner);
191        self
192    }
193
194    /// Changes the configured converter.
195    pub fn with_rpc_converter<RpcNew>(
196        self,
197        rpc_converter: RpcNew,
198    ) -> EthApiBuilder<N, RpcNew, NextEnv> {
199        let Self {
200            components,
201            rpc_converter: _,
202            gas_cap,
203            max_simulate_blocks,
204            max_trace_bytes,
205            max_response_size,
206            compute_state_root_for_eth_simulate,
207            eth_proof_window,
208            fee_history_cache_config,
209            proof_permits,
210            eth_state_cache_config,
211            eth_cache,
212            gas_oracle,
213            blocking_task_pool,
214            task_spawner,
215            gas_oracle_config,
216            next_env,
217            max_batch_size,
218            max_blocking_io_requests,
219            pending_block_kind,
220            raw_tx_forwarder,
221            sender_recovery_cache,
222            send_raw_transaction_sync_timeout,
223            evm_memory_limit,
224            force_blob_sidecar_upcasting,
225        } = self;
226        EthApiBuilder {
227            components,
228            rpc_converter,
229            gas_cap,
230            max_simulate_blocks,
231            max_trace_bytes,
232            max_response_size,
233            compute_state_root_for_eth_simulate,
234            eth_proof_window,
235            fee_history_cache_config,
236            proof_permits,
237            eth_state_cache_config,
238            eth_cache,
239            gas_oracle,
240            blocking_task_pool,
241            task_spawner,
242            gas_oracle_config,
243            next_env,
244            max_batch_size,
245            max_blocking_io_requests,
246            pending_block_kind,
247            raw_tx_forwarder,
248            sender_recovery_cache,
249            send_raw_transaction_sync_timeout,
250            evm_memory_limit,
251            force_blob_sidecar_upcasting,
252        }
253    }
254
255    /// Changes the configured pending environment builder.
256    pub fn with_pending_env_builder<NextEnvNew>(
257        self,
258        next_env: NextEnvNew,
259    ) -> EthApiBuilder<N, Rpc, NextEnvNew> {
260        let Self {
261            components,
262            rpc_converter,
263            gas_cap,
264            max_simulate_blocks,
265            max_trace_bytes,
266            max_response_size,
267            compute_state_root_for_eth_simulate,
268            eth_proof_window,
269            fee_history_cache_config,
270            proof_permits,
271            eth_state_cache_config,
272            eth_cache,
273            gas_oracle,
274            blocking_task_pool,
275            task_spawner,
276            gas_oracle_config,
277            next_env: _,
278            max_batch_size,
279            max_blocking_io_requests,
280            pending_block_kind,
281            raw_tx_forwarder,
282            sender_recovery_cache,
283            send_raw_transaction_sync_timeout,
284            evm_memory_limit,
285            force_blob_sidecar_upcasting,
286        } = self;
287        EthApiBuilder {
288            components,
289            rpc_converter,
290            gas_cap,
291            max_simulate_blocks,
292            max_trace_bytes,
293            max_response_size,
294            compute_state_root_for_eth_simulate,
295            eth_proof_window,
296            fee_history_cache_config,
297            proof_permits,
298            eth_state_cache_config,
299            eth_cache,
300            gas_oracle,
301            blocking_task_pool,
302            task_spawner,
303            gas_oracle_config,
304            next_env,
305            max_batch_size,
306            max_blocking_io_requests,
307            pending_block_kind,
308            raw_tx_forwarder,
309            sender_recovery_cache,
310            send_raw_transaction_sync_timeout,
311            evm_memory_limit,
312            force_blob_sidecar_upcasting,
313        }
314    }
315
316    /// Sets `eth_cache` config for the cache that will be used if no [`EthStateCache`] is
317    /// configured.
318    pub const fn eth_state_cache_config(
319        mut self,
320        eth_state_cache_config: EthStateCacheConfig,
321    ) -> Self {
322        self.eth_state_cache_config = eth_state_cache_config;
323        self
324    }
325
326    /// Sets `eth_cache` instance
327    pub fn eth_cache(mut self, eth_cache: EthStateCache<N::Primitives>) -> Self {
328        self.eth_cache = Some(eth_cache);
329        self
330    }
331
332    /// Sets `gas_oracle` config for the gas oracle that will be used if no [`GasPriceOracle`] is
333    /// configured.
334    pub const fn gas_oracle_config(mut self, gas_oracle_config: GasPriceOracleConfig) -> Self {
335        self.gas_oracle_config = gas_oracle_config;
336        self
337    }
338
339    /// Sets `gas_oracle` instance
340    pub fn gas_oracle(mut self, gas_oracle: GasPriceOracle<N::Provider>) -> Self {
341        self.gas_oracle = Some(gas_oracle);
342        self
343    }
344
345    /// Sets the gas cap.
346    pub const fn gas_cap(mut self, gas_cap: GasCap) -> Self {
347        self.gas_cap = gas_cap;
348        self
349    }
350
351    /// Sets the maximum number of blocks for `eth_simulateV1`.
352    pub const fn max_simulate_blocks(mut self, max_simulate_blocks: u64) -> Self {
353        self.max_simulate_blocks = max_simulate_blocks;
354        self
355    }
356
357    /// Sets the maximum bytes a single traced transaction may record. `None` is unlimited.
358    pub const fn max_trace_bytes(mut self, max_trace_bytes: Option<usize>) -> Self {
359        self.max_trace_bytes = max_trace_bytes;
360        self
361    }
362
363    /// Sets the RPC server's response size limit in bytes, which bounds the struct logs of a
364    /// debug trace response. `None` is unlimited.
365    pub const fn max_response_size(mut self, max_response_size: Option<usize>) -> Self {
366        self.max_response_size = max_response_size;
367        self
368    }
369
370    /// Sets whether to compute state roots for `eth_simulateV1`.
371    pub const fn compute_state_root_for_eth_simulate(mut self, enabled: bool) -> Self {
372        self.compute_state_root_for_eth_simulate = enabled;
373        self
374    }
375
376    /// Sets the maximum number of blocks into the past for generating state proofs.
377    pub const fn eth_proof_window(mut self, eth_proof_window: u64) -> Self {
378        self.eth_proof_window = eth_proof_window;
379        self
380    }
381
382    /// Sets the blocking task pool.
383    pub fn blocking_task_pool(mut self, blocking_task_pool: BlockingTaskPool) -> Self {
384        self.blocking_task_pool = Some(blocking_task_pool);
385        self
386    }
387
388    /// Sets the fee history cache.
389    pub const fn fee_history_cache_config(
390        mut self,
391        fee_history_cache_config: FeeHistoryCacheConfig,
392    ) -> Self {
393        self.fee_history_cache_config = fee_history_cache_config;
394        self
395    }
396
397    /// Sets the proof permits.
398    pub const fn proof_permits(mut self, proof_permits: usize) -> Self {
399        self.proof_permits = proof_permits;
400        self
401    }
402
403    /// Sets the max batch size for batching transaction insertions.
404    pub const fn max_batch_size(mut self, max_batch_size: usize) -> Self {
405        self.max_batch_size = max_batch_size;
406        self
407    }
408
409    /// Sets the maximum number of concurrent blocking IO requests.
410    pub const fn max_blocking_io_requests(mut self, max_blocking_io_requests: usize) -> Self {
411        self.max_blocking_io_requests = max_blocking_io_requests;
412        self
413    }
414
415    /// Sets the pending block kind
416    pub const fn pending_block_kind(mut self, pending_block_kind: PendingBlockKind) -> Self {
417        self.pending_block_kind = pending_block_kind;
418        self
419    }
420
421    /// Sets the sender recovery cache shared with transaction ingress and execution.
422    pub fn sender_recovery_cache(mut self, cache: Option<SenderRecoveryCache>) -> Self {
423        self.sender_recovery_cache = cache;
424        self
425    }
426
427    /// Sets the raw transaction forwarder.
428    pub fn raw_tx_forwarder(mut self, tx_forwarder: ForwardConfig) -> Self {
429        self.raw_tx_forwarder = tx_forwarder;
430        self
431    }
432
433    /// Returns the gas cap.
434    pub const fn get_gas_cap(&self) -> &GasCap {
435        &self.gas_cap
436    }
437
438    /// Returns the maximum simulate blocks.
439    pub const fn get_max_simulate_blocks(&self) -> u64 {
440        self.max_simulate_blocks
441    }
442
443    /// Returns whether state roots are computed for `eth_simulateV1`.
444    pub const fn get_compute_state_root_for_eth_simulate(&self) -> bool {
445        self.compute_state_root_for_eth_simulate
446    }
447
448    /// Returns the ETH proof window.
449    pub const fn get_eth_proof_window(&self) -> u64 {
450        self.eth_proof_window
451    }
452
453    /// Returns a reference to the fee history cache config.
454    pub const fn get_fee_history_cache_config(&self) -> &FeeHistoryCacheConfig {
455        &self.fee_history_cache_config
456    }
457
458    /// Returns the proof permits.
459    pub const fn get_proof_permits(&self) -> usize {
460        self.proof_permits
461    }
462
463    /// Returns a reference to the ETH state cache config.
464    pub const fn get_eth_state_cache_config(&self) -> &EthStateCacheConfig {
465        &self.eth_state_cache_config
466    }
467
468    /// Returns a reference to the gas oracle config.
469    pub const fn get_gas_oracle_config(&self) -> &GasPriceOracleConfig {
470        &self.gas_oracle_config
471    }
472
473    /// Returns the max batch size.
474    pub const fn get_max_batch_size(&self) -> usize {
475        self.max_batch_size
476    }
477
478    /// Returns the pending block kind.
479    pub const fn get_pending_block_kind(&self) -> PendingBlockKind {
480        self.pending_block_kind
481    }
482
483    /// Returns a reference to the raw tx forwarder config.
484    pub const fn get_raw_tx_forwarder(&self) -> &ForwardConfig {
485        &self.raw_tx_forwarder
486    }
487
488    /// Returns a mutable reference to the fee history cache config.
489    pub const fn fee_history_cache_config_mut(&mut self) -> &mut FeeHistoryCacheConfig {
490        &mut self.fee_history_cache_config
491    }
492
493    /// Returns a mutable reference to the ETH state cache config.
494    pub const fn eth_state_cache_config_mut(&mut self) -> &mut EthStateCacheConfig {
495        &mut self.eth_state_cache_config
496    }
497
498    /// Returns a mutable reference to the gas oracle config.
499    pub const fn gas_oracle_config_mut(&mut self) -> &mut GasPriceOracleConfig {
500        &mut self.gas_oracle_config
501    }
502
503    /// Returns a mutable reference to the raw tx forwarder config.
504    pub const fn raw_tx_forwarder_mut(&mut self) -> &mut ForwardConfig {
505        &mut self.raw_tx_forwarder
506    }
507
508    /// Modifies the fee history cache configuration using a closure.
509    pub fn modify_fee_history_cache_config<F>(mut self, f: F) -> Self
510    where
511        F: FnOnce(&mut FeeHistoryCacheConfig),
512    {
513        f(&mut self.fee_history_cache_config);
514        self
515    }
516
517    /// Modifies the ETH state cache configuration using a closure.
518    pub fn modify_eth_state_cache_config<F>(mut self, f: F) -> Self
519    where
520        F: FnOnce(&mut EthStateCacheConfig),
521    {
522        f(&mut self.eth_state_cache_config);
523        self
524    }
525
526    /// Modifies the gas oracle configuration using a closure.
527    pub fn modify_gas_oracle_config<F>(mut self, f: F) -> Self
528    where
529        F: FnOnce(&mut GasPriceOracleConfig),
530    {
531        f(&mut self.gas_oracle_config);
532        self
533    }
534
535    /// Modifies the raw tx forwarder configuration using a closure.
536    pub fn modify_raw_tx_forwarder<F>(mut self, f: F) -> Self
537    where
538        F: FnOnce(&mut ForwardConfig),
539    {
540        f(&mut self.raw_tx_forwarder);
541        self
542    }
543
544    /// Builds the [`EthApiInner`] instance.
545    ///
546    /// If not configured, this will spawn the cache backend: [`EthStateCache::spawn_with`].
547    ///
548    /// # Panics
549    ///
550    /// This function panics if the blocking task pool cannot be built.
551    /// This will panic if called outside the context of a Tokio runtime.
552    pub fn build_inner(self) -> EthApiInner<N, Rpc>
553    where
554        Rpc: RpcConvert,
555        NextEnv: PendingEnvBuilder<N::Evm>,
556    {
557        let Self {
558            components,
559            rpc_converter,
560            eth_state_cache_config,
561            gas_oracle_config,
562            eth_cache,
563            gas_oracle,
564            gas_cap,
565            max_simulate_blocks,
566            max_trace_bytes,
567            max_response_size,
568            compute_state_root_for_eth_simulate,
569            eth_proof_window,
570            blocking_task_pool,
571            fee_history_cache_config,
572            proof_permits,
573            task_spawner,
574            next_env,
575            max_batch_size,
576            max_blocking_io_requests,
577            pending_block_kind,
578            raw_tx_forwarder,
579            sender_recovery_cache,
580            send_raw_transaction_sync_timeout,
581            evm_memory_limit,
582            force_blob_sidecar_upcasting,
583        } = self;
584
585        let provider = components.provider().clone();
586        let task_spawner = task_spawner.unwrap_or_else(Runtime::test);
587
588        let eth_cache = eth_cache.unwrap_or_else(|| {
589            EthStateCache::spawn_with(
590                provider.clone(),
591                eth_state_cache_config,
592                task_spawner.clone(),
593            )
594        });
595        let gas_oracle = gas_oracle.unwrap_or_else(|| {
596            GasPriceOracle::new(provider.clone(), gas_oracle_config, eth_cache.clone())
597        });
598        let fee_history_cache =
599            FeeHistoryCache::<HeaderTy<N::Primitives>>::new(fee_history_cache_config);
600        let new_canonical_blocks = provider.canonical_state_stream();
601        let fhc = fee_history_cache.clone();
602        let cache = eth_cache.clone();
603        task_spawner.spawn_critical_task(
604            "cache canonical blocks for fee history task",
605            async move {
606                fee_history_cache_new_blocks_task(fhc, new_canonical_blocks, provider, cache).await;
607            },
608        );
609
610        let settings = EthApiSettings {
611            sender_recovery_cache,
612            proof_permits,
613            max_batch_size,
614            max_blocking_io_requests,
615            cache_computed_bals: eth_state_cache_config.cache_computed_bals ||
616                eth_state_cache_config.prewarm_bals.is_some(),
617            gas_cap: gas_cap.into(),
618            max_simulate_blocks,
619            max_trace_bytes,
620            max_response_size,
621            compute_state_root_for_eth_simulate,
622            eth_proof_window,
623            pending_block_kind,
624            send_raw_transaction_sync_timeout,
625            evm_memory_limit,
626            force_blob_sidecar_upcasting,
627        };
628
629        EthApiInner::new(
630            components,
631            eth_cache,
632            gas_oracle,
633            settings,
634            blocking_task_pool.unwrap_or_else(|| {
635                BlockingTaskPool::builder()
636                    .thread_name(|i| format!("blocking-{i:02}"))
637                    .build()
638                    .map(BlockingTaskPool::new)
639                    .expect("failed to build blocking task pool")
640            }),
641            fee_history_cache,
642            task_spawner,
643            rpc_converter,
644            next_env,
645            raw_tx_forwarder.forwarder_client(),
646        )
647    }
648
649    /// Builds the [`EthApi`] instance.
650    ///
651    /// If not configured, this will spawn the cache backend: [`EthStateCache::spawn_with`].
652    ///
653    /// # Panics
654    ///
655    /// This function panics if the blocking task pool cannot be built.
656    /// This will panic if called outside the context of a Tokio runtime.
657    pub fn build(self) -> EthApi<N, Rpc>
658    where
659        Rpc: RpcConvert,
660        NextEnv: PendingEnvBuilder<N::Evm>,
661    {
662        EthApi { inner: Arc::new(self.build_inner()) }
663    }
664
665    /// Sets the timeout for `send_raw_transaction_sync` RPC method.
666    pub const fn send_raw_transaction_sync_timeout(mut self, timeout: Duration) -> Self {
667        self.send_raw_transaction_sync_timeout = timeout;
668        self
669    }
670
671    /// Sets the maximum memory the EVM can allocate per call frame in an RPC request.
672    pub const fn evm_memory_limit(mut self, memory_limit: u64) -> Self {
673        self.evm_memory_limit = memory_limit;
674        self
675    }
676
677    /// Sets whether to force upcasting EIP-4844 blob sidecars to EIP-7594 format.
678    pub const fn force_blob_sidecar_upcasting(mut self, force: bool) -> Self {
679        self.force_blob_sidecar_upcasting = force;
680        self
681    }
682}