forked from evmos/ethermint
-
Notifications
You must be signed in to change notification settings - Fork 54
fix: enhance gas estimation with execution_gas_used field #810
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
XinyuCRO
wants to merge
3
commits into
release/v0.22.x
Choose a base branch
from
xyz/release/v0.22.x
base: release/v0.22.x
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
68 changes: 68 additions & 0 deletions
68
tests/integration_tests/hardhat/contracts/GasConsumerTryCatch.sol
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,68 @@ | ||
| pragma solidity ^0.8.10; | ||
|
|
||
| /** | ||
| * @title GasConsumerTryCatch | ||
| * @notice A contract to test try-catch behavior with high gas consumption using a single contract | ||
| */ | ||
| contract GasConsumerTryCatch { | ||
| mapping(uint256 => uint256) public data; | ||
| uint256 public totalWrites; | ||
| uint256 public lastResult; | ||
| uint256 public callCount; | ||
|
|
||
| event TrySuccess(uint256 result, uint256 gasUsed); | ||
| event TryCatchFailed(string reason, uint256 gasUsed); | ||
| event TryCatchFailedBytes(bytes reason, uint256 gasUsed); | ||
|
|
||
| error GasConsumerReverted(uint256 iterationsCompleted); | ||
|
|
||
| /** | ||
| * @notice Consumes gas by writing to storage. | ||
| * Must be external to be called via this.consumeGas() in try-catch. | ||
| * @param iterations Number of storage writes (~20,000 gas each) | ||
| * @param shouldRevert If true, reverts after consuming gas | ||
| * @return The total number of writes performed | ||
| */ | ||
| function consumeGas(uint256 iterations, bool shouldRevert) external returns (uint256) { | ||
| uint256 startValue = totalWrites; | ||
|
|
||
| // Each SSTORE costs ~20,000 gas for a new slot (cold access) | ||
| // To consume ~400,000 gas, we need about 20 iterations | ||
| for (uint256 i = 0; i < iterations; i++) { | ||
| data[startValue + i] = block.timestamp + i; | ||
| totalWrites++; | ||
| } | ||
|
|
||
| if (shouldRevert) { | ||
| revert GasConsumerReverted(iterations); | ||
| } | ||
|
|
||
| return totalWrites; | ||
| } | ||
|
|
||
| /** | ||
| * @notice Calls the gas-consuming function with try-catch | ||
| * @param iterations Number of storage write iterations | ||
| * @param shouldRevert If true, the try block will revert after consuming gas | ||
| */ | ||
| function callWithTryCatch(uint256 iterations, bool shouldRevert) external returns (bool success) { | ||
| uint256 gasBefore = gasleft(); | ||
| callCount++; | ||
|
|
||
| // using "this" to make an external call, enabling try-catch | ||
| try this.consumeGas(iterations, shouldRevert) returns (uint256 result) { | ||
| uint256 gasUsed = gasBefore - gasleft(); | ||
| lastResult = result; | ||
| emit TrySuccess(result, gasUsed); | ||
| return true; | ||
| } catch Error(string memory reason) { | ||
| uint256 gasUsed = gasBefore - gasleft(); | ||
| emit TryCatchFailed(reason, gasUsed); | ||
| return false; | ||
| } catch (bytes memory reason) { | ||
| uint256 gasUsed = gasBefore - gasleft(); | ||
| emit TryCatchFailedBytes(reason, gasUsed); | ||
| return false; | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| from concurrent.futures import ThreadPoolExecutor | ||
|
|
||
| import pytest | ||
|
|
||
| from .utils import ADDRS, CONTRACTS, deploy_contract, send_transaction | ||
|
|
||
| pytestmark = pytest.mark.filter | ||
|
|
||
|
|
||
| def test_trycatch_gas_estimation_underestimate(ethermint, geth): | ||
| def process(w3, name): | ||
| contract, _ = deploy_contract(w3, CONTRACTS["GasConsumerTryCatch"]) | ||
| tx = contract.functions.callWithTryCatch(20, False).build_transaction( | ||
| { | ||
| "from": ADDRS["community"], | ||
| } | ||
| ) | ||
|
|
||
| estimated_gas = w3.eth.estimate_gas(tx) | ||
| tx["gas"] = 1000000 | ||
| receipt = send_transaction(w3, tx) | ||
| actual_gas = receipt["gasUsed"] | ||
|
|
||
| # Calculate the difference | ||
| gas_diff = actual_gas - estimated_gas | ||
|
|
||
| return { | ||
| "name": name, | ||
| "estimated_gas": estimated_gas, | ||
| "actual_gas": actual_gas, | ||
| "gas_diff": gas_diff, | ||
| } | ||
|
|
||
| with ThreadPoolExecutor(max_workers=2) as executor: | ||
| ethermint_future = executor.submit(process, ethermint.w3, "ethermint") | ||
| geth_future = executor.submit(process, geth.w3, "geth") | ||
| ethermint_result = ethermint_future.result() | ||
| geth_result = geth_future.result() | ||
|
|
||
| # Compare results from ethermint and geth | ||
| for result in (ethermint_result, geth_result): | ||
| assert result["gas_diff"] == 0, ( | ||
| f"Testing on {result['name']} " | ||
| f"Gas estimation is not accurate: " | ||
| f"{result['estimated_gas']} estimated vs " | ||
| f"{result['actual_gas']} actual " | ||
| f"({result['gas_diff']} difference)" | ||
| ) | ||
|
|
||
| assert ethermint_result["estimated_gas"] == geth_result["estimated_gas"] | ||
| assert ethermint_result["actual_gas"] == geth_result["actual_gas"] | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -20,6 +20,7 @@ import ( | |
| "encoding/json" | ||
| "errors" | ||
| "fmt" | ||
| "math" | ||
| "math/big" | ||
| "time" | ||
|
|
||
|
|
@@ -352,6 +353,12 @@ func (k Keeper) EstimateGas(c context.Context, req *types.EthCallRequest) (*type | |
| } else { | ||
| gasCap = hi | ||
| } | ||
|
|
||
| // Cap hi to MaxInt64 since gas calculations use int64 internally | ||
| if hi > math.MaxInt64 { | ||
| hi = math.MaxInt64 | ||
| } | ||
|
|
||
| cfg, err := k.EVMConfig(ctx, chainID, common.Hash{}) | ||
| if err != nil { | ||
| return nil, status.Error(codes.Internal, "failed to load evm config") | ||
|
|
@@ -383,35 +390,43 @@ func (k Keeper) EstimateGas(c context.Context, req *types.EthCallRequest) (*type | |
| } | ||
| return true, nil, err // Bail out | ||
| } | ||
| return len(rsp.VmError) > 0, rsp, nil | ||
| return rsp.Failed(), rsp, nil | ||
| } | ||
|
|
||
| // Execute the binary search and hone in on an executable gas limit | ||
| hi, err = types.BinSearch(lo, hi, executable) | ||
| // We first execute the transaction at the highest allowable gas limit, since if this fails we | ||
| // can return error immediately. | ||
| failed, result, err := executable(hi) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| // Reject the transaction as invalid if it still fails at the highest allowance | ||
| if hi == gasCap { | ||
| failed, result, err := executable(hi) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| if failed { | ||
| if result != nil && result.VmError != vm.ErrOutOfGas.Error() { | ||
| if result.VmError == vm.ErrExecutionReverted.Error() { | ||
| return &types.EstimateGasResponse{ | ||
| Ret: result.Ret, | ||
| VmError: result.VmError, | ||
| }, nil | ||
| } | ||
| return nil, errors.New(result.VmError) | ||
| if failed { | ||
| if result != nil && result.VmError != vm.ErrOutOfGas.Error() { | ||
| if result.VmError == vm.ErrExecutionReverted.Error() { | ||
| return &types.EstimateGasResponse{ | ||
| Ret: result.Ret, | ||
| VmError: result.VmError, | ||
| }, nil | ||
| } | ||
| // Otherwise, the specified gas cap is too low | ||
| return nil, fmt.Errorf("gas required exceeds allowance (%d)", gasCap) | ||
| return nil, errors.New(result.VmError) | ||
| } | ||
| // Otherwise, the specified gas cap is too low | ||
| return nil, fmt.Errorf("gas required exceeds allowance (%d)", hi) | ||
| } | ||
|
|
||
| // For almost any transaction, the gas consumed by the unconstrained execution | ||
| // above lower-bounds the gas limit required for it to succeed. One exception | ||
| // is those that explicitly check gas remaining in order to execute within a | ||
| // given limit, but we probably don't want to return the lowest possible gas | ||
| // limit for these cases anyway. | ||
| // Use ExecutionGasUsed (actual gas before minGasMultiplier adjustment) for accurate estimation. | ||
| if result.ExecutionGasUsed > 0 { | ||
| lo = result.ExecutionGasUsed - 1 | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. why is it -1?
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. the binary search will start with lo+1 |
||
| } | ||
|
|
||
| // Execute the binary search and hone in on an executable gas limit | ||
| hi, err = types.BinSearch(lo, hi, executable) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| return &types.EstimateGasResponse{Gas: hi}, nil | ||
| } | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
assert gas_diff equals to 0 only works for a tx that doesn't trigger gas refunds.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
yes, in this call there is no refund