Skip to content

Commit

Permalink
test: fixed tests after merge
Browse files Browse the repository at this point in the history
  • Loading branch information
onikonychev committed Jan 8, 2025
2 parents b4c7bba + 8c6e021 commit 0932e28
Show file tree
Hide file tree
Showing 29 changed files with 1,390 additions and 26 deletions.
7 changes: 6 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,14 +51,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
Remove unnecessary argument in the `VerifyFee` function, which returns the token
payment required based on the effective fee from the tx data. Improve
documentation.
- [#2127](https://github.com/NibiruChain/nibiru/pull/2127) - fix(vesting): disabled built in auth/vesting module functionality
- [#2125](https://github.com/NibiruChain/nibiru/pull/2125) - feat(evm-precompile):Emit EVM events created to reflect the ABCI events that occur outside the EVM to make sure that block explorers and indexers can find indexed ABCI event information.
- [#2127](https://github.com/NibiruChain/nibiru/pull/2127) - fix(vesting): disabled built in auth/vesting module functionality
- [#2129](https://github.com/NibiruChain/nibiru/pull/2129) - fix(evm): issue with infinite recursion in erc20 funtoken contracts
- [#2130](https://github.com/NibiruChain/nibiru/pull/2130) - fix(evm): proper nonce management in statedb
- [#2132](https://github.com/NibiruChain/nibiru/pull/2132) - fix(evm): proper tx gas refund
- [#2134](https://github.com/NibiruChain/nibiru/pull/2134) - fix(evm): query of NIBI should use bank state, not the StateDB
- [#2139](https://github.com/NibiruChain/nibiru/pull/2139) - fix(evm): erc20 born funtoken: properly burn bank coins after converting coin back to erc20
- [#2140](https://github.com/NibiruChain/nibiru/pull/2140) - fix(bank): bank keeper extension now charges gas for the bank operations
- [#2141](https://github.com/NibiruChain/nibiru/pull/2141) - refactor: simplify account retrieval operation in `nibid q evm account`.
- [#2142](https://github.com/NibiruChain/nibiru/pull/2142) - fix(bank): add additional missing methods to the NibiruBankKeeper
- [#2144](https://github.com/NibiruChain/nibiru/pull/2144) - feat(token-registry): Implement strongly typed Nibiru Token Registry and generation command
- [#2145](https://github.com/NibiruChain/nibiru/pull/2145) - chore(token-registry): add xNIBI Astrovault LST to registry
- [#2147](https://github.com/NibiruChain/nibiru/pull/2147) - fix(simapp): manually add x/vesting Cosmos-SDK module types to the codec in simulation tests since they are expected by default

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

Expand Down
82 changes: 76 additions & 6 deletions eth/rpc/backend/backend_suite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ import (
"crypto/ecdsa"
"fmt"
"math/big"
"sync"
"testing"
"time"

"github.com/cosmos/cosmos-sdk/client/flags"
sdk "github.com/cosmos/cosmos-sdk/types"
gethcommon "github.com/ethereum/go-ethereum/common"
gethcore "github.com/ethereum/go-ethereum/core/types"
Expand All @@ -32,6 +34,9 @@ import (
"github.com/NibiruChain/nibiru/v2/x/common/testutil/testnetwork"
)

// testMutex is used to synchronize the tests which are broadcasting transactions concurrently
var testMutex sync.Mutex

var (
recipient = evmtest.NewEthPrivAcc().EthAddr
amountToSend = evm.NativeToWei(big.NewInt(1))
Expand Down Expand Up @@ -115,13 +120,12 @@ func (s *BackendSuite) SendNibiViaEthTransfer(
amount *big.Int,
waitForNextBlock bool,
) gethcommon.Hash {
nonce, err := s.backend.GetTransactionCount(s.fundedAccEthAddr, rpc.EthPendingBlockNumber)
s.Require().NoError(err)
nonce := s.getCurrentNonce(s.fundedAccEthAddr)
return SendTransaction(
s,
&gethcore.LegacyTx{
To: &to,
Nonce: uint64(*nonce),
Nonce: uint64(nonce),
Value: amount,
Gas: params.TxGas,
GasPrice: big.NewInt(1),
Expand All @@ -135,20 +139,20 @@ func (s *BackendSuite) DeployTestContract(waitForNextBlock bool) (gethcommon.Has
packedArgs, err := embeds.SmartContract_TestERC20.ABI.Pack("")
s.Require().NoError(err)
bytecodeForCall := append(embeds.SmartContract_TestERC20.Bytecode, packedArgs...)
nonce, err := s.backend.GetTransactionCount(s.fundedAccEthAddr, rpc.EthPendingBlockNumber)
nonce := s.getCurrentNonce(s.fundedAccEthAddr)
s.Require().NoError(err)

txHash := SendTransaction(
s,
&gethcore.LegacyTx{
Nonce: uint64(*nonce),
Nonce: uint64(nonce),
Data: bytecodeForCall,
Gas: 1500_000,
GasPrice: big.NewInt(1),
},
waitForNextBlock,
)
contractAddr := crypto.CreateAddress(s.fundedAccEthAddr, (uint64)(*nonce))
contractAddr := crypto.CreateAddress(s.fundedAccEthAddr, nonce)
return txHash, contractAddr
}

Expand Down Expand Up @@ -198,3 +202,69 @@ func (s *BackendSuite) getUnibiBalance(address gethcommon.Address) *big.Int {
s.Require().NoError(err)
return evm.WeiToNative(balance.ToInt())
}

// getCurrentNonce returns the current nonce of the funded account
func (s *BackendSuite) getCurrentNonce(address gethcommon.Address) uint64 {
nonce, err := s.backend.GetTransactionCount(s.fundedAccEthAddr, rpc.EthPendingBlockNumber)
s.Require().NoError(err)

return uint64(*nonce)
}

// broadcastSDKTx broadcasts the given SDK transaction and returns the response
func (s *BackendSuite) broadcastSDKTx(sdkTx sdk.Tx) *sdk.TxResponse {
txBytes, err := s.backend.ClientCtx().TxConfig.TxEncoder()(sdkTx)
s.Require().NoError(err)

syncCtx := s.backend.ClientCtx().WithBroadcastMode(flags.BroadcastSync)
rsp, err := syncCtx.BroadcastTx(txBytes)
s.Require().NoError(err)
return rsp
}

// buildContractCreationTx builds a contract creation transaction
func (s *BackendSuite) buildContractCreationTx(nonce uint64) gethcore.Transaction {
packedArgs, err := embeds.SmartContract_TestERC20.ABI.Pack("")
s.Require().NoError(err)
bytecodeForCall := append(embeds.SmartContract_TestERC20.Bytecode, packedArgs...)

creationTx := &gethcore.LegacyTx{
Nonce: nonce,
Data: bytecodeForCall,
Gas: 1_500_000,
GasPrice: big.NewInt(1),
}

signer := gethcore.LatestSignerForChainID(s.ethChainID)
signedTx, err := gethcore.SignNewTx(s.fundedAccPrivateKey, signer, creationTx)
s.Require().NoError(err)

return *signedTx
}

// buildContractCallTx builds a contract call transaction
func (s *BackendSuite) buildContractCallTx(nonce uint64, contractAddr gethcommon.Address) gethcore.Transaction {
//recipient := crypto.CreateAddress(s.fundedAccEthAddr, 29381)
transferAmount := big.NewInt(100)

packedArgs, err := embeds.SmartContract_TestERC20.ABI.Pack(
"transfer",
recipient,
transferAmount,
)
s.Require().NoError(err)

transferTx := &gethcore.LegacyTx{
Nonce: nonce,
Data: packedArgs,
Gas: 100_000,
GasPrice: big.NewInt(1),
To: &contractAddr,
}

signer := gethcore.LatestSignerForChainID(s.ethChainID)
signedTx, err := gethcore.SignNewTx(s.fundedAccPrivateKey, signer, transferTx)
s.Require().NoError(err)

return *signedTx
}
8 changes: 8 additions & 0 deletions eth/rpc/backend/gas_used_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ import (
// Test creates 2 eth transfer txs that are supposed to be included in the same block.
// It checks that gas used is the same for both txs and the total block gas is greater than the sum of 2 gas used.
func (s *BackendSuite) TestGasUsedTransfers() {
// Test is broadcasting txs. Lock to avoid nonce conflicts.
testMutex.Lock()
defer testMutex.Unlock()

// Start with new block
s.Require().NoError(s.network.WaitForNextBlock())
balanceBefore := s.getUnibiBalance(s.fundedAccEthAddr)
Expand Down Expand Up @@ -64,6 +68,10 @@ func (s *BackendSuite) TestGasUsedTransfers() {
// It also checks that txs are included in the same block and block gas is greater or equals
// to the total gas used by txs.
func (s *BackendSuite) TestGasUsedFunTokens() {
// Test is broadcasting txs. Lock to avoid nonce conflicts.
testMutex.Lock()
defer testMutex.Unlock()

// Create funtoken from erc20
erc20Addr, err := eth.NewEIP55AddrFromStr(testContractAddress.String())
s.Require().NoError(err)
Expand Down
79 changes: 79 additions & 0 deletions eth/rpc/backend/nonce_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package backend_test

import (
sdkmath "cosmossdk.io/math"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
sdk "github.com/cosmos/cosmos-sdk/types"
authtx "github.com/cosmos/cosmos-sdk/x/auth/tx"
gethcore "github.com/ethereum/go-ethereum/core/types"

"github.com/NibiruChain/nibiru/v2/x/evm"
)

// TestNonceIncrementWithMultipleMsgsTx tests that the nonce is incremented correctly
// when multiple messages are included in a single transaction.
func (s *BackendSuite) TestNonceIncrementWithMultipleMsgsTx() {
// Test is broadcasting txs. Lock to avoid nonce conflicts.
testMutex.Lock()
defer testMutex.Unlock()

nonce := s.getCurrentNonce(s.fundedAccEthAddr)

// Create series of 3 tx messages. Expecting nonce to be incremented by 3
creationTx := s.buildContractCreationTx(nonce)
firstTransferTx := s.buildContractCallTx(nonce+1, testContractAddress)
secondTransferTx := s.buildContractCallTx(nonce+2, testContractAddress)

// Create and broadcast SDK transaction
sdkTx := s.buildSDKTxWithEVMMessages(
creationTx,
firstTransferTx,
secondTransferTx,
)

// Broadcast transaction
rsp := s.broadcastSDKTx(sdkTx)
s.Assert().NotEqual(rsp.Code, 0)
s.Require().NoError(s.network.WaitForNextBlock())

// Expected nonce should be incremented by 3
currentNonce := s.getCurrentNonce(s.fundedAccEthAddr)
s.Assert().Equal(nonce+3, currentNonce)

// Assert all transactions included in block
for _, tx := range []gethcore.Transaction{creationTx, firstTransferTx, secondTransferTx} {
blockNum, blockHash, _ := WaitForReceipt(s, tx.Hash())
s.Require().NotNil(blockNum)
s.Require().NotNil(blockHash)
}
}

// buildSDKTxWithEVMMessages creates an SDK transaction with EVM messages
func (s *BackendSuite) buildSDKTxWithEVMMessages(txs ...gethcore.Transaction) sdk.Tx {
msgs := make([]sdk.Msg, len(txs))
for i, tx := range txs {
msg := &evm.MsgEthereumTx{}
err := msg.FromEthereumTx(&tx)
s.Require().NoError(err)
msgs[i] = msg
}

option, err := codectypes.NewAnyWithValue(&evm.ExtensionOptionsEthereumTx{})
s.Require().NoError(err)

txBuilder, _ := s.backend.ClientCtx().TxConfig.NewTxBuilder().(authtx.ExtensionOptionsTxBuilder)
txBuilder.SetExtensionOptions(option)
err = txBuilder.SetMsgs(msgs...)
s.Require().NoError(err)

// Set fees for all messages
totalGas := uint64(0)
for _, tx := range txs {
totalGas += tx.Gas()
}
fees := sdk.NewCoins(sdk.NewCoin("unibi", sdkmath.NewIntFromUint64(totalGas)))
txBuilder.SetFeeAmount(fees)
txBuilder.SetGasLimit(totalGas)

return txBuilder.GetTx()
}
4 changes: 4 additions & 0 deletions justfile
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@ gen-embeds:

alias gen-proto := proto-gen

# Generate the Nibiru Token Registry files
gen-token-registry:
go run token-registry/main/main.go

# Generate protobuf-based types in Rust
gen-proto-rs:
bash proto/buf.gen.rs.sh
Expand Down
21 changes: 17 additions & 4 deletions simapp/sim_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types"
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
vesting "github.com/cosmos/cosmos-sdk/x/auth/vesting/types"
authzkeeper "github.com/cosmos/cosmos-sdk/x/authz/keeper"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types"
Expand All @@ -36,6 +37,7 @@ import (
"github.com/stretchr/testify/require"

"github.com/NibiruChain/nibiru/v2/app"
"github.com/NibiruChain/nibiru/v2/app/codec"
devgastypes "github.com/NibiruChain/nibiru/v2/x/devgas/v1/types"
epochstypes "github.com/NibiruChain/nibiru/v2/x/epochs/types"
inflationtypes "github.com/NibiruChain/nibiru/v2/x/inflation/types"
Expand All @@ -59,6 +61,17 @@ type StoreKeysPrefixes struct {
Prefixes [][]byte
}

// makeEncodingConfig, similar to [app.MakeEncodingConfig], creates an
// EncodingConfig for an amino based test configuration. However, this function
// registers interfaces and types that are expected by default in the Cosmos-SDK
// even if they are disabled on Nibiru. This is the case for x/vesting Cosmos-SDK
// module.
func makeEncodingConfig() codec.EncodingConfig {
encCfg := app.MakeEncodingConfig()
vesting.RegisterInterfaces(encCfg.InterfaceRegistry)
return encCfg
}

func TestFullAppSimulation(t *testing.T) {
config := simcli.NewConfigFromFlags()
config.ChainID = SimAppChainID
Expand All @@ -78,7 +91,7 @@ func TestFullAppSimulation(t *testing.T) {
appOptions[flags.FlagHome] = app.DefaultNodeHome
appOptions[server.FlagInvCheckPeriod] = simcli.FlagPeriodValue

encoding := app.MakeEncodingConfig()
encoding := makeEncodingConfig()
app := app.NewNibiruApp(logger, db, nil, true, encoding, appOptions, baseapp.SetChainID(SimAppChainID))
require.Equal(t, "Nibiru", app.Name())
appCodec := app.AppCodec()
Expand Down Expand Up @@ -132,7 +145,7 @@ func TestAppStateDeterminism(t *testing.T) {
for j := 0; j < numTimesToRunPerSeed; j++ {
db := dbm.NewMemDB()
logger := log.NewNopLogger()
encoding := app.MakeEncodingConfig()
encoding := makeEncodingConfig()

app := app.NewNibiruApp(logger, db, nil, true, encoding, appOptions, baseapp.SetChainID(SimAppChainID))
appCodec := app.AppCodec()
Expand Down Expand Up @@ -191,7 +204,7 @@ func TestAppImportExport(t *testing.T) {
appOptions[flags.FlagHome] = app.DefaultNodeHome
appOptions[server.FlagInvCheckPeriod] = simcli.FlagPeriodValue

encoding := app.MakeEncodingConfig()
encoding := makeEncodingConfig()
oldApp := app.NewNibiruApp(logger, db, nil, true, encoding, appOptions, baseapp.SetChainID(SimAppChainID))
require.Equal(t, "Nibiru", oldApp.Name())
appCodec := oldApp.AppCodec()
Expand Down Expand Up @@ -315,7 +328,7 @@ func TestAppSimulationAfterImport(t *testing.T) {
appOptions[flags.FlagHome] = app.DefaultNodeHome
appOptions[server.FlagInvCheckPeriod] = simcli.FlagPeriodValue

encoding := app.MakeEncodingConfig()
encoding := makeEncodingConfig()
oldApp := app.NewNibiruApp(logger, db, nil, true, encoding, appOptions, baseapp.SetChainID(SimAppChainID))
require.Equal(t, "Nibiru", oldApp.Name())
appCodec := oldApp.AppCodec()
Expand Down
5 changes: 5 additions & 0 deletions token-registry/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Nibiru/token-registry

This directory implements the Nibiru Token Registry by providing a means to
register offchain digital token metadata to onchain identifiers for use with
applications like wallets.
Loading

0 comments on commit 0932e28

Please sign in to comment.