Skip to main content

reth_rpc_eth_api/helpers/
call.rs

1//! Loads a pending block from database. Helper trait for `eth_` transaction, call and trace RPC
2//! methods.
3
4use super::{LoadBlock, LoadPendingBlock, LoadState, LoadTransaction, SpawnBlocking, Trace};
5use crate::{helpers::estimate::EstimateCall, FromEvmError, FullEthApiTypes, RpcBlock};
6use alloy_consensus::{transaction::Transaction, BlockHeader};
7use alloy_eip7928::BlockAccessIndex;
8use alloy_eips::{
9    eip1559::calc_effective_gas_price, eip2718::Typed2718, eip2930::AccessListResult,
10};
11use alloy_network::TransactionBuilder;
12use alloy_primitives::{Bytes, B256, U256};
13use alloy_rpc_types_eth::{
14    simulate::{SimBlock, SimulatePayload, SimulatedBlock},
15    state::{EvmOverrides, StateOverride},
16    BlockId, Bundle, EthCallResponse, StateContext, TransactionInfo,
17};
18use evm2::evm::{CacheDB, DynDatabase};
19use evm2_inspectors::{access_list::AccessListInspector, transfer::TransferInspector};
20use futures::Future;
21use reth_chainspec::{ChainSpecProvider, EthChainSpec, EthereumHardforks};
22use reth_errors::{ProviderError, RethError};
23use reth_evm::{
24    database::StateProviderDatabase,
25    execute::{BlockBuilder, BlockExecutor, BlockExecutorFactory, BlockTransactionResult},
26    BlockExecutorFor, BundleState, ConfigureEvm, Database, Evm, EvmEnv, EvmEnvFor, EvmTypesFor,
27    TransactionEnvMut, TxEnvFor, TxResultWithStateFor,
28};
29use reth_execution_types::BundleSource;
30use reth_primitives_traits::{BlockBody, BlockTy, Recovered, RecoveredBlock};
31use reth_rpc_convert::{RpcConvert, RpcTxReq};
32use reth_rpc_eth_types::{
33    cache::db::{
34        apply_block_overrides, apply_state_overrides, apply_state_overrides_with_state,
35        attach_bal_before_tx,
36    },
37    error::{AsEthApiError, FromEthApiError},
38    simulate::{self, EthSimulateError, SimulatedState},
39    utils::CallManyBudget,
40    EthApiError, RpcInvalidTransactionError, StateCacheDb,
41};
42use reth_storage_api::{BlockIdReader, ProviderTx, StateProvider};
43use reth_tasks::cancel::is_cancelled;
44use std::fmt;
45use tracing::{debug, trace};
46
47/// Result type for `eth_simulateV1` RPC method.
48pub type SimulatedBlocksResult<N, E> = Result<Vec<SimulatedBlock<RpcBlock<N>>>, E>;
49
50/// Execution related functions for the [`EthApiServer`](crate::EthApiServer) trait in
51/// the `eth_` namespace.
52pub trait EthCall: EstimateCall + LoadBlock + FullEthApiTypes {
53    /// Estimate gas needed for execution of the `request` at the [`BlockId`].
54    fn estimate_gas_at(
55        &self,
56        request: RpcTxReq<<Self::RpcConvert as RpcConvert>::Network>,
57        at: BlockId,
58        overrides: EvmOverrides,
59    ) -> impl Future<Output = Result<U256, Self::Error>> + Send {
60        EstimateCall::estimate_gas_at(self, request, at, overrides)
61    }
62
63    /// `eth_simulateV1` executes an arbitrary number of transactions on top of the requested state.
64    /// The transactions are packed into individual blocks. Overrides can be provided.
65    ///
66    /// See also: <https://github.com/ethereum/go-ethereum/pull/27720>
67    fn simulate_v1(
68        &self,
69        payload: SimulatePayload<RpcTxReq<<Self::RpcConvert as RpcConvert>::Network>>,
70        block: Option<BlockId>,
71    ) -> impl Future<Output = SimulatedBlocksResult<Self::NetworkTypes, Self::Error>> + Send {
72        async move {
73            if payload.block_state_calls.len() > self.max_simulate_blocks() as usize {
74                return Err(EthApiError::other(EthSimulateError::TooManyBlocks).into())
75            }
76
77            let block = block.unwrap_or_default();
78
79            let SimulatePayload {
80                block_state_calls,
81                trace_transfers,
82                validation,
83                return_full_transactions,
84            } = payload;
85
86            if block_state_calls.is_empty() {
87                return Err(EthApiError::InvalidParams(String::from("calls are empty.")).into())
88            }
89
90            let permit = self
91                .acquire_owned_blocking_io()
92                .await
93                .map_err(|_| EthApiError::InternalEthError)?;
94
95            let base_block = self
96                .recovered_block(block)
97                .await?
98                .ok_or_else(|| EthApiError::other(EthSimulateError::BlockNotFound { block }))?;
99            let parent = base_block.sealed_header().clone();
100            let max_simulate_blocks = self.max_simulate_blocks();
101            // Load the state of the block resolved above: resolving a tag such as `latest` again
102            // could return a newer block than `parent`.
103            let state_at = if block.is_pending() { block } else { parent.hash().into() };
104
105            self.spawn_with_state_at_block(state_at, move |this, db| {
106                let _permit = permit;
107                let state_provider = db.db.into_inner().into_inner().0;
108                let mut db = CacheDB::new(evm2::evm::Db::new(StateProviderDatabase::new(
109                    (&state_provider).into_evm_state_provider(),
110                )));
111                let mut parent = parent;
112                let mut simulation_state =
113                    this.compute_state_root_for_eth_simulate().then(SimulatedState::default);
114
115                let chain_id = this.provider().chain_spec().chain_id();
116
117                // Validate block ordering and fill gaps with empty blocks so every entry has an
118                // explicit `number` and `time` override and the chain is contiguous (see the
119                // execution-apis spec note: "If the block number is increased more than 1 compared
120                // to the previous block, new empty blocks are generated in between.").
121                let block_state_calls = simulate::sanitize_chain(
122                    block_state_calls,
123                    &parent,
124                    chain_id,
125                    max_simulate_blocks,
126                )?;
127
128                let mut blocks: Vec<SimulatedBlock<RpcBlock<Self::NetworkTypes>>> =
129                    Vec::with_capacity(block_state_calls.len());
130
131                let call_gas_limit = this.call_gas_limit();
132                let mut remaining_call_gas_limit = (call_gas_limit > 0).then_some(call_gas_limit);
133
134                for block in block_state_calls {
135                    let SimBlock { block_overrides, state_overrides, calls } = block;
136
137                    let attributes = this
138                        .pending_env_builder()
139                        .pending_env_attributes(&parent, block_overrides.as_ref())
140                        .map_err(Self::Error::from_eth_err)?;
141
142                    let mut evm_env = this
143                        .evm_config()
144                        .next_evm_env(&parent, &attributes)
145                        .map_err(RethError::other)
146                        .map_err(Self::Error::from_eth_err)?;
147
148                    // Always disable EIP-3607
149                    evm_env.version_mut().features.remove(evm2::EvmFeatures::EIP3607);
150
151                    // EIP-7825's transaction gas cap is only active with Amsterdam's
152                    // regular/state-gas accounting, and only in validation mode. Without
153                    // validation the whole gas limit is execution gas.
154                    if !validation || !evm_env.version().feature(evm2::EvmFeatures::EIP8037) {
155                        evm_env.version_mut().tx_gas_limit_cap = u64::MAX;
156                    }
157                    // The EIP-8037 total transaction gas cap applies in neither mode, see
158                    // <https://github.com/ethereum/execution-apis/blob/main/docs-api/docs/ethsimulatev1-notes.mdx>.
159                    evm_env.version_mut().tx_total_gas_cap = u64::MAX;
160
161                    if !validation {
162                        // If not explicitly required, we disable nonce check <https://github.com/paradigmxyz/reth/issues/16108>
163                        evm_env.version_mut().features.remove(evm2::EvmFeatures::NONCE_CHECK);
164                        evm_env.version_mut().features.remove(evm2::EvmFeatures::BASE_FEE_CHECK);
165                        evm_env.block_env_mut().basefee = U256::ZERO;
166                        // The spec zeroes the blob base fee without validation, so a default
167                        // `maxFeePerBlobGas` of 0 passes the cap check and no blob fee is charged.
168                        evm_env.block_env_mut().blob_basefee = U256::ZERO;
169                    }
170
171                    // Set prevrandao to zero for simulated blocks by default,
172                    // matching spec behavior where MixDigest is zero-initialized.
173                    // If user provides an override, it will be applied by apply_block_overrides.
174                    evm_env.block_env_mut().prevrandao = U256::ZERO;
175                    if !this
176                        .provider()
177                        .chain_spec()
178                        .is_paris_active_at_block(evm_env.block_env().number.to())
179                    {
180                        evm_env.block_env_mut().difficulty = parent.difficulty();
181                    }
182
183                    if let Some(block_overrides) = block_overrides {
184                        // ensure we don't allow uncapped gas limit per block
185                        if let Some(gas_limit_override) = block_overrides.gas_limit &&
186                            gas_limit_override > evm_env.block_env().gas_limit.to::<u64>() &&
187                            gas_limit_override > this.call_gas_limit()
188                        {
189                            return Err(EthApiError::other(EthSimulateError::GasLimitReached).into())
190                        }
191                        apply_block_overrides(block_overrides, &mut db, &mut evm_env);
192                    }
193                    if let Some(ref state_overrides) = state_overrides {
194                        let mut changes = simulation_state.as_ref().map(|_| BundleState::default());
195                        apply_state_overrides_with_state(
196                            state_overrides.clone(),
197                            &mut db,
198                            changes.as_mut(),
199                        )
200                        .map_err(Self::Error::from_eth_err)?;
201                        if let Some(simulation_state) = simulation_state.as_mut() &&
202                            let Some(changes) = changes
203                        {
204                            simulation_state
205                                .extend(&state_provider, &changes)
206                                .map_err(Self::Error::from_eth_err)?;
207                        }
208                    }
209
210                    let chain_id = evm_env.chain_id();
211                    let build_bal = this.provider().chain_spec().is_amsterdam_active_at_timestamp(
212                        evm_env.block_env().timestamp.to::<u64>(),
213                    );
214
215                    let ctx = this
216                        .evm_config()
217                        .context_for_next_block(&parent, attributes)
218                        .map_err(RethError::other)
219                        .map_err(Self::Error::from_eth_err)?;
220                    let map_err = |e: EthApiError| -> Self::Error {
221                        match e.as_simulate_error() {
222                            Some(sim_err) => Self::Error::from_eth_err(EthApiError::other(sim_err)),
223                            None => Self::Error::from_eth_err(e),
224                        }
225                    };
226
227                    // EIP-7708 already emits transfer logs: https://eips.ethereum.org/EIPS/eip-7708
228                    let trace_transfers =
229                        trace_transfers && !evm_env.version().feature(evm2::EvmFeatures::EIP7708);
230                    let mut evm = this.evm_config().evm_with_env(&mut db, evm_env.clone());
231                    if trace_transfers {
232                        // prepare inspector to capture transfer inside the evm so they are recorded
233                        // and included in logs
234                        evm.set_inspector(TransferInspector::new(false).with_logs(true));
235                    }
236                    let mut builder =
237                        this.evm_config().create_block_builder(evm, evm_env, &parent, ctx);
238                    if build_bal {
239                        builder.executor_mut().enable_block_access_list_builder();
240                    }
241
242                    if let Some(ref state_overrides) = state_overrides {
243                        simulate::apply_precompile_overrides(state_overrides, builder.evm_mut())
244                            .map_err(|e| Self::Error::from_eth_err(EthApiError::other(e)))?;
245                    }
246
247                    let (result, results) = simulate::execute_transactions(
248                        builder,
249                        &*state_provider,
250                        calls,
251                        &mut remaining_call_gas_limit,
252                        chain_id,
253                        simulation_state.as_mut(),
254                        this.converter(),
255                        |call, db| this.simulate_call_nonce(call, db),
256                    )
257                    .map_err(map_err)?;
258
259                    db.commit_source(&BundleSource(&result.execution_state));
260                    let simulated_header = result.block.clone_sealed_header();
261                    db.insert_block_hash(
262                        &U256::from(simulated_header.number()),
263                        &simulated_header.hash(),
264                    );
265                    parent = simulated_header;
266
267                    let block =
268                        simulate::build_simulated_block::<Self::Error, _, EvmTypesFor<Self::Evm>>(
269                            result.block,
270                            results,
271                            return_full_transactions.into(),
272                            this.converter(),
273                        )?;
274
275                    blocks.push(block);
276                }
277
278                Ok(blocks)
279            })
280            .await
281        }
282    }
283
284    /// Executes the call request (`eth_call`) and returns the output
285    fn call(
286        &self,
287        request: RpcTxReq<<Self::RpcConvert as RpcConvert>::Network>,
288        block_number: Option<BlockId>,
289        overrides: EvmOverrides,
290    ) -> impl Future<Output = Result<Bytes, Self::Error>> + Send {
291        async move {
292            let res =
293                self.transact_call_at(request, block_number.unwrap_or_default(), overrides).await?;
294
295            Self::Error::ensure_success::<EvmTypesFor<Self::Evm>>(res.result)
296        }
297    }
298
299    /// Simulate transactions at an arbitrary blockchain index, with the optionality of state
300    /// overrides.
301    ///
302    /// The request is bounded by [`CallManyBudget`]: its calls share the RPC gas cap.
303    fn call_many(
304        &self,
305        bundles: Vec<Bundle<RpcTxReq<<Self::RpcConvert as RpcConvert>::Network>>>,
306        state_context: Option<StateContext>,
307        mut state_override: Option<StateOverride>,
308    ) -> impl Future<Output = Result<Vec<Vec<EthCallResponse>>, Self::Error>> + Send
309    where
310        Self: Trace,
311    {
312        async move {
313            // Check if the vector of bundles is empty
314            if bundles.is_empty() {
315                return Err(EthApiError::InvalidParams(String::from("bundles are empty.")).into());
316            }
317            let mut budget = CallManyBudget::for_bundles(&bundles, self.call_gas_limit())?;
318
319            let permit = self
320                .acquire_owned_blocking_io()
321                .await
322                .map_err(|_| EthApiError::InternalEthError)?;
323
324            let StateContext { transaction_index, block_number } =
325                state_context.unwrap_or_default();
326            let transaction_index = transaction_index.unwrap_or_default();
327
328            let mut target_block = block_number.unwrap_or_default();
329            let is_block_target_pending = target_block.is_pending();
330
331            // if it's not pending, we should always use block_hash over block_number to ensure that
332            // different provider calls query data related to the same block.
333            if !is_block_target_pending {
334                let Some(block_hash) = self
335                    .provider()
336                    .block_hash_for_id(target_block)
337                    .map_err(Self::Error::from_eth_err::<ProviderError>)?
338                else {
339                    return Err(EthApiError::HeaderNotFound(target_block).into())
340                };
341                target_block = block_hash.into();
342            }
343
344            let block = self
345                .recovered_block(target_block)
346                .await?
347                .ok_or(EthApiError::HeaderNotFound(target_block))?;
348            let evm_env = self.evm_env_for_header(block.sealed_block().sealed_header())?;
349
350            // we're essentially replaying the transactions in the block here, hence we need the
351            // state that points to the beginning of the block, which is the state at
352            // the parent block
353            let mut at = block.parent_hash();
354            let mut replay_block_txs = true;
355
356            let num_txs =
357                transaction_index.index().unwrap_or_else(|| block.body().transactions().len());
358            // but if all transactions are to be replayed, we can use the state at the block itself,
359            // however only if we're not targeting the pending block, because for pending we can't
360            // rely on the block's state being available
361            if !is_block_target_pending && num_txs == block.body().transactions().len() {
362                at = block.hash();
363                replay_block_txs = false;
364            }
365
366            self.spawn_with_state_at_block(at, move |this, mut db| {
367                let _permit = permit;
368                let mut all_results = Vec::with_capacity(bundles.len());
369
370                if replay_block_txs {
371                    // no BAL positioning here: bundle transactions commit state on top, and an
372                    // attached BAL would take read precedence over the committed changes
373                    this.replay_block_until(&mut db, &block, num_txs, None)?;
374                }
375
376                // transact all bundles
377                for (bundle_index, bundle) in bundles.into_iter().enumerate() {
378                    let Bundle { transactions, block_override } = bundle;
379                    if transactions.is_empty() {
380                        // Skip empty bundles
381                        continue;
382                    }
383
384                    let mut bundle_results = Vec::with_capacity(transactions.len());
385                    let block_overrides = block_override.map(Box::new);
386
387                    // transact all transactions in the bundle
388                    for (tx_index, tx) in transactions.into_iter().enumerate() {
389                        if is_cancelled() {
390                            return Err(EthApiError::InternalEthError.into())
391                        }
392
393                        // Apply overrides, state overrides are only applied for the first tx in the
394                        // request
395                        let overrides =
396                            EvmOverrides::new(state_override.take(), block_overrides.clone());
397
398                        let (current_evm_env, mut prepared_tx) = this
399                            .prepare_call_env(evm_env.clone(), tx, &mut db, overrides)
400                            .map_err(|err| {
401                                Self::Error::from_eth_err(EthApiError::call_many_error(
402                                    bundle_index,
403                                    tx_index,
404                                    err.into(),
405                                ))
406                            })?;
407                        budget.admit(&mut prepared_tx)?;
408                        let res = this.transact(&mut db, current_evm_env, prepared_tx).map_err(
409                            |err| {
410                                Self::Error::from_eth_err(EthApiError::call_many_error(
411                                    bundle_index,
412                                    tx_index,
413                                    budget.map_call_err(err).into(),
414                                ))
415                            },
416                        )?;
417                        budget.charge(&res.result).map_err(|err| {
418                            Self::Error::from_eth_err(EthApiError::call_many_error(
419                                bundle_index,
420                                tx_index,
421                                err.into(),
422                            ))
423                        })?;
424
425                        match Self::Error::ensure_success::<EvmTypesFor<Self::Evm>>(res.result) {
426                            Ok(output) => {
427                                bundle_results
428                                    .push(EthCallResponse { value: Some(output), error: None });
429                            }
430                            Err(err) => {
431                                bundle_results.push(EthCallResponse {
432                                    value: None,
433                                    error: Some(err.to_string()),
434                                });
435                            }
436                        }
437
438                        // Commit state changes after each transaction to allow subsequent calls to
439                        // see the updates
440                        db.commit_source(&res.pending_state);
441                    }
442
443                    all_results.push(bundle_results);
444                }
445
446                Ok(all_results)
447            })
448            .await
449        }
450    }
451
452    /// Creates [`AccessListResult`] for the [`RpcTxReq`] at the given
453    /// [`BlockId`], or latest block.
454    fn create_access_list_at(
455        &self,
456        request: RpcTxReq<<Self::RpcConvert as RpcConvert>::Network>,
457        block_number: Option<BlockId>,
458        state_override: Option<StateOverride>,
459    ) -> impl Future<Output = Result<AccessListResult, Self::Error>> + Send
460    where
461        Self: Trace,
462    {
463        async move {
464            let block_id = block_number.unwrap_or_default();
465            let (evm_env, at) = self.evm_env_at(block_id).await?;
466
467            self.create_access_list_with(evm_env, at, request, state_override).await
468        }
469    }
470
471    /// Creates [`AccessListResult`] for the [`RpcTxReq`] at the given
472    /// [`BlockId`].
473    ///
474    /// Waits for a blocking IO permit, which the blocking task holds until both executions are
475    /// done, even if the returned future is dropped.
476    fn create_access_list_with(
477        &self,
478        evm_env: EvmEnvFor<Self::Evm>,
479        at: BlockId,
480        request: RpcTxReq<<Self::RpcConvert as RpcConvert>::Network>,
481        state_override: Option<StateOverride>,
482    ) -> impl Future<Output = Result<AccessListResult, Self::Error>> + Send
483    where
484        Self: Trace,
485    {
486        async move {
487            let permit = self
488                .acquire_owned_blocking_io()
489                .await
490                .map_err(|_| EthApiError::InternalEthError)?;
491
492            self.spawn_with_state_at_block(at, move |this, mut db| {
493                let _permit = permit;
494                let initial = request.as_ref().access_list().cloned().unwrap_or_default();
495                let tx_gas_limit_cap = evm_env.version().tx_gas_limit_cap;
496                let (mut evm_env, mut tx_env) = this.prepare_call_env(
497                    evm_env,
498                    request,
499                    &mut db,
500                    EvmOverrides::state(state_override),
501                )?;
502                // The access list is used to send a transaction, so under EIP-8037 keep the
503                // execution gas cap that the transaction will run with, like geth does. The total
504                // gas cap stays lifted, also like geth, so with an RPC gas cap above `2^32 - 1`
505                // this can return an access list for a gas limit no transaction can have.
506                if evm_env.version().feature(evm2::EvmFeatures::EIP8037) {
507                    evm_env.version_mut().tx_gas_limit_cap = tx_gas_limit_cap;
508                }
509                let chain_id = evm_env.chain_id();
510
511                let mut evm = this.evm_config().evm_with_env(&mut db, evm_env);
512
513                // EIP-7702 authorities are warmed during authorization processing, so listing them
514                // would only add access list cost.
515                let inspector = AccessListInspector::new(initial)
516                    .with_excluded_from_tx(tx_env.inner(), chain_id);
517                let (inspector, result) = evm
518                    .transact_with_inspector(&tx_env, inspector)
519                    .map_err(Self::Error::from_evm_err)?;
520                let access_list = inspector.into_access_list();
521                let gas_used = result.result.tx_gas_used();
522                if let Err(err) =
523                    Self::Error::ensure_success::<EvmTypesFor<Self::Evm>>(result.result)
524                {
525                    return Ok(AccessListResult {
526                        access_list,
527                        gas_used: U256::from(gas_used),
528                        error: Some(err.to_string()),
529                    });
530                }
531
532                if is_cancelled() {
533                    return Err(EthApiError::InternalEthError.into())
534                }
535
536                tx_env.inner_mut().set_access_list(access_list.clone());
537
538                // Transact again to get the exact gas used with the returned access list.
539                let result = evm.transact_result(&tx_env).map_err(Self::Error::from_evm_err)?;
540                let gas_used = result.tx_gas_used();
541                let error = Self::Error::ensure_success::<EvmTypesFor<Self::Evm>>(result)
542                    .err()
543                    .map(|e| e.to_string());
544
545                Ok(AccessListResult { access_list, gas_used: U256::from(gas_used), error })
546            })
547            .await
548        }
549    }
550}
551
552/// Executes code on state.
553pub trait Call:
554    LoadState<
555        RpcConvert: RpcConvert<Evm = Self::Evm>,
556        Error: FromEvmError<Self::Evm>
557                   + From<<Self::RpcConvert as RpcConvert>::Error>
558                   + From<ProviderError>,
559    > + SpawnBlocking
560{
561    /// Returns default gas limit to use for `eth_call` and tracing RPC methods.
562    ///
563    /// Data access in default trait method implementations.
564    fn call_gas_limit(&self) -> u64 {
565        self.eth_api_settings().gas_cap
566    }
567
568    /// Returns the maximum number of blocks accepted for `eth_simulateV1`.
569    fn max_simulate_blocks(&self) -> u64 {
570        self.eth_api_settings().max_simulate_blocks
571    }
572
573    /// Returns whether `eth_simulateV1` should compute state roots.
574    fn compute_state_root_for_eth_simulate(&self) -> bool {
575        self.eth_api_settings().compute_state_root_for_eth_simulate
576    }
577
578    /// Returns the maximum memory the EVM can allocate per call frame in an RPC request.
579    fn evm_memory_limit(&self) -> u64 {
580        self.eth_api_settings().evm_memory_limit
581    }
582
583    /// Returns the nonce for an `eth_simulateV1` call that has none.
584    ///
585    /// `db` holds the simulation state before the call, including all earlier calls. `None` falls
586    /// back to the sender's account nonce, which suits networks with a single nonce per account.
587    fn simulate_call_nonce(
588        &self,
589        _request: &RpcTxReq<<Self::RpcConvert as RpcConvert>::Network>,
590        _db: &mut dyn DynDatabase,
591    ) -> Result<Option<u64>, EthApiError> {
592        Ok(None)
593    }
594
595    /// Returns the max gas limit that the caller can afford given a transaction environment.
596    fn caller_gas_allowance(
597        &self,
598        mut db: impl Database<Error: Into<EthApiError>>,
599        _evm_env: &EvmEnvFor<Self::Evm>,
600        tx_env: &TxEnvFor<Self::Evm>,
601    ) -> Result<u64, Self::Error> {
602        let balance = db
603            .get_account(&tx_env.signer())
604            .map_err(Into::into)
605            .map_err(Self::Error::from_eth_err)?
606            .map(|account| account.balance)
607            .unwrap_or_default();
608        let value = tx_env.value();
609        let blob_fee = if tx_env.is_eip4844() {
610            U256::from(tx_env.blob_gas_used().unwrap_or_default()) *
611                U256::from(tx_env.max_fee_per_blob_gas().unwrap_or_default())
612        } else {
613            U256::ZERO
614        };
615        // Reserve the maximum blob fee before allocating execution gas. Subtract separately so
616        // an overflowing value plus blob fee cannot become an affordable allowance.
617        let available = balance
618            .checked_sub(value)
619            .and_then(|remaining| remaining.checked_sub(blob_fee))
620            .ok_or_else(|| {
621                EthApiError::from(RpcInvalidTransactionError::InsufficientFunds {
622                    cost: value.saturating_add(blob_fee),
623                    balance,
624                })
625            })?;
626
627        Ok(available
628            .checked_div(U256::from(tx_env.effective_gas_price(None)))
629            .unwrap_or_default()
630            .saturating_to())
631    }
632
633    /// Executes the `TxEnv` against the given [Database] without committing state
634    /// changes.
635    fn transact<DB>(
636        &self,
637        db: DB,
638        evm_env: EvmEnvFor<Self::Evm>,
639        tx_env: TxEnvFor<Self::Evm>,
640    ) -> Result<TxResultWithStateFor<Self::Evm>, Self::Error>
641    where
642        DB: Database + fmt::Debug,
643    {
644        let mut evm = self.evm_config().evm_with_env(db, evm_env);
645        let res = evm.transact(&tx_env).map_err(Self::Error::from_evm_err)?;
646
647        Ok(res)
648    }
649
650    /// Executes the [`reth_evm::EvmEnv`] against the given [`Database`] without committing state
651    /// changes.
652    fn transact_with_inspector<DB, I>(
653        &self,
654        db: DB,
655        evm_env: EvmEnvFor<Self::Evm>,
656        tx_env: TxEnvFor<Self::Evm>,
657        inspector: I,
658    ) -> Result<(I, TxResultWithStateFor<Self::Evm>), Self::Error>
659    where
660        DB: Database + fmt::Debug,
661        I: evm2::Inspector<EvmTypesFor<Self::Evm>> + 'static,
662    {
663        let mut evm = self.evm_config().evm_with_env(db, evm_env);
664        let res =
665            evm.transact_with_inspector(&tx_env, inspector).map_err(Self::Error::from_evm_err)?;
666
667        Ok(res)
668    }
669
670    /// Executes the call request at the given [`BlockId`].
671    ///
672    /// This spawns a new task that obtains the state for the given [`BlockId`] and then transacts
673    /// the call [`Self::transact`]. If the future is dropped before the (blocking) transact
674    /// call is invoked, then the task is cancelled early, (for example if the request is terminated
675    /// early client-side).
676    fn transact_call_at(
677        &self,
678        request: RpcTxReq<<Self::RpcConvert as RpcConvert>::Network>,
679        at: BlockId,
680        overrides: EvmOverrides,
681    ) -> impl Future<Output = Result<TxResultWithStateFor<Self::Evm>, Self::Error>> + Send
682    where
683        Self: LoadPendingBlock,
684    {
685        async move {
686            let permit = self
687                .acquire_owned_blocking_io()
688                .await
689                .map_err(|_| EthApiError::InternalEthError)?;
690            let this = self.clone();
691
692            self.spawn_with_call_at(request, at, overrides, move |db, evm_env, tx_env| {
693                let _permit = permit;
694                if is_cancelled() {
695                    // callsite dropped the request
696                    return Err(EthApiError::InternalEthError.into())
697                }
698                this.transact(db, evm_env, tx_env)
699            })
700            .await
701        }
702    }
703
704    /// Executes the closure with the state that corresponds to the given [`BlockId`] on a new task
705    fn spawn_with_state_at_block<F, R>(
706        &self,
707        at: impl Into<BlockId>,
708        f: F,
709    ) -> impl Future<Output = Result<R, Self::Error>> + Send
710    where
711        F: FnOnce(Self, StateCacheDb) -> Result<R, Self::Error> + Send + 'static,
712        R: Send + 'static,
713    {
714        self.spawn_blocking_io_with_state(at.into(), move |this, state| {
715            let db = evm2::evm::CacheDB::new(evm2::evm::Db::new(StateProviderDatabase::new(
716                state.into_evm_state_provider(),
717            )));
718            f(this, db)
719        })
720    }
721
722    /// Prepares the state and env for the given [`RpcTxReq`] at the given [`BlockId`] and
723    /// executes the closure on a new task returning the result of the closure.
724    ///
725    /// This returns the configured [`reth_evm::EvmEnv`] for the given [`RpcTxReq`] at
726    /// the given [`BlockId`] and with configured call settings: `prepare_call_env`.
727    ///
728    /// This is primarily used by `eth_call`.
729    ///
730    /// # Blocking behaviour
731    ///
732    /// This assumes executing the call is relatively more expensive on IO than CPU because it
733    /// transacts a single transaction on an empty in memory database. Because `eth_call`s are
734    /// usually allowed to consume a lot of gas, this also allows a lot of memory operations so
735    /// we assume this is not primarily CPU bound and instead spawn the call on a regular tokio task
736    /// instead, where blocking IO is less problematic.
737    fn spawn_with_call_at<F, R>(
738        &self,
739        request: RpcTxReq<<Self::RpcConvert as RpcConvert>::Network>,
740        at: BlockId,
741        overrides: EvmOverrides,
742        f: F,
743    ) -> impl Future<Output = Result<R, Self::Error>> + Send
744    where
745        Self: LoadPendingBlock,
746        F: FnOnce(
747                &mut StateCacheDb,
748                EvmEnvFor<Self::Evm>,
749                TxEnvFor<Self::Evm>,
750            ) -> Result<R, Self::Error>
751            + Send
752            + 'static,
753        R: Send + 'static,
754    {
755        async move {
756            let (evm_env, at) = self.evm_env_at(at).await?;
757            self.spawn_with_state_at_block(at, move |this, mut db| {
758                let (evm_env, tx_env) =
759                    this.prepare_call_env(evm_env, request, &mut db, overrides)?;
760
761                f(&mut db, evm_env, tx_env)
762            })
763            .await
764        }
765    }
766
767    /// Retrieves the transaction if it exists and executes it.
768    ///
769    /// Before the transaction is executed, the state is positioned right before the transaction,
770    /// either by attaching the block's cached BAL or by executing all previous transactions in the
771    /// block. The transaction is executed through the block executor, see [`Call::block_executor`].
772    /// The callback `f` is invoked with the [`TxResultWithStateFor`] after the transaction was
773    /// executed and the database that points to the beginning of the transaction. The database
774    /// may have the block's BAL attached and must only be used for reads, because an attached
775    /// BAL takes read precedence over state committed on top, see [`attach_bal_before_tx`].
776    ///
777    /// Note: Implementers should use a threadpool where blocking is allowed, such as
778    /// [`BlockingTaskPool`](reth_tasks::pool::BlockingTaskPool).
779    fn spawn_replay_transaction<F, R>(
780        &self,
781        hash: B256,
782        f: F,
783    ) -> impl Future<Output = Result<Option<R>, Self::Error>> + Send
784    where
785        Self: LoadBlock + LoadTransaction,
786        F: FnOnce(
787                TransactionInfo,
788                TxResultWithStateFor<Self::Evm>,
789                StateCacheDb,
790            ) -> Result<R, Self::Error>
791            + Send
792            + 'static,
793        R: Send + 'static,
794    {
795        async move {
796            let (transaction, block, bal) =
797                match self.transaction_and_block_and_maybe_bal(hash).await? {
798                    None => return Ok(None),
799                    Some(res) => res,
800                };
801            let (tx, tx_info) = transaction.split();
802
803            // we need to get the state of the parent block because we're essentially replaying the
804            // block the transaction is included in
805            let parent_block = block.parent_hash();
806            let evm_env = self.evm_env_for_header(block.sealed_block().sealed_header())?;
807
808            self.spawn_with_state_at_block(parent_block, move |this, mut db| {
809                if let Some((bal, tx_index)) = bal.zip(tx_info.index) {
810                    attach_bal_before_tx(&mut db, &bal, tx_index as usize);
811
812                    let mut executor = this.block_executor(&block, &mut db, evm_env)?;
813                    executor.set_block_access_index(BlockAccessIndex::from_tx_index(tx_index));
814                    let res = executor
815                        .execute_transaction_without_commit(tx)
816                        .map_err(Self::Error::from_evm_err)?
817                        .into_result();
818                    let cache = executor.evm_mut().take_state_cache();
819                    drop(executor);
820                    db.cache.merge(cache);
821                    return f(tx_info, res, db)
822                }
823
824                let block_txs = block.transactions_recovered();
825
826                let ctx = this
827                    .evm_config()
828                    .context_for_block(block.sealed_block())
829                    .map_err(RethError::other)
830                    .map_err(Self::Error::from_eth_err)?;
831                let changes = this
832                    .evm_config()
833                    .pre_block_state_changes(&mut db, evm_env.clone(), ctx)
834                    .map_err(Self::Error::from_eth_err)?;
835                db.commit_source(&reth_execution_types::BundleSource(&changes));
836
837                let mut executor = this.block_executor(&block, &mut db, evm_env)?;
838                this.replay_transactions_until_with_executor(
839                    &mut executor,
840                    block_txs,
841                    tx_info.index.expect("included transaction has an index") as usize,
842                )?;
843                let res = executor
844                    .execute_transaction_without_commit(tx)
845                    .map_err(Self::Error::from_evm_err)?
846                    .into_result();
847                let cache = executor.evm_mut().take_state_cache();
848                drop(executor);
849                db.cache.merge(cache);
850                f(tx_info, res, db)
851            })
852            .await
853            .map(Some)
854        }
855    }
856
857    /// Replays all transactions before the target transaction index through the given executor.
858    ///
859    /// If the target index is greater than or equal to the iterator length, all transactions are
860    /// replayed.
861    fn replay_transactions_until_with_executor<'a, Txs>(
862        &self,
863        executor: &mut BlockExecutorFor<'_, Self::Evm>,
864        transactions: Txs,
865        target_tx_index: usize,
866    ) -> Result<(), Self::Error>
867    where
868        Txs: IntoIterator<Item = Recovered<&'a ProviderTx<Self::Provider>>>,
869    {
870        for (index, tx) in transactions.into_iter().enumerate() {
871            if index == target_tx_index {
872                // reached the target transaction
873                break
874            }
875            if is_cancelled() {
876                return Err(EthApiError::InternalEthError.into())
877            }
878
879            executor.execute_transaction(tx).map_err(Self::Error::from_evm_err)?;
880        }
881        Ok(())
882    }
883
884    /// Creates a block executor for `block` on `db` with the given EVM environment.
885    ///
886    /// Replaying a block's own transactions through the executor rather than a bare EVM includes
887    /// the changes the executor applies on top of each EVM result, so replayed results agree with
888    /// the block's receipts and state. The executor does not apply the block's pre-execution
889    /// changes: callers apply them to `db` first or position `db` with the block's BAL, see
890    /// [`attach_bal_before_tx`].
891    fn block_executor<'a>(
892        &'a self,
893        block: &'a RecoveredBlock<BlockTy<Self::Primitives>>,
894        db: &'a mut StateCacheDb,
895        evm_env: EvmEnvFor<Self::Evm>,
896    ) -> Result<BlockExecutorFor<'a, Self::Evm>, Self::Error> {
897        let ctx = self
898            .evm_config()
899            .context_for_block(block.sealed_block())
900            .map_err(RethError::other)
901            .map_err(Self::Error::from_eth_err)?;
902        let evm = self.evm_config().evm_with_env(db, evm_env);
903        Ok(self.evm_config().block_executor_factory().create_executor(evm, ctx))
904    }
905
906    ///
907    /// All `TxEnv` fields are derived from the given [`RpcTxReq`], if fields are
908    /// `None`, they fall back to the [`reth_evm::EvmEnv`]'s settings.
909    fn create_txn_env(
910        &self,
911        evm_env: &EvmEnvFor<Self::Evm>,
912        mut request: RpcTxReq<<Self::RpcConvert as RpcConvert>::Network>,
913        mut db: impl Database<Error: Into<EthApiError>>,
914    ) -> Result<TxEnvFor<Self::Evm>, Self::Error> {
915        if request.as_ref().nonce().is_none() {
916            let nonce = db
917                .get_account(&request.as_ref().from().unwrap_or_default())
918                .map_err(Into::into)
919                .map_err(Self::Error::from_eth_err)?
920                .map(|account| account.nonce)
921                .unwrap_or_default();
922            request.as_mut().set_nonce(nonce);
923        }
924
925        Ok(self.converter().tx_env(request, evm_env)?)
926    }
927
928    /// Prepares the [`reth_evm::EvmEnv`] for execution of calls.
929    ///
930    /// Does not commit any changes to the underlying database.
931    ///
932    /// ## EVM settings
933    ///
934    /// This modifies certain EVM settings to mirror geth's `SkipAccountChecks` when transacting requests, see also: <https://github.com/ethereum/go-ethereum/blob/380688c636a654becc8f114438c2a5d93d2db032/core/state_transition.go#L145-L148>:
935    ///
936    ///  - `disable_eip3607` is set to `true`
937    ///  - `disable_base_fee` is set to `true`
938    ///  - `nonce` is set to `None`
939    ///  - the EIP-7825 and EIP-8037 transaction gas caps are lifted, mirroring geth's
940    ///    `SkipGasLimitCapCheck` and `SkipExecutionGasCapCheck`
941    ///
942    /// In addition, this changes the block's gas limit to the configured [`Self::call_gas_limit`].
943    #[expect(clippy::type_complexity)]
944    fn prepare_call_env<DB>(
945        &self,
946        mut evm_env: EvmEnvFor<Self::Evm>,
947        mut request: RpcTxReq<<Self::RpcConvert as RpcConvert>::Network>,
948        db: &mut CacheDB<DB>,
949        overrides: EvmOverrides,
950    ) -> Result<(EvmEnvFor<Self::Evm>, TxEnvFor<Self::Evm>), Self::Error>
951    where
952        DB: DynDatabase,
953    {
954        // track whether the request has a gas limit set
955        let requested_gas = request.as_ref().gas_limit();
956
957        // Disable block gas limit check to allow executing transactions with higher gas limit (call
958        // gas limit): https://github.com/paradigmxyz/reth/issues/18577
959        evm_env.version_mut().features.remove(evm2::EvmFeatures::BLOCK_GAS_LIMIT_CHECK);
960
961        // Disabled because eth_call is sometimes used with eoa senders
962        // See <https://github.com/paradigmxyz/reth/issues/1959>
963        evm_env.version_mut().features.remove(evm2::EvmFeatures::EIP3607);
964
965        // The basefee should be ignored for eth_call
966        // See:
967        // <https://github.com/ethereum/go-ethereum/blob/ee8e83fa5f6cb261dad2ed0a7bbcde4930c41e6c/internal/ethapi/api.go#L985>
968        evm_env.version_mut().features.remove(evm2::EvmFeatures::BASE_FEE_CHECK);
969
970        // Disable the EIP-7825 transaction gas cap and, under Amsterdam's EIP-8037, the total
971        // transaction gas cap, so the whole gas limit, bounded by the RPC gas cap, is available for
972        // execution. Calls never go into a block, so the caps that keep a single transaction from
973        // filling one don't apply. Mirrors geth's `SkipGasLimitCapCheck` and
974        // `SkipExecutionGasCapCheck`.
975        evm_env.version_mut().tx_gas_limit_cap = u64::MAX;
976        evm_env.version_mut().tx_total_gas_cap = u64::MAX;
977
978        // Disable additional fee charges, e.g. opstack operator fee charge
979        // See:
980        // <https://github.com/paradigmxyz/reth/issues/18470>
981        evm_env.version_mut().features.remove(evm2::EvmFeatures::FEE_CHARGE);
982
983        // Calls do not pay upfront fees. Preserve the caller's actual balance so value transfers
984        // still fail during execution when it is insufficient, without topping up the account.
985        evm_env
986            .version_mut()
987            .features
988            .remove(evm2::EvmFeatures::BALANCE_CHECK | evm2::EvmFeatures::BALANCE_TOP_UP);
989
990        evm_env.version_mut().memory_limit = self.evm_memory_limit();
991
992        // set nonce to None so that the correct nonce is chosen by the EVM
993        request.as_mut().take_nonce();
994
995        if let Some(block_overrides) = overrides.block {
996            apply_block_overrides(*block_overrides, db, &mut evm_env);
997        }
998        if let Some(state_overrides) = overrides.state {
999            apply_state_overrides(state_overrides, db)
1000                .map_err(EthApiError::from_state_overrides_err)?;
1001        }
1002
1003        let gas_price = request_gas_price(request.as_ref(), evm_env.block_base_fee());
1004        // Convert the request once, as sent, and apply every gas limit cap to the prepared env:
1005        // converting again with a changed gas limit could change the recovered caller or fee payer
1006        // when the signature commits to the gas limit.
1007        let mut tx_env = self.create_txn_env(&evm_env, request, &mut *db)?;
1008
1009        if let Some(requested_gas) = requested_gas {
1010            let global_gas_cap = self.call_gas_limit();
1011            if global_gas_cap != 0 && global_gas_cap < requested_gas {
1012                // Callers routinely send gas limits above the cap, so this is not worth a warning.
1013                // Log only the limits: the request carries caller calldata and addresses.
1014                debug!(target: "rpc::eth::call", requested_gas, global_gas_cap, "Capping gas limit to global gas cap");
1015                tx_env.inner_mut().set_gas_limit(global_gas_cap);
1016            }
1017        } else {
1018            // cap request's gas limit to call gas limit
1019            tx_env.inner_mut().set_gas_limit(self.call_gas_limit());
1020        }
1021
1022        // lower the basefee to 0 to avoid breaking EVM invariants (basefee < gasprice): <https://github.com/ethereum/go-ethereum/blob/355228b011ef9a85ebc0f21e7196f892038d49f0/internal/ethapi/api.go#L700-L704>
1023        if gas_price == 0 {
1024            evm_env.block_env_mut().basefee = U256::ZERO;
1025        }
1026
1027        if requested_gas.is_none() {
1028            // No gas limit was provided in the request, so we need to cap the transaction gas limit
1029            if gas_price > 0 {
1030                // If gas price is specified, cap transaction gas limit with caller allowance
1031                trace!(target: "rpc::eth::call", ?tx_env, "Applying gas limit cap with caller allowance");
1032                let mut cap = self.caller_gas_allowance(&mut *db, &evm_env, &tx_env)?;
1033                // The allowance must not raise the already applied RPC gas cap.
1034                if self.call_gas_limit() != 0 {
1035                    cap = cap.min(tx_env.gas_limit());
1036                }
1037                // ensure we cap gas_limit to the block's
1038                tx_env
1039                    .inner_mut()
1040                    .set_gas_limit(cap.min(evm_env.block_env().gas_limit.to::<u64>()));
1041            }
1042        }
1043
1044        Ok((evm_env, tx_env))
1045    }
1046}
1047
1048pub(super) fn request_gas_price(
1049    request: &alloy_rpc_types_eth::TransactionRequest,
1050    block_base_fee: u64,
1051) -> u128 {
1052    if let Some(gas_price) = request.gas_price {
1053        return gas_price
1054    }
1055
1056    match (request.max_fee_per_gas, request.max_priority_fee_per_gas) {
1057        (None, None) => 0,
1058        (max_fee, priority_fee) => calc_effective_gas_price(
1059            max_fee.unwrap_or(u128::MAX),
1060            priority_fee.unwrap_or_default(),
1061            Some(block_base_fee),
1062        ),
1063    }
1064}