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): proper tx gas refund outside of CallContract #2132

Merged
merged 18 commits into from
Jan 14, 2025
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ only on the "bankkeeper.BaseKeeper"'s gas consumption.
Remove unnecessary argument in the `VerifyFee` function, which returns the token
payment required based on the effective fee from the tx data. Improve
documentation.
- [#2131](https://github.com/NibiruChain/nibiru/pull/2131) - fix(evm): proper block gas calculation in precompile calls

#### Nibiru EVM | Before Audit 2 - 2024-12-06

Expand Down
9 changes: 0 additions & 9 deletions x/evm/keeper/call_contract.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,14 +108,11 @@ func (k Keeper) CallContractWithInput(
ctx, evmMsg, evm.NewNoOpTracer(), commit, evmCfg, txConfig, true,
)
if err != nil {
// We don't know the actual gas used, so consuming the gas limit
k.ResetGasMeterAndConsumeGas(ctx, gasLimit)
err = errors.Wrap(err, "failed to apply ethereum core message")
return
}

if evmResp.Failed() {
k.ResetGasMeterAndConsumeGas(ctx, evmResp.GasUsed)
if strings.Contains(evmResp.VmError, vm.ErrOutOfGas.Error()) {
err = fmt.Errorf("gas required exceeds allowance (%d)", gasLimit)
return
Expand All @@ -130,12 +127,6 @@ func (k Keeper) CallContractWithInput(

// Success, update block gas used and bloom filter
if commit {
blockGasUsed, err := k.AddToBlockGasUsed(ctx, evmResp.GasUsed)
if err != nil {
k.ResetGasMeterAndConsumeGas(ctx, ctx.GasMeter().Limit())
return nil, nil, errors.Wrap(err, "error adding transient gas used to block")
}
k.ResetGasMeterAndConsumeGas(ctx, blockGasUsed)
k.updateBlockBloom(ctx, evmResp, uint64(txConfig.LogIndex))
// TODO: remove after migrating logs
//err = k.EmitLogEvents(ctx, evmResp)
Expand Down
8 changes: 7 additions & 1 deletion x/evm/keeper/funtoken_from_coin.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,12 +78,18 @@ func (k *Keeper) deployERC20ForBankCoin(
bytecodeForCall := append(embeds.SmartContract_ERC20Minter.Bytecode, packedArgs...)

// nil address for contract creation
_, _, err = k.CallContractWithInput(
evmResp, _, err := k.CallContractWithInput(
ctx, evm.EVM_MODULE_ADDRESS, nil, true, bytecodeForCall, Erc20GasLimitDeploy,
)
if err != nil {
k.ResetGasMeterAndConsumeGas(ctx, ctx.GasMeter().Limit())
return gethcommon.Address{}, errors.Wrap(err, "failed to deploy ERC20 contract")
}
blockGasUsed, errBlockGasUsed := k.AddToBlockGasUsed(ctx, evmResp.GasUsed)
if errBlockGasUsed != nil {
return gethcommon.Address{}, errors.Wrap(errBlockGasUsed, "error adding transient gas used")
}
k.ResetGasMeterAndConsumeGas(ctx, blockGasUsed)

return erc20Addr, nil
}
2 changes: 2 additions & 0 deletions x/evm/keeper/funtoken_from_coin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,8 @@ func (s *FunTokenFromCoinSuite) TestConvertCoinToEvmAndBack() {
s.Require().NoError(err)
s.Require().Equal("0", balance.String())

deps.ResetGasMeter()

s.T().Log("sad: Convert more erc-20 to back to bank coin, insufficient funds")
_, err = deps.EvmKeeper.CallContract(
deps.Ctx,
Expand Down
3 changes: 2 additions & 1 deletion x/evm/keeper/keeper.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ func (k *Keeper) AddToBlockGasUsed(
) (blockGasUsed uint64, err error) {
// Either k.EvmState.BlockGasUsed.GetOr() or k.EvmState.BlockGasUsed.Set()
// also consume gas and could panic.
defer HandleOutOfGasPanic(&err, "")
defer HandleOutOfGasPanic(&err, "")()

blockGasUsed = k.EvmState.BlockGasUsed.GetOr(ctx, 0) + gasUsed
if blockGasUsed < gasUsed {
Expand Down Expand Up @@ -147,6 +147,7 @@ func HandleOutOfGasPanic(err *error, format string) func() {
if r := recover(); r != nil {
switch r.(type) {
case sdk.ErrorOutOfGas:

*err = vm.ErrOutOfGas
default:
panic(r)
Expand Down
20 changes: 13 additions & 7 deletions x/evm/keeper/msg_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,22 +72,21 @@ func (k *Keeper) EthereumTx(

k.updateBlockBloom(ctx, evmResp, uint64(txConfig.LogIndex))

blockGasUsed, err := k.AddToBlockGasUsed(ctx, evmResp.GasUsed)
if err != nil {
return nil, errors.Wrap(err, "error adding transient gas used to block")
}

// refund gas in order to match the Ethereum gas consumption instead of the
// default SDK one.
refundGas := uint64(0)
if evmMsg.Gas() > blockGasUsed {
refundGas = evmMsg.Gas() - blockGasUsed
if evmMsg.Gas() > evmResp.GasUsed {
refundGas = evmMsg.Gas() - evmResp.GasUsed
}
weiPerGas := txMsg.EffectiveGasPriceWeiPerGas(evmConfig.BaseFeeWei)
if err = k.RefundGas(ctx, evmMsg.From(), refundGas, weiPerGas); err != nil {
return nil, errors.Wrapf(err, "error refunding leftover gas to sender %s", evmMsg.From())
}

blockGasUsed, err := k.AddToBlockGasUsed(ctx, evmResp.GasUsed)
if err != nil {
return nil, errors.Wrap(err, "error adding transient gas used to block")
}
// reset the gas meter for current TxMsg (EthereumTx)
k.ResetGasMeterAndConsumeGas(ctx, blockGasUsed)

Expand Down Expand Up @@ -563,8 +562,15 @@ func (k Keeper) convertCoinToEvmBornCoin(
coin.Amount.BigInt(),
)
if err != nil {
k.ResetGasMeterAndConsumeGas(ctx, ctx.GasMeter().Limit())
return nil, err
}
blockGasUsed, errBlockGasUsed := k.AddToBlockGasUsed(ctx, evmResp.GasUsed)
if errBlockGasUsed != nil {
return nil, errors.Wrap(errBlockGasUsed, "error adding transient gas used")
}
Comment on lines +574 to +577
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Assess potential error impact on block gas used.

This snippet adds to the block’s total gas usage and then checks for errors. Confirm that an error during AddToBlockGasUsed or subsequent steps won’t accidentally skip the consumption of already-calculated usage, resulting in potential gas mismatch.

k.ResetGasMeterAndConsumeGas(ctx, blockGasUsed)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't we consume evmResp.GasUsed instead of blockGasUsed here?


if evmResp.Failed() {
return nil,
fmt.Errorf("failed to mint erc-20 tokens of contract %s", erc20Addr.String())
Expand Down
6 changes: 4 additions & 2 deletions x/evm/precompile/funtoken_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,8 @@ func (s *FuntokenSuite) TestHappyPath() {
sdk.NewCoins(sdk.NewCoin(s.funtoken.BankDenom, sdk.NewInt(69_420))),
))

deps.ResetGasMeter()

s.Run("IFunToken.bankBalance", func() {
s.Require().NotEmpty(funtoken.BankDenom)
evmResp, err := deps.EvmKeeper.CallContract(
Expand Down Expand Up @@ -222,7 +224,6 @@ func (s *FuntokenSuite) TestHappyPath() {
input, err := embeds.SmartContract_FunToken.ABI.Pack(string(precompile.FunTokenMethod_sendToBank), callArgs...)
s.NoError(err)

deps.ResetGasMeter()
_, ethTxResp, err := evmtest.CallContractTx(
&deps,
precompile.PrecompileAddr_FunToken,
Expand All @@ -242,7 +243,6 @@ func (s *FuntokenSuite) TestHappyPath() {
s.Equal(sdk.NewInt(420).String(),
deps.App.BankKeeper.GetBalance(deps.Ctx, randomAcc, funtoken.BankDenom).Amount.String(),
)
s.deps.ResetGasMeter()
s.Require().NotNil(deps.EvmKeeper.Bank.StateDB)

s.T().Log("Parse the response contract addr and response bytes")
Expand All @@ -255,6 +255,8 @@ func (s *FuntokenSuite) TestHappyPath() {
s.NoError(err)
s.Require().Equal("420", sentAmt.String())

deps.ResetGasMeter()

s.Run("IFuntoken.balance", func() {
evmResp, err := deps.EvmKeeper.CallContract(
deps.Ctx,
Expand Down
Loading