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