Skip to content
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

fix(evm): The estimated gas and the gas used for executing the message are not consistent #1943

Merged
merged 18 commits into from
Nov 2, 2023
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ Ref: https://keepachangelog.com/en/1.0.0/
### Bug Fixes

- (evm) [#1801](https://github.com/evmos/evmos/pull/1801) Fixed the problem gas_used is 0 when using evm type tx to transfer token to module account.
- (evm) [#1943](https://github.com/evmos/evmos/pull/1943) Fix gas estimation (`eth_estimateGas`) to be consistent with gas used in EVM extensions transactions
cuiweixie marked this conversation as resolved.
Show resolved Hide resolved

## [v15.0.0] - 2023-10-31

Expand Down
2 changes: 1 addition & 1 deletion tests/nix_tests/test_osmosis_outpost.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def test_ibc_transfer(ibc):

assert receipt.status == 1
# check gas used
assert receipt.gasUsed == 133680
assert receipt.gasUsed == 74092

fee = receipt.gasUsed * evmos_gas_price

Expand Down
2 changes: 1 addition & 1 deletion tests/nix_tests/test_precompiles.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def test_ibc_transfer(ibc):

assert receipt.status == 1
# check gas used
assert receipt.gasUsed == 133680
assert receipt.gasUsed == 74092

fee = receipt.gasUsed * evmos_gas_price

Expand Down
4 changes: 2 additions & 2 deletions x/erc20/keeper/evm.go
Original file line number Diff line number Diff line change
Expand Up @@ -186,10 +186,10 @@ func (k Keeper) CallEVMWithData(
return nil, errorsmod.Wrapf(errortypes.ErrJSONMarshal, "failed to marshal tx args: %s", err.Error())
}

gasRes, err := k.evmKeeper.EstimateGas(sdk.WrapSDKContext(ctx), &evmtypes.EthCallRequest{
gasRes, err := k.evmKeeper.EstimateGasInternal(sdk.WrapSDKContext(ctx), &evmtypes.EthCallRequest{
Args: args,
GasCap: config.DefaultGasCap,
})
}, evmtypes.Internal)
if err != nil {
return nil, err
}
Expand Down
6 changes: 3 additions & 3 deletions x/erc20/keeper/evm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -251,15 +251,15 @@ func (suite *KeeperTestSuite) TestForceFail() {
{
"Force estimate gas error",
func() {
mockEVMKeeper.On("EstimateGas", mock.Anything, mock.Anything).Return(nil, fmt.Errorf("forced EstimateGas error"))
mockEVMKeeper.On("EstimateGasInternal", mock.Anything, mock.Anything, mock.Anything).Return(nil, fmt.Errorf("forced EstimateGas error"))
},
true,
false,
},
{
"Force ApplyMessage error",
func() {
mockEVMKeeper.On("EstimateGas", mock.Anything, mock.Anything).Return(&evmtypes.EstimateGasResponse{Gas: uint64(200)}, nil)
mockEVMKeeper.On("EstimateGasInternal", mock.Anything, mock.Anything, mock.Anything).Return(&evmtypes.EstimateGasResponse{Gas: uint64(200)}, nil)
mockEVMKeeper.On("ApplyMessage", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil, fmt.Errorf("forced ApplyMessage error"))
},
true,
Expand All @@ -268,7 +268,7 @@ func (suite *KeeperTestSuite) TestForceFail() {
{
"Force ApplyMessage failed",
func() {
mockEVMKeeper.On("EstimateGas", mock.Anything, mock.Anything).Return(&evmtypes.EstimateGasResponse{Gas: uint64(200)}, nil)
mockEVMKeeper.On("EstimateGasInternal", mock.Anything, mock.Anything, mock.Anything).Return(&evmtypes.EstimateGasResponse{Gas: uint64(200)}, nil)
mockEVMKeeper.On("ApplyMessage", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&evmtypes.MsgEthereumTxResponse{VmError: "SomeError"}, nil)
},
true,
Expand Down
4 changes: 2 additions & 2 deletions x/erc20/keeper/mock_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ func (m *MockEVMKeeper) GetAccountWithoutBalance(_ sdk.Context, _ common.Address
return args.Get(0).(*statedb.Account)
}

func (m *MockEVMKeeper) EstimateGas(_ context.Context, _ *evm.EthCallRequest) (*evm.EstimateGasResponse, error) {
args := m.Called(mock.Anything, mock.Anything)
func (m *MockEVMKeeper) EstimateGasInternal(_ context.Context, _ *evm.EthCallRequest, _ evm.CallType) (*evm.EstimateGasResponse, error) {
args := m.Called(mock.Anything, mock.Anything, mock.Anything)
if args.Get(0) == nil {
return nil, args.Error(1)
}
Expand Down
40 changes: 20 additions & 20 deletions x/erc20/keeper/msg_server_test.go

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions x/erc20/keeper/proposals_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ func (suite KeeperTestSuite) TestRegisterCoin() { //nolint:govet // we can copy
authtypes.NewModuleAddress(govtypes.ModuleName), suite.app.AccountKeeper,
suite.app.BankKeeper, mockEVMKeeper, suite.app.StakingKeeper, suite.app.ClaimsKeeper)

mockEVMKeeper.On("EstimateGas", mock.Anything, mock.Anything).Return(&evmtypes.EstimateGasResponse{Gas: uint64(200)}, nil)
mockEVMKeeper.On("EstimateGasInternal", mock.Anything, mock.Anything, mock.Anything).Return(&evmtypes.EstimateGasResponse{Gas: uint64(200)}, nil)
mockEVMKeeper.On("ApplyMessage", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil, fmt.Errorf("forced ApplyMessage error"))
},
false,
Expand Down Expand Up @@ -298,7 +298,7 @@ func (suite KeeperTestSuite) TestRegisterERC20() { //nolint:govet // we can copy
authtypes.NewModuleAddress(govtypes.ModuleName), suite.app.AccountKeeper,
suite.app.BankKeeper, mockEVMKeeper, suite.app.StakingKeeper, suite.app.ClaimsKeeper)

mockEVMKeeper.On("EstimateGas", mock.Anything, mock.Anything).Return(&evmtypes.EstimateGasResponse{Gas: uint64(200)}, nil)
mockEVMKeeper.On("EstimateGasInternal", mock.Anything, mock.Anything, mock.Anything).Return(&evmtypes.EstimateGasResponse{Gas: uint64(200)}, nil)
mockEVMKeeper.On("ApplyMessage", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil, fmt.Errorf("forced ApplyMessage error"))
},
false,
Expand Down
2 changes: 1 addition & 1 deletion x/erc20/types/interfaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ type StakingKeeper interface {
type EVMKeeper interface {
GetParams(ctx sdk.Context) evmtypes.Params
GetAccountWithoutBalance(ctx sdk.Context, addr common.Address) *statedb.Account
EstimateGas(c context.Context, req *evmtypes.EthCallRequest) (*evmtypes.EstimateGasResponse, error)
EstimateGasInternal(c context.Context, req *evmtypes.EthCallRequest, fromType evmtypes.CallType) (*evmtypes.EstimateGasResponse, error)
ApplyMessage(ctx sdk.Context, msg core.Message, tracer vm.EVMLogger, commit bool) (*evmtypes.MsgEthereumTxResponse, error)
}

Expand Down
38 changes: 36 additions & 2 deletions x/evm/keeper/grpc_query.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
"math/big"
"time"

storetypes "github.com/cosmos/cosmos-sdk/store/types"

"github.com/ethereum/go-ethereum/eth/tracers"
"github.com/ethereum/go-ethereum/eth/tracers/logger"

Expand Down Expand Up @@ -256,6 +258,16 @@

// EstimateGas implements eth_estimateGas rpc api.
func (k Keeper) EstimateGas(c context.Context, req *types.EthCallRequest) (*types.EstimateGasResponse, error) {
return k.EstimateGasInternal(c, req, types.RPC)
}

// EstimateGasInternal returns the gas estimation for the corresponding request.
// This function is called from the RPC client (eth_estimateGas) and internally
// by the CallEVMWithData function in the x/erc20 module keeper.
// When called from the RPC client, we need to reset the gas meter before
// simulating the transaction to have
// an accurate gas estimation for EVM extensions transactions
cuiweixie marked this conversation as resolved.
Show resolved Hide resolved
func (k Keeper) EstimateGasInternal(c context.Context, req *types.EthCallRequest, fromType types.CallType) (*types.EstimateGasResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
Expand All @@ -267,7 +279,7 @@
}

if req.GasCap < ethparams.TxGas {
return nil, status.Error(codes.InvalidArgument, "gas cap cannot be lower than 21,000")
return nil, status.Errorf(codes.InvalidArgument, "gas cap cannot be lower than %d", ethparams.TxGas)
}

var args types.TransactionArgs
Expand Down Expand Up @@ -341,8 +353,30 @@
msg.IsFake(),
)

tmpCtx := ctx
if fromType == types.RPC {
tmpCtx, _ = ctx.CacheContext()

acct := k.GetAccount(tmpCtx, msg.From())

from := msg.From()
if acct == nil {
acc := k.accountKeeper.NewAccountWithAddress(tmpCtx, from[:])
k.accountKeeper.SetAccount(tmpCtx, acc)
acct = statedb.NewEmptyAccount()
}
// When submitting a transaction, the `EthIncrementSenderSequence` ante handler increases the account nonce
acct.Nonce = nonce + 1
err = k.SetAccount(tmpCtx, from, *acct)
if err != nil {
return true, nil, err
}

Check warning on line 373 in x/evm/keeper/grpc_query.go

View check run for this annotation

Codecov / codecov/patch

x/evm/keeper/grpc_query.go#L372-L373

Added lines #L372 - L373 were not covered by tests
// resetting the gasMeter after increasing the sequence to have an accurate gas estimation on EVM extensions transactions
tmpCtx = tmpCtx.WithGasMeter(evmostypes.NewInfiniteGasMeterWithLimit(msg.Gas())).WithKVGasConfig(storetypes.GasConfig{}).
WithTransientKVGasConfig(storetypes.GasConfig{})
}
// pass false to not commit StateDB
rsp, err = k.ApplyMessageWithConfig(ctx, msg, nil, false, cfg, txConfig)
rsp, err = k.ApplyMessageWithConfig(tmpCtx, msg, nil, false, cfg, txConfig)
if err != nil {
if errors.Is(err, core.ErrIntrinsicGas) {
return true, nil, nil // Special case, raise gas limit
Expand Down
12 changes: 12 additions & 0 deletions x/evm/types/call.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// Copyright Tharsis Labs Ltd.(Evmos)
// SPDX-License-Identifier:ENCL-1.0(https://github.com/evmos/evmos/blob/main/LICENSE)
package types

type CallType int

const (
// RPC call type is used on requests to eth_estimateGas rpc API endpoint
RPC CallType = iota + 1
// Internal call type is used in case of smart contract methods calls
Internal
)