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