Skip to main content

reth_rpc_eth_api/helpers/
estimate.rs

1//! Estimate gas needed implementation
2
3use super::{Call, LoadPendingBlock};
4use crate::{AsEthApiError, FromEthApiError, IntoEthApiError};
5use alloy_evm::overrides::{apply_block_overrides, apply_state_overrides};
6use alloy_network::TransactionBuilder;
7use alloy_primitives::{TxKind, U256};
8use alloy_rpc_types_eth::{state::EvmOverrides, BlockId};
9use futures::Future;
10use reth_chainspec::MIN_TRANSACTION_GAS;
11use reth_errors::ProviderError;
12use reth_evm::{
13    env::BlockEnvironment, ConfigureEvm, Database, Evm, EvmEnvFor, EvmFor, TransactionEnvMut,
14    TxEnvFor,
15};
16use reth_revm::{
17    database::{EvmStateProvider, StateProviderDatabase},
18    db::{bal::EvmDatabaseError, State},
19};
20use reth_rpc_convert::{RpcConvert, RpcTxReq};
21use reth_rpc_eth_types::{
22    error::{
23        api::{FromEvmHalt, FromRevert},
24        FromEvmError,
25    },
26    EthApiError, RpcInvalidTransactionError,
27};
28use reth_rpc_server_types::constants::gas_oracle::{CALL_STIPEND_GAS, ESTIMATE_GAS_ERROR_RATIO};
29use revm::{
30    context::Block,
31    context_interface::{result::ExecutionResult, Cfg, Transaction},
32    primitives::KECCAK_EMPTY,
33};
34use tracing::trace;
35
36/// Gas execution estimates
37pub trait EstimateCall: Call {
38    /// Estimates the gas usage of the `request` with the state.
39    ///
40    /// This will execute the [`RpcTxReq`] and find the best gas limit via binary search.
41    ///
42    /// ## EVM settings
43    ///
44    /// 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>:
45    ///
46    ///  - `disable_eip3607` is set to `true`
47    ///  - `disable_base_fee` is set to `true`
48    ///  - `disable_fee_charge` is set to `true`
49    ///  - `nonce` is set to `None`
50    fn estimate_gas_with<S>(
51        &self,
52        mut evm_env: EvmEnvFor<Self::Evm>,
53        mut request: RpcTxReq<<Self::RpcConvert as RpcConvert>::Network>,
54        state: S,
55        overrides: EvmOverrides,
56    ) -> Result<U256, Self::Error>
57    where
58        S: EvmStateProvider,
59    {
60        // Disabled because eth_estimateGas is sometimes used with eoa senders
61        // See <https://github.com/paradigmxyz/reth/issues/1959>
62        evm_env.cfg_env.disable_eip3607 = true;
63
64        // The basefee should be ignored for eth_estimateGas and similar
65        // See:
66        // <https://github.com/ethereum/go-ethereum/blob/ee8e83fa5f6cb261dad2ed0a7bbcde4930c41e6c/internal/ethapi/api.go#L985>
67        evm_env.cfg_env.disable_base_fee = true;
68
69        // Disable additional fee charges (e.g. L2 operator fees) for gas estimation,
70        // consistent with `prepare_call_env` for `eth_call`.
71        evm_env.cfg_env.disable_fee_charge = true;
72
73        // set nonce to None so that the correct nonce is chosen by the EVM
74        request.as_mut().take_nonce();
75
76        // Keep a copy of gas related request values
77        let tx_request_gas_limit = request.as_ref().gas_limit();
78        let tx_request_gas_price = request.as_ref().gas_price();
79
80        // Configure the evm env
81        let mut db = State::builder().with_database(StateProviderDatabase::new(state)).build();
82
83        // Apply any block overrides before deriving block-derived limits and the tx env so
84        // overrides for `gasLimit`, `baseFee` and `blobBaseFee` are visible to estimation.
85        // Mirrors geth's behavior, see:
86        // <https://github.com/ethereum/go-ethereum/pull/30695>
87        if let Some(block_overrides) = overrides.block {
88            apply_block_overrides(*block_overrides, &mut db, evm_env.block_env.inner_mut());
89        }
90
91        // Apply any state overrides if specified.
92        if let Some(state_override) = overrides.state {
93            apply_state_overrides(state_override, &mut db).map_err(Self::Error::from_eth_err)?;
94        }
95
96        // the gas limit of the corresponding block
97        let block_gas_limit = evm_env.block_env.gas_limit();
98        // If EIP-8037 is enabled, the transaction gas limit cap is not applicable
99        let max_gas_limit = if evm_env.cfg_env.is_amsterdam_eip8037_enabled() {
100            block_gas_limit
101        } else {
102            evm_env.cfg_env.tx_gas_limit_cap().min(block_gas_limit)
103        };
104
105        // Determine the highest possible gas limit, considering both the request's specified limit
106        // and the block's limit.
107        let mut highest_gas_limit = tx_request_gas_limit
108            .map(|mut tx_gas_limit| {
109                if max_gas_limit < tx_gas_limit {
110                    // requested gas limit is higher than the allowed gas limit, capping
111                    tx_gas_limit = max_gas_limit;
112                }
113                tx_gas_limit
114            })
115            .unwrap_or(max_gas_limit);
116
117        let mut tx_env = self.create_txn_env(&evm_env, request, &mut db)?;
118
119        // Check if this is a basic transfer (no input data to account with no code)
120        let is_basic_transfer = if tx_env.input().is_empty() &&
121            let TxKind::Call(to) = tx_env.kind()
122        {
123            match db.database.basic_account(&to) {
124                Ok(Some(account)) => {
125                    account.bytecode_hash.is_none() || account.bytecode_hash == Some(KECCAK_EMPTY)
126                }
127                _ => true,
128            }
129        } else {
130            false
131        };
132
133        // Check funds of the sender (only useful to check if transaction gas price is more than 0).
134        //
135        // The caller allowance is check by doing `(account.balance - tx.value) / tx.gas_price`
136        if tx_env.gas_price() > 0 {
137            // cap the highest gas limit by max gas caller can afford with given gas price
138            highest_gas_limit =
139                highest_gas_limit.min(self.caller_gas_allowance(&mut db, &evm_env, &tx_env)?);
140        }
141
142        // If the provided gas limit is less than computed cap, use that
143        tx_env.set_gas_limit(tx_env.gas_limit().min(highest_gas_limit));
144
145        // Create EVM instance once and reuse it throughout the entire estimation process
146        let mut evm = self.evm_config().evm_with_env(&mut db, evm_env);
147
148        // For basic transfers, try using minimum gas before running full binary search
149        if is_basic_transfer {
150            // If the tx is a simple transfer (call to an account with no code) we can
151            // shortcircuit. But simply returning
152            // `MIN_TRANSACTION_GAS` is dangerous because there might be additional
153            // field combos that bump the price up, so we try executing the function
154            // with the minimum gas limit to make sure.
155            let mut min_tx_env = tx_env.clone();
156            min_tx_env.set_gas_limit(MIN_TRANSACTION_GAS);
157
158            // Reuse the same EVM instance
159            if let Ok(res) = evm.transact(min_tx_env).map_err(Self::Error::from_evm_err) &&
160                res.result.is_success()
161            {
162                return Ok(U256::from(MIN_TRANSACTION_GAS))
163            }
164        }
165
166        trace!(target: "rpc::eth::estimate", ?tx_env, gas_limit = tx_env.gas_limit(), is_basic_transfer, "Starting gas estimation");
167
168        // Execute the transaction with the highest possible gas limit.
169        let mut res = match evm.transact(tx_env.clone()).map_err(Self::Error::from_evm_err) {
170            // Handle the exceptional case where the transaction initialization uses too much
171            // gas. If the gas price or gas limit was specified in the request,
172            // retry the transaction with the block's gas limit to determine if
173            // the failure was due to insufficient gas.
174            Err(err)
175                if err.is_gas_too_high() &&
176                    (tx_request_gas_limit.is_some() || tx_request_gas_price.is_some()) =>
177            {
178                return Self::map_out_of_gas_err(&mut evm, tx_env, max_gas_limit);
179            }
180            Err(err) if err.is_gas_too_low() => {
181                // This failed because the configured gas cost of the tx was lower than what
182                // actually consumed by the tx This can happen if the
183                // request provided fee values manually and the resulting gas cost exceeds the
184                // sender's allowance, so we return the appropriate error here
185                return Err(RpcInvalidTransactionError::GasRequiredExceedsAllowance {
186                    gas_limit: tx_env.gas_limit(),
187                }
188                .into_eth_err());
189            }
190            // Propagate other results (successful or other errors).
191            ethres => ethres?,
192        };
193
194        let gas_refund = match res.result {
195            ExecutionResult::Success { gas, .. } => gas.final_refunded(),
196            ExecutionResult::Halt { reason, .. } => {
197                // here we don't check for invalid opcode because already executed with highest gas
198                // limit
199                return Err(Self::Error::from_evm_halt(reason, tx_env.gas_limit()))
200            }
201            ExecutionResult::Revert { output, .. } => {
202                // if price or limit was included in the request then we can execute the request
203                // again with the block's gas limit to check if revert is gas related or not
204                return if tx_request_gas_limit.is_some() || tx_request_gas_price.is_some() {
205                    Self::map_out_of_gas_err(&mut evm, tx_env, max_gas_limit)
206                } else {
207                    // the transaction did revert
208                    Err(Self::Error::from_revert(output))
209                };
210            }
211        };
212
213        // At this point we know the call succeeded but want to find the _best_ (lowest) gas the
214        // transaction succeeds with. We find this by doing a binary search over the possible range.
215
216        // we know the tx succeeded with the configured gas limit, so we can use that as the
217        // highest, in case we applied a gas cap due to caller allowance above
218        highest_gas_limit = tx_env.gas_limit();
219
220        // NOTE: this is the gas the transaction used, which is less than the
221        // transaction requires to succeed.
222        let mut gas_used = res.result.tx_gas_used();
223        // the lowest value is capped by the gas used by the unconstrained transaction
224        let mut lowest_gas_limit = gas_used.saturating_sub(1);
225
226        // As stated in Geth, there is a good chance that the transaction will pass if we set the
227        // gas limit to the execution gas used plus the gas refund, so we check this first
228        // <https://github.com/ethereum/go-ethereum/blob/a5a4fa7032bb248f5a7c40f4e8df2b131c4186a4/eth/gasestimator/gasestimator.go#L135
229        //
230        // Calculate the optimistic gas limit by adding gas used and gas refund,
231        // then applying a 64/63 multiplier to account for gas forwarding rules.
232        let optimistic_gas_limit = (gas_used + gas_refund + CALL_STIPEND_GAS) * 64 / 63;
233        if optimistic_gas_limit < highest_gas_limit {
234            // Set the transaction's gas limit to the calculated optimistic gas limit.
235            let mut optimistic_tx_env = tx_env.clone();
236            optimistic_tx_env.set_gas_limit(optimistic_gas_limit);
237
238            // Re-execute the transaction with the new gas limit and update the result and
239            // environment.
240            res = evm.transact(optimistic_tx_env).map_err(Self::Error::from_evm_err)?;
241
242            // Update the gas used based on the new result.
243            gas_used = res.result.tx_gas_used();
244            // Update the gas limit estimates (highest and lowest) based on the execution result.
245            update_estimated_gas_range(
246                res.result,
247                optimistic_gas_limit,
248                &mut highest_gas_limit,
249                &mut lowest_gas_limit,
250            )?;
251        };
252
253        // Pick a point that's close to the estimated gas
254        let mut mid_gas_limit = std::cmp::min(
255            gas_used * 3,
256            ((highest_gas_limit as u128 + lowest_gas_limit as u128) / 2) as u64,
257        );
258
259        trace!(target: "rpc::eth::estimate", ?highest_gas_limit, ?lowest_gas_limit, ?mid_gas_limit, "Starting binary search for gas");
260
261        // Binary search narrows the range to find the minimum gas limit needed for the transaction
262        // to succeed.
263        while lowest_gas_limit + 1 < highest_gas_limit {
264            // An estimation error is allowed once the current gas limit range used in the binary
265            // search is small enough (less than 1.5% of the highest gas limit)
266            // <https://github.com/ethereum/go-ethereum/blob/a5a4fa7032bb248f5a7c40f4e8df2b131c4186a4/eth/gasestimator/gasestimator.go#L152
267            let ratio = (highest_gas_limit - lowest_gas_limit) as f64 / (highest_gas_limit as f64);
268            if ratio < ESTIMATE_GAS_ERROR_RATIO {
269                break
270            };
271
272            let mut mid_tx_env = tx_env.clone();
273            mid_tx_env.set_gas_limit(mid_gas_limit);
274
275            // Execute transaction and handle potential gas errors, adjusting limits accordingly.
276            match evm.transact(mid_tx_env).map_err(Self::Error::from_evm_err) {
277                Err(err) if err.is_gas_too_high() => {
278                    // Decrease the highest gas limit if gas is too high
279                    highest_gas_limit = mid_gas_limit;
280                }
281                Err(err) if err.is_gas_too_low() => {
282                    // Increase the lowest gas limit if gas is too low
283                    lowest_gas_limit = mid_gas_limit;
284                }
285                // Handle other cases, including successful transactions.
286                ethres => {
287                    // Unpack the result and environment if the transaction was successful.
288                    res = ethres?;
289                    // Update the estimated gas range based on the transaction result.
290                    update_estimated_gas_range(
291                        res.result,
292                        mid_gas_limit,
293                        &mut highest_gas_limit,
294                        &mut lowest_gas_limit,
295                    )?;
296                }
297            }
298
299            // New midpoint
300            mid_gas_limit = ((highest_gas_limit as u128 + lowest_gas_limit as u128) / 2) as u64;
301        }
302
303        Ok(U256::from(highest_gas_limit))
304    }
305
306    /// Estimate gas needed for execution of the `request` at the [`BlockId`].
307    fn estimate_gas_at(
308        &self,
309        request: RpcTxReq<<Self::RpcConvert as RpcConvert>::Network>,
310        at: BlockId,
311        overrides: EvmOverrides,
312    ) -> impl Future<Output = Result<U256, Self::Error>> + Send
313    where
314        Self: LoadPendingBlock,
315    {
316        async move {
317            let (evm_env, at) = self.evm_env_at(at).await?;
318
319            self.spawn_blocking_io_fut(async move |this| {
320                let state = this.state_at_block_id(at).await?;
321                EstimateCall::estimate_gas_with(&this, evm_env, request, state, overrides)
322            })
323            .await
324        }
325    }
326
327    /// Executes the requests again after an out of gas error to check if the error is gas related
328    /// or not
329    #[inline]
330    fn map_out_of_gas_err<DB>(
331        evm: &mut EvmFor<Self::Evm, DB>,
332        mut tx_env: TxEnvFor<Self::Evm>,
333        max_gas_limit: u64,
334    ) -> Result<U256, Self::Error>
335    where
336        DB: Database<Error = EvmDatabaseError<ProviderError>>,
337        EthApiError: From<DB::Error>,
338    {
339        let req_gas_limit = tx_env.gas_limit();
340        tx_env.set_gas_limit(max_gas_limit);
341
342        let retry_res = evm.transact(tx_env).map_err(Self::Error::from_evm_err)?;
343
344        match retry_res.result {
345            ExecutionResult::Success { .. } => {
346                // Transaction succeeded by manually increasing the gas limit,
347                // which means the caller lacks funds to pay for the tx
348                Err(RpcInvalidTransactionError::BasicOutOfGas(req_gas_limit).into_eth_err())
349            }
350            ExecutionResult::Revert { output, .. } => {
351                // reverted again after bumping the limit
352                Err(Self::Error::from_revert(output))
353            }
354            ExecutionResult::Halt { reason, .. } => {
355                Err(Self::Error::from_evm_halt(reason, req_gas_limit))
356            }
357        }
358    }
359}
360
361/// Updates the highest and lowest gas limits for binary search based on the execution result.
362///
363/// This function refines the gas limit estimates used in a binary search to find the optimal
364/// gas limit for a transaction. It adjusts the highest or lowest gas limits depending on
365/// whether the execution succeeded, reverted, or halted due to specific reasons.
366#[inline]
367pub fn update_estimated_gas_range<Halt>(
368    result: ExecutionResult<Halt>,
369    tx_gas_limit: u64,
370    highest_gas_limit: &mut u64,
371    lowest_gas_limit: &mut u64,
372) -> Result<(), EthApiError> {
373    match result {
374        ExecutionResult::Success { .. } => {
375            // Cap the highest gas limit with the succeeding gas limit.
376            *highest_gas_limit = tx_gas_limit;
377        }
378        ExecutionResult::Revert { .. } | ExecutionResult::Halt { .. } => {
379            // We know that transaction succeeded with a higher gas limit before, so any failure
380            // means that we need to increase it.
381            //
382            // We are ignoring all halts here, and not just OOG errors because there are cases when
383            // non-OOG halt might flag insufficient gas limit as well.
384            //
385            // Common usage of invalid opcode in OpenZeppelin:
386            // <https://github.com/OpenZeppelin/openzeppelin-contracts/blob/94697be8a3f0dfcd95dfb13ffbd39b5973f5c65d/contracts/metatx/ERC2771Forwarder.sol#L360-L367>
387            *lowest_gas_limit = tx_gas_limit;
388        }
389    };
390
391    Ok(())
392}