-
Notifications
You must be signed in to change notification settings - Fork 193
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
test(evm): unit tests for evm_ante #1912
Merged
Merged
Changes from 14 commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
c82c668
test(evm): unit tests for evm_ante_sigverify
onikonychev cba648f
chore: changelog update
onikonychev 87bbee0
Merge branch 'main' of github.com:NibiruChain/nibiru into on/evm-ante…
onikonychev af87b51
test(evm): ante gas wanted full coverage
onikonychev a862309
test(evm): ante handler setup ctx coverage
onikonychev 9b20a6c
test(evm): ante handler emit event coverage
onikonychev 5a237b6
test(evm): evmante hanlers emit_event, setup_ctx and validate_basic
onikonychev 032c6ae
chore: resolve conflicts
onikonychev c631d4e
test(evm): evmante validate basic full coverage
onikonychev f807e6f
fix: lint
onikonychev 93ca583
test(evm): evmante fee checker coverage
onikonychev 52ef738
test(evm): evmante fees test coverage
onikonychev 89cc591
test(evm): split evmante handlers 1 handler 1 file
onikonychev ec4dfca
test(evm): evmante tests for can_transfer, fee_checker, gas_comsume
onikonychev fde2383
test(evm): evmante increment_sender_seq, validate_basic, gas_consume,…
onikonychev 8a50e0e
test: tried -v flag for integration tests
onikonychev 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 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 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,94 @@ | ||
// Copyright (c) 2023-2024 Nibi, Inc. | ||
package app | ||
|
||
import ( | ||
"math/big" | ||
|
||
"cosmossdk.io/errors" | ||
sdk "github.com/cosmos/cosmos-sdk/types" | ||
errortypes "github.com/cosmos/cosmos-sdk/types/errors" | ||
|
||
"github.com/NibiruChain/nibiru/x/evm" | ||
"github.com/NibiruChain/nibiru/x/evm/statedb" | ||
|
||
gethcommon "github.com/ethereum/go-ethereum/common" | ||
gethcore "github.com/ethereum/go-ethereum/core/types" | ||
) | ||
|
||
// CanTransferDecorator checks if the sender is allowed to transfer funds according to the EVM block | ||
// context rules. | ||
type CanTransferDecorator struct { | ||
AppKeepers | ||
} | ||
|
||
// NewCanTransferDecorator creates a new CanTransferDecorator instance. | ||
func NewCanTransferDecorator(k AppKeepers) CanTransferDecorator { | ||
return CanTransferDecorator{ | ||
AppKeepers: k, | ||
} | ||
} | ||
|
||
// AnteHandle creates an EVM from the message and calls the BlockContext CanTransfer function to | ||
// see if the address can execute the transaction. | ||
func (ctd CanTransferDecorator) AnteHandle( | ||
ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler, | ||
) (sdk.Context, error) { | ||
params := ctd.EvmKeeper.GetParams(ctx) | ||
ethCfg := evm.EthereumConfig(ctd.EvmKeeper.EthChainID(ctx)) | ||
signer := gethcore.MakeSigner(ethCfg, big.NewInt(ctx.BlockHeight())) | ||
|
||
for _, msg := range tx.GetMsgs() { | ||
msgEthTx, ok := msg.(*evm.MsgEthereumTx) | ||
if !ok { | ||
return ctx, errors.Wrapf(errortypes.ErrUnknownRequest, "invalid message type %T, expected %T", msg, (*evm.MsgEthereumTx)(nil)) | ||
} | ||
|
||
baseFee := ctd.EvmKeeper.GetBaseFee(ctx) | ||
|
||
coreMsg, err := msgEthTx.AsMessage(signer, baseFee) | ||
if err != nil { | ||
return ctx, errors.Wrapf( | ||
err, | ||
"failed to create an ethereum core.Message from signer %T", signer, | ||
) | ||
} | ||
|
||
if baseFee == nil { | ||
return ctx, errors.Wrap( | ||
evm.ErrInvalidBaseFee, | ||
"base fee is supported but evm block context value is nil", | ||
) | ||
} | ||
if coreMsg.GasFeeCap().Cmp(baseFee) < 0 { | ||
return ctx, errors.Wrapf( | ||
errortypes.ErrInsufficientFee, | ||
"max fee per gas less than block base fee (%s < %s)", | ||
coreMsg.GasFeeCap(), baseFee, | ||
) | ||
} | ||
|
||
// NOTE: pass in an empty coinbase address and nil tracer as we don't need them for the check below | ||
cfg := &statedb.EVMConfig{ | ||
ChainConfig: ethCfg, | ||
Params: params, | ||
CoinBase: gethcommon.Address{}, | ||
BaseFee: baseFee, | ||
} | ||
|
||
stateDB := statedb.New(ctx, &ctd.EvmKeeper, statedb.NewEmptyTxConfig(gethcommon.BytesToHash(ctx.HeaderHash().Bytes()))) | ||
evm := ctd.EvmKeeper.NewEVM(ctx, coreMsg, cfg, evm.NewNoOpTracer(), stateDB) | ||
|
||
// check that caller has enough balance to cover asset transfer for **topmost** call | ||
// NOTE: here the gas consumed is from the context with the infinite gas meter | ||
if coreMsg.Value().Sign() > 0 && !evm.Context.CanTransfer(stateDB, coreMsg.From(), coreMsg.Value()) { | ||
return ctx, errors.Wrapf( | ||
errortypes.ErrInsufficientFunds, | ||
"failed to transfer %s from address %s using the EVM block context transfer function", | ||
coreMsg.Value(), | ||
coreMsg.From(), | ||
) | ||
} | ||
} | ||
|
||
return next(ctx, tx, simulate) | ||
} |
This file contains 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,97 @@ | ||
package app_test | ||
|
||
import ( | ||
sdk "github.com/cosmos/cosmos-sdk/types" | ||
|
||
"github.com/NibiruChain/nibiru/app" | ||
"github.com/NibiruChain/nibiru/eth" | ||
"github.com/NibiruChain/nibiru/x/evm/evmtest" | ||
) | ||
|
||
func (s *TestSuite) TestNewDynamicFeeChecker() { | ||
testCases := []struct { | ||
name string | ||
txSetup func(deps *evmtest.TestDeps) sdk.FeeTx | ||
ctxSetup func(deps *evmtest.TestDeps) | ||
wantErr string | ||
wantFee int64 | ||
wantPriority int64 | ||
}{ | ||
{ | ||
name: "happy: genesis tx with sufficient fee", | ||
ctxSetup: func(deps *evmtest.TestDeps) { | ||
gasPrice := sdk.NewInt64Coin("unibi", 1) | ||
deps.Ctx = deps.Ctx. | ||
WithBlockHeight(0). | ||
WithMinGasPrices( | ||
sdk.NewDecCoins(sdk.NewDecCoinFromCoin(gasPrice)), | ||
). | ||
WithIsCheckTx(true) | ||
}, | ||
txSetup: func(deps *evmtest.TestDeps) sdk.FeeTx { | ||
txMsg := happyCreateContractTx(deps) | ||
txBuilder := deps.EncCfg.TxConfig.NewTxBuilder() | ||
tx, err := txMsg.BuildTx(txBuilder, eth.EthBaseDenom) | ||
s.Require().NoError(err) | ||
return tx | ||
}, | ||
wantErr: "", | ||
wantFee: gasLimitCreateContract().Int64(), | ||
wantPriority: 0, | ||
}, | ||
{ | ||
name: "sad: genesis tx insufficient fee", | ||
ctxSetup: func(deps *evmtest.TestDeps) { | ||
gasPrice := sdk.NewInt64Coin("unibi", 2) | ||
deps.Ctx = deps.Ctx. | ||
WithBlockHeight(0). | ||
WithMinGasPrices( | ||
sdk.NewDecCoins(sdk.NewDecCoinFromCoin(gasPrice)), | ||
). | ||
WithIsCheckTx(true) | ||
}, | ||
txSetup: func(deps *evmtest.TestDeps) sdk.FeeTx { | ||
txMsg := happyCreateContractTx(deps) | ||
txBuilder := deps.EncCfg.TxConfig.NewTxBuilder() | ||
tx, err := txMsg.BuildTx(txBuilder, eth.EthBaseDenom) | ||
s.Require().NoError(err) | ||
return tx | ||
}, | ||
wantErr: "insufficient fee", | ||
}, | ||
{ | ||
name: "happy: tx with sufficient fee", | ||
txSetup: func(deps *evmtest.TestDeps) sdk.FeeTx { | ||
txMsg := happyCreateContractTx(deps) | ||
txBuilder := deps.EncCfg.TxConfig.NewTxBuilder() | ||
tx, err := txMsg.BuildTx(txBuilder, eth.EthBaseDenom) | ||
s.Require().NoError(err) | ||
return tx | ||
}, | ||
wantErr: "", | ||
wantFee: gasLimitCreateContract().Int64(), | ||
wantPriority: 0, | ||
}, | ||
} | ||
|
||
for _, tc := range testCases { | ||
s.Run(tc.name, func() { | ||
deps := evmtest.NewTestDeps() | ||
checker := app.NewDynamicFeeChecker(deps.K) | ||
|
||
if tc.ctxSetup != nil { | ||
tc.ctxSetup(&deps) | ||
} | ||
|
||
fee, priority, err := checker(deps.Ctx, tc.txSetup(&deps)) | ||
|
||
if tc.wantErr != "" { | ||
s.Require().ErrorContains(err, tc.wantErr) | ||
return | ||
} | ||
s.Require().NoError(err) | ||
s.Require().Equal(tc.wantFee, fee.AmountOf("unibi").Int64()) | ||
s.Require().Equal(tc.wantPriority, priority) | ||
}) | ||
} | ||
} | ||
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. Enhance test coverage for edge cases. The current tests cover basic scenarios. Consider adding more edge cases, such as boundary values for fees and gas prices, to ensure robustness. |
This file contains 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,59 @@ | ||
// Copyright (c) 2023-2024 Nibi, Inc. | ||
package app | ||
|
||
import ( | ||
"strconv" | ||
|
||
errorsmod "cosmossdk.io/errors" | ||
sdk "github.com/cosmos/cosmos-sdk/types" | ||
errortypes "github.com/cosmos/cosmos-sdk/types/errors" | ||
|
||
"github.com/NibiruChain/nibiru/x/evm" | ||
) | ||
|
||
// EthEmitEventDecorator emit events in ante handler in case of tx execution failed (out of block gas limit). | ||
type EthEmitEventDecorator struct { | ||
AppKeepers | ||
} | ||
|
||
// NewEthEmitEventDecorator creates a new EthEmitEventDecorator | ||
func NewEthEmitEventDecorator(k AppKeepers) EthEmitEventDecorator { | ||
return EthEmitEventDecorator{AppKeepers: k} | ||
} | ||
|
||
// AnteHandle emits some basic events for the eth messages | ||
func (eeed EthEmitEventDecorator) AnteHandle( | ||
ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler, | ||
) (newCtx sdk.Context, err error) { | ||
// After eth tx passed ante handler, the fee is deducted and nonce increased, | ||
// it shouldn't be ignored by json-rpc. We need to emit some events at the | ||
// very end of ante handler to be indexed by the consensus engine. | ||
txIndex := eeed.EvmKeeper.EVMState().BlockTxIndex.GetOr(ctx, 0) | ||
|
||
for i, msg := range tx.GetMsgs() { | ||
msgEthTx, ok := msg.(*evm.MsgEthereumTx) | ||
if !ok { | ||
return ctx, errorsmod.Wrapf( | ||
errortypes.ErrUnknownRequest, | ||
"invalid message type %T, expected %T", | ||
msg, (*evm.MsgEthereumTx)(nil), | ||
) | ||
} | ||
|
||
// emit ethereum tx hash as an event so that it can be indexed by | ||
// Tendermint for query purposes it's emitted in ante handler, so we can | ||
// query failed transaction (out of block gas limit). | ||
ctx.EventManager().EmitEvent( | ||
sdk.NewEvent( | ||
evm.EventTypeEthereumTx, | ||
sdk.NewAttribute(evm.AttributeKeyEthereumTxHash, msgEthTx.Hash), | ||
sdk.NewAttribute( | ||
evm.AttributeKeyTxIndex, strconv.FormatUint(txIndex+uint64(i), | ||
10, | ||
), | ||
), // #nosec G701 | ||
)) | ||
} | ||
|
||
return next(ctx, tx, simulate) | ||
} |
This file contains 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,79 @@ | ||
package app_test | ||
|
||
import ( | ||
sdk "github.com/cosmos/cosmos-sdk/types" | ||
"github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx" | ||
|
||
"github.com/NibiruChain/nibiru/x/evm" | ||
|
||
"github.com/NibiruChain/nibiru/app" | ||
"github.com/NibiruChain/nibiru/x/evm/evmtest" | ||
tf "github.com/NibiruChain/nibiru/x/tokenfactory/types" | ||
) | ||
|
||
func (s *TestSuite) TestEthEmitEventDecorator() { | ||
testCases := []struct { | ||
name string | ||
txSetup func(deps *evmtest.TestDeps) sdk.Tx | ||
wantErr string | ||
}{ | ||
{ | ||
name: "sad: non ethereum tx", | ||
txSetup: func(deps *evmtest.TestDeps) sdk.Tx { | ||
return legacytx.StdTx{ | ||
Msgs: []sdk.Msg{ | ||
&tf.MsgMint{}, | ||
}, | ||
} | ||
}, | ||
wantErr: "invalid message", | ||
}, | ||
{ | ||
name: "happy: eth tx emitted event", | ||
txSetup: func(deps *evmtest.TestDeps) sdk.Tx { | ||
tx := happyCreateContractTx(deps) | ||
return tx | ||
}, | ||
wantErr: "", | ||
}, | ||
} | ||
|
||
for _, tc := range testCases { | ||
s.Run(tc.name, func() { | ||
deps := evmtest.NewTestDeps() | ||
stateDB := deps.StateDB() | ||
anteDec := app.NewEthEmitEventDecorator(deps.Chain.AppKeepers) | ||
|
||
tx := tc.txSetup(&deps) | ||
s.Require().NoError(stateDB.Commit()) | ||
|
||
_, err := anteDec.AnteHandle( | ||
deps.Ctx, tx, false, NextNoOpAnteHandler, | ||
) | ||
if tc.wantErr != "" { | ||
s.Require().ErrorContains(err, tc.wantErr) | ||
return | ||
} | ||
s.Require().NoError(err) | ||
events := deps.Ctx.EventManager().Events() | ||
|
||
s.Require().Greater(len(events), 0) | ||
event := events[len(events)-1] | ||
s.Require().Equal(evm.EventTypeEthereumTx, event.Type) | ||
|
||
// Convert tx to msg to get hash | ||
txMsg, ok := tx.GetMsgs()[0].(*evm.MsgEthereumTx) | ||
s.Require().True(ok) | ||
|
||
// TX hash attr must present | ||
attr, ok := event.GetAttribute(evm.AttributeKeyEthereumTxHash) | ||
s.Require().True(ok, "tx hash attribute not found") | ||
s.Require().Equal(txMsg.Hash, attr.Value) | ||
|
||
// TX index attr must present | ||
attr, ok = event.GetAttribute(evm.AttributeKeyTxIndex) | ||
s.Require().True(ok, "tx index attribute not found") | ||
s.Require().Equal("0", attr.Value) | ||
}) | ||
} | ||
} |
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.
Ensure robust error handling and clear error messages.
The error messages are clear, but consider adding more specific logging for debugging purposes, especially around the Ethereum transaction handling in lines 48-54 and 82-90.