@@ -311,9 +311,13 @@ func (e *EVM) EstimateGas(
311311 stateOverrides * ethTypes.StateOverride ,
312312) (uint64 , error ) {
313313 iterations := 0
314- defer func () {
315- e .collector .GasEstimationIterations (iterations )
316- }()
314+
315+ dryRun := func (gasLimit uint64 ) (* evmTypes.Result , error ) {
316+ tx .Gas = gasLimit
317+ result , err := e .dryRunTx (tx , from , height , stateOverrides , nil )
318+ iterations += 1
319+ return result , err
320+ }
317321
318322 // Note: The following algorithm, is largely inspired from
319323 // https://github.com/onflow/go-ethereum/blob/master/eth/gasestimator/gasestimator.go#L49-L192,
@@ -328,11 +332,10 @@ func (e *EVM) EstimateGas(
328332 if tx .Gas >= gethParams .TxGas {
329333 passingGasLimit = tx .Gas
330334 }
331- tx . Gas = passingGasLimit
335+
332336 // We first execute the transaction at the highest allowable gas limit,
333337 // since if this fails we can return the error immediately.
334- result , err := e .dryRunTx (tx , from , height , stateOverrides , nil )
335- iterations += 1
338+ result , err := dryRun (passingGasLimit )
336339 if err != nil {
337340 return 0 , err
338341 }
@@ -344,6 +347,12 @@ func (e *EVM) EstimateGas(
344347 return 0 , errs .NewFailedTransactionError (resultSummary .ErrorMessage )
345348 }
346349
350+ // We do not want to report iterations for calls/transactions
351+ // that errored out or had their execution reverted.
352+ defer func () {
353+ e .collector .GasEstimationIterations (iterations )
354+ }()
355+
347356 // For almost any transaction, the gas consumed by the unconstrained execution
348357 // above lower-bounds the gas limit required for it to succeed. One exception
349358 // is those that explicitly check gas remaining in order to execute within a
@@ -356,9 +365,7 @@ func (e *EVM) EstimateGas(
356365 // Explicitly check that gas amount and use as a limit for the binary search.
357366 optimisticGasLimit := (result .GasConsumed + result .GasRefund + gethParams .CallStipend ) * 64 / 63
358367 if optimisticGasLimit < passingGasLimit {
359- tx .Gas = optimisticGasLimit
360- result , err = e .dryRunTx (tx , from , height , stateOverrides , nil )
361- iterations += 1
368+ result , err := dryRun (optimisticGasLimit )
362369 if err != nil {
363370 // This should not happen under normal conditions since if we make it this far the
364371 // transaction had run without error at least once before.
@@ -387,9 +394,7 @@ func (e *EVM) EstimateGas(
387394 // range here is skewed to favor the low side.
388395 mid = failingGasLimit * 2
389396 }
390- tx .Gas = mid
391- result , err = e .dryRunTx (tx , from , height , stateOverrides , nil )
392- iterations += 1
397+ result , err := dryRun (mid )
393398 if err != nil {
394399 return 0 , err
395400 }
0 commit comments