From aeb8d5599838a5d02793ac6d69931524587723c9 Mon Sep 17 00:00:00 2001 From: skosito Date: Thu, 15 Feb 2024 01:40:30 +0100 Subject: [PATCH 01/18] Improve gas price coverage --- testutil/keeper/mocks/crosschain/account.go | 2 +- testutil/keeper/mocks/crosschain/bank.go | 2 +- testutil/keeper/mocks/crosschain/fungible.go | 2 +- testutil/keeper/mocks/crosschain/observer.go | 7 +- testutil/keeper/mocks/crosschain/staking.go | 2 +- testutil/keeper/mocks/fungible/account.go | 2 +- testutil/keeper/mocks/fungible/bank.go | 2 +- testutil/keeper/mocks/fungible/evm.go | 22 +- testutil/keeper/mocks/fungible/observer.go | 9 +- x/fungible/keeper/evm_test.go | 5 +- x/fungible/keeper/gas_price.go | 16 +- x/fungible/keeper/gas_price_test.go | 238 +++++++++++++++++++ x/fungible/types/errors.go | 1 + x/fungible/types/expected_keepers.go | 1 + 14 files changed, 277 insertions(+), 34 deletions(-) diff --git a/testutil/keeper/mocks/crosschain/account.go b/testutil/keeper/mocks/crosschain/account.go index 274a79766d..c8d33e57a6 100644 --- a/testutil/keeper/mocks/crosschain/account.go +++ b/testutil/keeper/mocks/crosschain/account.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.39.1. DO NOT EDIT. +// Code generated by mockery v2.41.0. DO NOT EDIT. package mocks diff --git a/testutil/keeper/mocks/crosschain/bank.go b/testutil/keeper/mocks/crosschain/bank.go index 278cccb833..29e339bdad 100644 --- a/testutil/keeper/mocks/crosschain/bank.go +++ b/testutil/keeper/mocks/crosschain/bank.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.39.1. DO NOT EDIT. +// Code generated by mockery v2.41.0. DO NOT EDIT. package mocks diff --git a/testutil/keeper/mocks/crosschain/fungible.go b/testutil/keeper/mocks/crosschain/fungible.go index b40bd35c40..2be37b5efa 100644 --- a/testutil/keeper/mocks/crosschain/fungible.go +++ b/testutil/keeper/mocks/crosschain/fungible.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.39.1. DO NOT EDIT. +// Code generated by mockery v2.41.0. DO NOT EDIT. package mocks diff --git a/testutil/keeper/mocks/crosschain/observer.go b/testutil/keeper/mocks/crosschain/observer.go index 5000f37e03..95316ad556 100644 --- a/testutil/keeper/mocks/crosschain/observer.go +++ b/testutil/keeper/mocks/crosschain/observer.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.39.1. DO NOT EDIT. +// Code generated by mockery v2.41.0. DO NOT EDIT. package mocks @@ -843,11 +843,6 @@ func (_m *CrosschainObserverKeeper) SetNonceToCctx(ctx types.Context, nonceToCct _m.Called(ctx, nonceToCctx) } -// SetObservers provides a mock function with given fields: ctx, om -func (_m *CrosschainObserverKeeper) SetObservers(ctx types.Context, om observertypes.ObserverSet) { - _m.Called(ctx, om) -} - // SetPendingNonces provides a mock function with given fields: ctx, pendingNonces func (_m *CrosschainObserverKeeper) SetPendingNonces(ctx types.Context, pendingNonces observertypes.PendingNonces) { _m.Called(ctx, pendingNonces) diff --git a/testutil/keeper/mocks/crosschain/staking.go b/testutil/keeper/mocks/crosschain/staking.go index 772bb09971..f6bd25dd1d 100644 --- a/testutil/keeper/mocks/crosschain/staking.go +++ b/testutil/keeper/mocks/crosschain/staking.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.39.1. DO NOT EDIT. +// Code generated by mockery v2.41.0. DO NOT EDIT. package mocks diff --git a/testutil/keeper/mocks/fungible/account.go b/testutil/keeper/mocks/fungible/account.go index 94b7a84d75..f7a2788969 100644 --- a/testutil/keeper/mocks/fungible/account.go +++ b/testutil/keeper/mocks/fungible/account.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.39.1. DO NOT EDIT. +// Code generated by mockery v2.41.0. DO NOT EDIT. package mocks diff --git a/testutil/keeper/mocks/fungible/bank.go b/testutil/keeper/mocks/fungible/bank.go index d44da595c0..fe6b8c6b14 100644 --- a/testutil/keeper/mocks/fungible/bank.go +++ b/testutil/keeper/mocks/fungible/bank.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.39.1. DO NOT EDIT. +// Code generated by mockery v2.41.0. DO NOT EDIT. package mocks diff --git a/testutil/keeper/mocks/fungible/evm.go b/testutil/keeper/mocks/fungible/evm.go index 64c041b22d..b59f7d477e 100644 --- a/testutil/keeper/mocks/fungible/evm.go +++ b/testutil/keeper/mocks/fungible/evm.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.39.1. DO NOT EDIT. +// Code generated by mockery v2.41.0. DO NOT EDIT. package mocks @@ -146,6 +146,26 @@ func (_m *FungibleEVMKeeper) GetBlockBloomTransient(ctx types.Context) *big.Int return r0 } +// GetCode provides a mock function with given fields: ctx, codeHash +func (_m *FungibleEVMKeeper) GetCode(ctx types.Context, codeHash common.Hash) []byte { + ret := _m.Called(ctx, codeHash) + + if len(ret) == 0 { + panic("no return value specified for GetCode") + } + + var r0 []byte + if rf, ok := ret.Get(0).(func(types.Context, common.Hash) []byte); ok { + r0 = rf(ctx, codeHash) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]byte) + } + } + + return r0 +} + // GetLogSizeTransient provides a mock function with given fields: ctx func (_m *FungibleEVMKeeper) GetLogSizeTransient(ctx types.Context) uint64 { ret := _m.Called(ctx) diff --git a/testutil/keeper/mocks/fungible/observer.go b/testutil/keeper/mocks/fungible/observer.go index a808da6d5f..606d71138a 100644 --- a/testutil/keeper/mocks/fungible/observer.go +++ b/testutil/keeper/mocks/fungible/observer.go @@ -1,11 +1,11 @@ -// Code generated by mockery v2.39.1. DO NOT EDIT. +// Code generated by mockery v2.41.0. DO NOT EDIT. package mocks import ( mock "github.com/stretchr/testify/mock" + common "github.com/zeta-chain/zetacore/common" - "github.com/zeta-chain/zetacore/common" observertypes "github.com/zeta-chain/zetacore/x/observer/types" types "github.com/cosmos/cosmos-sdk/types" @@ -185,11 +185,6 @@ func (_m *FungibleObserverKeeper) SetBallot(ctx types.Context, ballot *observert _m.Called(ctx, ballot) } -// SetObservers provides a mock function with given fields: ctx, om -func (_m *FungibleObserverKeeper) SetObservers(ctx types.Context, om observertypes.ObserverSet) { - _m.Called(ctx, om) -} - // NewFungibleObserverKeeper creates a new instance of FungibleObserverKeeper. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. func NewFungibleObserverKeeper(t interface { diff --git a/x/fungible/keeper/evm_test.go b/x/fungible/keeper/evm_test.go index b6810a6998..42399f5104 100644 --- a/x/fungible/keeper/evm_test.go +++ b/x/fungible/keeper/evm_test.go @@ -8,7 +8,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" - evmkeeper "github.com/evmos/ethermint/x/evm/keeper" evmtypes "github.com/evmos/ethermint/x/evm/types" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -33,7 +32,7 @@ func getValidChainID(t *testing.T) int64 { } // require that a contract has been deployed by checking stored code is non-empty. -func assertContractDeployment(t *testing.T, k *evmkeeper.Keeper, ctx sdk.Context, contractAddress common.Address) { +func assertContractDeployment(t *testing.T, k types.EVMKeeper, ctx sdk.Context, contractAddress common.Address) { acc := k.GetAccount(ctx, contractAddress) require.NotNil(t, acc) @@ -46,7 +45,7 @@ func deploySystemContracts( t *testing.T, ctx sdk.Context, k *fungiblekeeper.Keeper, - evmk *evmkeeper.Keeper, + evmk types.EVMKeeper, ) (wzeta, uniswapV2Factory, uniswapV2Router, connector, systemContract common.Address) { var err error diff --git a/x/fungible/keeper/gas_price.go b/x/fungible/keeper/gas_price.go index 3f2ee63d28..e829f59377 100644 --- a/x/fungible/keeper/gas_price.go +++ b/x/fungible/keeper/gas_price.go @@ -12,6 +12,9 @@ import ( // SetGasPrice sets gas price on the system contract in zEVM; return the gasUsed and error code func (k Keeper) SetGasPrice(ctx sdk.Context, chainid *big.Int, gasPrice *big.Int) (uint64, error) { + if gasPrice == nil { + return 0, sdkerrors.Wrapf(types.ErrNilGasPrice, "gas price param should be set") + } system, found := k.GetSystemContract(ctx) if !found { return 0, sdkerrors.Wrapf(types.ErrContractNotFound, "system contract state variable not found") @@ -28,9 +31,6 @@ func (k Keeper) SetGasPrice(ctx sdk.Context, chainid *big.Int, gasPrice *big.Int if err != nil { return 0, sdkerrors.Wrapf(types.ErrContractCall, err.Error()) } - if res.Failed() { - return res.GasUsed, sdkerrors.Wrapf(types.ErrContractCall, "setGasPrice tx failed") - } return res.GasUsed, nil } @@ -48,13 +48,10 @@ func (k Keeper) SetGasCoin(ctx sdk.Context, chainid *big.Int, address common.Add if err != nil { return sdkerrors.Wrapf(types.ErrABIGet, "SystemContractMetaData") } - res, err := k.CallEVM(ctx, *abi, types.ModuleAddressEVM, oracle, BigIntZero, nil, true, false, "setGasCoinZRC20", chainid, address) + _, err = k.CallEVM(ctx, *abi, types.ModuleAddressEVM, oracle, BigIntZero, nil, true, false, "setGasCoinZRC20", chainid, address) if err != nil { return sdkerrors.Wrapf(types.ErrContractCall, err.Error()) } - if res.Failed() { - return sdkerrors.Wrapf(types.ErrContractCall, "setGasCoinZRC20 tx failed") - } return nil } @@ -72,13 +69,10 @@ func (k Keeper) SetGasZetaPool(ctx sdk.Context, chainid *big.Int, pool common.Ad if err != nil { return sdkerrors.Wrapf(types.ErrABIGet, "SystemContractMetaData") } - res, err := k.CallEVM(ctx, *abi, types.ModuleAddressEVM, oracle, BigIntZero, nil, true, false, "setGasZetaPool", chainid, pool) + _, err = k.CallEVM(ctx, *abi, types.ModuleAddressEVM, oracle, BigIntZero, nil, true, false, "setGasZetaPool", chainid, pool) if err != nil { return sdkerrors.Wrapf(types.ErrContractCall, err.Error()) } - if res.Failed() { - return sdkerrors.Wrapf(types.ErrContractCall, "setGasZetaPool tx failed") - } return nil } diff --git a/x/fungible/keeper/gas_price_test.go b/x/fungible/keeper/gas_price_test.go index ec1bf267d8..b951bd751c 100644 --- a/x/fungible/keeper/gas_price_test.go +++ b/x/fungible/keeper/gas_price_test.go @@ -5,9 +5,13 @@ import ( "testing" ethcommon "github.com/ethereum/go-ethereum/common" + "github.com/evmos/ethermint/x/evm/statedb" + evmtypes "github.com/evmos/ethermint/x/evm/types" + "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/systemcontract.sol" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" + fungiblemocks "github.com/zeta-chain/zetacore/testutil/keeper/mocks/fungible" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/fungible/keeper" "github.com/zeta-chain/zetacore/x/fungible/types" @@ -36,6 +40,78 @@ func TestKeeper_SetGasPrice(t *testing.T) { require.Equal(t, big.NewInt(42), queryGasPrice(big.NewInt(1))) } +func TestKeeper_SetGasPriceContractNotFound(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + _, err := k.SetGasPrice(ctx, big.NewInt(1), big.NewInt(42)) + require.ErrorIs(t, err, types.ErrContractNotFound) +} + +func TestKeeper_SetNilGasPrice(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + _, err := k.SetGasPrice(ctx, big.NewInt(1), nil) + require.ErrorIs(t, err, types.ErrNilGasPrice) +} + +func TestKeeper_SetGasPriceContractIs0x0(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) + k.SetSystemContract(ctx, types.SystemContract{}) + + _, err := k.SetGasPrice(ctx, big.NewInt(1), big.NewInt(42)) + require.ErrorIs(t, err, types.ErrContractNotFound) +} + +func TestKeeper_SetGasPriceReverts(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + setupMockEVMKeeperForSystemContractDeployment(t, mockEVMKeeper) + deploySystemContracts(t, ctx, k, mockEVMKeeper) + + mockEVMKeeper.On( + "ApplyMessage", + ctx, + mock.Anything, + mock.Anything, + mock.Anything, + ).Return(&evmtypes.MsgEthereumTxResponse{}, sample.ErrSample) + _, err := k.SetGasPrice(ctx, big.NewInt(1), big.NewInt(1)) + require.ErrorIs(t, err, types.ErrContractCall) +} + +func TestKeeper_SetGasPriceRevertsOnVmError(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + setupMockEVMKeeperForSystemContractDeployment(t, mockEVMKeeper) + + deploySystemContracts(t, ctx, k, mockEVMKeeper) + + mockEVMKeeper.On( + "ApplyMessage", + ctx, + mock.Anything, + mock.Anything, + mock.Anything, + ).Return(&evmtypes.MsgEthereumTxResponse{ + VmError: "test error", + }, nil) + _, err := k.SetGasPrice(ctx, big.NewInt(1), big.NewInt(1)) + require.ErrorIs(t, err, types.ErrContractCall) +} + func TestKeeper_SetGasCoin(t *testing.T) { k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) @@ -50,6 +126,71 @@ func TestKeeper_SetGasCoin(t *testing.T) { require.Equal(t, gas.Hex(), found.Hex()) } +func TestKeeper_SetGasCoinContractNotFound(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + gas := sample.EthAddress() + + err := k.SetGasCoin(ctx, big.NewInt(1), gas) + require.ErrorIs(t, err, types.ErrContractNotFound) +} + +func TestKeeper_SetGasCoinContractIs0x0(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + gas := sample.EthAddress() + + deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) + k.SetSystemContract(ctx, types.SystemContract{}) + + err := k.SetGasCoin(ctx, big.NewInt(1), gas) + require.ErrorIs(t, err, types.ErrContractNotFound) +} + +func TestKeeper_SetGasCoinReverts(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + setupMockEVMKeeperForSystemContractDeployment(t, mockEVMKeeper) + deploySystemContracts(t, ctx, k, mockEVMKeeper) + + mockEVMKeeper.On( + "ApplyMessage", + ctx, + mock.Anything, + mock.Anything, + mock.Anything, + ).Return(&evmtypes.MsgEthereumTxResponse{}, sample.ErrSample) + err := k.SetGasCoin(ctx, big.NewInt(1), sample.EthAddress()) + require.ErrorIs(t, err, types.ErrContractCall) +} + +func TestKeeper_SetGasCoinRevertsOnVmError(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + setupMockEVMKeeperForSystemContractDeployment(t, mockEVMKeeper) + deploySystemContracts(t, ctx, k, mockEVMKeeper) + + mockEVMKeeper.On( + "ApplyMessage", + ctx, + mock.Anything, + mock.Anything, + mock.Anything, + ).Return(&evmtypes.MsgEthereumTxResponse{ + VmError: "test error", + }, sample.ErrSample) + err := k.SetGasCoin(ctx, big.NewInt(1), sample.EthAddress()) + require.ErrorIs(t, err, types.ErrContractCall) +} + func TestKeeper_SetGasZetaPool(t *testing.T) { k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) @@ -73,3 +214,100 @@ func TestKeeper_SetGasZetaPool(t *testing.T) { require.NoError(t, err) require.NotEqual(t, ethcommon.Address{}, queryZetaPool(big.NewInt(1))) } + +func TestKeeper_SetGasZetaPoolContractNotFound(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + zrc20 := sample.EthAddress() + + err := k.SetGasZetaPool(ctx, big.NewInt(1), zrc20) + require.ErrorIs(t, err, types.ErrContractNotFound) +} + +func TestKeeper_SetGasZetaPoolContractIs0x0(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + zrc20 := sample.EthAddress() + + deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) + k.SetSystemContract(ctx, types.SystemContract{}) + + err := k.SetGasZetaPool(ctx, big.NewInt(1), zrc20) + require.ErrorIs(t, err, types.ErrContractNotFound) +} + +func TestKeeper_SetGasZetaPoolReverts(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + setupMockEVMKeeperForSystemContractDeployment(t, mockEVMKeeper) + deploySystemContracts(t, ctx, k, mockEVMKeeper) + + mockEVMKeeper.On( + "ApplyMessage", + ctx, + mock.Anything, + mock.Anything, + mock.Anything, + ).Return(&evmtypes.MsgEthereumTxResponse{}, sample.ErrSample) + err := k.SetGasZetaPool(ctx, big.NewInt(1), sample.EthAddress()) + require.ErrorIs(t, err, types.ErrContractCall) +} + +func TestKeeper_SetGasZetaPoolRevertsOnVmError(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + setupMockEVMKeeperForSystemContractDeployment(t, mockEVMKeeper) + deploySystemContracts(t, ctx, k, mockEVMKeeper) + + mockEVMKeeper.On( + "ApplyMessage", + ctx, + mock.Anything, + mock.Anything, + mock.Anything, + ).Return(&evmtypes.MsgEthereumTxResponse{ + VmError: "test error", + }, sample.ErrSample) + err := k.SetGasZetaPool(ctx, big.NewInt(1), sample.EthAddress()) + require.ErrorIs(t, err, types.ErrContractCall) +} + +func setupMockEVMKeeperForSystemContractDeployment(t *testing.T, mockEVMKeeper *fungiblemocks.FungibleEVMKeeper) { + gasRes := &evmtypes.EstimateGasResponse{Gas: 1000} + msgRes := &evmtypes.MsgEthereumTxResponse{} + + mockEVMKeeper.On("WithChainID", mock.Anything).Maybe().Return(mock.Anything) + mockEVMKeeper.On("ChainID").Maybe().Return(big.NewInt(1)) + mockEVMKeeper.On( + "EstimateGas", + mock.Anything, + mock.Anything, + ).Return(gasRes, nil) + mockEVMKeeper.On( + "ApplyMessage", + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything, + ).Return(msgRes, nil).Times(5) + mockEVMKeeper.On( + "GetAccount", + mock.Anything, + mock.Anything, + ).Return(&statedb.Account{ + Nonce: 1, + }) + mockEVMKeeper.On( + "GetCode", + mock.Anything, + mock.Anything, + ).Return([]byte{1, 2, 3}) +} diff --git a/x/fungible/types/errors.go b/x/fungible/types/errors.go index 2652442b4a..ddcef768e5 100644 --- a/x/fungible/types/errors.go +++ b/x/fungible/types/errors.go @@ -27,4 +27,5 @@ var ( ErrCallNonContract = sdkerrors.Register(ModuleName, 1124, "can't call a non-contract address") ErrForeignCoinAlreadyExist = sdkerrors.Register(ModuleName, 1125, "foreign coin already exist") ErrInvalidHash = sdkerrors.Register(ModuleName, 1126, "invalid hash") + ErrNilGasPrice = sdkerrors.Register(ModuleName, 1127, "nil gas price") ) diff --git a/x/fungible/types/expected_keepers.go b/x/fungible/types/expected_keepers.go index c576a7cafc..3ce72397e3 100644 --- a/x/fungible/types/expected_keepers.go +++ b/x/fungible/types/expected_keepers.go @@ -65,5 +65,6 @@ type EVMKeeper interface { commit bool, ) (*evmtypes.MsgEthereumTxResponse, error) GetAccount(ctx sdk.Context, addr ethcommon.Address) *statedb.Account + GetCode(ctx sdk.Context, codeHash ethcommon.Hash) []byte SetAccount(ctx sdk.Context, addr ethcommon.Address, account statedb.Account) error } From 0a1a492a9783e7cd7e3f9956db3ef1b8f7ea561c Mon Sep 17 00:00:00 2001 From: skosito Date: Thu, 15 Feb 2024 13:19:07 +0100 Subject: [PATCH 02/18] Improve msg update system contract coverage and cleanup --- x/fungible/keeper/evm_test.go | 82 ++++++++--- x/fungible/keeper/gas_coin_and_pool_test.go | 2 +- x/fungible/keeper/gas_price_test.go | 136 +----------------- .../msg_server_update_system_contract_test.go | 103 ++++++++++++- ...g_server_update_zrc20_withdraw_fee_test.go | 49 +------ 5 files changed, 175 insertions(+), 197 deletions(-) diff --git a/x/fungible/keeper/evm_test.go b/x/fungible/keeper/evm_test.go index 42399f5104..01bd93e8f9 100644 --- a/x/fungible/keeper/evm_test.go +++ b/x/fungible/keeper/evm_test.go @@ -8,6 +8,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/evmos/ethermint/x/evm/statedb" evmtypes "github.com/evmos/ethermint/x/evm/types" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -16,6 +17,7 @@ import ( "github.com/zeta-chain/zetacore/server/config" "github.com/zeta-chain/zetacore/testutil/contracts" testkeeper "github.com/zeta-chain/zetacore/testutil/keeper" + fungiblemocks "github.com/zeta-chain/zetacore/testutil/keeper/mocks/fungible" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/fungible/keeper" fungiblekeeper "github.com/zeta-chain/zetacore/x/fungible/keeper" @@ -447,13 +449,7 @@ func TestKeeper_CallEVMWithData(t *testing.T) { mock.Anything, &evmtypes.EthCallRequest{Args: args, GasCap: config.DefaultGasCap}, ).Return(gasRes, nil) - mockEVMKeeper.On( - "ApplyMessage", - ctx, - mock.Anything, - mock.Anything, - mock.Anything, - ).Return(msgRes, nil) + mockEVMSuccessCallOnce(mockEVMKeeper) mockEVMKeeper.On("WithChainID", mock.Anything).Maybe().Return(ctx) mockEVMKeeper.On("ChainID").Maybe().Return(big.NewInt(1)) @@ -496,13 +492,7 @@ func TestKeeper_CallEVMWithData(t *testing.T) { mock.Anything, sdk.AccAddress(fromAddr.Bytes()), ).Return(uint64(1), nil) - mockEVMKeeper.On( - "ApplyMessage", - ctx, - mock.Anything, - mock.Anything, - mock.Anything, - ).Return(msgRes, nil) + mockEVMSuccessCallOnce(mockEVMKeeper) mockEVMKeeper.On("WithChainID", mock.Anything).Maybe().Return(ctx) mockEVMKeeper.On("ChainID").Maybe().Return(big.NewInt(1)) @@ -603,7 +593,6 @@ func TestKeeper_CallEVMWithData(t *testing.T) { Data: (*hexutil.Bytes)(&data), }) gasRes := &evmtypes.EstimateGasResponse{Gas: 1000} - msgRes := &evmtypes.MsgEthereumTxResponse{} // Set up mocked methods mockAuthKeeper.On( @@ -616,13 +605,7 @@ func TestKeeper_CallEVMWithData(t *testing.T) { mock.Anything, &evmtypes.EthCallRequest{Args: args, GasCap: config.DefaultGasCap}, ).Return(gasRes, nil) - mockEVMKeeper.On( - "ApplyMessage", - ctx, - mock.Anything, - mock.Anything, - mock.Anything, - ).Return(msgRes, sample.ErrSample) + mockEVMFailCallOnce(mockEVMKeeper) mockEVMKeeper.On("WithChainID", mock.Anything).Maybe().Return(ctx) mockEVMKeeper.On("ChainID").Maybe().Return(big.NewInt(1)) @@ -641,3 +624,58 @@ func TestKeeper_CallEVMWithData(t *testing.T) { require.ErrorIs(t, err, sample.ErrSample) }) } + +func setupMockEVMKeeperForSystemContractDeployment(mockEVMKeeper *fungiblemocks.FungibleEVMKeeper, applyMessageExpectedCounter int) { + gasRes := &evmtypes.EstimateGasResponse{Gas: 1000} + mockEVMKeeper.On("WithChainID", mock.Anything).Maybe().Return(mock.Anything) + mockEVMKeeper.On("ChainID").Maybe().Return(big.NewInt(1)) + mockEVMKeeper.On( + "EstimateGas", + mock.Anything, + mock.Anything, + ).Return(gasRes, nil) + mockEVMSuccessCallOnce(mockEVMKeeper) + mockEVMKeeper.On( + "GetAccount", + mock.Anything, + mock.Anything, + ).Return(&statedb.Account{ + Nonce: 1, + }) + mockEVMKeeper.On( + "GetCode", + mock.Anything, + mock.Anything, + ).Return([]byte{1, 2, 3}) +} + +func mockEVMSuccessCallOnce(mockEVMKeeper *fungiblemocks.FungibleEVMKeeper) { + mockEVMSuccessCallOnceWithReturn(mockEVMKeeper, &evmtypes.MsgEthereumTxResponse{}) +} + +func mockEVMSuccessCallOnceWithReturn(mockEVMKeeper *fungiblemocks.FungibleEVMKeeper, ret *evmtypes.MsgEthereumTxResponse) { + mockEVMSuccessCallTimesWithReturn(mockEVMKeeper, ret, 1) +} + +func mockEVMSuccessCallTimesWithReturn(mockEVMKeeper *fungiblemocks.FungibleEVMKeeper, ret *evmtypes.MsgEthereumTxResponse, times int) { + if ret == nil { + ret = &evmtypes.MsgEthereumTxResponse{} + } + mockEVMKeeper.On( + "ApplyMessage", + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything, + ).Return(ret, nil).Times(times) +} + +func mockEVMFailCallOnce(mockEVMKeeper *fungiblemocks.FungibleEVMKeeper) { + mockEVMKeeper.On( + "ApplyMessage", + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything, + ).Return(&evmtypes.MsgEthereumTxResponse{}, sample.ErrSample).Once() +} diff --git a/x/fungible/keeper/gas_coin_and_pool_test.go b/x/fungible/keeper/gas_coin_and_pool_test.go index 9bdd139fdc..b6f05431ac 100644 --- a/x/fungible/keeper/gas_coin_and_pool_test.go +++ b/x/fungible/keeper/gas_coin_and_pool_test.go @@ -19,7 +19,7 @@ func setupGasCoin( t *testing.T, ctx sdk.Context, k *fungiblekeeper.Keeper, - evmk *evmkeeper.Keeper, + evmk types.EVMKeeper, chainID int64, assetName string, symbol string, diff --git a/x/fungible/keeper/gas_price_test.go b/x/fungible/keeper/gas_price_test.go index b951bd751c..d084701447 100644 --- a/x/fungible/keeper/gas_price_test.go +++ b/x/fungible/keeper/gas_price_test.go @@ -5,13 +5,9 @@ import ( "testing" ethcommon "github.com/ethereum/go-ethereum/common" - "github.com/evmos/ethermint/x/evm/statedb" - evmtypes "github.com/evmos/ethermint/x/evm/types" - "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/systemcontract.sol" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" - fungiblemocks "github.com/zeta-chain/zetacore/testutil/keeper/mocks/fungible" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/fungible/keeper" "github.com/zeta-chain/zetacore/x/fungible/types" @@ -74,40 +70,10 @@ func TestKeeper_SetGasPriceReverts(t *testing.T) { k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) - setupMockEVMKeeperForSystemContractDeployment(t, mockEVMKeeper) + setupMockEVMKeeperForSystemContractDeployment(mockEVMKeeper, 5) deploySystemContracts(t, ctx, k, mockEVMKeeper) - mockEVMKeeper.On( - "ApplyMessage", - ctx, - mock.Anything, - mock.Anything, - mock.Anything, - ).Return(&evmtypes.MsgEthereumTxResponse{}, sample.ErrSample) - _, err := k.SetGasPrice(ctx, big.NewInt(1), big.NewInt(1)) - require.ErrorIs(t, err, types.ErrContractCall) -} - -func TestKeeper_SetGasPriceRevertsOnVmError(t *testing.T) { - k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ - UseEVMMock: true, - }) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - - mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) - setupMockEVMKeeperForSystemContractDeployment(t, mockEVMKeeper) - - deploySystemContracts(t, ctx, k, mockEVMKeeper) - - mockEVMKeeper.On( - "ApplyMessage", - ctx, - mock.Anything, - mock.Anything, - mock.Anything, - ).Return(&evmtypes.MsgEthereumTxResponse{ - VmError: "test error", - }, nil) + mockEVMFailCallOnce(mockEVMKeeper) _, err := k.SetGasPrice(ctx, big.NewInt(1), big.NewInt(1)) require.ErrorIs(t, err, types.ErrContractCall) } @@ -154,39 +120,10 @@ func TestKeeper_SetGasCoinReverts(t *testing.T) { k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) - setupMockEVMKeeperForSystemContractDeployment(t, mockEVMKeeper) - deploySystemContracts(t, ctx, k, mockEVMKeeper) - - mockEVMKeeper.On( - "ApplyMessage", - ctx, - mock.Anything, - mock.Anything, - mock.Anything, - ).Return(&evmtypes.MsgEthereumTxResponse{}, sample.ErrSample) - err := k.SetGasCoin(ctx, big.NewInt(1), sample.EthAddress()) - require.ErrorIs(t, err, types.ErrContractCall) -} - -func TestKeeper_SetGasCoinRevertsOnVmError(t *testing.T) { - k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ - UseEVMMock: true, - }) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - - mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) - setupMockEVMKeeperForSystemContractDeployment(t, mockEVMKeeper) + setupMockEVMKeeperForSystemContractDeployment(mockEVMKeeper, 5) deploySystemContracts(t, ctx, k, mockEVMKeeper) - mockEVMKeeper.On( - "ApplyMessage", - ctx, - mock.Anything, - mock.Anything, - mock.Anything, - ).Return(&evmtypes.MsgEthereumTxResponse{ - VmError: "test error", - }, sample.ErrSample) + mockEVMFailCallOnce(mockEVMKeeper) err := k.SetGasCoin(ctx, big.NewInt(1), sample.EthAddress()) require.ErrorIs(t, err, types.ErrContractCall) } @@ -243,71 +180,10 @@ func TestKeeper_SetGasZetaPoolReverts(t *testing.T) { k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) - setupMockEVMKeeperForSystemContractDeployment(t, mockEVMKeeper) - deploySystemContracts(t, ctx, k, mockEVMKeeper) - - mockEVMKeeper.On( - "ApplyMessage", - ctx, - mock.Anything, - mock.Anything, - mock.Anything, - ).Return(&evmtypes.MsgEthereumTxResponse{}, sample.ErrSample) - err := k.SetGasZetaPool(ctx, big.NewInt(1), sample.EthAddress()) - require.ErrorIs(t, err, types.ErrContractCall) -} - -func TestKeeper_SetGasZetaPoolRevertsOnVmError(t *testing.T) { - k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ - UseEVMMock: true, - }) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - - mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) - setupMockEVMKeeperForSystemContractDeployment(t, mockEVMKeeper) + setupMockEVMKeeperForSystemContractDeployment(mockEVMKeeper, 5) deploySystemContracts(t, ctx, k, mockEVMKeeper) - mockEVMKeeper.On( - "ApplyMessage", - ctx, - mock.Anything, - mock.Anything, - mock.Anything, - ).Return(&evmtypes.MsgEthereumTxResponse{ - VmError: "test error", - }, sample.ErrSample) + mockEVMFailCallOnce(mockEVMKeeper) err := k.SetGasZetaPool(ctx, big.NewInt(1), sample.EthAddress()) require.ErrorIs(t, err, types.ErrContractCall) } - -func setupMockEVMKeeperForSystemContractDeployment(t *testing.T, mockEVMKeeper *fungiblemocks.FungibleEVMKeeper) { - gasRes := &evmtypes.EstimateGasResponse{Gas: 1000} - msgRes := &evmtypes.MsgEthereumTxResponse{} - - mockEVMKeeper.On("WithChainID", mock.Anything).Maybe().Return(mock.Anything) - mockEVMKeeper.On("ChainID").Maybe().Return(big.NewInt(1)) - mockEVMKeeper.On( - "EstimateGas", - mock.Anything, - mock.Anything, - ).Return(gasRes, nil) - mockEVMKeeper.On( - "ApplyMessage", - mock.Anything, - mock.Anything, - mock.Anything, - mock.Anything, - ).Return(msgRes, nil).Times(5) - mockEVMKeeper.On( - "GetAccount", - mock.Anything, - mock.Anything, - ).Return(&statedb.Account{ - Nonce: 1, - }) - mockEVMKeeper.On( - "GetCode", - mock.Anything, - mock.Anything, - ).Return([]byte{1, 2, 3}) -} diff --git a/x/fungible/keeper/msg_server_update_system_contract_test.go b/x/fungible/keeper/msg_server_update_system_contract_test.go index b464da209c..667ee245d9 100644 --- a/x/fungible/keeper/msg_server_update_system_contract_test.go +++ b/x/fungible/keeper/msg_server_update_system_contract_test.go @@ -6,9 +6,10 @@ import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/ethereum/go-ethereum/common" + evmtypes "github.com/evmos/ethermint/x/evm/types" "github.com/stretchr/testify/require" "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/systemcontract.sol" - "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/zrc20.sol" + zrc20 "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/zrc20.sol" zetacommon "github.com/zeta-chain/zetacore/common" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" @@ -74,6 +75,41 @@ func TestKeeper_UpdateSystemContract(t *testing.T) { require.Equal(t, newSystemContract.Hex(), queryZRC20SystemContract(gas2)) }) + t.Run("can update the system contract if system contract not found", func(t *testing.T) { + k, ctx, _, zk := keepertest.FungibleKeeper(t) + msgServer := keeper.NewMsgServerImpl(*k) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + admin := sample.AccAddress() + setAdminPolicies(ctx, zk, admin, observertypes.Policy_Type_group2) + + chains := zetacommon.DefaultChainsList() + require.True(t, len(chains) > 1) + require.NotNil(t, chains[0]) + require.NotNil(t, chains[1]) + + wzeta, err := k.DeployWZETA(ctx) + require.NoError(t, err) + + factory, err := k.DeployUniswapV2Factory(ctx) + require.NoError(t, err) + + router, err := k.DeployUniswapV2Router02(ctx, factory, wzeta) + require.NoError(t, err) + + // deploy a new system contracts + newSystemContract, err := k.DeployContract(ctx, systemcontract.SystemContractMetaData, wzeta, factory, router) + require.NoError(t, err) + + // can update the system contract + _, err = msgServer.UpdateSystemContract(ctx, types.NewMsgUpdateSystemContract(admin, newSystemContract.Hex())) + require.NoError(t, err) + + // can retrieve the system contract + sc, found := k.GetSystemContract(ctx) + require.True(t, found) + require.Equal(t, newSystemContract.Hex(), sc.SystemContract) + }) + t.Run("should not update the system contract if not admin", func(t *testing.T) { k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) msgServer := keeper.NewMsgServerImpl(*k) @@ -109,4 +145,69 @@ func TestKeeper_UpdateSystemContract(t *testing.T) { require.Error(t, err) require.ErrorIs(t, err, sdkerrors.ErrInvalidAddress) }) + + t.Run("should not update if any of 3 evm calls for foreign coin fail", func(t *testing.T) { + k, ctx, _, zk := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + msgServer := keeper.NewMsgServerImpl(*k) + setupMockEVMKeeperForSystemContractDeployment(mockEVMKeeper, 9) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + admin := sample.AccAddress() + setAdminPolicies(ctx, zk, admin, observertypes.Policy_Type_group2) + + chains := zetacommon.DefaultChainsList() + require.True(t, len(chains) > 1) + require.NotNil(t, chains[0]) + require.NotNil(t, chains[1]) + chainID1 := chains[0].ChainId + + wzeta, factory, router, _, _ := deploySystemContracts(t, ctx, k, mockEVMKeeper) + // setup mocks and setup gas coin + var encodedAddress [32]byte + copy(encodedAddress[12:], router[:]) + uniswapMock := &evmtypes.MsgEthereumTxResponse{ + Ret: encodedAddress[:], + } + mockEVMSuccessCallOnceWithReturn(mockEVMKeeper, uniswapMock) + mockEVMSuccessCallOnce(mockEVMKeeper) + + addLiqMockReturn := &evmtypes.MsgEthereumTxResponse{ + Ret: make([]byte, 3*32), + } + mockEVMSuccessCallOnceWithReturn(mockEVMKeeper, addLiqMockReturn) + + setupGasCoin(t, ctx, k, mockEVMKeeper, chainID1, "foo", "foo") + + // deploy a new system contracts + mockEVMSuccessCallOnce(mockEVMKeeper) + newSystemContract, err := k.DeployContract(ctx, systemcontract.SystemContractMetaData, wzeta, factory, router) + require.NoError(t, err) + + // fail on first evm call + mockEVMFailCallOnce(mockEVMKeeper) + + // can update the system contract + _, err = msgServer.UpdateSystemContract(ctx, types.NewMsgUpdateSystemContract(admin, newSystemContract.Hex())) + require.ErrorIs(t, err, types.ErrContractCall) + + // fail on second evm call + mockEVMSuccessCallOnce(mockEVMKeeper) + mockEVMFailCallOnce(mockEVMKeeper) + + // can update the system contract + _, err = msgServer.UpdateSystemContract(ctx, types.NewMsgUpdateSystemContract(admin, newSystemContract.Hex())) + require.ErrorIs(t, err, types.ErrContractCall) + + // fail on third evm call + mockEVMSuccessCallTimesWithReturn(mockEVMKeeper, nil, 2) + mockEVMFailCallOnce(mockEVMKeeper) + + // can update the system contract + _, err = msgServer.UpdateSystemContract(ctx, types.NewMsgUpdateSystemContract(admin, newSystemContract.Hex())) + require.ErrorIs(t, err, types.ErrContractCall) + }) } diff --git a/x/fungible/keeper/msg_server_update_zrc20_withdraw_fee_test.go b/x/fungible/keeper/msg_server_update_zrc20_withdraw_fee_test.go index 108c70c664..c34db26993 100644 --- a/x/fungible/keeper/msg_server_update_zrc20_withdraw_fee_test.go +++ b/x/fungible/keeper/msg_server_update_zrc20_withdraw_fee_test.go @@ -1,7 +1,6 @@ package keeper_test import ( - "errors" "math/big" "testing" @@ -176,32 +175,14 @@ func TestKeeper_UpdateZRC20WithdrawFee(t *testing.T) { require.NoError(t, err) protocolFlatFee, err := zrc20ABI.Methods["PROTOCOL_FLAT_FEE"].Outputs.Pack(big.NewInt(42)) require.NoError(t, err) - mockEVMKeeper.On( - "ApplyMessage", - mock.Anything, - mock.Anything, - mock.Anything, - false, - ).Return(&evmtypes.MsgEthereumTxResponse{Ret: protocolFlatFee}, nil) + mockEVMSuccessCallOnceWithReturn(mockEVMKeeper, &evmtypes.MsgEthereumTxResponse{Ret: protocolFlatFee}) gasLimit, err := zrc20ABI.Methods["GAS_LIMIT"].Outputs.Pack(big.NewInt(42)) require.NoError(t, err) - mockEVMKeeper.On( - "ApplyMessage", - mock.Anything, - mock.Anything, - mock.Anything, - false, - ).Return(&evmtypes.MsgEthereumTxResponse{Ret: gasLimit}, nil) + mockEVMSuccessCallOnceWithReturn(mockEVMKeeper, &evmtypes.MsgEthereumTxResponse{Ret: gasLimit}) // this is the update call (commit == true) - mockEVMKeeper.On( - "ApplyMessage", - mock.Anything, - mock.Anything, - mock.Anything, - true, - ).Return(&evmtypes.MsgEthereumTxResponse{}, errors.New("transaction failed")) + mockEVMFailCallOnce(mockEVMKeeper) _, err = msgServer.UpdateZRC20WithdrawFee(ctx, types.NewMsgUpdateZRC20WithdrawFee( admin, @@ -239,32 +220,14 @@ func TestKeeper_UpdateZRC20WithdrawFee(t *testing.T) { require.NoError(t, err) protocolFlatFee, err := zrc20ABI.Methods["PROTOCOL_FLAT_FEE"].Outputs.Pack(big.NewInt(42)) require.NoError(t, err) - mockEVMKeeper.On( - "ApplyMessage", - mock.Anything, - mock.Anything, - mock.Anything, - false, - ).Return(&evmtypes.MsgEthereumTxResponse{Ret: protocolFlatFee}, nil) + mockEVMSuccessCallOnceWithReturn(mockEVMKeeper, &evmtypes.MsgEthereumTxResponse{Ret: protocolFlatFee}) gasLimit, err := zrc20ABI.Methods["GAS_LIMIT"].Outputs.Pack(big.NewInt(42)) require.NoError(t, err) - mockEVMKeeper.On( - "ApplyMessage", - mock.Anything, - mock.Anything, - mock.Anything, - false, - ).Return(&evmtypes.MsgEthereumTxResponse{Ret: gasLimit}, nil) + mockEVMSuccessCallOnceWithReturn(mockEVMKeeper, &evmtypes.MsgEthereumTxResponse{Ret: gasLimit}) // this is the update call (commit == true) - mockEVMKeeper.On( - "ApplyMessage", - mock.Anything, - mock.Anything, - mock.Anything, - true, - ).Return(&evmtypes.MsgEthereumTxResponse{}, errors.New("transaction failed")) + mockEVMFailCallOnce(mockEVMKeeper) _, err = msgServer.UpdateZRC20WithdrawFee(ctx, types.NewMsgUpdateZRC20WithdrawFee( admin, From 9f7f6f580cae5076750d5d8d9dc099624a5e6da7 Mon Sep 17 00:00:00 2001 From: skosito Date: Thu, 15 Feb 2024 13:38:32 +0100 Subject: [PATCH 03/18] Cleanup --- x/fungible/keeper/evm_test.go | 8 ++++++-- x/fungible/keeper/gas_price_test.go | 6 +++--- .../keeper/msg_server_update_system_contract_test.go | 5 +++-- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/x/fungible/keeper/evm_test.go b/x/fungible/keeper/evm_test.go index 01bd93e8f9..e1c1c7eadf 100644 --- a/x/fungible/keeper/evm_test.go +++ b/x/fungible/keeper/evm_test.go @@ -625,7 +625,7 @@ func TestKeeper_CallEVMWithData(t *testing.T) { }) } -func setupMockEVMKeeperForSystemContractDeployment(mockEVMKeeper *fungiblemocks.FungibleEVMKeeper, applyMessageExpectedCounter int) { +func setupMockEVMKeeperForSystemContractDeployment(mockEVMKeeper *fungiblemocks.FungibleEVMKeeper) { gasRes := &evmtypes.EstimateGasResponse{Gas: 1000} mockEVMKeeper.On("WithChainID", mock.Anything).Maybe().Return(mock.Anything) mockEVMKeeper.On("ChainID").Maybe().Return(big.NewInt(1)) @@ -634,7 +634,7 @@ func setupMockEVMKeeperForSystemContractDeployment(mockEVMKeeper *fungiblemocks. mock.Anything, mock.Anything, ).Return(gasRes, nil) - mockEVMSuccessCallOnce(mockEVMKeeper) + mockEVMSuccessCallTimes(mockEVMKeeper, 5) mockEVMKeeper.On( "GetAccount", mock.Anything, @@ -653,6 +653,10 @@ func mockEVMSuccessCallOnce(mockEVMKeeper *fungiblemocks.FungibleEVMKeeper) { mockEVMSuccessCallOnceWithReturn(mockEVMKeeper, &evmtypes.MsgEthereumTxResponse{}) } +func mockEVMSuccessCallTimes(mockEVMKeeper *fungiblemocks.FungibleEVMKeeper, times int) { + mockEVMSuccessCallTimesWithReturn(mockEVMKeeper, &evmtypes.MsgEthereumTxResponse{}, times) +} + func mockEVMSuccessCallOnceWithReturn(mockEVMKeeper *fungiblemocks.FungibleEVMKeeper, ret *evmtypes.MsgEthereumTxResponse) { mockEVMSuccessCallTimesWithReturn(mockEVMKeeper, ret, 1) } diff --git a/x/fungible/keeper/gas_price_test.go b/x/fungible/keeper/gas_price_test.go index d084701447..6cafa7aaa6 100644 --- a/x/fungible/keeper/gas_price_test.go +++ b/x/fungible/keeper/gas_price_test.go @@ -70,7 +70,7 @@ func TestKeeper_SetGasPriceReverts(t *testing.T) { k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) - setupMockEVMKeeperForSystemContractDeployment(mockEVMKeeper, 5) + setupMockEVMKeeperForSystemContractDeployment(mockEVMKeeper) deploySystemContracts(t, ctx, k, mockEVMKeeper) mockEVMFailCallOnce(mockEVMKeeper) @@ -120,7 +120,7 @@ func TestKeeper_SetGasCoinReverts(t *testing.T) { k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) - setupMockEVMKeeperForSystemContractDeployment(mockEVMKeeper, 5) + setupMockEVMKeeperForSystemContractDeployment(mockEVMKeeper) deploySystemContracts(t, ctx, k, mockEVMKeeper) mockEVMFailCallOnce(mockEVMKeeper) @@ -180,7 +180,7 @@ func TestKeeper_SetGasZetaPoolReverts(t *testing.T) { k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) - setupMockEVMKeeperForSystemContractDeployment(mockEVMKeeper, 5) + setupMockEVMKeeperForSystemContractDeployment(mockEVMKeeper) deploySystemContracts(t, ctx, k, mockEVMKeeper) mockEVMFailCallOnce(mockEVMKeeper) diff --git a/x/fungible/keeper/msg_server_update_system_contract_test.go b/x/fungible/keeper/msg_server_update_system_contract_test.go index 667ee245d9..66633582a1 100644 --- a/x/fungible/keeper/msg_server_update_system_contract_test.go +++ b/x/fungible/keeper/msg_server_update_system_contract_test.go @@ -154,7 +154,7 @@ func TestKeeper_UpdateSystemContract(t *testing.T) { mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) msgServer := keeper.NewMsgServerImpl(*k) - setupMockEVMKeeperForSystemContractDeployment(mockEVMKeeper, 9) + setupMockEVMKeeperForSystemContractDeployment(mockEVMKeeper) k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) admin := sample.AccAddress() setAdminPolicies(ctx, zk, admin, observertypes.Policy_Type_group2) @@ -172,6 +172,7 @@ func TestKeeper_UpdateSystemContract(t *testing.T) { uniswapMock := &evmtypes.MsgEthereumTxResponse{ Ret: encodedAddress[:], } + mockEVMSuccessCallTimes(mockEVMKeeper, 4) mockEVMSuccessCallOnceWithReturn(mockEVMKeeper, uniswapMock) mockEVMSuccessCallOnce(mockEVMKeeper) @@ -203,7 +204,7 @@ func TestKeeper_UpdateSystemContract(t *testing.T) { require.ErrorIs(t, err, types.ErrContractCall) // fail on third evm call - mockEVMSuccessCallTimesWithReturn(mockEVMKeeper, nil, 2) + mockEVMSuccessCallTimes(mockEVMKeeper, 2) mockEVMFailCallOnce(mockEVMKeeper) // can update the system contract From 55a78b5d3e0e65c72ff2a96b0f4682f93d0888c7 Mon Sep 17 00:00:00 2001 From: skosito Date: Thu, 15 Feb 2024 13:50:37 +0100 Subject: [PATCH 04/18] Improve readability of mocking evm calls methods --- testutil/keeper/fungible.go | 74 ++++++++++++++++++- x/fungible/keeper/evm_test.go | 67 +---------------- x/fungible/keeper/gas_price_test.go | 12 +-- .../msg_server_update_system_contract_test.go | 22 +++--- ...g_server_update_zrc20_withdraw_fee_test.go | 12 +-- 5 files changed, 98 insertions(+), 89 deletions(-) diff --git a/testutil/keeper/fungible.go b/testutil/keeper/fungible.go index 0ef4e981f4..5f9f2b0cfd 100644 --- a/testutil/keeper/fungible.go +++ b/testutil/keeper/fungible.go @@ -1,6 +1,7 @@ package keeper import ( + "math/big" "testing" "github.com/cosmos/cosmos-sdk/codec" @@ -8,9 +9,13 @@ import ( storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" paramskeeper "github.com/cosmos/cosmos-sdk/x/params/keeper" + "github.com/evmos/ethermint/x/evm/statedb" + evmtypes "github.com/evmos/ethermint/x/evm/types" + "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" tmdb "github.com/tendermint/tm-db" fungiblemocks "github.com/zeta-chain/zetacore/testutil/keeper/mocks/fungible" + "github.com/zeta-chain/zetacore/testutil/sample" fungiblemodule "github.com/zeta-chain/zetacore/x/fungible" "github.com/zeta-chain/zetacore/x/fungible/keeper" "github.com/zeta-chain/zetacore/x/fungible/types" @@ -164,8 +169,73 @@ func GetFungibleObserverMock(t testing.TB, keeper *keeper.Keeper) *fungiblemocks return fok } -func GetFungibleEVMMock(t testing.TB, keeper *keeper.Keeper) *fungiblemocks.FungibleEVMKeeper { +func GetFungibleEVMMock(t testing.TB, keeper *keeper.Keeper) *FungibleMockEVMKeeper { fek, ok := keeper.GetEVMKeeper().(*fungiblemocks.FungibleEVMKeeper) require.True(t, ok) - return fek + return &FungibleMockEVMKeeper{ + FungibleEVMKeeper: fek, + } +} + +type FungibleMockEVMKeeper struct { + *fungiblemocks.FungibleEVMKeeper +} + +func (m *FungibleMockEVMKeeper) SetupMockEVMKeeperForSystemContractDeployment() { + gasRes := &evmtypes.EstimateGasResponse{Gas: 1000} + m.On("WithChainID", mock.Anything).Maybe().Return(mock.Anything) + m.On("ChainID").Maybe().Return(big.NewInt(1)) + m.On( + "EstimateGas", + mock.Anything, + mock.Anything, + ).Return(gasRes, nil) + m.MockEVMSuccessCallTimes(5) + m.On( + "GetAccount", + mock.Anything, + mock.Anything, + ).Return(&statedb.Account{ + Nonce: 1, + }) + m.On( + "GetCode", + mock.Anything, + mock.Anything, + ).Return([]byte{1, 2, 3}) +} + +func (m *FungibleMockEVMKeeper) MockEVMSuccessCallOnce() { + m.MockEVMSuccessCallOnceWithReturn(&evmtypes.MsgEthereumTxResponse{}) +} + +func (m *FungibleMockEVMKeeper) MockEVMSuccessCallTimes(times int) { + m.MockEVMSuccessCallTimesWithReturn(&evmtypes.MsgEthereumTxResponse{}, times) +} + +func (m *FungibleMockEVMKeeper) MockEVMSuccessCallOnceWithReturn(ret *evmtypes.MsgEthereumTxResponse) { + m.MockEVMSuccessCallTimesWithReturn(ret, 1) +} + +func (m *FungibleMockEVMKeeper) MockEVMSuccessCallTimesWithReturn(ret *evmtypes.MsgEthereumTxResponse, times int) { + if ret == nil { + ret = &evmtypes.MsgEthereumTxResponse{} + } + m.On( + "ApplyMessage", + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything, + ).Return(ret, nil).Times(times) +} + +func (m *FungibleMockEVMKeeper) MockEVMFailCallOnce() { + m.On( + "ApplyMessage", + mock.Anything, + mock.Anything, + mock.Anything, + mock.Anything, + ).Return(&evmtypes.MsgEthereumTxResponse{}, sample.ErrSample).Once() } diff --git a/x/fungible/keeper/evm_test.go b/x/fungible/keeper/evm_test.go index e1c1c7eadf..49dcfd22ec 100644 --- a/x/fungible/keeper/evm_test.go +++ b/x/fungible/keeper/evm_test.go @@ -8,7 +8,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/evmos/ethermint/x/evm/statedb" evmtypes "github.com/evmos/ethermint/x/evm/types" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -17,7 +16,6 @@ import ( "github.com/zeta-chain/zetacore/server/config" "github.com/zeta-chain/zetacore/testutil/contracts" testkeeper "github.com/zeta-chain/zetacore/testutil/keeper" - fungiblemocks "github.com/zeta-chain/zetacore/testutil/keeper/mocks/fungible" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/fungible/keeper" fungiblekeeper "github.com/zeta-chain/zetacore/x/fungible/keeper" @@ -449,7 +447,7 @@ func TestKeeper_CallEVMWithData(t *testing.T) { mock.Anything, &evmtypes.EthCallRequest{Args: args, GasCap: config.DefaultGasCap}, ).Return(gasRes, nil) - mockEVMSuccessCallOnce(mockEVMKeeper) + mockEVMKeeper.MockEVMSuccessCallOnce() mockEVMKeeper.On("WithChainID", mock.Anything).Maybe().Return(ctx) mockEVMKeeper.On("ChainID").Maybe().Return(big.NewInt(1)) @@ -492,7 +490,7 @@ func TestKeeper_CallEVMWithData(t *testing.T) { mock.Anything, sdk.AccAddress(fromAddr.Bytes()), ).Return(uint64(1), nil) - mockEVMSuccessCallOnce(mockEVMKeeper) + mockEVMKeeper.MockEVMSuccessCallOnce() mockEVMKeeper.On("WithChainID", mock.Anything).Maybe().Return(ctx) mockEVMKeeper.On("ChainID").Maybe().Return(big.NewInt(1)) @@ -605,7 +603,7 @@ func TestKeeper_CallEVMWithData(t *testing.T) { mock.Anything, &evmtypes.EthCallRequest{Args: args, GasCap: config.DefaultGasCap}, ).Return(gasRes, nil) - mockEVMFailCallOnce(mockEVMKeeper) + mockEVMKeeper.MockEVMFailCallOnce() mockEVMKeeper.On("WithChainID", mock.Anything).Maybe().Return(ctx) mockEVMKeeper.On("ChainID").Maybe().Return(big.NewInt(1)) @@ -624,62 +622,3 @@ func TestKeeper_CallEVMWithData(t *testing.T) { require.ErrorIs(t, err, sample.ErrSample) }) } - -func setupMockEVMKeeperForSystemContractDeployment(mockEVMKeeper *fungiblemocks.FungibleEVMKeeper) { - gasRes := &evmtypes.EstimateGasResponse{Gas: 1000} - mockEVMKeeper.On("WithChainID", mock.Anything).Maybe().Return(mock.Anything) - mockEVMKeeper.On("ChainID").Maybe().Return(big.NewInt(1)) - mockEVMKeeper.On( - "EstimateGas", - mock.Anything, - mock.Anything, - ).Return(gasRes, nil) - mockEVMSuccessCallTimes(mockEVMKeeper, 5) - mockEVMKeeper.On( - "GetAccount", - mock.Anything, - mock.Anything, - ).Return(&statedb.Account{ - Nonce: 1, - }) - mockEVMKeeper.On( - "GetCode", - mock.Anything, - mock.Anything, - ).Return([]byte{1, 2, 3}) -} - -func mockEVMSuccessCallOnce(mockEVMKeeper *fungiblemocks.FungibleEVMKeeper) { - mockEVMSuccessCallOnceWithReturn(mockEVMKeeper, &evmtypes.MsgEthereumTxResponse{}) -} - -func mockEVMSuccessCallTimes(mockEVMKeeper *fungiblemocks.FungibleEVMKeeper, times int) { - mockEVMSuccessCallTimesWithReturn(mockEVMKeeper, &evmtypes.MsgEthereumTxResponse{}, times) -} - -func mockEVMSuccessCallOnceWithReturn(mockEVMKeeper *fungiblemocks.FungibleEVMKeeper, ret *evmtypes.MsgEthereumTxResponse) { - mockEVMSuccessCallTimesWithReturn(mockEVMKeeper, ret, 1) -} - -func mockEVMSuccessCallTimesWithReturn(mockEVMKeeper *fungiblemocks.FungibleEVMKeeper, ret *evmtypes.MsgEthereumTxResponse, times int) { - if ret == nil { - ret = &evmtypes.MsgEthereumTxResponse{} - } - mockEVMKeeper.On( - "ApplyMessage", - mock.Anything, - mock.Anything, - mock.Anything, - mock.Anything, - ).Return(ret, nil).Times(times) -} - -func mockEVMFailCallOnce(mockEVMKeeper *fungiblemocks.FungibleEVMKeeper) { - mockEVMKeeper.On( - "ApplyMessage", - mock.Anything, - mock.Anything, - mock.Anything, - mock.Anything, - ).Return(&evmtypes.MsgEthereumTxResponse{}, sample.ErrSample).Once() -} diff --git a/x/fungible/keeper/gas_price_test.go b/x/fungible/keeper/gas_price_test.go index 6cafa7aaa6..5a232928d8 100644 --- a/x/fungible/keeper/gas_price_test.go +++ b/x/fungible/keeper/gas_price_test.go @@ -70,10 +70,10 @@ func TestKeeper_SetGasPriceReverts(t *testing.T) { k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) - setupMockEVMKeeperForSystemContractDeployment(mockEVMKeeper) + mockEVMKeeper.SetupMockEVMKeeperForSystemContractDeployment() deploySystemContracts(t, ctx, k, mockEVMKeeper) - mockEVMFailCallOnce(mockEVMKeeper) + mockEVMKeeper.MockEVMFailCallOnce() _, err := k.SetGasPrice(ctx, big.NewInt(1), big.NewInt(1)) require.ErrorIs(t, err, types.ErrContractCall) } @@ -120,10 +120,10 @@ func TestKeeper_SetGasCoinReverts(t *testing.T) { k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) - setupMockEVMKeeperForSystemContractDeployment(mockEVMKeeper) + mockEVMKeeper.SetupMockEVMKeeperForSystemContractDeployment() deploySystemContracts(t, ctx, k, mockEVMKeeper) - mockEVMFailCallOnce(mockEVMKeeper) + mockEVMKeeper.MockEVMFailCallOnce() err := k.SetGasCoin(ctx, big.NewInt(1), sample.EthAddress()) require.ErrorIs(t, err, types.ErrContractCall) } @@ -180,10 +180,10 @@ func TestKeeper_SetGasZetaPoolReverts(t *testing.T) { k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) - setupMockEVMKeeperForSystemContractDeployment(mockEVMKeeper) + mockEVMKeeper.SetupMockEVMKeeperForSystemContractDeployment() deploySystemContracts(t, ctx, k, mockEVMKeeper) - mockEVMFailCallOnce(mockEVMKeeper) + mockEVMKeeper.MockEVMFailCallOnce() err := k.SetGasZetaPool(ctx, big.NewInt(1), sample.EthAddress()) require.ErrorIs(t, err, types.ErrContractCall) } diff --git a/x/fungible/keeper/msg_server_update_system_contract_test.go b/x/fungible/keeper/msg_server_update_system_contract_test.go index 66633582a1..cabbf337cf 100644 --- a/x/fungible/keeper/msg_server_update_system_contract_test.go +++ b/x/fungible/keeper/msg_server_update_system_contract_test.go @@ -154,7 +154,7 @@ func TestKeeper_UpdateSystemContract(t *testing.T) { mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) msgServer := keeper.NewMsgServerImpl(*k) - setupMockEVMKeeperForSystemContractDeployment(mockEVMKeeper) + mockEVMKeeper.SetupMockEVMKeeperForSystemContractDeployment() k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) admin := sample.AccAddress() setAdminPolicies(ctx, zk, admin, observertypes.Policy_Type_group2) @@ -172,40 +172,40 @@ func TestKeeper_UpdateSystemContract(t *testing.T) { uniswapMock := &evmtypes.MsgEthereumTxResponse{ Ret: encodedAddress[:], } - mockEVMSuccessCallTimes(mockEVMKeeper, 4) - mockEVMSuccessCallOnceWithReturn(mockEVMKeeper, uniswapMock) - mockEVMSuccessCallOnce(mockEVMKeeper) + mockEVMKeeper.MockEVMSuccessCallTimes(4) + mockEVMKeeper.MockEVMSuccessCallOnceWithReturn(uniswapMock) + mockEVMKeeper.MockEVMSuccessCallOnce() addLiqMockReturn := &evmtypes.MsgEthereumTxResponse{ Ret: make([]byte, 3*32), } - mockEVMSuccessCallOnceWithReturn(mockEVMKeeper, addLiqMockReturn) + mockEVMKeeper.MockEVMSuccessCallOnceWithReturn(addLiqMockReturn) setupGasCoin(t, ctx, k, mockEVMKeeper, chainID1, "foo", "foo") // deploy a new system contracts - mockEVMSuccessCallOnce(mockEVMKeeper) + mockEVMKeeper.MockEVMSuccessCallOnce() newSystemContract, err := k.DeployContract(ctx, systemcontract.SystemContractMetaData, wzeta, factory, router) require.NoError(t, err) // fail on first evm call - mockEVMFailCallOnce(mockEVMKeeper) + mockEVMKeeper.MockEVMFailCallOnce() // can update the system contract _, err = msgServer.UpdateSystemContract(ctx, types.NewMsgUpdateSystemContract(admin, newSystemContract.Hex())) require.ErrorIs(t, err, types.ErrContractCall) // fail on second evm call - mockEVMSuccessCallOnce(mockEVMKeeper) - mockEVMFailCallOnce(mockEVMKeeper) + mockEVMKeeper.MockEVMSuccessCallOnce() + mockEVMKeeper.MockEVMFailCallOnce() // can update the system contract _, err = msgServer.UpdateSystemContract(ctx, types.NewMsgUpdateSystemContract(admin, newSystemContract.Hex())) require.ErrorIs(t, err, types.ErrContractCall) // fail on third evm call - mockEVMSuccessCallTimes(mockEVMKeeper, 2) - mockEVMFailCallOnce(mockEVMKeeper) + mockEVMKeeper.MockEVMSuccessCallTimes(2) + mockEVMKeeper.MockEVMFailCallOnce() // can update the system contract _, err = msgServer.UpdateSystemContract(ctx, types.NewMsgUpdateSystemContract(admin, newSystemContract.Hex())) diff --git a/x/fungible/keeper/msg_server_update_zrc20_withdraw_fee_test.go b/x/fungible/keeper/msg_server_update_zrc20_withdraw_fee_test.go index c34db26993..29a5e157ae 100644 --- a/x/fungible/keeper/msg_server_update_zrc20_withdraw_fee_test.go +++ b/x/fungible/keeper/msg_server_update_zrc20_withdraw_fee_test.go @@ -175,14 +175,14 @@ func TestKeeper_UpdateZRC20WithdrawFee(t *testing.T) { require.NoError(t, err) protocolFlatFee, err := zrc20ABI.Methods["PROTOCOL_FLAT_FEE"].Outputs.Pack(big.NewInt(42)) require.NoError(t, err) - mockEVMSuccessCallOnceWithReturn(mockEVMKeeper, &evmtypes.MsgEthereumTxResponse{Ret: protocolFlatFee}) + mockEVMKeeper.MockEVMSuccessCallOnceWithReturn(&evmtypes.MsgEthereumTxResponse{Ret: protocolFlatFee}) gasLimit, err := zrc20ABI.Methods["GAS_LIMIT"].Outputs.Pack(big.NewInt(42)) require.NoError(t, err) - mockEVMSuccessCallOnceWithReturn(mockEVMKeeper, &evmtypes.MsgEthereumTxResponse{Ret: gasLimit}) + mockEVMKeeper.MockEVMSuccessCallOnceWithReturn(&evmtypes.MsgEthereumTxResponse{Ret: gasLimit}) // this is the update call (commit == true) - mockEVMFailCallOnce(mockEVMKeeper) + mockEVMKeeper.MockEVMFailCallOnce() _, err = msgServer.UpdateZRC20WithdrawFee(ctx, types.NewMsgUpdateZRC20WithdrawFee( admin, @@ -220,14 +220,14 @@ func TestKeeper_UpdateZRC20WithdrawFee(t *testing.T) { require.NoError(t, err) protocolFlatFee, err := zrc20ABI.Methods["PROTOCOL_FLAT_FEE"].Outputs.Pack(big.NewInt(42)) require.NoError(t, err) - mockEVMSuccessCallOnceWithReturn(mockEVMKeeper, &evmtypes.MsgEthereumTxResponse{Ret: protocolFlatFee}) + mockEVMKeeper.MockEVMSuccessCallOnceWithReturn(&evmtypes.MsgEthereumTxResponse{Ret: protocolFlatFee}) gasLimit, err := zrc20ABI.Methods["GAS_LIMIT"].Outputs.Pack(big.NewInt(42)) require.NoError(t, err) - mockEVMSuccessCallOnceWithReturn(mockEVMKeeper, &evmtypes.MsgEthereumTxResponse{Ret: gasLimit}) + mockEVMKeeper.MockEVMSuccessCallOnceWithReturn(&evmtypes.MsgEthereumTxResponse{Ret: gasLimit}) // this is the update call (commit == true) - mockEVMFailCallOnce(mockEVMKeeper) + mockEVMKeeper.MockEVMFailCallOnce() _, err = msgServer.UpdateZRC20WithdrawFee(ctx, types.NewMsgUpdateZRC20WithdrawFee( admin, From 858192439f18112550ffc978b9041aba50aa5b25 Mon Sep 17 00:00:00 2001 From: skosito Date: Thu, 15 Feb 2024 14:15:07 +0100 Subject: [PATCH 05/18] Add error tests for existing system contract tests --- x/fungible/keeper/system_contract.go | 13 +- x/fungible/keeper/system_contract_test.go | 243 ++++++++++++++++++++++ 2 files changed, 250 insertions(+), 6 deletions(-) diff --git a/x/fungible/keeper/system_contract.go b/x/fungible/keeper/system_contract.go index a6e1ae8e03..be531f1597 100644 --- a/x/fungible/keeper/system_contract.go +++ b/x/fungible/keeper/system_contract.go @@ -77,7 +77,8 @@ func (k *Keeper) GetWZetaContractAddress(ctx sdk.Context) (ethcommon.Address, er "wZetaContractAddress", ) if err != nil { - return ethcommon.Address{}, cosmoserrors.Wrapf(err, "failed to call wZetaContractAddress") + return ethcommon.Address{}, cosmoserrors.Wrapf(types.ErrContractCall, "failed to call wZetaContractAddress (%s)", err.Error()) + } type AddressResponse struct { Value ethcommon.Address @@ -113,7 +114,7 @@ func (k *Keeper) GetUniswapV2FactoryAddress(ctx sdk.Context) (ethcommon.Address, "uniswapv2FactoryAddress", ) if err != nil { - return ethcommon.Address{}, cosmoserrors.Wrapf(err, "failed to call uniswapv2FactoryAddress") + return ethcommon.Address{}, cosmoserrors.Wrapf(types.ErrContractCall, "failed to call uniswapv2FactoryAddress (%s)", err.Error()) } type AddressResponse struct { Value ethcommon.Address @@ -149,7 +150,7 @@ func (k *Keeper) GetUniswapV2Router02Address(ctx sdk.Context) (ethcommon.Address "uniswapv2Router02Address", ) if err != nil { - return ethcommon.Address{}, cosmoserrors.Wrapf(err, "failed to call uniswapv2Router02Address") + return ethcommon.Address{}, cosmoserrors.Wrapf(types.ErrContractCall, "failed to call uniswapv2Router02Address (%s)", err.Error()) } type AddressResponse struct { Value ethcommon.Address @@ -185,7 +186,7 @@ func (k *Keeper) CallWZetaDeposit(ctx sdk.Context, sender ethcommon.Address, amo "deposit", ) if err != nil { - return cosmoserrors.Wrapf(err, "failed to call wzeta deposit") + return cosmoserrors.Wrapf(types.ErrContractCall, "failed to call wzeta deposit (%s)", err.Error()) } return nil } @@ -215,7 +216,7 @@ func (k *Keeper) QueryWZetaBalanceOf(ctx sdk.Context, addr ethcommon.Address) (* addr, ) if err != nil { - return nil, cosmoserrors.Wrapf(err, "failed to call balanceOf") + return nil, cosmoserrors.Wrapf(types.ErrContractCall, "failed to call balanceOf (%s)", err.Error()) } type BigIntResponse struct { @@ -254,7 +255,7 @@ func (k *Keeper) QuerySystemContractGasCoinZRC20(ctx sdk.Context, chainid *big.I chainid, ) if err != nil { - return ethcommon.Address{}, cosmoserrors.Wrapf(err, "failed to call gasCoinZRC20ByChainId") + return ethcommon.Address{}, cosmoserrors.Wrapf(types.ErrContractCall, "failed to call gasCoinZRC20ByChainId (%s)", err.Error()) } type AddressResponse struct { diff --git a/x/fungible/keeper/system_contract_test.go b/x/fungible/keeper/system_contract_test.go index 3874f52435..f737309979 100644 --- a/x/fungible/keeper/system_contract_test.go +++ b/x/fungible/keeper/system_contract_test.go @@ -52,6 +52,44 @@ func TestKeeper_GetWZetaContractAddress(t *testing.T) { require.Equal(t, wzeta, found) } +func TestKeeper_GetWZetaContractAddressFails(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + _, err := k.GetWZetaContractAddress(ctx) + require.Error(t, err) + require.ErrorIs(t, err, types.ErrStateVariableNotFound) + + mockEVMKeeper.SetupMockEVMKeeperForSystemContractDeployment() + deploySystemContracts(t, ctx, k, mockEVMKeeper) + + mockEVMKeeper.MockEVMFailCallOnce() + _, err = k.GetWZetaContractAddress(ctx) + require.ErrorIs(t, err, types.ErrContractCall) +} + +func TestKeeper_GetWZetaContractAddressFailsToUnpack(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + _, err := k.GetWZetaContractAddress(ctx) + require.Error(t, err) + require.ErrorIs(t, err, types.ErrStateVariableNotFound) + + mockEVMKeeper.SetupMockEVMKeeperForSystemContractDeployment() + deploySystemContracts(t, ctx, k, mockEVMKeeper) + + mockEVMKeeper.MockEVMSuccessCallOnce() + _, err = k.GetWZetaContractAddress(ctx) + require.ErrorIs(t, err, types.ErrABIUnpack) +} + func TestKeeper_GetUniswapV2FactoryAddress(t *testing.T) { k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) @@ -66,6 +104,44 @@ func TestKeeper_GetUniswapV2FactoryAddress(t *testing.T) { require.Equal(t, factory, found) } +func TestKeeper_GetUniswapV2FactoryAddressFails(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + _, err := k.GetUniswapV2FactoryAddress(ctx) + require.Error(t, err) + require.ErrorIs(t, err, types.ErrStateVariableNotFound) + + mockEVMKeeper.SetupMockEVMKeeperForSystemContractDeployment() + deploySystemContracts(t, ctx, k, mockEVMKeeper) + + mockEVMKeeper.MockEVMFailCallOnce() + _, err = k.GetUniswapV2FactoryAddress(ctx) + require.ErrorIs(t, err, types.ErrContractCall) +} + +func TestKeeper_GetUniswapV2FactoryAddressFailsToUnpack(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + _, err := k.GetUniswapV2FactoryAddress(ctx) + require.Error(t, err) + require.ErrorIs(t, err, types.ErrStateVariableNotFound) + + mockEVMKeeper.SetupMockEVMKeeperForSystemContractDeployment() + deploySystemContracts(t, ctx, k, mockEVMKeeper) + + mockEVMKeeper.MockEVMSuccessCallOnce() + _, err = k.GetUniswapV2FactoryAddress(ctx) + require.ErrorIs(t, err, types.ErrABIUnpack) +} + func TestKeeper_GetUniswapV2Router02Address(t *testing.T) { k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) @@ -80,6 +156,44 @@ func TestKeeper_GetUniswapV2Router02Address(t *testing.T) { require.Equal(t, router, found) } +func TestKeeper_GetUniswapV2Router02AddressFails(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + _, err := k.GetUniswapV2Router02Address(ctx) + require.Error(t, err) + require.ErrorIs(t, err, types.ErrStateVariableNotFound) + + mockEVMKeeper.SetupMockEVMKeeperForSystemContractDeployment() + deploySystemContracts(t, ctx, k, mockEVMKeeper) + + mockEVMKeeper.MockEVMFailCallOnce() + _, err = k.GetUniswapV2Router02Address(ctx) + require.ErrorIs(t, err, types.ErrContractCall) +} + +func TestKeeper_GetUniswapV2Router02AddressFailsToUnpack(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + _, err := k.GetUniswapV2Router02Address(ctx) + require.Error(t, err) + require.ErrorIs(t, err, types.ErrStateVariableNotFound) + + mockEVMKeeper.SetupMockEVMKeeperForSystemContractDeployment() + deploySystemContracts(t, ctx, k, mockEVMKeeper) + + mockEVMKeeper.MockEVMSuccessCallOnce() + _, err = k.GetUniswapV2Router02Address(ctx) + require.ErrorIs(t, err, types.ErrABIUnpack) +} + func TestKeeper_CallWZetaDeposit(t *testing.T) { k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) @@ -108,6 +222,93 @@ func TestKeeper_CallWZetaDeposit(t *testing.T) { require.Equal(t, big.NewInt(42), balance) } +func TestKeeper_CallWZetaDepositFails(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + // mint tokens + addr := sample.Bech32AccAddress() + ethAddr := common.BytesToAddress(addr.Bytes()) + coins := sample.Coins() + err := sdkk.BankKeeper.MintCoins(ctx, types.ModuleName, sample.Coins()) + require.NoError(t, err) + err = sdkk.BankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, addr, coins) + require.NoError(t, err) + + // fail if no system contract + err = k.CallWZetaDeposit(ctx, ethAddr, big.NewInt(42)) + require.Error(t, err) + + mockEVMKeeper.SetupMockEVMKeeperForSystemContractDeployment() + deploySystemContracts(t, ctx, k, mockEVMKeeper) + + // deposit + mockEVMKeeper.MockEVMFailCallOnce() + err = k.CallWZetaDeposit(ctx, ethAddr, big.NewInt(42)) + require.ErrorIs(t, err, types.ErrContractCall) +} + +func TestKeeper_QueryWZetaBalanceOfFails(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + // mint tokens + addr := sample.Bech32AccAddress() + ethAddr := common.BytesToAddress(addr.Bytes()) + coins := sample.Coins() + err := sdkk.BankKeeper.MintCoins(ctx, types.ModuleName, sample.Coins()) + require.NoError(t, err) + err = sdkk.BankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, addr, coins) + require.NoError(t, err) + + // fail if no system contract + err = k.CallWZetaDeposit(ctx, ethAddr, big.NewInt(42)) + require.Error(t, err) + + mockEVMKeeper.SetupMockEVMKeeperForSystemContractDeployment() + deploySystemContracts(t, ctx, k, mockEVMKeeper) + + // deposit + mockEVMKeeper.MockEVMFailCallOnce() + _, err = k.QueryWZetaBalanceOf(ctx, ethAddr) + require.ErrorIs(t, err, types.ErrContractCall) +} + +func TestKeeper_QueryWZetaBalanceOfFailsToUnpack(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + // mint tokens + addr := sample.Bech32AccAddress() + ethAddr := common.BytesToAddress(addr.Bytes()) + coins := sample.Coins() + err := sdkk.BankKeeper.MintCoins(ctx, types.ModuleName, sample.Coins()) + require.NoError(t, err) + err = sdkk.BankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, addr, coins) + require.NoError(t, err) + + // fail if no system contract + err = k.CallWZetaDeposit(ctx, ethAddr, big.NewInt(42)) + require.Error(t, err) + + mockEVMKeeper.SetupMockEVMKeeperForSystemContractDeployment() + deploySystemContracts(t, ctx, k, mockEVMKeeper) + + // deposit + mockEVMKeeper.MockEVMSuccessCallOnce() + _, err = k.QueryWZetaBalanceOf(ctx, ethAddr) + require.ErrorIs(t, err, types.ErrABIUnpack) +} + func TestKeeper_QuerySystemContractGasCoinZRC20(t *testing.T) { k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) @@ -124,3 +325,45 @@ func TestKeeper_QuerySystemContractGasCoinZRC20(t *testing.T) { require.NoError(t, err) require.Equal(t, zrc20, found) } + +func TestKeeper_QuerySystemContractGasCoinZRC20Fails(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + chainID := getValidChainID(t) + + _, err := k.QuerySystemContractGasCoinZRC20(ctx, big.NewInt(chainID)) + require.Error(t, err) + require.ErrorIs(t, err, types.ErrStateVariableNotFound) + + mockEVMKeeper.SetupMockEVMKeeperForSystemContractDeployment() + deploySystemContracts(t, ctx, k, mockEVMKeeper) + + mockEVMKeeper.MockEVMFailCallOnce() + _, err = k.QuerySystemContractGasCoinZRC20(ctx, big.NewInt(chainID)) + require.ErrorIs(t, err, types.ErrContractCall) +} + +func TestKeeper_QuerySystemContractGasCoinZRC20FailsToUnpack(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + chainID := getValidChainID(t) + + _, err := k.QuerySystemContractGasCoinZRC20(ctx, big.NewInt(chainID)) + require.Error(t, err) + require.ErrorIs(t, err, types.ErrStateVariableNotFound) + + mockEVMKeeper.SetupMockEVMKeeperForSystemContractDeployment() + deploySystemContracts(t, ctx, k, mockEVMKeeper) + + mockEVMKeeper.MockEVMSuccessCallOnce() + _, err = k.QuerySystemContractGasCoinZRC20(ctx, big.NewInt(chainID)) + require.ErrorIs(t, err, types.ErrABIUnpack) +} From dbbb0feae38eaf959d4f50720e9f24f368dfca8d Mon Sep 17 00:00:00 2001 From: skosito Date: Thu, 15 Feb 2024 16:07:10 +0100 Subject: [PATCH 06/18] Cleanup duplication --- x/fungible/keeper/evm_test.go | 15 +++++++-- x/fungible/keeper/foreign_coins.go | 10 +++--- x/fungible/keeper/gas_price_test.go | 9 ++--- .../msg_server_update_system_contract_test.go | 3 +- ..._server_update_zrc20_paused_status_test.go | 3 +- x/fungible/keeper/system_contract_test.go | 33 +++++++------------ 6 files changed, 34 insertions(+), 39 deletions(-) diff --git a/x/fungible/keeper/evm_test.go b/x/fungible/keeper/evm_test.go index 49dcfd22ec..df8037aa06 100644 --- a/x/fungible/keeper/evm_test.go +++ b/x/fungible/keeper/evm_test.go @@ -17,7 +17,6 @@ import ( "github.com/zeta-chain/zetacore/testutil/contracts" testkeeper "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" - "github.com/zeta-chain/zetacore/x/fungible/keeper" fungiblekeeper "github.com/zeta-chain/zetacore/x/fungible/keeper" "github.com/zeta-chain/zetacore/x/fungible/types" ) @@ -40,6 +39,16 @@ func assertContractDeployment(t *testing.T, k types.EVMKeeper, ctx sdk.Context, require.NotEmpty(t, code) } +func deploySystemContractsWithMockEvmKeeper( + t *testing.T, + ctx sdk.Context, + k *fungiblekeeper.Keeper, + mockEVMKeeper *testkeeper.FungibleMockEVMKeeper, +) (wzeta, uniswapV2Factory, uniswapV2Router, connector, systemContract common.Address) { + mockEVMKeeper.SetupMockEVMKeeperForSystemContractDeployment() + return deploySystemContracts(t, ctx, k, mockEVMKeeper) +} + // deploySystemContracts deploys the system contracts and returns their addresses. func deploySystemContracts( t *testing.T, @@ -81,7 +90,7 @@ func deploySystemContracts( func assertExampleBarValue( t *testing.T, ctx sdk.Context, - k *keeper.Keeper, + k *fungiblekeeper.Keeper, address common.Address, expected int64, ) { @@ -98,6 +107,7 @@ func assertExampleBarValue( false, "bar", ) + require.NoError(t, err) unpacked, err := exampleABI.Unpack("bar", res.Ret) require.NoError(t, err) require.NotZero(t, len(unpacked)) @@ -262,6 +272,7 @@ func TestKeeper_DepositZRC20AndCallContract(t *testing.T) { false, "bar", ) + require.NoError(t, err) unpacked, err := exampleABI.Unpack("bar", res.Ret) require.NoError(t, err) require.NotZero(t, len(unpacked)) diff --git a/x/fungible/keeper/foreign_coins.go b/x/fungible/keeper/foreign_coins.go index faa96d2876..028c961609 100644 --- a/x/fungible/keeper/foreign_coins.go +++ b/x/fungible/keeper/foreign_coins.go @@ -1,8 +1,6 @@ package keeper import ( - "fmt" - "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" ethcommon "github.com/ethereum/go-ethereum/common" @@ -12,7 +10,7 @@ import ( // SetForeignCoins set a specific foreignCoins in the store from its index func (k Keeper) SetForeignCoins(ctx sdk.Context, foreignCoins types.ForeignCoins) { - p := types.KeyPrefix(fmt.Sprintf("%s", types.ForeignCoinsKeyPrefix)) + p := types.KeyPrefix(types.ForeignCoinsKeyPrefix) store := prefix.NewStore(ctx.KVStore(k.storeKey), p) b := k.cdc.MustMarshal(&foreignCoins) store.Set(types.ForeignCoinsKey( @@ -25,7 +23,7 @@ func (k Keeper) GetForeignCoins( ctx sdk.Context, zrc20Addr string, ) (val types.ForeignCoins, found bool) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(fmt.Sprintf("%s", types.ForeignCoinsKeyPrefix))) + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ForeignCoinsKeyPrefix)) b := store.Get(types.ForeignCoinsKey( zrc20Addr, @@ -51,7 +49,7 @@ func (k Keeper) RemoveForeignCoins( // GetAllForeignCoinsForChain returns all foreignCoins on a given chain func (k Keeper) GetAllForeignCoinsForChain(ctx sdk.Context, foreignChainID int64) (list []types.ForeignCoins) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(fmt.Sprintf("%s", types.ForeignCoinsKeyPrefix))) + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ForeignCoinsKeyPrefix)) iterator := sdk.KVStorePrefixIterator(store, []byte{}) defer iterator.Close() @@ -68,7 +66,7 @@ func (k Keeper) GetAllForeignCoinsForChain(ctx sdk.Context, foreignChainID int64 // GetAllForeignCoins returns all foreignCoins func (k Keeper) GetAllForeignCoins(ctx sdk.Context) (list []types.ForeignCoins) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(fmt.Sprintf("%s", types.ForeignCoinsKeyPrefix))) + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ForeignCoinsKeyPrefix)) iterator := sdk.KVStorePrefixIterator(store, []byte{}) defer iterator.Close() diff --git a/x/fungible/keeper/gas_price_test.go b/x/fungible/keeper/gas_price_test.go index 5a232928d8..acd03d359b 100644 --- a/x/fungible/keeper/gas_price_test.go +++ b/x/fungible/keeper/gas_price_test.go @@ -70,8 +70,7 @@ func TestKeeper_SetGasPriceReverts(t *testing.T) { k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) - mockEVMKeeper.SetupMockEVMKeeperForSystemContractDeployment() - deploySystemContracts(t, ctx, k, mockEVMKeeper) + deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) mockEVMKeeper.MockEVMFailCallOnce() _, err := k.SetGasPrice(ctx, big.NewInt(1), big.NewInt(1)) @@ -120,8 +119,7 @@ func TestKeeper_SetGasCoinReverts(t *testing.T) { k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) - mockEVMKeeper.SetupMockEVMKeeperForSystemContractDeployment() - deploySystemContracts(t, ctx, k, mockEVMKeeper) + deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) mockEVMKeeper.MockEVMFailCallOnce() err := k.SetGasCoin(ctx, big.NewInt(1), sample.EthAddress()) @@ -180,8 +178,7 @@ func TestKeeper_SetGasZetaPoolReverts(t *testing.T) { k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) - mockEVMKeeper.SetupMockEVMKeeperForSystemContractDeployment() - deploySystemContracts(t, ctx, k, mockEVMKeeper) + deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) mockEVMKeeper.MockEVMFailCallOnce() err := k.SetGasZetaPool(ctx, big.NewInt(1), sample.EthAddress()) diff --git a/x/fungible/keeper/msg_server_update_system_contract_test.go b/x/fungible/keeper/msg_server_update_system_contract_test.go index cabbf337cf..130d4a63e5 100644 --- a/x/fungible/keeper/msg_server_update_system_contract_test.go +++ b/x/fungible/keeper/msg_server_update_system_contract_test.go @@ -154,7 +154,6 @@ func TestKeeper_UpdateSystemContract(t *testing.T) { mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) msgServer := keeper.NewMsgServerImpl(*k) - mockEVMKeeper.SetupMockEVMKeeperForSystemContractDeployment() k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) admin := sample.AccAddress() setAdminPolicies(ctx, zk, admin, observertypes.Policy_Type_group2) @@ -165,7 +164,7 @@ func TestKeeper_UpdateSystemContract(t *testing.T) { require.NotNil(t, chains[1]) chainID1 := chains[0].ChainId - wzeta, factory, router, _, _ := deploySystemContracts(t, ctx, k, mockEVMKeeper) + wzeta, factory, router, _, _ := deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) // setup mocks and setup gas coin var encodedAddress [32]byte copy(encodedAddress[12:], router[:]) diff --git a/x/fungible/keeper/msg_server_update_zrc20_paused_status_test.go b/x/fungible/keeper/msg_server_update_zrc20_paused_status_test.go index bc4238a780..82b6beb977 100644 --- a/x/fungible/keeper/msg_server_update_zrc20_paused_status_test.go +++ b/x/fungible/keeper/msg_server_update_zrc20_paused_status_test.go @@ -156,12 +156,13 @@ func TestKeeper_UpdateZRC20PausedStatus(t *testing.T) { []string{sample.EthAddress().String()}, types.UpdatePausedStatusAction_PAUSE, )) + require.ErrorIs(t, err, sdkerrors.ErrUnauthorized) admin := sample.AccAddress() setAdminPolicies(ctx, zk, admin, observertypes.Policy_Type_group1) _, err = msgServer.UpdateZRC20PausedStatus(ctx, types.NewMsgUpdateZRC20PausedStatus( - sample.AccAddress(), + admin, []string{sample.EthAddress().String()}, types.UpdatePausedStatusAction_UNPAUSE, )) diff --git a/x/fungible/keeper/system_contract_test.go b/x/fungible/keeper/system_contract_test.go index f737309979..850952e162 100644 --- a/x/fungible/keeper/system_contract_test.go +++ b/x/fungible/keeper/system_contract_test.go @@ -63,8 +63,7 @@ func TestKeeper_GetWZetaContractAddressFails(t *testing.T) { require.Error(t, err) require.ErrorIs(t, err, types.ErrStateVariableNotFound) - mockEVMKeeper.SetupMockEVMKeeperForSystemContractDeployment() - deploySystemContracts(t, ctx, k, mockEVMKeeper) + deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) mockEVMKeeper.MockEVMFailCallOnce() _, err = k.GetWZetaContractAddress(ctx) @@ -82,8 +81,7 @@ func TestKeeper_GetWZetaContractAddressFailsToUnpack(t *testing.T) { require.Error(t, err) require.ErrorIs(t, err, types.ErrStateVariableNotFound) - mockEVMKeeper.SetupMockEVMKeeperForSystemContractDeployment() - deploySystemContracts(t, ctx, k, mockEVMKeeper) + deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) mockEVMKeeper.MockEVMSuccessCallOnce() _, err = k.GetWZetaContractAddress(ctx) @@ -115,8 +113,7 @@ func TestKeeper_GetUniswapV2FactoryAddressFails(t *testing.T) { require.Error(t, err) require.ErrorIs(t, err, types.ErrStateVariableNotFound) - mockEVMKeeper.SetupMockEVMKeeperForSystemContractDeployment() - deploySystemContracts(t, ctx, k, mockEVMKeeper) + deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) mockEVMKeeper.MockEVMFailCallOnce() _, err = k.GetUniswapV2FactoryAddress(ctx) @@ -134,8 +131,7 @@ func TestKeeper_GetUniswapV2FactoryAddressFailsToUnpack(t *testing.T) { require.Error(t, err) require.ErrorIs(t, err, types.ErrStateVariableNotFound) - mockEVMKeeper.SetupMockEVMKeeperForSystemContractDeployment() - deploySystemContracts(t, ctx, k, mockEVMKeeper) + deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) mockEVMKeeper.MockEVMSuccessCallOnce() _, err = k.GetUniswapV2FactoryAddress(ctx) @@ -167,8 +163,7 @@ func TestKeeper_GetUniswapV2Router02AddressFails(t *testing.T) { require.Error(t, err) require.ErrorIs(t, err, types.ErrStateVariableNotFound) - mockEVMKeeper.SetupMockEVMKeeperForSystemContractDeployment() - deploySystemContracts(t, ctx, k, mockEVMKeeper) + deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) mockEVMKeeper.MockEVMFailCallOnce() _, err = k.GetUniswapV2Router02Address(ctx) @@ -186,8 +181,7 @@ func TestKeeper_GetUniswapV2Router02AddressFailsToUnpack(t *testing.T) { require.Error(t, err) require.ErrorIs(t, err, types.ErrStateVariableNotFound) - mockEVMKeeper.SetupMockEVMKeeperForSystemContractDeployment() - deploySystemContracts(t, ctx, k, mockEVMKeeper) + deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) mockEVMKeeper.MockEVMSuccessCallOnce() _, err = k.GetUniswapV2Router02Address(ctx) @@ -242,8 +236,7 @@ func TestKeeper_CallWZetaDepositFails(t *testing.T) { err = k.CallWZetaDeposit(ctx, ethAddr, big.NewInt(42)) require.Error(t, err) - mockEVMKeeper.SetupMockEVMKeeperForSystemContractDeployment() - deploySystemContracts(t, ctx, k, mockEVMKeeper) + deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) // deposit mockEVMKeeper.MockEVMFailCallOnce() @@ -271,8 +264,7 @@ func TestKeeper_QueryWZetaBalanceOfFails(t *testing.T) { err = k.CallWZetaDeposit(ctx, ethAddr, big.NewInt(42)) require.Error(t, err) - mockEVMKeeper.SetupMockEVMKeeperForSystemContractDeployment() - deploySystemContracts(t, ctx, k, mockEVMKeeper) + deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) // deposit mockEVMKeeper.MockEVMFailCallOnce() @@ -300,8 +292,7 @@ func TestKeeper_QueryWZetaBalanceOfFailsToUnpack(t *testing.T) { err = k.CallWZetaDeposit(ctx, ethAddr, big.NewInt(42)) require.Error(t, err) - mockEVMKeeper.SetupMockEVMKeeperForSystemContractDeployment() - deploySystemContracts(t, ctx, k, mockEVMKeeper) + deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) // deposit mockEVMKeeper.MockEVMSuccessCallOnce() @@ -339,8 +330,7 @@ func TestKeeper_QuerySystemContractGasCoinZRC20Fails(t *testing.T) { require.Error(t, err) require.ErrorIs(t, err, types.ErrStateVariableNotFound) - mockEVMKeeper.SetupMockEVMKeeperForSystemContractDeployment() - deploySystemContracts(t, ctx, k, mockEVMKeeper) + deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) mockEVMKeeper.MockEVMFailCallOnce() _, err = k.QuerySystemContractGasCoinZRC20(ctx, big.NewInt(chainID)) @@ -360,8 +350,7 @@ func TestKeeper_QuerySystemContractGasCoinZRC20FailsToUnpack(t *testing.T) { require.Error(t, err) require.ErrorIs(t, err, types.ErrStateVariableNotFound) - mockEVMKeeper.SetupMockEVMKeeperForSystemContractDeployment() - deploySystemContracts(t, ctx, k, mockEVMKeeper) + deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) mockEVMKeeper.MockEVMSuccessCallOnce() _, err = k.QuerySystemContractGasCoinZRC20(ctx, big.NewInt(chainID)) From 4964b4a6f289a072a277f224a43130b3c7d112bb Mon Sep 17 00:00:00 2001 From: skosito Date: Thu, 15 Feb 2024 16:14:56 +0100 Subject: [PATCH 07/18] Cleanup comments --- x/fungible/keeper/msg_server_update_system_contract_test.go | 6 +++--- x/fungible/keeper/system_contract_test.go | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/x/fungible/keeper/msg_server_update_system_contract_test.go b/x/fungible/keeper/msg_server_update_system_contract_test.go index 130d4a63e5..ab3c7a43fc 100644 --- a/x/fungible/keeper/msg_server_update_system_contract_test.go +++ b/x/fungible/keeper/msg_server_update_system_contract_test.go @@ -190,7 +190,7 @@ func TestKeeper_UpdateSystemContract(t *testing.T) { // fail on first evm call mockEVMKeeper.MockEVMFailCallOnce() - // can update the system contract + // can't update the system contract _, err = msgServer.UpdateSystemContract(ctx, types.NewMsgUpdateSystemContract(admin, newSystemContract.Hex())) require.ErrorIs(t, err, types.ErrContractCall) @@ -198,7 +198,7 @@ func TestKeeper_UpdateSystemContract(t *testing.T) { mockEVMKeeper.MockEVMSuccessCallOnce() mockEVMKeeper.MockEVMFailCallOnce() - // can update the system contract + // can't update the system contract _, err = msgServer.UpdateSystemContract(ctx, types.NewMsgUpdateSystemContract(admin, newSystemContract.Hex())) require.ErrorIs(t, err, types.ErrContractCall) @@ -206,7 +206,7 @@ func TestKeeper_UpdateSystemContract(t *testing.T) { mockEVMKeeper.MockEVMSuccessCallTimes(2) mockEVMKeeper.MockEVMFailCallOnce() - // can update the system contract + // can't update the system contract _, err = msgServer.UpdateSystemContract(ctx, types.NewMsgUpdateSystemContract(admin, newSystemContract.Hex())) require.ErrorIs(t, err, types.ErrContractCall) }) diff --git a/x/fungible/keeper/system_contract_test.go b/x/fungible/keeper/system_contract_test.go index 850952e162..e2340cb4c1 100644 --- a/x/fungible/keeper/system_contract_test.go +++ b/x/fungible/keeper/system_contract_test.go @@ -266,7 +266,7 @@ func TestKeeper_QueryWZetaBalanceOfFails(t *testing.T) { deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) - // deposit + // query mockEVMKeeper.MockEVMFailCallOnce() _, err = k.QueryWZetaBalanceOf(ctx, ethAddr) require.ErrorIs(t, err, types.ErrContractCall) @@ -294,7 +294,7 @@ func TestKeeper_QueryWZetaBalanceOfFailsToUnpack(t *testing.T) { deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) - // deposit + // query mockEVMKeeper.MockEVMSuccessCallOnce() _, err = k.QueryWZetaBalanceOf(ctx, ethAddr) require.ErrorIs(t, err, types.ErrABIUnpack) From 3374bd839986c2817590e2a6ca2b8cc730e06df7 Mon Sep 17 00:00:00 2001 From: skosito Date: Fri, 16 Feb 2024 12:28:57 +0100 Subject: [PATCH 08/18] Fix PR comments --- x/fungible/keeper/gas_price.go | 13 ++++++++++-- .../msg_server_update_system_contract_test.go | 21 ++++++++++++------- 2 files changed, 25 insertions(+), 9 deletions(-) diff --git a/x/fungible/keeper/gas_price.go b/x/fungible/keeper/gas_price.go index e829f59377..58ca702b69 100644 --- a/x/fungible/keeper/gas_price.go +++ b/x/fungible/keeper/gas_price.go @@ -31,6 +31,9 @@ func (k Keeper) SetGasPrice(ctx sdk.Context, chainid *big.Int, gasPrice *big.Int if err != nil { return 0, sdkerrors.Wrapf(types.ErrContractCall, err.Error()) } + if res.Failed() { + return res.GasUsed, sdkerrors.Wrapf(types.ErrContractCall, "setGasPrice tx failed") + } return res.GasUsed, nil } @@ -48,10 +51,13 @@ func (k Keeper) SetGasCoin(ctx sdk.Context, chainid *big.Int, address common.Add if err != nil { return sdkerrors.Wrapf(types.ErrABIGet, "SystemContractMetaData") } - _, err = k.CallEVM(ctx, *abi, types.ModuleAddressEVM, oracle, BigIntZero, nil, true, false, "setGasCoinZRC20", chainid, address) + res, err := k.CallEVM(ctx, *abi, types.ModuleAddressEVM, oracle, BigIntZero, nil, true, false, "setGasCoinZRC20", chainid, address) if err != nil { return sdkerrors.Wrapf(types.ErrContractCall, err.Error()) } + if res.Failed() { + return sdkerrors.Wrapf(types.ErrContractCall, "setGasCoinZRC20 tx failed") + } return nil } @@ -69,10 +75,13 @@ func (k Keeper) SetGasZetaPool(ctx sdk.Context, chainid *big.Int, pool common.Ad if err != nil { return sdkerrors.Wrapf(types.ErrABIGet, "SystemContractMetaData") } - _, err = k.CallEVM(ctx, *abi, types.ModuleAddressEVM, oracle, BigIntZero, nil, true, false, "setGasZetaPool", chainid, pool) + res, err := k.CallEVM(ctx, *abi, types.ModuleAddressEVM, oracle, BigIntZero, nil, true, false, "setGasZetaPool", chainid, pool) if err != nil { return sdkerrors.Wrapf(types.ErrContractCall, err.Error()) } + if res.Failed() { + return sdkerrors.Wrapf(types.ErrContractCall, "setGasZetaPool tx failed") + } return nil } diff --git a/x/fungible/keeper/msg_server_update_system_contract_test.go b/x/fungible/keeper/msg_server_update_system_contract_test.go index ab3c7a43fc..0fbc261c47 100644 --- a/x/fungible/keeper/msg_server_update_system_contract_test.go +++ b/x/fungible/keeper/msg_server_update_system_contract_test.go @@ -75,18 +75,13 @@ func TestKeeper_UpdateSystemContract(t *testing.T) { require.Equal(t, newSystemContract.Hex(), queryZRC20SystemContract(gas2)) }) - t.Run("can update the system contract if system contract not found", func(t *testing.T) { + t.Run("can update and overwrite the system contract if system contract not found", func(t *testing.T) { k, ctx, _, zk := keepertest.FungibleKeeper(t) msgServer := keeper.NewMsgServerImpl(*k) k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) admin := sample.AccAddress() setAdminPolicies(ctx, zk, admin, observertypes.Policy_Type_group2) - chains := zetacommon.DefaultChainsList() - require.True(t, len(chains) > 1) - require.NotNil(t, chains[0]) - require.NotNil(t, chains[1]) - wzeta, err := k.DeployWZETA(ctx) require.NoError(t, err) @@ -108,6 +103,19 @@ func TestKeeper_UpdateSystemContract(t *testing.T) { sc, found := k.GetSystemContract(ctx) require.True(t, found) require.Equal(t, newSystemContract.Hex(), sc.SystemContract) + + // deploy a new system contracts + newSystemContract, err = k.DeployContract(ctx, systemcontract.SystemContractMetaData, wzeta, factory, router) + require.NoError(t, err) + + // can overwrite the previous system contract + _, err = msgServer.UpdateSystemContract(ctx, types.NewMsgUpdateSystemContract(admin, newSystemContract.Hex())) + require.NoError(t, err) + + // can retrieve the system contract + sc, found = k.GetSystemContract(ctx) + require.True(t, found) + require.Equal(t, newSystemContract.Hex(), sc.SystemContract) }) t.Run("should not update the system contract if not admin", func(t *testing.T) { @@ -161,7 +169,6 @@ func TestKeeper_UpdateSystemContract(t *testing.T) { chains := zetacommon.DefaultChainsList() require.True(t, len(chains) > 1) require.NotNil(t, chains[0]) - require.NotNil(t, chains[1]) chainID1 := chains[0].ChainId wzeta, factory, router, _, _ := deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) From 062acce9f84ebbfd29fd8133ec9dd212363c40aa Mon Sep 17 00:00:00 2001 From: skosito Date: Fri, 16 Feb 2024 12:30:20 +0100 Subject: [PATCH 09/18] Add changelog entry --- changelog.md | 1 + 1 file changed, 1 insertion(+) diff --git a/changelog.md b/changelog.md index 5fa64f61a2..c327be0096 100644 --- a/changelog.md +++ b/changelog.md @@ -38,6 +38,7 @@ * [1584](https://github.com/zeta-chain/node/pull/1584) - allow to run E2E tests on any networks * [1753](https://github.com/zeta-chain/node/pull/1753) - fix gosec errors on usage of rand package +* [1762](https://github.com/zeta-chain/node/pull/1762) - improve coverage for fungibile module ### CI From fa855ec8d3a31279bdd36d1fb291ce36923fbe8b Mon Sep 17 00:00:00 2001 From: skosito Date: Mon, 19 Feb 2024 18:59:21 +0100 Subject: [PATCH 10/18] Add tests for missing functions --- x/fungible/keeper/gas_coin_and_pool_test.go | 70 +++++ x/fungible/keeper/system_contract.go | 20 +- x/fungible/keeper/system_contract_test.go | 294 +++++++++++++++++++- 3 files changed, 361 insertions(+), 23 deletions(-) diff --git a/x/fungible/keeper/gas_coin_and_pool_test.go b/x/fungible/keeper/gas_coin_and_pool_test.go index b6f05431ac..a422183a31 100644 --- a/x/fungible/keeper/gas_coin_and_pool_test.go +++ b/x/fungible/keeper/gas_coin_and_pool_test.go @@ -9,6 +9,9 @@ import ( evmkeeper "github.com/evmos/ethermint/x/evm/keeper" "github.com/stretchr/testify/require" + bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" + uniswapv2router02 "github.com/zeta-chain/protocol-contracts/pkg/uniswap/v2-periphery/contracts/uniswapv2router02.sol" + "github.com/zeta-chain/zetacore/cmd/zetacored/config" testkeeper "github.com/zeta-chain/zetacore/testutil/keeper" fungiblekeeper "github.com/zeta-chain/zetacore/x/fungible/keeper" "github.com/zeta-chain/zetacore/x/fungible/types" @@ -62,6 +65,73 @@ func deployZRC20( return addr } +// setupZRC20Pool setup a Uniswap pool with liquidity for the pair zeta/asset +func setupZRC20Pool( + t *testing.T, + ctx sdk.Context, + k *fungiblekeeper.Keeper, + bankKeeper bankkeeper.Keeper, + zrc20Addr common.Address, +) { + routerAddress, err := k.GetUniswapV2Router02Address(ctx) + require.NoError(t, err) + routerABI, err := uniswapv2router02.UniswapV2Router02MetaData.GetAbi() + require.NoError(t, err) + + // enough for the small numbers used in test + liquidityAmount := big.NewInt(1e17) + + // mint some zrc20 and zeta + _, err = k.DepositZRC20(ctx, zrc20Addr, types.ModuleAddressEVM, liquidityAmount) + require.NoError(t, err) + err = bankKeeper.MintCoins( + ctx, + types.ModuleName, + sdk.NewCoins(sdk.NewCoin(config.BaseDenom, sdk.NewIntFromBigInt(liquidityAmount))), + ) + require.NoError(t, err) + + // approve the router to spend the zeta + err = k.CallZRC20Approve( + ctx, + types.ModuleAddressEVM, + zrc20Addr, + routerAddress, + liquidityAmount, + false, + ) + require.NoError(t, err) + + // k2 := liquidityAmount.Sub(liquidityAmount, big.NewInt(1000)) + // add the liquidity + //function addLiquidityETH( + // address token, + // uint amountTokenDesired, + // uint amountTokenMin, + // uint amountETHMin, + // address to, + // uint deadline + //) + _, err = k.CallEVM( + ctx, + *routerABI, + types.ModuleAddressEVM, + routerAddress, + liquidityAmount, + big.NewInt(5_000_000), + true, + false, + "addLiquidityETH", + zrc20Addr, + liquidityAmount, + fungiblekeeper.BigIntZero, + fungiblekeeper.BigIntZero, + types.ModuleAddressEVM, + liquidityAmount, + ) + require.NoError(t, err) +} + func TestKeeper_SetupChainGasCoinAndPool(t *testing.T) { t.Run("can setup a new chain gas coin", func(t *testing.T) { k, ctx, sdkk, _ := testkeeper.FungibleKeeper(t) diff --git a/x/fungible/keeper/system_contract.go b/x/fungible/keeper/system_contract.go index be531f1597..8f74d77d2c 100644 --- a/x/fungible/keeper/system_contract.go +++ b/x/fungible/keeper/system_contract.go @@ -316,7 +316,7 @@ func (k *Keeper) CallUniswapV2RouterSwapExactTokensForTokens( big.NewInt(1e17), ) if err != nil { - return nil, cosmoserrors.Wrapf(err, "failed to CallEVM method swapExactTokensForTokens") + return nil, cosmoserrors.Wrapf(types.ErrContractCall, "failed to CallEVM method swapExactTokensForTokens (%s)", err.Error()) } amounts := new([3]*big.Int) @@ -374,7 +374,7 @@ func (k *Keeper) CallUniswapV2RouterSwapExactTokensForETH( big.NewInt(1e17), ) if err != nil { - return nil, cosmoserrors.Wrapf(err, "failed to CallEVM method swapExactTokensForETH") + return nil, cosmoserrors.Wrapf(types.ErrContractCall, "failed to CallEVM method swapExactTokensForETH (%s)", err.Error()) } amounts := new([2]*big.Int) @@ -426,7 +426,7 @@ func (k *Keeper) CallUniswapV2RouterSwapExactETHForToken( big.NewInt(1e17), ) if err != nil { - return nil, cosmoserrors.Wrapf(err, "failed to CallEVM method swapExactETHForTokens") + return nil, cosmoserrors.Wrapf(types.ErrContractCall, "failed to CallEVM method swapExactETHForTokens (%s)", err.Error()) } amounts := new([2]*big.Int) @@ -477,7 +477,7 @@ func (k *Keeper) CallUniswapV2RouterSwapEthForExactToken( big.NewInt(1e17), ) if err != nil { - return nil, cosmoserrors.Wrapf(err, "failed to CallEVM method swapETHForExactTokens") + return nil, cosmoserrors.Wrapf(types.ErrContractCall, "failed to CallEVM method swapETHForExactTokens (%s)", err.Error()) } amounts := new([2]*big.Int) @@ -519,7 +519,7 @@ func (k *Keeper) QueryUniswapV2RouterGetZetaAmountsIn(ctx sdk.Context, amountOut []ethcommon.Address{wzetaAddr, outZRC4}, ) if err != nil { - return nil, cosmoserrors.Wrapf(err, "failed to CallEVM method getAmountsIn") + return nil, cosmoserrors.Wrapf(types.ErrContractCall, "failed to CallEVM method getAmountsIn (%s)", err.Error()) } amounts := new([2]*big.Int) @@ -560,7 +560,7 @@ func (k *Keeper) QueryUniswapV2RouterGetZRC4AmountsIn(ctx sdk.Context, amountOut []ethcommon.Address{inZRC4, wzetaAddr}, ) if err != nil { - return nil, cosmoserrors.Wrapf(err, "failed to CallEVM method getAmountsIn") + return nil, cosmoserrors.Wrapf(types.ErrContractCall, "failed to CallEVM method getAmountsIn (%s)", err.Error()) } amounts := new([2]*big.Int) @@ -601,7 +601,7 @@ func (k *Keeper) QueryUniswapV2RouterGetZRC4ToZRC4AmountsIn(ctx sdk.Context, amo []ethcommon.Address{inZRC4, wzetaAddr, outZRC4}, ) if err != nil { - return nil, cosmoserrors.Wrapf(err, "failed to CallEVM method getAmountsIn") + return nil, cosmoserrors.Wrapf(types.ErrContractCall, "failed to CallEVM method getAmountsIn (%s)", err.Error()) } amounts := new([3]*big.Int) @@ -638,7 +638,7 @@ func (k *Keeper) CallZRC20Burn( amount, ) if err != nil { - return cosmoserrors.Wrapf(err, "failed to CallEVM method burn") + return cosmoserrors.Wrapf(types.ErrContractCall, "failed to CallEVM method burn (%s)", err.Error()) } return nil @@ -671,7 +671,7 @@ func (k *Keeper) CallZRC20Deposit( amount, ) if err != nil { - return cosmoserrors.Wrapf(err, "failed to CallEVM method burn") + return cosmoserrors.Wrapf(types.ErrContractCall, "failed to CallEVM method burn (%s)", err.Error()) } return nil } @@ -704,7 +704,7 @@ func (k *Keeper) CallZRC20Approve( amount, ) if err != nil { - return cosmoserrors.Wrapf(err, "failed to CallEVM method approve") + return cosmoserrors.Wrapf(types.ErrContractCall, "failed to CallEVM method approve (%s)", err.Error()) } return nil diff --git a/x/fungible/keeper/system_contract_test.go b/x/fungible/keeper/system_contract_test.go index e2340cb4c1..2f9eb8e229 100644 --- a/x/fungible/keeper/system_contract_test.go +++ b/x/fungible/keeper/system_contract_test.go @@ -4,7 +4,9 @@ import ( "math/big" "testing" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/ethereum/go-ethereum/common" + evmtypes "github.com/evmos/ethermint/x/evm/types" "github.com/stretchr/testify/require" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" @@ -232,10 +234,6 @@ func TestKeeper_CallWZetaDepositFails(t *testing.T) { err = sdkk.BankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, addr, coins) require.NoError(t, err) - // fail if no system contract - err = k.CallWZetaDeposit(ctx, ethAddr, big.NewInt(42)) - require.Error(t, err) - deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) // deposit @@ -244,7 +242,7 @@ func TestKeeper_CallWZetaDepositFails(t *testing.T) { require.ErrorIs(t, err, types.ErrContractCall) } -func TestKeeper_QueryWZetaBalanceOfFails(t *testing.T) { +func TestKeeper_QueryWZetaBalanceOfFailsToReturnSystemContract(t *testing.T) { k, ctx, sdkk, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ UseEVMMock: true, }) @@ -260,10 +258,6 @@ func TestKeeper_QueryWZetaBalanceOfFails(t *testing.T) { err = sdkk.BankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, addr, coins) require.NoError(t, err) - // fail if no system contract - err = k.CallWZetaDeposit(ctx, ethAddr, big.NewInt(42)) - require.Error(t, err) - deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) // query @@ -272,6 +266,29 @@ func TestKeeper_QueryWZetaBalanceOfFails(t *testing.T) { require.ErrorIs(t, err, types.ErrContractCall) } +func TestKeeper_QueryWZetaBalanceOfFails(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + // mint tokens + + wzeta, factory, router, _, _ := deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) + var encodedAddress [32]byte + copy(encodedAddress[12:], router[:]) + addLiqMockReturn := &evmtypes.MsgEthereumTxResponse{ + Ret: make([]byte, 3*32), + } + mockEVMKeeper.MockEVMSuccessCallOnceWithReturn(addLiqMockReturn) + + // query + mockEVMKeeper.MockEVMFailCallOnce() + _, err := k.QueryWZetaBalanceOf(ctx, sample.EthAddress()) + require.ErrorIs(t, err, types.ErrContractCall) +} + func TestKeeper_QueryWZetaBalanceOfFailsToUnpack(t *testing.T) { k, ctx, sdkk, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ UseEVMMock: true, @@ -288,10 +305,6 @@ func TestKeeper_QueryWZetaBalanceOfFailsToUnpack(t *testing.T) { err = sdkk.BankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, addr, coins) require.NoError(t, err) - // fail if no system contract - err = k.CallWZetaDeposit(ctx, ethAddr, big.NewInt(42)) - require.Error(t, err) - deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) // query @@ -356,3 +369,258 @@ func TestKeeper_QuerySystemContractGasCoinZRC20FailsToUnpack(t *testing.T) { _, err = k.QuerySystemContractGasCoinZRC20(ctx, big.NewInt(chainID)) require.ErrorIs(t, err, types.ErrABIUnpack) } + +func TestKeeper_CallUniswapV2RouterSwapExactETHForToken(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + chainID := getValidChainID(t) + + // fail if no system contract + _, err := k.CallUniswapV2RouterSwapExactETHForToken( + ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, big.NewInt(1), sample.EthAddress(), true) + require.Error(t, err) + + // deploy system contracts and swap exact eth for 1 token + tokenAmount := big.NewInt(1) + deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) + zrc20 := setupGasCoin(t, ctx, k, sdkk.EvmKeeper, chainID, "foobar", "foobar") + + amountToSwap, err := k.QueryUniswapV2RouterGetZetaAmountsIn(ctx, tokenAmount, zrc20) + require.NoError(t, err) + err = sdkk.BankKeeper.MintCoins(ctx, types.ModuleName, sdk.NewCoins(sdk.NewCoin("azeta", sdk.NewIntFromBigInt(amountToSwap)))) + require.NoError(t, err) + + amounts, err := k.CallUniswapV2RouterSwapExactETHForToken( + ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, amountToSwap, zrc20, true) + require.NoError(t, err) + + require.Equal(t, 2, len(amounts)) + require.Equal(t, tokenAmount, amounts[1]) +} + +func TestKeeper_CallUniswapV2RouterSwapExactETHForTokenFails(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + chainID := getValidChainID(t) + + // deploy system contracts and swap 1 token fails because of missing wrapped balance + deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) + zrc20 := setupGasCoin(t, ctx, k, sdkk.EvmKeeper, chainID, "foobar", "foobar") + + amountToSwap, err := k.QueryUniswapV2RouterGetZetaAmountsIn(ctx, big.NewInt(1), zrc20) + require.NoError(t, err) + + _, err = k.CallUniswapV2RouterSwapExactETHForToken( + ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, amountToSwap, zrc20, true) + require.ErrorIs(t, err, types.ErrContractCall) +} + +func TestKeeper_CallUniswapV2RouterSwapEthForExactToken(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + chainID := getValidChainID(t) + + // fail if no system contract + _, err := k.CallUniswapV2RouterSwapExactETHForToken( + ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, big.NewInt(1), sample.EthAddress(), true) + require.Error(t, err) + + // deploy system contracts and swap exact 1 token + tokenAmount := big.NewInt(1) + deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) + zrc20 := setupGasCoin(t, ctx, k, sdkk.EvmKeeper, chainID, "foobar", "foobar") + + amountToSwap, err := k.QueryUniswapV2RouterGetZetaAmountsIn(ctx, tokenAmount, zrc20) + require.NoError(t, err) + err = sdkk.BankKeeper.MintCoins(ctx, types.ModuleName, sdk.NewCoins(sdk.NewCoin("azeta", sdk.NewIntFromBigInt(amountToSwap)))) + require.NoError(t, err) + + amounts, err := k.CallUniswapV2RouterSwapEthForExactToken( + ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, amountToSwap, tokenAmount, zrc20) + require.NoError(t, err) + + require.Equal(t, 2, len(amounts)) + require.Equal(t, big.NewInt(1), amounts[1]) +} + +func TestKeeper_CallUniswapV2RouterSwapEthForExactTokenFails(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + chainID := getValidChainID(t) + + // deploy system contracts and swap 1 token fails because of missing wrapped balance + tokenAmount := big.NewInt(1) + deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) + zrc20 := setupGasCoin(t, ctx, k, sdkk.EvmKeeper, chainID, "foobar", "foobar") + + amountToSwap, err := k.QueryUniswapV2RouterGetZetaAmountsIn(ctx, tokenAmount, zrc20) + require.NoError(t, err) + + _, err = k.CallUniswapV2RouterSwapEthForExactToken( + ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, amountToSwap, tokenAmount, zrc20) + require.ErrorIs(t, err, types.ErrContractCall) +} + +func TestKeeper_CallUniswapV2RouterSwapExactTokensForETH(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + chainID := getValidChainID(t) + + // fail if no system contract + _, err := k.CallUniswapV2RouterSwapExactTokensForETH( + ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, big.NewInt(1), sample.EthAddress(), true) + require.Error(t, err) + + // deploy system contracts and swap exact eth for 1 token + ethAmount := big.NewInt(1) + _, _, router, _, _ := deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) + zrc20 := setupGasCoin(t, ctx, k, sdkk.EvmKeeper, chainID, "foobar", "foobar") + + amountToSwap, err := k.QueryUniswapV2RouterGetZRC4AmountsIn(ctx, ethAmount, zrc20) + require.NoError(t, err) + + _, err = k.DepositZRC20(ctx, zrc20, types.ModuleAddressEVM, amountToSwap) + require.NoError(t, err) + k.CallZRC20Approve( + ctx, + types.ModuleAddressEVM, + zrc20, + router, + amountToSwap, + false, + ) + + amounts, err := k.CallUniswapV2RouterSwapExactTokensForETH( + ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, amountToSwap, zrc20, true) + require.NoError(t, err) + + require.Equal(t, 2, len(amounts)) + require.Equal(t, ethAmount, amounts[0]) +} + +func TestKeeper_CallUniswapV2RouterSwapExactTokensForETHFails(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + chainID := getValidChainID(t) + + // fail if no system contract + _, err := k.CallUniswapV2RouterSwapExactTokensForETH( + ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, big.NewInt(1), sample.EthAddress(), true) + require.Error(t, err) + + // deploy system contracts and swap fails because of missing balance + ethAmount := big.NewInt(1) + deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) + zrc20 := setupGasCoin(t, ctx, k, sdkk.EvmKeeper, chainID, "foobar", "foobar") + + amountToSwap, err := k.QueryUniswapV2RouterGetZRC4AmountsIn(ctx, ethAmount, zrc20) + require.NoError(t, err) + + _, err = k.CallUniswapV2RouterSwapExactTokensForETH( + ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, amountToSwap, zrc20, true) + require.ErrorIs(t, err, types.ErrContractCall) +} + +func TestKeeper_CallUniswapV2RouterSwapExactTokensForTokens(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + chainID := getValidChainID(t) + + // fail if no system contract + _, err := k.CallUniswapV2RouterSwapExactTokensForTokens( + ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, big.NewInt(1), sample.EthAddress(), sample.EthAddress(), true) + require.Error(t, err) + + // deploy system contracts and swap exact token for 1 token + tokenAmount := big.NewInt(1) + _, _, router, _, _ := deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) + + inzrc20 := deployZRC20(t, ctx, k, sdkk.EvmKeeper, chainID, "foo", sample.EthAddress().String(), "foo") + outzrc20 := deployZRC20(t, ctx, k, sdkk.EvmKeeper, chainID, "bar", sample.EthAddress().String(), "bar") + setupZRC20Pool(t, ctx, k, sdkk.BankKeeper, inzrc20) + setupZRC20Pool(t, ctx, k, sdkk.BankKeeper, outzrc20) + + amountToSwap, err := k.QueryUniswapV2RouterGetZRC4ToZRC4AmountsIn(ctx, tokenAmount, inzrc20, outzrc20) + require.NoError(t, err) + + _, err = k.DepositZRC20(ctx, inzrc20, types.ModuleAddressEVM, amountToSwap) + require.NoError(t, err) + k.CallZRC20Approve( + ctx, + types.ModuleAddressEVM, + inzrc20, + router, + amountToSwap, + false, + ) + + amounts, err := k.CallUniswapV2RouterSwapExactTokensForTokens( + ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, amountToSwap, inzrc20, outzrc20, true) + require.NoError(t, err) + require.Equal(t, 3, len(amounts)) + require.Equal(t, amounts[2], tokenAmount) +} + +func TestKeeper_CallUniswapV2RouterSwapExactTokensForTokensFails(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + chainID := getValidChainID(t) + + // deploy system contracts and swap fails because of missing balance + tokenAmount := big.NewInt(1) + deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) + + inzrc20 := deployZRC20(t, ctx, k, sdkk.EvmKeeper, chainID, "foo", sample.EthAddress().String(), "foo") + outzrc20 := deployZRC20(t, ctx, k, sdkk.EvmKeeper, chainID, "bar", sample.EthAddress().String(), "bar") + setupZRC20Pool(t, ctx, k, sdkk.BankKeeper, inzrc20) + setupZRC20Pool(t, ctx, k, sdkk.BankKeeper, outzrc20) + + amountToSwap, err := k.QueryUniswapV2RouterGetZRC4ToZRC4AmountsIn(ctx, tokenAmount, inzrc20, outzrc20) + require.NoError(t, err) + + _, err = k.CallUniswapV2RouterSwapExactTokensForTokens( + ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, amountToSwap, inzrc20, outzrc20, true) + require.ErrorIs(t, err, types.ErrContractCall) +} + +func TestKeeper_CallZRC20BurnFails(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) + + mockEVMKeeper.MockEVMFailCallOnce() + err := k.CallZRC20Burn(ctx, types.ModuleAddressEVM, sample.EthAddress(), big.NewInt(1), false) + require.ErrorIs(t, err, types.ErrContractCall) +} + +func TestKeeper_CallZRC20ApproveFails(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) + + mockEVMKeeper.MockEVMFailCallOnce() + err := k.CallZRC20Approve(ctx, types.ModuleAddressEVM, sample.EthAddress(), types.ModuleAddressEVM, big.NewInt(1), false) + require.ErrorIs(t, err, types.ErrContractCall) +} + +func TestKeeper_CallZRC20DepositFails(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) + + mockEVMKeeper.MockEVMFailCallOnce() + err := k.CallZRC20Deposit(ctx, types.ModuleAddressEVM, sample.EthAddress(), types.ModuleAddressEVM, big.NewInt(1)) + require.ErrorIs(t, err, types.ErrContractCall) +} From 7e85202a6ca7f7ec517f5f3e535b93de1b61e030 Mon Sep 17 00:00:00 2001 From: skosito Date: Mon, 19 Feb 2024 20:51:00 +0100 Subject: [PATCH 11/18] Cleanup and test more cases --- x/fungible/keeper/evm_test.go | 50 +++ x/fungible/keeper/system_contract.go | 19 +- x/fungible/keeper/system_contract_test.go | 467 ++++++++++++---------- 3 files changed, 317 insertions(+), 219 deletions(-) diff --git a/x/fungible/keeper/evm_test.go b/x/fungible/keeper/evm_test.go index df8037aa06..e698f2a01c 100644 --- a/x/fungible/keeper/evm_test.go +++ b/x/fungible/keeper/evm_test.go @@ -86,6 +86,56 @@ func deploySystemContracts( return } +type SystemContractDeployConfig struct { + DeployWZeta bool + DeployUniswapV2Factory bool + DeployUniswapV2Router bool +} + +// deploySystemContracts deploys the system contracts and returns their addresses. +func deploySystemContractsConfigurable( + t *testing.T, + ctx sdk.Context, + k *fungiblekeeper.Keeper, + evmk types.EVMKeeper, + config *SystemContractDeployConfig, +) (wzeta, uniswapV2Factory, uniswapV2Router, connector, systemContract common.Address) { + var err error + + if config.DeployWZeta { + wzeta, err = k.DeployWZETA(ctx) + require.NoError(t, err) + require.NotEmpty(t, wzeta) + assertContractDeployment(t, evmk, ctx, wzeta) + } + + if config.DeployUniswapV2Factory { + uniswapV2Factory, err = k.DeployUniswapV2Factory(ctx) + require.NoError(t, err) + require.NotEmpty(t, uniswapV2Factory) + assertContractDeployment(t, evmk, ctx, uniswapV2Factory) + } + + if config.DeployUniswapV2Router { + uniswapV2Router, err = k.DeployUniswapV2Router02(ctx, uniswapV2Factory, wzeta) + require.NoError(t, err) + require.NotEmpty(t, uniswapV2Router) + assertContractDeployment(t, evmk, ctx, uniswapV2Router) + } + + connector, err = k.DeployConnectorZEVM(ctx, wzeta) + require.NoError(t, err) + require.NotEmpty(t, connector) + assertContractDeployment(t, evmk, ctx, connector) + + systemContract, err = k.DeploySystemContract(ctx, wzeta, uniswapV2Factory, uniswapV2Router) + require.NoError(t, err) + require.NotEmpty(t, systemContract) + assertContractDeployment(t, evmk, ctx, systemContract) + + return +} + // assertExampleBarValue asserts value Bar of the contract Example, used to test onCrossChainCall func assertExampleBarValue( t *testing.T, diff --git a/x/fungible/keeper/system_contract.go b/x/fungible/keeper/system_contract.go index 8f74d77d2c..f93138a973 100644 --- a/x/fungible/keeper/system_contract.go +++ b/x/fungible/keeper/system_contract.go @@ -6,6 +6,7 @@ import ( cosmoserrors "cosmossdk.io/errors" "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ethcommon "github.com/ethereum/go-ethereum/common" "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/systemcontract.sol" "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/wzeta.sol" @@ -87,6 +88,10 @@ func (k *Keeper) GetWZetaContractAddress(ctx sdk.Context) (ethcommon.Address, er if err := sysABI.UnpackIntoInterface(&wzetaResponse, "wZetaContractAddress", res.Ret); err != nil { return ethcommon.Address{}, cosmoserrors.Wrapf(types.ErrABIUnpack, "failed to unpack wZetaContractAddress: %s", err.Error()) } + + if wzetaResponse.Value == ethcommon.HexToAddress("0x0") { + return ethcommon.Address{}, sdkerrors.Wrapf(types.ErrContractNotFound, "wzeta contract invalid address") + } return wzetaResponse.Value, nil } @@ -119,11 +124,15 @@ func (k *Keeper) GetUniswapV2FactoryAddress(ctx sdk.Context) (ethcommon.Address, type AddressResponse struct { Value ethcommon.Address } - var wzetaResponse AddressResponse - if err := sysABI.UnpackIntoInterface(&wzetaResponse, "uniswapv2FactoryAddress", res.Ret); err != nil { + var uniswapFactoryResponse AddressResponse + if err := sysABI.UnpackIntoInterface(&uniswapFactoryResponse, "uniswapv2FactoryAddress", res.Ret); err != nil { return ethcommon.Address{}, cosmoserrors.Wrapf(types.ErrABIUnpack, "failed to unpack uniswapv2FactoryAddress: %s", err.Error()) } - return wzetaResponse.Value, nil + + if uniswapFactoryResponse.Value == ethcommon.HexToAddress("0x0") { + return ethcommon.Address{}, sdkerrors.Wrapf(types.ErrContractNotFound, "uniswap factory contract invalid address") + } + return uniswapFactoryResponse.Value, nil } // GetUniswapV2Router02Address returns the uniswapv2 router02 address on ZetaChain @@ -159,6 +168,10 @@ func (k *Keeper) GetUniswapV2Router02Address(ctx sdk.Context) (ethcommon.Address if err := sysABI.UnpackIntoInterface(&routerResponse, "uniswapv2Router02Address", res.Ret); err != nil { return ethcommon.Address{}, cosmoserrors.Wrapf(types.ErrABIUnpack, "failed to unpack uniswapv2Router02Address: %s", err.Error()) } + + if routerResponse.Value == ethcommon.HexToAddress("0x0") { + return ethcommon.Address{}, sdkerrors.Wrapf(types.ErrContractNotFound, "uniswap router contract invalid address") + } return routerResponse.Value, nil } diff --git a/x/fungible/keeper/system_contract_test.go b/x/fungible/keeper/system_contract_test.go index 2f9eb8e229..90550a2051 100644 --- a/x/fungible/keeper/system_contract_test.go +++ b/x/fungible/keeper/system_contract_test.go @@ -6,7 +6,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/ethereum/go-ethereum/common" - evmtypes "github.com/evmos/ethermint/x/evm/types" "github.com/stretchr/testify/require" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" @@ -55,39 +54,17 @@ func TestKeeper_GetWZetaContractAddress(t *testing.T) { } func TestKeeper_GetWZetaContractAddressFails(t *testing.T) { - k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ - UseEVMMock: true, - }) - mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - - _, err := k.GetWZetaContractAddress(ctx) - require.Error(t, err) - require.ErrorIs(t, err, types.ErrStateVariableNotFound) - - deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) - - mockEVMKeeper.MockEVMFailCallOnce() - _, err = k.GetWZetaContractAddress(ctx) - require.ErrorIs(t, err, types.ErrContractCall) -} - -func TestKeeper_GetWZetaContractAddressFailsToUnpack(t *testing.T) { - k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ - UseEVMMock: true, - }) - mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) _, err := k.GetWZetaContractAddress(ctx) require.Error(t, err) require.ErrorIs(t, err, types.ErrStateVariableNotFound) - deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) - - mockEVMKeeper.MockEVMSuccessCallOnce() - _, err = k.GetWZetaContractAddress(ctx) - require.ErrorIs(t, err, types.ErrABIUnpack) + wzeta, _, _, _, _ := deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) + found, err := k.GetWZetaContractAddress(ctx) + require.NoError(t, err) + require.Equal(t, wzeta, found) } func TestKeeper_GetUniswapV2FactoryAddress(t *testing.T) { @@ -104,42 +81,6 @@ func TestKeeper_GetUniswapV2FactoryAddress(t *testing.T) { require.Equal(t, factory, found) } -func TestKeeper_GetUniswapV2FactoryAddressFails(t *testing.T) { - k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ - UseEVMMock: true, - }) - mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - - _, err := k.GetUniswapV2FactoryAddress(ctx) - require.Error(t, err) - require.ErrorIs(t, err, types.ErrStateVariableNotFound) - - deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) - - mockEVMKeeper.MockEVMFailCallOnce() - _, err = k.GetUniswapV2FactoryAddress(ctx) - require.ErrorIs(t, err, types.ErrContractCall) -} - -func TestKeeper_GetUniswapV2FactoryAddressFailsToUnpack(t *testing.T) { - k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ - UseEVMMock: true, - }) - mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - - _, err := k.GetUniswapV2FactoryAddress(ctx) - require.Error(t, err) - require.ErrorIs(t, err, types.ErrStateVariableNotFound) - - deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) - - mockEVMKeeper.MockEVMSuccessCallOnce() - _, err = k.GetUniswapV2FactoryAddress(ctx) - require.ErrorIs(t, err, types.ErrABIUnpack) -} - func TestKeeper_GetUniswapV2Router02Address(t *testing.T) { k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) @@ -154,42 +95,6 @@ func TestKeeper_GetUniswapV2Router02Address(t *testing.T) { require.Equal(t, router, found) } -func TestKeeper_GetUniswapV2Router02AddressFails(t *testing.T) { - k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ - UseEVMMock: true, - }) - mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - - _, err := k.GetUniswapV2Router02Address(ctx) - require.Error(t, err) - require.ErrorIs(t, err, types.ErrStateVariableNotFound) - - deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) - - mockEVMKeeper.MockEVMFailCallOnce() - _, err = k.GetUniswapV2Router02Address(ctx) - require.ErrorIs(t, err, types.ErrContractCall) -} - -func TestKeeper_GetUniswapV2Router02AddressFailsToUnpack(t *testing.T) { - k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ - UseEVMMock: true, - }) - mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - - _, err := k.GetUniswapV2Router02Address(ctx) - require.Error(t, err) - require.ErrorIs(t, err, types.ErrStateVariableNotFound) - - deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) - - mockEVMKeeper.MockEVMSuccessCallOnce() - _, err = k.GetUniswapV2Router02Address(ctx) - require.ErrorIs(t, err, types.ErrABIUnpack) -} - func TestKeeper_CallWZetaDeposit(t *testing.T) { k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) @@ -218,99 +123,55 @@ func TestKeeper_CallWZetaDeposit(t *testing.T) { require.Equal(t, big.NewInt(42), balance) } -func TestKeeper_CallWZetaDepositFails(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ - UseEVMMock: true, - }) - mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) +func TestKeeper_QueryWZetaBalanceOfFails(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeper(t) k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - // mint tokens - addr := sample.Bech32AccAddress() - ethAddr := common.BytesToAddress(addr.Bytes()) - coins := sample.Coins() - err := sdkk.BankKeeper.MintCoins(ctx, types.ModuleName, sample.Coins()) - require.NoError(t, err) - err = sdkk.BankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, addr, coins) - require.NoError(t, err) - - deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) - - // deposit - mockEVMKeeper.MockEVMFailCallOnce() - err = k.CallWZetaDeposit(ctx, ethAddr, big.NewInt(42)) - require.ErrorIs(t, err, types.ErrContractCall) + // fail if no system contract + _, err := k.QueryWZetaBalanceOf(ctx, sample.EthAddress()) + require.Error(t, err) } -func TestKeeper_QueryWZetaBalanceOfFailsToReturnSystemContract(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ - UseEVMMock: true, - }) - mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) +func TestKeeper_GetWZetaFailsIfNotSet(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - // mint tokens - addr := sample.Bech32AccAddress() - ethAddr := common.BytesToAddress(addr.Bytes()) - coins := sample.Coins() - err := sdkk.BankKeeper.MintCoins(ctx, types.ModuleName, sample.Coins()) - require.NoError(t, err) - err = sdkk.BankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, addr, coins) - require.NoError(t, err) - - deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) + deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ + DeployWZeta: false, + DeployUniswapV2Router: true, + DeployUniswapV2Factory: true, + }) - // query - mockEVMKeeper.MockEVMFailCallOnce() - _, err = k.QueryWZetaBalanceOf(ctx, ethAddr) - require.ErrorIs(t, err, types.ErrContractCall) + _, err := k.GetWZetaContractAddress(ctx) + require.ErrorIs(t, err, types.ErrContractNotFound) } -func TestKeeper_QueryWZetaBalanceOfFails(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ - UseEVMMock: true, - }) - mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) +func TestKeeper_GetUniswapFactoryFailsIfNotSet(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - // mint tokens - - wzeta, factory, router, _, _ := deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) - var encodedAddress [32]byte - copy(encodedAddress[12:], router[:]) - addLiqMockReturn := &evmtypes.MsgEthereumTxResponse{ - Ret: make([]byte, 3*32), - } - mockEVMKeeper.MockEVMSuccessCallOnceWithReturn(addLiqMockReturn) + deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ + DeployWZeta: true, + DeployUniswapV2Router: true, + DeployUniswapV2Factory: false, + }) - // query - mockEVMKeeper.MockEVMFailCallOnce() - _, err := k.QueryWZetaBalanceOf(ctx, sample.EthAddress()) - require.ErrorIs(t, err, types.ErrContractCall) + _, err := k.GetUniswapV2FactoryAddress(ctx) + require.ErrorIs(t, err, types.ErrContractNotFound) } -func TestKeeper_QueryWZetaBalanceOfFailsToUnpack(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ - UseEVMMock: true, - }) - mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) +func TestKeeper_GetUniswapRouterFailsIfNotSet(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - // mint tokens - addr := sample.Bech32AccAddress() - ethAddr := common.BytesToAddress(addr.Bytes()) - coins := sample.Coins() - err := sdkk.BankKeeper.MintCoins(ctx, types.ModuleName, sample.Coins()) - require.NoError(t, err) - err = sdkk.BankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, addr, coins) - require.NoError(t, err) - - deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) + deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ + DeployWZeta: true, + DeployUniswapV2Router: false, + DeployUniswapV2Factory: true, + }) - // query - mockEVMKeeper.MockEVMSuccessCallOnce() - _, err = k.QueryWZetaBalanceOf(ctx, ethAddr) - require.ErrorIs(t, err, types.ErrABIUnpack) + _, err := k.GetUniswapV2Router02Address(ctx) + require.ErrorIs(t, err, types.ErrContractNotFound) } func TestKeeper_QuerySystemContractGasCoinZRC20(t *testing.T) { @@ -330,46 +191,6 @@ func TestKeeper_QuerySystemContractGasCoinZRC20(t *testing.T) { require.Equal(t, zrc20, found) } -func TestKeeper_QuerySystemContractGasCoinZRC20Fails(t *testing.T) { - k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ - UseEVMMock: true, - }) - mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - - chainID := getValidChainID(t) - - _, err := k.QuerySystemContractGasCoinZRC20(ctx, big.NewInt(chainID)) - require.Error(t, err) - require.ErrorIs(t, err, types.ErrStateVariableNotFound) - - deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) - - mockEVMKeeper.MockEVMFailCallOnce() - _, err = k.QuerySystemContractGasCoinZRC20(ctx, big.NewInt(chainID)) - require.ErrorIs(t, err, types.ErrContractCall) -} - -func TestKeeper_QuerySystemContractGasCoinZRC20FailsToUnpack(t *testing.T) { - k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ - UseEVMMock: true, - }) - mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - - chainID := getValidChainID(t) - - _, err := k.QuerySystemContractGasCoinZRC20(ctx, big.NewInt(chainID)) - require.Error(t, err) - require.ErrorIs(t, err, types.ErrStateVariableNotFound) - - deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) - - mockEVMKeeper.MockEVMSuccessCallOnce() - _, err = k.QuerySystemContractGasCoinZRC20(ctx, big.NewInt(chainID)) - require.ErrorIs(t, err, types.ErrABIUnpack) -} - func TestKeeper_CallUniswapV2RouterSwapExactETHForToken(t *testing.T) { k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) @@ -415,6 +236,36 @@ func TestKeeper_CallUniswapV2RouterSwapExactETHForTokenFails(t *testing.T) { require.ErrorIs(t, err, types.ErrContractCall) } +func TestKeeper_CallUniswapV2RouterSwapExactETHForTokenFailsIfWZetaContractNotSet(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ + DeployWZeta: false, + DeployUniswapV2Factory: true, + DeployUniswapV2Router: true, + }) + + _, err := k.CallUniswapV2RouterSwapExactETHForToken( + ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, big.NewInt(1), sample.EthAddress(), true) + require.ErrorIs(t, err, types.ErrContractNotFound) +} + +func TestKeeper_CallUniswapV2RouterSwapExactETHForTokenFailsIfRouterContractNotSet(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ + DeployWZeta: true, + DeployUniswapV2Factory: true, + DeployUniswapV2Router: false, + }) + + _, err := k.CallUniswapV2RouterSwapExactETHForToken( + ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, big.NewInt(1), sample.EthAddress(), true) + require.ErrorIs(t, err, types.ErrContractNotFound) +} + func TestKeeper_CallUniswapV2RouterSwapEthForExactToken(t *testing.T) { k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) @@ -461,6 +312,36 @@ func TestKeeper_CallUniswapV2RouterSwapEthForExactTokenFails(t *testing.T) { require.ErrorIs(t, err, types.ErrContractCall) } +func TestKeeper_CallUniswapV2RouterSwapEthForExactTokenFailsIfWZetaContractNotSet(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ + DeployWZeta: false, + DeployUniswapV2Factory: true, + DeployUniswapV2Router: true, + }) + + _, err := k.CallUniswapV2RouterSwapEthForExactToken( + ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, big.NewInt(1), big.NewInt(1), sample.EthAddress()) + require.ErrorIs(t, err, types.ErrContractNotFound) +} + +func TestKeeper_CallUniswapV2RouterSwapEthForExactTokenFailsIfRouterContractNotSet(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ + DeployWZeta: true, + DeployUniswapV2Factory: true, + DeployUniswapV2Router: false, + }) + + _, err := k.CallUniswapV2RouterSwapEthForExactToken( + ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, big.NewInt(1), big.NewInt(1), sample.EthAddress()) + require.ErrorIs(t, err, types.ErrContractNotFound) +} + func TestKeeper_CallUniswapV2RouterSwapExactTokensForETH(t *testing.T) { k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) @@ -498,6 +379,34 @@ func TestKeeper_CallUniswapV2RouterSwapExactTokensForETH(t *testing.T) { require.Equal(t, ethAmount, amounts[0]) } +func TestKeeper_CallUniswapV2RouterSwapExactTokensForETHFailsIfWZetaContractNotSet(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ + DeployWZeta: false, + DeployUniswapV2Factory: true, + DeployUniswapV2Router: true, + }) + _, err := k.CallUniswapV2RouterSwapExactTokensForETH( + ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, big.NewInt(1), sample.EthAddress(), true) + require.ErrorIs(t, err, types.ErrContractNotFound) +} + +func TestKeeper_CallUniswapV2RouterSwapExactTokensForETHFailsIfRouterContractNotSet(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ + DeployWZeta: true, + DeployUniswapV2Factory: true, + DeployUniswapV2Router: false, + }) + _, err := k.CallUniswapV2RouterSwapExactTokensForETH( + ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, big.NewInt(1), sample.EthAddress(), true) + require.ErrorIs(t, err, types.ErrContractNotFound) +} + func TestKeeper_CallUniswapV2RouterSwapExactTokensForETHFails(t *testing.T) { k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) @@ -561,6 +470,48 @@ func TestKeeper_CallUniswapV2RouterSwapExactTokensForTokens(t *testing.T) { require.Equal(t, amounts[2], tokenAmount) } +func TestKeeper_CallUniswapV2RouterSwapExactTokensForTokensFailsIfRouterContractNotSet(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + // fail if no system contract + _, err := k.CallUniswapV2RouterSwapExactTokensForTokens( + ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, big.NewInt(1), sample.EthAddress(), sample.EthAddress(), true) + require.Error(t, err) + + // deploy system contracts except router + deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ + DeployUniswapV2Router: false, + DeployWZeta: true, + DeployUniswapV2Factory: true, + }) + + _, err = k.CallUniswapV2RouterSwapExactTokensForTokens( + ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, big.NewInt(1), sample.EthAddress(), sample.EthAddress(), true) + require.ErrorIs(t, err, types.ErrContractNotFound) +} + +func TestKeeper_CallUniswapV2RouterSwapExactTokensForTokensFailsIfWzetaContractNotSet(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + // fail if no system contract + _, err := k.CallUniswapV2RouterSwapExactTokensForTokens( + ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, big.NewInt(1), sample.EthAddress(), sample.EthAddress(), true) + require.Error(t, err) + + // deploy system contracts except router + deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ + DeployUniswapV2Router: true, + DeployWZeta: false, + DeployUniswapV2Factory: true, + }) + + _, err = k.CallUniswapV2RouterSwapExactTokensForTokens( + ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, big.NewInt(1), sample.EthAddress(), sample.EthAddress(), true) + require.ErrorIs(t, err, types.ErrContractNotFound) +} + func TestKeeper_CallUniswapV2RouterSwapExactTokensForTokensFails(t *testing.T) { k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) @@ -583,6 +534,90 @@ func TestKeeper_CallUniswapV2RouterSwapExactTokensForTokensFails(t *testing.T) { require.ErrorIs(t, err, types.ErrContractCall) } +func TestKeeper_QueryUniswapV2RouterGetZRC4AmountsInFailsIfWZetaContractNotSet(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ + DeployWZeta: false, + DeployUniswapV2Factory: true, + DeployUniswapV2Router: true, + }) + + _, err := k.QueryUniswapV2RouterGetZRC4AmountsIn(ctx, big.NewInt(1), sample.EthAddress()) + require.ErrorIs(t, err, types.ErrContractNotFound) +} + +func TestKeeper_QueryUniswapV2RouterGetZRC4AmountsInFailsIfRouterContractNotSet(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ + DeployWZeta: true, + DeployUniswapV2Factory: true, + DeployUniswapV2Router: false, + }) + + _, err := k.QueryUniswapV2RouterGetZRC4AmountsIn(ctx, big.NewInt(1), sample.EthAddress()) + require.ErrorIs(t, err, types.ErrContractNotFound) +} + +func TestKeeper_QueryUniswapV2RouterGetZetaAmountsInFailsIfWZetaContractNotSet(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ + DeployWZeta: false, + DeployUniswapV2Factory: true, + DeployUniswapV2Router: true, + }) + + _, err := k.QueryUniswapV2RouterGetZetaAmountsIn(ctx, big.NewInt(1), sample.EthAddress()) + require.ErrorIs(t, err, types.ErrContractNotFound) +} + +func TestKeeper_QueryUniswapV2RouterGetZetaAmountsInFailsIfRouterContractNotSet(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ + DeployWZeta: true, + DeployUniswapV2Factory: true, + DeployUniswapV2Router: false, + }) + + _, err := k.QueryUniswapV2RouterGetZetaAmountsIn(ctx, big.NewInt(1), sample.EthAddress()) + require.ErrorIs(t, err, types.ErrContractNotFound) +} + +func TestKeeper_QueryUniswapV2RouterGetZRC4ToZRC4AmountsInFailsIfWZetaContractNotSet(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ + DeployWZeta: false, + DeployUniswapV2Factory: true, + DeployUniswapV2Router: true, + }) + + _, err := k.QueryUniswapV2RouterGetZRC4ToZRC4AmountsIn(ctx, big.NewInt(1), sample.EthAddress(), sample.EthAddress()) + require.ErrorIs(t, err, types.ErrContractNotFound) +} + +func TestKeeper_QueryUniswapV2RouterGetZRC4ToZRC4AmountsInFailsIfRouterContractNotSet(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ + DeployWZeta: true, + DeployUniswapV2Factory: true, + DeployUniswapV2Router: false, + }) + + _, err := k.QueryUniswapV2RouterGetZRC4ToZRC4AmountsIn(ctx, big.NewInt(1), sample.EthAddress(), sample.EthAddress()) + require.ErrorIs(t, err, types.ErrContractNotFound) +} + func TestKeeper_CallZRC20BurnFails(t *testing.T) { k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ UseEVMMock: true, From 7ded44638d363f98e6e66ab4981fdda6394c6140 Mon Sep 17 00:00:00 2001 From: skosito Date: Tue, 20 Feb 2024 11:26:07 +0100 Subject: [PATCH 12/18] Add more tests --- x/crosschain/keeper/utils_test.go | 2 +- x/fungible/keeper/evm_test.go | 3 +- x/fungible/keeper/gas_coin_and_pool_test.go | 2 +- x/fungible/keeper/system_contract.go | 4 +- x/fungible/keeper/system_contract_test.go | 179 ++++++++++++++++++-- 5 files changed, 172 insertions(+), 18 deletions(-) diff --git a/x/crosschain/keeper/utils_test.go b/x/crosschain/keeper/utils_test.go index 253e20dbb6..aed660b70b 100644 --- a/x/crosschain/keeper/utils_test.go +++ b/x/crosschain/keeper/utils_test.go @@ -175,7 +175,7 @@ func setupZRC20Pool( ) require.NoError(t, err) - // approve the router to spend the zeta + // approve the router to spend the zrc20 err = k.CallZRC20Approve( ctx, types.ModuleAddressEVM, diff --git a/x/fungible/keeper/evm_test.go b/x/fungible/keeper/evm_test.go index e698f2a01c..e1af5c041c 100644 --- a/x/fungible/keeper/evm_test.go +++ b/x/fungible/keeper/evm_test.go @@ -92,7 +92,8 @@ type SystemContractDeployConfig struct { DeployUniswapV2Router bool } -// deploySystemContracts deploys the system contracts and returns their addresses. +// deploySystemContractsConfigurable deploys the system contracts and returns their addresses +// while having a possibility to skip some deployments to test different scenarios func deploySystemContractsConfigurable( t *testing.T, ctx sdk.Context, diff --git a/x/fungible/keeper/gas_coin_and_pool_test.go b/x/fungible/keeper/gas_coin_and_pool_test.go index a422183a31..9935f11ee6 100644 --- a/x/fungible/keeper/gas_coin_and_pool_test.go +++ b/x/fungible/keeper/gas_coin_and_pool_test.go @@ -91,7 +91,7 @@ func setupZRC20Pool( ) require.NoError(t, err) - // approve the router to spend the zeta + // approve the router to spend the zrc20 err = k.CallZRC20Approve( ctx, types.ModuleAddressEVM, diff --git a/x/fungible/keeper/system_contract.go b/x/fungible/keeper/system_contract.go index f93138a973..65f4a4c169 100644 --- a/x/fungible/keeper/system_contract.go +++ b/x/fungible/keeper/system_contract.go @@ -79,7 +79,6 @@ func (k *Keeper) GetWZetaContractAddress(ctx sdk.Context) (ethcommon.Address, er ) if err != nil { return ethcommon.Address{}, cosmoserrors.Wrapf(types.ErrContractCall, "failed to call wZetaContractAddress (%s)", err.Error()) - } type AddressResponse struct { Value ethcommon.Address @@ -278,6 +277,9 @@ func (k *Keeper) QuerySystemContractGasCoinZRC20(ctx sdk.Context, chainid *big.I if err := sysABI.UnpackIntoInterface(&zrc20Res, "gasCoinZRC20ByChainId", res.Ret); err != nil { return ethcommon.Address{}, cosmoserrors.Wrapf(types.ErrABIUnpack, "failed to unpack gasCoinZRC20ByChainId: %s", err.Error()) } + if zrc20Res.Value == ethcommon.HexToAddress("0x0") { + return ethcommon.Address{}, sdkerrors.Wrapf(types.ErrContractNotFound, "gas coin contract invalid address") + } return zrc20Res.Value, nil } diff --git a/x/fungible/keeper/system_contract_test.go b/x/fungible/keeper/system_contract_test.go index 90550a2051..f3b538cb92 100644 --- a/x/fungible/keeper/system_contract_test.go +++ b/x/fungible/keeper/system_contract_test.go @@ -53,20 +53,6 @@ func TestKeeper_GetWZetaContractAddress(t *testing.T) { require.Equal(t, wzeta, found) } -func TestKeeper_GetWZetaContractAddressFails(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - - _, err := k.GetWZetaContractAddress(ctx) - require.Error(t, err) - require.ErrorIs(t, err, types.ErrStateVariableNotFound) - - wzeta, _, _, _, _ := deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) - found, err := k.GetWZetaContractAddress(ctx) - require.NoError(t, err) - require.Equal(t, wzeta, found) -} - func TestKeeper_GetUniswapV2FactoryAddress(t *testing.T) { k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) @@ -146,6 +132,36 @@ func TestKeeper_GetWZetaFailsIfNotSet(t *testing.T) { require.ErrorIs(t, err, types.ErrContractNotFound) } +func TestKeeper_GetWZetaFails(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) + + mockEVMKeeper.MockEVMFailCallOnce() + + _, err := k.GetWZetaContractAddress(ctx) + require.ErrorIs(t, err, types.ErrContractCall) +} + +func TestKeeper_GetWZetaFailsToUnpack(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) + + mockEVMKeeper.MockEVMSuccessCallOnce() + + _, err := k.GetWZetaContractAddress(ctx) + require.ErrorIs(t, err, types.ErrABIUnpack) +} + func TestKeeper_GetUniswapFactoryFailsIfNotSet(t *testing.T) { k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) @@ -160,6 +176,36 @@ func TestKeeper_GetUniswapFactoryFailsIfNotSet(t *testing.T) { require.ErrorIs(t, err, types.ErrContractNotFound) } +func TestKeeper_GetUniswapFactoryFails(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) + + mockEVMKeeper.MockEVMFailCallOnce() + + _, err := k.GetUniswapV2FactoryAddress(ctx) + require.ErrorIs(t, err, types.ErrContractCall) +} + +func TestKeeper_TestKeeper_GetUniswapFactoryFailsToUnpack(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) + + mockEVMKeeper.MockEVMSuccessCallOnce() + + _, err := k.GetUniswapV2FactoryAddress(ctx) + require.ErrorIs(t, err, types.ErrABIUnpack) +} + func TestKeeper_GetUniswapRouterFailsIfNotSet(t *testing.T) { k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) @@ -174,6 +220,36 @@ func TestKeeper_GetUniswapRouterFailsIfNotSet(t *testing.T) { require.ErrorIs(t, err, types.ErrContractNotFound) } +func TestKeeper_GetUniswapRouterFails(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) + + mockEVMKeeper.MockEVMFailCallOnce() + + _, err := k.GetUniswapV2Router02Address(ctx) + require.ErrorIs(t, err, types.ErrContractCall) +} + +func TestKeeper_TestKeeper_TestKeeper_GetUniswapRouterFailsToUnpack(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) + + mockEVMKeeper.MockEVMSuccessCallOnce() + + _, err := k.GetUniswapV2Router02Address(ctx) + require.ErrorIs(t, err, types.ErrABIUnpack) +} + func TestKeeper_QuerySystemContractGasCoinZRC20(t *testing.T) { k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) @@ -191,6 +267,51 @@ func TestKeeper_QuerySystemContractGasCoinZRC20(t *testing.T) { require.Equal(t, zrc20, found) } +func TestKeeper_QuerySystemContractGasCoinZRC20FailsIfContractNotSet(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + chainID := getValidChainID(t) + + _, err := k.QuerySystemContractGasCoinZRC20(ctx, big.NewInt(chainID)) + require.Error(t, err) + require.ErrorIs(t, err, types.ErrStateVariableNotFound) + + deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) + + _, err = k.QuerySystemContractGasCoinZRC20(ctx, big.NewInt(chainID)) + require.ErrorIs(t, err, types.ErrContractNotFound) +} + +func TestKeeper_QuerySystemContractGasCoinZRC20Fails(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) + + mockEVMKeeper.MockEVMFailCallOnce() + + _, err := k.QuerySystemContractGasCoinZRC20(ctx, big.NewInt(1)) + require.ErrorIs(t, err, types.ErrContractCall) +} + +func TestKeeper_QuerySystemContractGasCoinZRC20FailsToUnpack(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) + + mockEVMKeeper.MockEVMSuccessCallOnce() + + _, err := k.QuerySystemContractGasCoinZRC20(ctx, big.NewInt(1)) + require.ErrorIs(t, err, types.ErrABIUnpack) +} + func TestKeeper_CallUniswapV2RouterSwapExactETHForToken(t *testing.T) { k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) @@ -534,6 +655,16 @@ func TestKeeper_CallUniswapV2RouterSwapExactTokensForTokensFails(t *testing.T) { require.ErrorIs(t, err, types.ErrContractCall) } +func TestKeeper_QueryUniswapV2RouterGetZRC4AmountsInFails(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) + + _, err := k.QueryUniswapV2RouterGetZRC4AmountsIn(ctx, big.NewInt(1), sample.EthAddress()) + require.ErrorIs(t, err, types.ErrContractCall) +} + func TestKeeper_QueryUniswapV2RouterGetZRC4AmountsInFailsIfWZetaContractNotSet(t *testing.T) { k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) @@ -562,6 +693,16 @@ func TestKeeper_QueryUniswapV2RouterGetZRC4AmountsInFailsIfRouterContractNotSet( require.ErrorIs(t, err, types.ErrContractNotFound) } +func TestKeeper_QueryUniswapV2RouterGetZetaAmountsInFails(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) + + _, err := k.QueryUniswapV2RouterGetZetaAmountsIn(ctx, big.NewInt(1), sample.EthAddress()) + require.ErrorIs(t, err, types.ErrContractCall) +} + func TestKeeper_QueryUniswapV2RouterGetZetaAmountsInFailsIfWZetaContractNotSet(t *testing.T) { k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) @@ -590,6 +731,16 @@ func TestKeeper_QueryUniswapV2RouterGetZetaAmountsInFailsIfRouterContractNotSet( require.ErrorIs(t, err, types.ErrContractNotFound) } +func TestKeeper_QueryUniswapV2RouterGetZRC4ToZRC4AmountsInFails(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) + + _, err := k.QueryUniswapV2RouterGetZRC4ToZRC4AmountsIn(ctx, big.NewInt(1), sample.EthAddress(), sample.EthAddress()) + require.ErrorIs(t, err, types.ErrContractCall) +} + func TestKeeper_QueryUniswapV2RouterGetZRC4ToZRC4AmountsInFailsIfWZetaContractNotSet(t *testing.T) { k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) From 2107ac82940c64e2ff024385fe4e5ab01895ab23 Mon Sep 17 00:00:00 2001 From: skosito Date: Tue, 20 Feb 2024 11:37:21 +0100 Subject: [PATCH 13/18] Add changelog entry --- changelog.md | 1 + 1 file changed, 1 insertion(+) diff --git a/changelog.md b/changelog.md index 45b7888344..373aef1ac2 100644 --- a/changelog.md +++ b/changelog.md @@ -41,6 +41,7 @@ * [1584](https://github.com/zeta-chain/node/pull/1584) - allow to run E2E tests on any networks * [1753](https://github.com/zeta-chain/node/pull/1753) - fix gosec errors on usage of rand package * [1762](https://github.com/zeta-chain/node/pull/1762) - improve coverage for fungibile module +* [1782](https://github.com/zeta-chain/node/pull/1782) - improve coverage for fungibile module system contract ### CI From 760dbd96e1d05a38acce45ef76189fb4a88d0813 Mon Sep 17 00:00:00 2001 From: skosito Date: Tue, 20 Feb 2024 17:59:41 +0100 Subject: [PATCH 14/18] PR comments formatting fixes --- x/fungible/keeper/system_contract_test.go | 152 +++++++++++++++++++--- 1 file changed, 132 insertions(+), 20 deletions(-) diff --git a/x/fungible/keeper/system_contract_test.go b/x/fungible/keeper/system_contract_test.go index f3b538cb92..9d218568ff 100644 --- a/x/fungible/keeper/system_contract_test.go +++ b/x/fungible/keeper/system_contract_test.go @@ -115,7 +115,7 @@ func TestKeeper_QueryWZetaBalanceOfFails(t *testing.T) { // fail if no system contract _, err := k.QueryWZetaBalanceOf(ctx, sample.EthAddress()) - require.Error(t, err) + require.ErrorIs(t, err, types.ErrStateVariableNotFound) } func TestKeeper_GetWZetaFailsIfNotSet(t *testing.T) { @@ -235,7 +235,7 @@ func TestKeeper_GetUniswapRouterFails(t *testing.T) { require.ErrorIs(t, err, types.ErrContractCall) } -func TestKeeper_TestKeeper_TestKeeper_GetUniswapRouterFailsToUnpack(t *testing.T) { +func TestKeeper_GetUniswapRouterFailsToUnpack(t *testing.T) { k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ UseEVMMock: true, }) @@ -319,7 +319,13 @@ func TestKeeper_CallUniswapV2RouterSwapExactETHForToken(t *testing.T) { // fail if no system contract _, err := k.CallUniswapV2RouterSwapExactETHForToken( - ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, big.NewInt(1), sample.EthAddress(), true) + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + big.NewInt(1), + sample.EthAddress(), + true, + ) require.Error(t, err) // deploy system contracts and swap exact eth for 1 token @@ -333,7 +339,13 @@ func TestKeeper_CallUniswapV2RouterSwapExactETHForToken(t *testing.T) { require.NoError(t, err) amounts, err := k.CallUniswapV2RouterSwapExactETHForToken( - ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, amountToSwap, zrc20, true) + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + amountToSwap, + zrc20, + true, + ) require.NoError(t, err) require.Equal(t, 2, len(amounts)) @@ -353,7 +365,13 @@ func TestKeeper_CallUniswapV2RouterSwapExactETHForTokenFails(t *testing.T) { require.NoError(t, err) _, err = k.CallUniswapV2RouterSwapExactETHForToken( - ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, amountToSwap, zrc20, true) + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + amountToSwap, + zrc20, + true, + ) require.ErrorIs(t, err, types.ErrContractCall) } @@ -368,7 +386,13 @@ func TestKeeper_CallUniswapV2RouterSwapExactETHForTokenFailsIfWZetaContractNotSe }) _, err := k.CallUniswapV2RouterSwapExactETHForToken( - ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, big.NewInt(1), sample.EthAddress(), true) + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + big.NewInt(1), + sample.EthAddress(), + true, + ) require.ErrorIs(t, err, types.ErrContractNotFound) } @@ -383,7 +407,13 @@ func TestKeeper_CallUniswapV2RouterSwapExactETHForTokenFailsIfRouterContractNotS }) _, err := k.CallUniswapV2RouterSwapExactETHForToken( - ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, big.NewInt(1), sample.EthAddress(), true) + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + big.NewInt(1), + sample.EthAddress(), + true, + ) require.ErrorIs(t, err, types.ErrContractNotFound) } @@ -408,7 +438,13 @@ func TestKeeper_CallUniswapV2RouterSwapEthForExactToken(t *testing.T) { require.NoError(t, err) amounts, err := k.CallUniswapV2RouterSwapEthForExactToken( - ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, amountToSwap, tokenAmount, zrc20) + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + amountToSwap, + tokenAmount, + zrc20, + ) require.NoError(t, err) require.Equal(t, 2, len(amounts)) @@ -429,7 +465,13 @@ func TestKeeper_CallUniswapV2RouterSwapEthForExactTokenFails(t *testing.T) { require.NoError(t, err) _, err = k.CallUniswapV2RouterSwapEthForExactToken( - ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, amountToSwap, tokenAmount, zrc20) + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + amountToSwap, + tokenAmount, + zrc20, + ) require.ErrorIs(t, err, types.ErrContractCall) } @@ -444,7 +486,13 @@ func TestKeeper_CallUniswapV2RouterSwapEthForExactTokenFailsIfWZetaContractNotSe }) _, err := k.CallUniswapV2RouterSwapEthForExactToken( - ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, big.NewInt(1), big.NewInt(1), sample.EthAddress()) + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + big.NewInt(1), + big.NewInt(1), + sample.EthAddress(), + ) require.ErrorIs(t, err, types.ErrContractNotFound) } @@ -459,7 +507,13 @@ func TestKeeper_CallUniswapV2RouterSwapEthForExactTokenFailsIfRouterContractNotS }) _, err := k.CallUniswapV2RouterSwapEthForExactToken( - ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, big.NewInt(1), big.NewInt(1), sample.EthAddress()) + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + big.NewInt(1), + big.NewInt(1), + sample.EthAddress(), + ) require.ErrorIs(t, err, types.ErrContractNotFound) } @@ -470,7 +524,13 @@ func TestKeeper_CallUniswapV2RouterSwapExactTokensForETH(t *testing.T) { // fail if no system contract _, err := k.CallUniswapV2RouterSwapExactTokensForETH( - ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, big.NewInt(1), sample.EthAddress(), true) + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + big.NewInt(1), + sample.EthAddress(), + true, + ) require.Error(t, err) // deploy system contracts and swap exact eth for 1 token @@ -493,7 +553,13 @@ func TestKeeper_CallUniswapV2RouterSwapExactTokensForETH(t *testing.T) { ) amounts, err := k.CallUniswapV2RouterSwapExactTokensForETH( - ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, amountToSwap, zrc20, true) + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + amountToSwap, + zrc20, + true, + ) require.NoError(t, err) require.Equal(t, 2, len(amounts)) @@ -510,7 +576,13 @@ func TestKeeper_CallUniswapV2RouterSwapExactTokensForETHFailsIfWZetaContractNotS DeployUniswapV2Router: true, }) _, err := k.CallUniswapV2RouterSwapExactTokensForETH( - ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, big.NewInt(1), sample.EthAddress(), true) + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + big.NewInt(1), + sample.EthAddress(), + true, + ) require.ErrorIs(t, err, types.ErrContractNotFound) } @@ -524,7 +596,13 @@ func TestKeeper_CallUniswapV2RouterSwapExactTokensForETHFailsIfRouterContractNot DeployUniswapV2Router: false, }) _, err := k.CallUniswapV2RouterSwapExactTokensForETH( - ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, big.NewInt(1), sample.EthAddress(), true) + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + big.NewInt(1), + sample.EthAddress(), + true, + ) require.ErrorIs(t, err, types.ErrContractNotFound) } @@ -535,7 +613,13 @@ func TestKeeper_CallUniswapV2RouterSwapExactTokensForETHFails(t *testing.T) { // fail if no system contract _, err := k.CallUniswapV2RouterSwapExactTokensForETH( - ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, big.NewInt(1), sample.EthAddress(), true) + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + big.NewInt(1), + sample.EthAddress(), + true, + ) require.Error(t, err) // deploy system contracts and swap fails because of missing balance @@ -558,7 +642,14 @@ func TestKeeper_CallUniswapV2RouterSwapExactTokensForTokens(t *testing.T) { // fail if no system contract _, err := k.CallUniswapV2RouterSwapExactTokensForTokens( - ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, big.NewInt(1), sample.EthAddress(), sample.EthAddress(), true) + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + big.NewInt(1), + sample.EthAddress(), + sample.EthAddress(), + true, + ) require.Error(t, err) // deploy system contracts and swap exact token for 1 token @@ -608,7 +699,14 @@ func TestKeeper_CallUniswapV2RouterSwapExactTokensForTokensFailsIfRouterContract }) _, err = k.CallUniswapV2RouterSwapExactTokensForTokens( - ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, big.NewInt(1), sample.EthAddress(), sample.EthAddress(), true) + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + big.NewInt(1), + sample.EthAddress(), + sample.EthAddress(), + true, + ) require.ErrorIs(t, err, types.ErrContractNotFound) } @@ -629,7 +727,14 @@ func TestKeeper_CallUniswapV2RouterSwapExactTokensForTokensFailsIfWzetaContractN }) _, err = k.CallUniswapV2RouterSwapExactTokensForTokens( - ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, big.NewInt(1), sample.EthAddress(), sample.EthAddress(), true) + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + big.NewInt(1), + sample.EthAddress(), + sample.EthAddress(), + true, + ) require.ErrorIs(t, err, types.ErrContractNotFound) } @@ -651,7 +756,14 @@ func TestKeeper_CallUniswapV2RouterSwapExactTokensForTokensFails(t *testing.T) { require.NoError(t, err) _, err = k.CallUniswapV2RouterSwapExactTokensForTokens( - ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, amountToSwap, inzrc20, outzrc20, true) + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + amountToSwap, + inzrc20, + outzrc20, + true, + ) require.ErrorIs(t, err, types.ErrContractCall) } From 36860b8981dff5b2f7f907b5c165062ab721ce71 Mon Sep 17 00:00:00 2001 From: skosito Date: Tue, 20 Feb 2024 19:06:38 +0100 Subject: [PATCH 15/18] Introduce subtests --- x/fungible/keeper/system_contract_test.go | 1640 +++++++++++---------- 1 file changed, 882 insertions(+), 758 deletions(-) diff --git a/x/fungible/keeper/system_contract_test.go b/x/fungible/keeper/system_contract_test.go index 9d218568ff..10f7908807 100644 --- a/x/fungible/keeper/system_contract_test.go +++ b/x/fungible/keeper/system_contract_test.go @@ -13,912 +13,1036 @@ import ( ) func TestKeeper_GetSystemContract(t *testing.T) { - k, ctx, _, _ := keepertest.FungibleKeeper(t) - k.SetSystemContract(ctx, types.SystemContract{SystemContract: "test"}) - val, found := k.GetSystemContract(ctx) - require.True(t, found) - require.Equal(t, types.SystemContract{SystemContract: "test"}, val) - - // can remove contract - k.RemoveSystemContract(ctx) - _, found = k.GetSystemContract(ctx) - require.False(t, found) + t.Run("should get and remove system contract", func(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeper(t) + k.SetSystemContract(ctx, types.SystemContract{SystemContract: "test"}) + val, found := k.GetSystemContract(ctx) + require.True(t, found) + require.Equal(t, types.SystemContract{SystemContract: "test"}, val) + + // can remove contract + k.RemoveSystemContract(ctx) + _, found = k.GetSystemContract(ctx) + require.False(t, found) + }) } func TestKeeper_GetSystemContractAddress(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + t.Run("should fail to get system contract address if system contracts are not deployed", func(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + _, err := k.GetSystemContractAddress(ctx) + require.Error(t, err) + require.ErrorIs(t, err, types.ErrStateVariableNotFound) + }) - _, err := k.GetSystemContractAddress(ctx) - require.Error(t, err) - require.ErrorIs(t, err, types.ErrStateVariableNotFound) + t.Run("should get system contract address if system contracts are deployed", func(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - _, _, _, _, systemContract := deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) - found, err := k.GetSystemContractAddress(ctx) - require.NoError(t, err) - require.Equal(t, systemContract, found) + _, _, _, _, systemContract := deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) + found, err := k.GetSystemContractAddress(ctx) + require.NoError(t, err) + require.Equal(t, systemContract, found) + }) } func TestKeeper_GetWZetaContractAddress(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + t.Run("should fail to get wzeta contract address if system contracts are not deployed", func(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - _, err := k.GetWZetaContractAddress(ctx) - require.Error(t, err) - require.ErrorIs(t, err, types.ErrStateVariableNotFound) + _, err := k.GetWZetaContractAddress(ctx) + require.Error(t, err) + require.ErrorIs(t, err, types.ErrStateVariableNotFound) + }) - wzeta, _, _, _, _ := deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) - found, err := k.GetWZetaContractAddress(ctx) - require.NoError(t, err) - require.Equal(t, wzeta, found) -} + t.Run("should get wzeta contract address if system contracts are deployed", func(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) -func TestKeeper_GetUniswapV2FactoryAddress(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + wzeta, _, _, _, _ := deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) + found, err := k.GetWZetaContractAddress(ctx) + require.NoError(t, err) + require.Equal(t, wzeta, found) + }) - _, err := k.GetUniswapV2FactoryAddress(ctx) - require.Error(t, err) - require.ErrorIs(t, err, types.ErrStateVariableNotFound) + t.Run("should fail if wzeta not deployed", func(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - _, factory, _, _, _ := deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) - found, err := k.GetUniswapV2FactoryAddress(ctx) - require.NoError(t, err) - require.Equal(t, factory, found) -} + deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ + DeployWZeta: false, + DeployUniswapV2Router: true, + DeployUniswapV2Factory: true, + }) -func TestKeeper_GetUniswapV2Router02Address(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + _, err := k.GetWZetaContractAddress(ctx) + require.ErrorIs(t, err, types.ErrContractNotFound) + }) - _, err := k.GetUniswapV2Router02Address(ctx) - require.Error(t, err) - require.ErrorIs(t, err, types.ErrStateVariableNotFound) + t.Run("should fail if evm call fails", func(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - _, _, router, _, _ := deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) - found, err := k.GetUniswapV2Router02Address(ctx) - require.NoError(t, err) - require.Equal(t, router, found) -} + deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) -func TestKeeper_CallWZetaDeposit(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - - // mint tokens - addr := sample.Bech32AccAddress() - ethAddr := common.BytesToAddress(addr.Bytes()) - coins := sample.Coins() - err := sdkk.BankKeeper.MintCoins(ctx, types.ModuleName, sample.Coins()) - require.NoError(t, err) - err = sdkk.BankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, addr, coins) - require.NoError(t, err) - - // fail if no system contract - err = k.CallWZetaDeposit(ctx, ethAddr, big.NewInt(42)) - require.Error(t, err) - - deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) - - // deposit - err = k.CallWZetaDeposit(ctx, ethAddr, big.NewInt(42)) - require.NoError(t, err) - - balance, err := k.QueryWZetaBalanceOf(ctx, ethAddr) - require.NoError(t, err) - require.Equal(t, big.NewInt(42), balance) -} + mockEVMKeeper.MockEVMFailCallOnce() -func TestKeeper_QueryWZetaBalanceOfFails(t *testing.T) { - k, ctx, _, _ := keepertest.FungibleKeeper(t) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + _, err := k.GetWZetaContractAddress(ctx) + require.ErrorIs(t, err, types.ErrContractCall) + }) + + t.Run("should fail if abi unpack fails", func(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) + + mockEVMKeeper.MockEVMSuccessCallOnce() - // fail if no system contract - _, err := k.QueryWZetaBalanceOf(ctx, sample.EthAddress()) - require.ErrorIs(t, err, types.ErrStateVariableNotFound) + _, err := k.GetWZetaContractAddress(ctx) + require.ErrorIs(t, err, types.ErrABIUnpack) + }) } -func TestKeeper_GetWZetaFailsIfNotSet(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) +func TestKeeper_GetUniswapV2FactoryAddress(t *testing.T) { + t.Run("should fail to get uniswapfactory contract address if system contracts are not deployed", func(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ - DeployWZeta: false, - DeployUniswapV2Router: true, - DeployUniswapV2Factory: true, + _, err := k.GetUniswapV2FactoryAddress(ctx) + require.Error(t, err) + require.ErrorIs(t, err, types.ErrStateVariableNotFound) }) - _, err := k.GetWZetaContractAddress(ctx) - require.ErrorIs(t, err, types.ErrContractNotFound) -} + t.Run("should get uniswapfactory contract address if system contracts are deployed", func(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) -func TestKeeper_GetWZetaFails(t *testing.T) { - k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ - UseEVMMock: true, + _, factory, _, _, _ := deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) + found, err := k.GetUniswapV2FactoryAddress(ctx) + require.NoError(t, err) + require.Equal(t, factory, found) }) - mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) + t.Run("should fail in factory not deployed", func(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - mockEVMKeeper.MockEVMFailCallOnce() + deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ + DeployWZeta: true, + DeployUniswapV2Router: true, + DeployUniswapV2Factory: false, + }) - _, err := k.GetWZetaContractAddress(ctx) - require.ErrorIs(t, err, types.ErrContractCall) -} + _, err := k.GetUniswapV2FactoryAddress(ctx) + require.ErrorIs(t, err, types.ErrContractNotFound) + }) + + t.Run("should fail if evm call fails", func(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) -func TestKeeper_GetWZetaFailsToUnpack(t *testing.T) { - k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ - UseEVMMock: true, + mockEVMKeeper.MockEVMFailCallOnce() + + _, err := k.GetUniswapV2FactoryAddress(ctx) + require.ErrorIs(t, err, types.ErrContractCall) }) - mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) + t.Run("should fail if abi unpack fails", func(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) - mockEVMKeeper.MockEVMSuccessCallOnce() + mockEVMKeeper.MockEVMSuccessCallOnce() - _, err := k.GetWZetaContractAddress(ctx) - require.ErrorIs(t, err, types.ErrABIUnpack) + _, err := k.GetUniswapV2FactoryAddress(ctx) + require.ErrorIs(t, err, types.ErrABIUnpack) + }) } -func TestKeeper_GetUniswapFactoryFailsIfNotSet(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) +func TestKeeper_GetUniswapV2Router02Address(t *testing.T) { + t.Run("should fail to get uniswaprouter contract address if system contracts are not deployed", func(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ - DeployWZeta: true, - DeployUniswapV2Router: true, - DeployUniswapV2Factory: false, + _, err := k.GetUniswapV2Router02Address(ctx) + require.Error(t, err) + require.ErrorIs(t, err, types.ErrStateVariableNotFound) }) - _, err := k.GetUniswapV2FactoryAddress(ctx) - require.ErrorIs(t, err, types.ErrContractNotFound) -} + t.Run("should get uniswaprouter contract address if system contracts are deployed", func(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) -func TestKeeper_GetUniswapFactoryFails(t *testing.T) { - k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ - UseEVMMock: true, + _, _, router, _, _ := deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) + found, err := k.GetUniswapV2Router02Address(ctx) + require.NoError(t, err) + require.Equal(t, router, found) }) - mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) + t.Run("should fail in router not deployed", func(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - mockEVMKeeper.MockEVMFailCallOnce() - - _, err := k.GetUniswapV2FactoryAddress(ctx) - require.ErrorIs(t, err, types.ErrContractCall) -} + deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ + DeployWZeta: true, + DeployUniswapV2Router: false, + DeployUniswapV2Factory: true, + }) -func TestKeeper_TestKeeper_GetUniswapFactoryFailsToUnpack(t *testing.T) { - k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ - UseEVMMock: true, + _, err := k.GetUniswapV2Router02Address(ctx) + require.ErrorIs(t, err, types.ErrContractNotFound) }) - mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) + t.Run("should fail if evm call fails", func(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - mockEVMKeeper.MockEVMSuccessCallOnce() + deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) - _, err := k.GetUniswapV2FactoryAddress(ctx) - require.ErrorIs(t, err, types.ErrABIUnpack) -} - -func TestKeeper_GetUniswapRouterFailsIfNotSet(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + mockEVMKeeper.MockEVMFailCallOnce() - deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ - DeployWZeta: true, - DeployUniswapV2Router: false, - DeployUniswapV2Factory: true, + _, err := k.GetUniswapV2Router02Address(ctx) + require.ErrorIs(t, err, types.ErrContractCall) }) - _, err := k.GetUniswapV2Router02Address(ctx) - require.ErrorIs(t, err, types.ErrContractNotFound) + t.Run("should fail if abi unpack fails", func(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) + + mockEVMKeeper.MockEVMSuccessCallOnce() + + _, err := k.GetUniswapV2Router02Address(ctx) + require.ErrorIs(t, err, types.ErrABIUnpack) + }) } -func TestKeeper_GetUniswapRouterFails(t *testing.T) { - k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ - UseEVMMock: true, +func TestKeeper_CallWZetaDeposit(t *testing.T) { + t.Run("should fail to deposit if system contracts are not deployed", func(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + // mint tokens + addr := sample.Bech32AccAddress() + ethAddr := common.BytesToAddress(addr.Bytes()) + coins := sample.Coins() + err := sdkk.BankKeeper.MintCoins(ctx, types.ModuleName, sample.Coins()) + require.NoError(t, err) + err = sdkk.BankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, addr, coins) + require.NoError(t, err) + + // fail if no system contract + err = k.CallWZetaDeposit(ctx, ethAddr, big.NewInt(42)) + require.Error(t, err) }) - mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) + t.Run("should deposit if system contracts are deployed", func(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - mockEVMKeeper.MockEVMFailCallOnce() + // mint tokens + addr := sample.Bech32AccAddress() + ethAddr := common.BytesToAddress(addr.Bytes()) + coins := sample.Coins() + err := sdkk.BankKeeper.MintCoins(ctx, types.ModuleName, sample.Coins()) + require.NoError(t, err) + err = sdkk.BankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, addr, coins) + require.NoError(t, err) - _, err := k.GetUniswapV2Router02Address(ctx) - require.ErrorIs(t, err, types.ErrContractCall) -} + deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) -func TestKeeper_GetUniswapRouterFailsToUnpack(t *testing.T) { - k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ - UseEVMMock: true, - }) - mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + // deposit + err = k.CallWZetaDeposit(ctx, ethAddr, big.NewInt(42)) + require.NoError(t, err) - deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) + balance, err := k.QueryWZetaBalanceOf(ctx, ethAddr) + require.NoError(t, err) + require.Equal(t, big.NewInt(42), balance) + }) +} - mockEVMKeeper.MockEVMSuccessCallOnce() +func TestKeeper_QueryWZetaBalanceOf(t *testing.T) { + t.Run("should fail if system contracts are not deployed", func(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - _, err := k.GetUniswapV2Router02Address(ctx) - require.ErrorIs(t, err, types.ErrABIUnpack) + // fail if no system contract + _, err := k.QueryWZetaBalanceOf(ctx, sample.EthAddress()) + require.ErrorIs(t, err, types.ErrStateVariableNotFound) + }) } func TestKeeper_QuerySystemContractGasCoinZRC20(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - chainID := getValidChainID(t) + t.Run("should fail if system contracts are not deployed", func(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + chainID := getValidChainID(t) + + _, err := k.QuerySystemContractGasCoinZRC20(ctx, big.NewInt(chainID)) + require.Error(t, err) + require.ErrorIs(t, err, types.ErrStateVariableNotFound) + }) - _, err := k.QuerySystemContractGasCoinZRC20(ctx, big.NewInt(chainID)) - require.Error(t, err) - require.ErrorIs(t, err, types.ErrStateVariableNotFound) + t.Run("should query if system contracts are deployed", func(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + chainID := getValidChainID(t) - deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) - zrc20 := setupGasCoin(t, ctx, k, sdkk.EvmKeeper, chainID, "foobar", "foobar") + _, err := k.QuerySystemContractGasCoinZRC20(ctx, big.NewInt(chainID)) + require.Error(t, err) + require.ErrorIs(t, err, types.ErrStateVariableNotFound) - found, err := k.QuerySystemContractGasCoinZRC20(ctx, big.NewInt(chainID)) - require.NoError(t, err) - require.Equal(t, zrc20, found) -} + deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) + zrc20 := setupGasCoin(t, ctx, k, sdkk.EvmKeeper, chainID, "foobar", "foobar") -func TestKeeper_QuerySystemContractGasCoinZRC20FailsIfContractNotSet(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - chainID := getValidChainID(t) + found, err := k.QuerySystemContractGasCoinZRC20(ctx, big.NewInt(chainID)) + require.NoError(t, err) + require.Equal(t, zrc20, found) + }) - _, err := k.QuerySystemContractGasCoinZRC20(ctx, big.NewInt(chainID)) - require.Error(t, err) - require.ErrorIs(t, err, types.ErrStateVariableNotFound) + t.Run("should fail if gas coin not setup", func(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + chainID := getValidChainID(t) - deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) + _, err := k.QuerySystemContractGasCoinZRC20(ctx, big.NewInt(chainID)) + require.Error(t, err) + require.ErrorIs(t, err, types.ErrStateVariableNotFound) - _, err = k.QuerySystemContractGasCoinZRC20(ctx, big.NewInt(chainID)) - require.ErrorIs(t, err, types.ErrContractNotFound) -} + deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) -func TestKeeper_QuerySystemContractGasCoinZRC20Fails(t *testing.T) { - k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ - UseEVMMock: true, + _, err = k.QuerySystemContractGasCoinZRC20(ctx, big.NewInt(chainID)) + require.ErrorIs(t, err, types.ErrContractNotFound) }) - mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) + t.Run("should fail if evm call fails", func(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - mockEVMKeeper.MockEVMFailCallOnce() + deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) - _, err := k.QuerySystemContractGasCoinZRC20(ctx, big.NewInt(1)) - require.ErrorIs(t, err, types.ErrContractCall) -} + mockEVMKeeper.MockEVMFailCallOnce() -func TestKeeper_QuerySystemContractGasCoinZRC20FailsToUnpack(t *testing.T) { - k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ - UseEVMMock: true, + _, err := k.QuerySystemContractGasCoinZRC20(ctx, big.NewInt(1)) + require.ErrorIs(t, err, types.ErrContractCall) }) - mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) + t.Run("should fail if abi unpack fails", func(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - mockEVMKeeper.MockEVMSuccessCallOnce() + deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) - _, err := k.QuerySystemContractGasCoinZRC20(ctx, big.NewInt(1)) - require.ErrorIs(t, err, types.ErrABIUnpack) + mockEVMKeeper.MockEVMSuccessCallOnce() + + _, err := k.QuerySystemContractGasCoinZRC20(ctx, big.NewInt(1)) + require.ErrorIs(t, err, types.ErrABIUnpack) + }) } func TestKeeper_CallUniswapV2RouterSwapExactETHForToken(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - chainID := getValidChainID(t) - - // fail if no system contract - _, err := k.CallUniswapV2RouterSwapExactETHForToken( - ctx, - types.ModuleAddressEVM, - types.ModuleAddressEVM, - big.NewInt(1), - sample.EthAddress(), - true, - ) - require.Error(t, err) - - // deploy system contracts and swap exact eth for 1 token - tokenAmount := big.NewInt(1) - deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) - zrc20 := setupGasCoin(t, ctx, k, sdkk.EvmKeeper, chainID, "foobar", "foobar") - - amountToSwap, err := k.QueryUniswapV2RouterGetZetaAmountsIn(ctx, tokenAmount, zrc20) - require.NoError(t, err) - err = sdkk.BankKeeper.MintCoins(ctx, types.ModuleName, sdk.NewCoins(sdk.NewCoin("azeta", sdk.NewIntFromBigInt(amountToSwap)))) - require.NoError(t, err) - - amounts, err := k.CallUniswapV2RouterSwapExactETHForToken( - ctx, - types.ModuleAddressEVM, - types.ModuleAddressEVM, - amountToSwap, - zrc20, - true, - ) - require.NoError(t, err) - - require.Equal(t, 2, len(amounts)) - require.Equal(t, tokenAmount, amounts[1]) -} + t.Run("should fail if system contracts are not deployed", func(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + // fail if no system contract + _, err := k.CallUniswapV2RouterSwapExactETHForToken( + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + big.NewInt(1), + sample.EthAddress(), + true, + ) + require.ErrorIs(t, err, types.ErrStateVariableNotFound) + }) -func TestKeeper_CallUniswapV2RouterSwapExactETHForTokenFails(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - chainID := getValidChainID(t) - - // deploy system contracts and swap 1 token fails because of missing wrapped balance - deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) - zrc20 := setupGasCoin(t, ctx, k, sdkk.EvmKeeper, chainID, "foobar", "foobar") - - amountToSwap, err := k.QueryUniswapV2RouterGetZetaAmountsIn(ctx, big.NewInt(1), zrc20) - require.NoError(t, err) - - _, err = k.CallUniswapV2RouterSwapExactETHForToken( - ctx, - types.ModuleAddressEVM, - types.ModuleAddressEVM, - amountToSwap, - zrc20, - true, - ) - require.ErrorIs(t, err, types.ErrContractCall) -} + t.Run("should swap if system contracts are deployed", func(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + chainID := getValidChainID(t) + + // deploy system contracts and swap exact eth for 1 token + tokenAmount := big.NewInt(1) + deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) + zrc20 := setupGasCoin(t, ctx, k, sdkk.EvmKeeper, chainID, "foobar", "foobar") + + amountToSwap, err := k.QueryUniswapV2RouterGetZetaAmountsIn(ctx, tokenAmount, zrc20) + require.NoError(t, err) + err = sdkk.BankKeeper.MintCoins(ctx, types.ModuleName, sdk.NewCoins(sdk.NewCoin("azeta", sdk.NewIntFromBigInt(amountToSwap)))) + require.NoError(t, err) + + amounts, err := k.CallUniswapV2RouterSwapExactETHForToken( + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + amountToSwap, + zrc20, + true, + ) + require.NoError(t, err) + + require.Equal(t, 2, len(amounts)) + require.Equal(t, tokenAmount, amounts[1]) + }) -func TestKeeper_CallUniswapV2RouterSwapExactETHForTokenFailsIfWZetaContractNotSet(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - - deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ - DeployWZeta: false, - DeployUniswapV2Factory: true, - DeployUniswapV2Router: true, - }) - - _, err := k.CallUniswapV2RouterSwapExactETHForToken( - ctx, - types.ModuleAddressEVM, - types.ModuleAddressEVM, - big.NewInt(1), - sample.EthAddress(), - true, - ) - require.ErrorIs(t, err, types.ErrContractNotFound) -} + t.Run("should fail if missing zeta balance", func(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + chainID := getValidChainID(t) + + // deploy system contracts and swap 1 token fails because of missing wrapped balance + deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) + zrc20 := setupGasCoin(t, ctx, k, sdkk.EvmKeeper, chainID, "foobar", "foobar") + + amountToSwap, err := k.QueryUniswapV2RouterGetZetaAmountsIn(ctx, big.NewInt(1), zrc20) + require.NoError(t, err) + + _, err = k.CallUniswapV2RouterSwapExactETHForToken( + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + amountToSwap, + zrc20, + true, + ) + require.ErrorIs(t, err, types.ErrContractCall) + }) + + t.Run("should fail if wzeta not deployed", func(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ + DeployWZeta: false, + DeployUniswapV2Factory: true, + DeployUniswapV2Router: true, + }) + + _, err := k.CallUniswapV2RouterSwapExactETHForToken( + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + big.NewInt(1), + sample.EthAddress(), + true, + ) + require.ErrorIs(t, err, types.ErrContractNotFound) + }) -func TestKeeper_CallUniswapV2RouterSwapExactETHForTokenFailsIfRouterContractNotSet(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - - deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ - DeployWZeta: true, - DeployUniswapV2Factory: true, - DeployUniswapV2Router: false, - }) - - _, err := k.CallUniswapV2RouterSwapExactETHForToken( - ctx, - types.ModuleAddressEVM, - types.ModuleAddressEVM, - big.NewInt(1), - sample.EthAddress(), - true, - ) - require.ErrorIs(t, err, types.ErrContractNotFound) + t.Run("should fail if router not deployed", func(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ + DeployWZeta: true, + DeployUniswapV2Factory: true, + DeployUniswapV2Router: false, + }) + + _, err := k.CallUniswapV2RouterSwapExactETHForToken( + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + big.NewInt(1), + sample.EthAddress(), + true, + ) + require.ErrorIs(t, err, types.ErrContractNotFound) + }) } func TestKeeper_CallUniswapV2RouterSwapEthForExactToken(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - chainID := getValidChainID(t) - - // fail if no system contract - _, err := k.CallUniswapV2RouterSwapExactETHForToken( - ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, big.NewInt(1), sample.EthAddress(), true) - require.Error(t, err) - - // deploy system contracts and swap exact 1 token - tokenAmount := big.NewInt(1) - deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) - zrc20 := setupGasCoin(t, ctx, k, sdkk.EvmKeeper, chainID, "foobar", "foobar") - - amountToSwap, err := k.QueryUniswapV2RouterGetZetaAmountsIn(ctx, tokenAmount, zrc20) - require.NoError(t, err) - err = sdkk.BankKeeper.MintCoins(ctx, types.ModuleName, sdk.NewCoins(sdk.NewCoin("azeta", sdk.NewIntFromBigInt(amountToSwap)))) - require.NoError(t, err) - - amounts, err := k.CallUniswapV2RouterSwapEthForExactToken( - ctx, - types.ModuleAddressEVM, - types.ModuleAddressEVM, - amountToSwap, - tokenAmount, - zrc20, - ) - require.NoError(t, err) - - require.Equal(t, 2, len(amounts)) - require.Equal(t, big.NewInt(1), amounts[1]) -} + t.Run("should fail if system contracts are not deployed", func(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + // fail if no system contract + _, err := k.CallUniswapV2RouterSwapExactETHForToken( + ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, big.NewInt(1), sample.EthAddress(), true) + require.ErrorIs(t, err, types.ErrStateVariableNotFound) + }) -func TestKeeper_CallUniswapV2RouterSwapEthForExactTokenFails(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - chainID := getValidChainID(t) - - // deploy system contracts and swap 1 token fails because of missing wrapped balance - tokenAmount := big.NewInt(1) - deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) - zrc20 := setupGasCoin(t, ctx, k, sdkk.EvmKeeper, chainID, "foobar", "foobar") - - amountToSwap, err := k.QueryUniswapV2RouterGetZetaAmountsIn(ctx, tokenAmount, zrc20) - require.NoError(t, err) - - _, err = k.CallUniswapV2RouterSwapEthForExactToken( - ctx, - types.ModuleAddressEVM, - types.ModuleAddressEVM, - amountToSwap, - tokenAmount, - zrc20, - ) - require.ErrorIs(t, err, types.ErrContractCall) -} + t.Run("should swap if system contracts are deployed", func(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + chainID := getValidChainID(t) + + // deploy system contracts and swap exact 1 token + tokenAmount := big.NewInt(1) + deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) + zrc20 := setupGasCoin(t, ctx, k, sdkk.EvmKeeper, chainID, "foobar", "foobar") + + amountToSwap, err := k.QueryUniswapV2RouterGetZetaAmountsIn(ctx, tokenAmount, zrc20) + require.NoError(t, err) + err = sdkk.BankKeeper.MintCoins(ctx, types.ModuleName, sdk.NewCoins(sdk.NewCoin("azeta", sdk.NewIntFromBigInt(amountToSwap)))) + require.NoError(t, err) + + amounts, err := k.CallUniswapV2RouterSwapEthForExactToken( + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + amountToSwap, + tokenAmount, + zrc20, + ) + require.NoError(t, err) + + require.Equal(t, 2, len(amounts)) + require.Equal(t, big.NewInt(1), amounts[1]) + }) -func TestKeeper_CallUniswapV2RouterSwapEthForExactTokenFailsIfWZetaContractNotSet(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - - deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ - DeployWZeta: false, - DeployUniswapV2Factory: true, - DeployUniswapV2Router: true, - }) - - _, err := k.CallUniswapV2RouterSwapEthForExactToken( - ctx, - types.ModuleAddressEVM, - types.ModuleAddressEVM, - big.NewInt(1), - big.NewInt(1), - sample.EthAddress(), - ) - require.ErrorIs(t, err, types.ErrContractNotFound) -} + t.Run("should fail if missing zeta balance", func(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + chainID := getValidChainID(t) + + // deploy system contracts and swap 1 token fails because of missing wrapped balance + tokenAmount := big.NewInt(1) + deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) + zrc20 := setupGasCoin(t, ctx, k, sdkk.EvmKeeper, chainID, "foobar", "foobar") + + amountToSwap, err := k.QueryUniswapV2RouterGetZetaAmountsIn(ctx, tokenAmount, zrc20) + require.NoError(t, err) + + _, err = k.CallUniswapV2RouterSwapEthForExactToken( + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + amountToSwap, + tokenAmount, + zrc20, + ) + require.ErrorIs(t, err, types.ErrContractCall) + }) -func TestKeeper_CallUniswapV2RouterSwapEthForExactTokenFailsIfRouterContractNotSet(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - - deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ - DeployWZeta: true, - DeployUniswapV2Factory: true, - DeployUniswapV2Router: false, - }) - - _, err := k.CallUniswapV2RouterSwapEthForExactToken( - ctx, - types.ModuleAddressEVM, - types.ModuleAddressEVM, - big.NewInt(1), - big.NewInt(1), - sample.EthAddress(), - ) - require.ErrorIs(t, err, types.ErrContractNotFound) + t.Run("should fail if wzeta not deployed", func(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ + DeployWZeta: false, + DeployUniswapV2Factory: true, + DeployUniswapV2Router: true, + }) + + _, err := k.CallUniswapV2RouterSwapEthForExactToken( + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + big.NewInt(1), + big.NewInt(1), + sample.EthAddress(), + ) + require.ErrorIs(t, err, types.ErrContractNotFound) + }) + + t.Run("should fail if router not deployed", func(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ + DeployWZeta: true, + DeployUniswapV2Factory: true, + DeployUniswapV2Router: false, + }) + + _, err := k.CallUniswapV2RouterSwapEthForExactToken( + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + big.NewInt(1), + big.NewInt(1), + sample.EthAddress(), + ) + require.ErrorIs(t, err, types.ErrContractNotFound) + }) } func TestKeeper_CallUniswapV2RouterSwapExactTokensForETH(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - chainID := getValidChainID(t) - - // fail if no system contract - _, err := k.CallUniswapV2RouterSwapExactTokensForETH( - ctx, - types.ModuleAddressEVM, - types.ModuleAddressEVM, - big.NewInt(1), - sample.EthAddress(), - true, - ) - require.Error(t, err) - - // deploy system contracts and swap exact eth for 1 token - ethAmount := big.NewInt(1) - _, _, router, _, _ := deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) - zrc20 := setupGasCoin(t, ctx, k, sdkk.EvmKeeper, chainID, "foobar", "foobar") - - amountToSwap, err := k.QueryUniswapV2RouterGetZRC4AmountsIn(ctx, ethAmount, zrc20) - require.NoError(t, err) - - _, err = k.DepositZRC20(ctx, zrc20, types.ModuleAddressEVM, amountToSwap) - require.NoError(t, err) - k.CallZRC20Approve( - ctx, - types.ModuleAddressEVM, - zrc20, - router, - amountToSwap, - false, - ) - - amounts, err := k.CallUniswapV2RouterSwapExactTokensForETH( - ctx, - types.ModuleAddressEVM, - types.ModuleAddressEVM, - amountToSwap, - zrc20, - true, - ) - require.NoError(t, err) - - require.Equal(t, 2, len(amounts)) - require.Equal(t, ethAmount, amounts[0]) -} + t.Run("should fail if system contracts are not deployed", func(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + // fail if no system contract + _, err := k.CallUniswapV2RouterSwapExactTokensForETH( + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + big.NewInt(1), + sample.EthAddress(), + true, + ) + require.ErrorIs(t, err, types.ErrStateVariableNotFound) + }) -func TestKeeper_CallUniswapV2RouterSwapExactTokensForETHFailsIfWZetaContractNotSet(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - - deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ - DeployWZeta: false, - DeployUniswapV2Factory: true, - DeployUniswapV2Router: true, - }) - _, err := k.CallUniswapV2RouterSwapExactTokensForETH( - ctx, - types.ModuleAddressEVM, - types.ModuleAddressEVM, - big.NewInt(1), - sample.EthAddress(), - true, - ) - require.ErrorIs(t, err, types.ErrContractNotFound) -} + t.Run("should swap if system contracts are deployed", func(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + chainID := getValidChainID(t) + + // fail if no system contract + _, err := k.CallUniswapV2RouterSwapExactTokensForETH( + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + big.NewInt(1), + sample.EthAddress(), + true, + ) + require.Error(t, err) + + // deploy system contracts and swap exact eth for 1 token + ethAmount := big.NewInt(1) + _, _, router, _, _ := deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) + zrc20 := setupGasCoin(t, ctx, k, sdkk.EvmKeeper, chainID, "foobar", "foobar") + + amountToSwap, err := k.QueryUniswapV2RouterGetZRC4AmountsIn(ctx, ethAmount, zrc20) + require.NoError(t, err) + + _, err = k.DepositZRC20(ctx, zrc20, types.ModuleAddressEVM, amountToSwap) + require.NoError(t, err) + k.CallZRC20Approve( + ctx, + types.ModuleAddressEVM, + zrc20, + router, + amountToSwap, + false, + ) + + amounts, err := k.CallUniswapV2RouterSwapExactTokensForETH( + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + amountToSwap, + zrc20, + true, + ) + require.NoError(t, err) + + require.Equal(t, 2, len(amounts)) + require.Equal(t, ethAmount, amounts[0]) + }) -func TestKeeper_CallUniswapV2RouterSwapExactTokensForETHFailsIfRouterContractNotSet(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - - deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ - DeployWZeta: true, - DeployUniswapV2Factory: true, - DeployUniswapV2Router: false, - }) - _, err := k.CallUniswapV2RouterSwapExactTokensForETH( - ctx, - types.ModuleAddressEVM, - types.ModuleAddressEVM, - big.NewInt(1), - sample.EthAddress(), - true, - ) - require.ErrorIs(t, err, types.ErrContractNotFound) -} + t.Run("should fail if missing tokens balance", func(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + chainID := getValidChainID(t) + + // fail if no system contract + _, err := k.CallUniswapV2RouterSwapExactTokensForETH( + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + big.NewInt(1), + sample.EthAddress(), + true, + ) + require.Error(t, err) + + // deploy system contracts and swap fails because of missing balance + ethAmount := big.NewInt(1) + deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) + zrc20 := setupGasCoin(t, ctx, k, sdkk.EvmKeeper, chainID, "foobar", "foobar") + + amountToSwap, err := k.QueryUniswapV2RouterGetZRC4AmountsIn(ctx, ethAmount, zrc20) + require.NoError(t, err) + + _, err = k.CallUniswapV2RouterSwapExactTokensForETH( + ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, amountToSwap, zrc20, true) + require.ErrorIs(t, err, types.ErrContractCall) + }) -func TestKeeper_CallUniswapV2RouterSwapExactTokensForETHFails(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - chainID := getValidChainID(t) - - // fail if no system contract - _, err := k.CallUniswapV2RouterSwapExactTokensForETH( - ctx, - types.ModuleAddressEVM, - types.ModuleAddressEVM, - big.NewInt(1), - sample.EthAddress(), - true, - ) - require.Error(t, err) - - // deploy system contracts and swap fails because of missing balance - ethAmount := big.NewInt(1) - deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) - zrc20 := setupGasCoin(t, ctx, k, sdkk.EvmKeeper, chainID, "foobar", "foobar") - - amountToSwap, err := k.QueryUniswapV2RouterGetZRC4AmountsIn(ctx, ethAmount, zrc20) - require.NoError(t, err) - - _, err = k.CallUniswapV2RouterSwapExactTokensForETH( - ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, amountToSwap, zrc20, true) - require.ErrorIs(t, err, types.ErrContractCall) -} + t.Run("should fail if wzeta not deployed", func(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ + DeployWZeta: false, + DeployUniswapV2Factory: true, + DeployUniswapV2Router: true, + }) + _, err := k.CallUniswapV2RouterSwapExactTokensForETH( + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + big.NewInt(1), + sample.EthAddress(), + true, + ) + require.ErrorIs(t, err, types.ErrContractNotFound) + }) -func TestKeeper_CallUniswapV2RouterSwapExactTokensForTokens(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - chainID := getValidChainID(t) - - // fail if no system contract - _, err := k.CallUniswapV2RouterSwapExactTokensForTokens( - ctx, - types.ModuleAddressEVM, - types.ModuleAddressEVM, - big.NewInt(1), - sample.EthAddress(), - sample.EthAddress(), - true, - ) - require.Error(t, err) - - // deploy system contracts and swap exact token for 1 token - tokenAmount := big.NewInt(1) - _, _, router, _, _ := deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) - - inzrc20 := deployZRC20(t, ctx, k, sdkk.EvmKeeper, chainID, "foo", sample.EthAddress().String(), "foo") - outzrc20 := deployZRC20(t, ctx, k, sdkk.EvmKeeper, chainID, "bar", sample.EthAddress().String(), "bar") - setupZRC20Pool(t, ctx, k, sdkk.BankKeeper, inzrc20) - setupZRC20Pool(t, ctx, k, sdkk.BankKeeper, outzrc20) - - amountToSwap, err := k.QueryUniswapV2RouterGetZRC4ToZRC4AmountsIn(ctx, tokenAmount, inzrc20, outzrc20) - require.NoError(t, err) - - _, err = k.DepositZRC20(ctx, inzrc20, types.ModuleAddressEVM, amountToSwap) - require.NoError(t, err) - k.CallZRC20Approve( - ctx, - types.ModuleAddressEVM, - inzrc20, - router, - amountToSwap, - false, - ) - - amounts, err := k.CallUniswapV2RouterSwapExactTokensForTokens( - ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, amountToSwap, inzrc20, outzrc20, true) - require.NoError(t, err) - require.Equal(t, 3, len(amounts)) - require.Equal(t, amounts[2], tokenAmount) + t.Run("should fail if router not deployed", func(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ + DeployWZeta: true, + DeployUniswapV2Factory: true, + DeployUniswapV2Router: false, + }) + _, err := k.CallUniswapV2RouterSwapExactTokensForETH( + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + big.NewInt(1), + sample.EthAddress(), + true, + ) + require.ErrorIs(t, err, types.ErrContractNotFound) + }) } -func TestKeeper_CallUniswapV2RouterSwapExactTokensForTokensFailsIfRouterContractNotSet(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - - // fail if no system contract - _, err := k.CallUniswapV2RouterSwapExactTokensForTokens( - ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, big.NewInt(1), sample.EthAddress(), sample.EthAddress(), true) - require.Error(t, err) - - // deploy system contracts except router - deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ - DeployUniswapV2Router: false, - DeployWZeta: true, - DeployUniswapV2Factory: true, - }) - - _, err = k.CallUniswapV2RouterSwapExactTokensForTokens( - ctx, - types.ModuleAddressEVM, - types.ModuleAddressEVM, - big.NewInt(1), - sample.EthAddress(), - sample.EthAddress(), - true, - ) - require.ErrorIs(t, err, types.ErrContractNotFound) -} +func TestKeeper_CallUniswapV2RouterSwapExactTokensForTokens(t *testing.T) { + t.Run("should fail if system contracts are not deployed", func(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + // fail if no system contract + _, err := k.CallUniswapV2RouterSwapExactTokensForTokens( + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + big.NewInt(1), + sample.EthAddress(), + sample.EthAddress(), + true, + ) + require.ErrorIs(t, err, types.ErrStateVariableNotFound) + }) -func TestKeeper_CallUniswapV2RouterSwapExactTokensForTokensFailsIfWzetaContractNotSet(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - - // fail if no system contract - _, err := k.CallUniswapV2RouterSwapExactTokensForTokens( - ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, big.NewInt(1), sample.EthAddress(), sample.EthAddress(), true) - require.Error(t, err) - - // deploy system contracts except router - deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ - DeployUniswapV2Router: true, - DeployWZeta: false, - DeployUniswapV2Factory: true, - }) - - _, err = k.CallUniswapV2RouterSwapExactTokensForTokens( - ctx, - types.ModuleAddressEVM, - types.ModuleAddressEVM, - big.NewInt(1), - sample.EthAddress(), - sample.EthAddress(), - true, - ) - require.ErrorIs(t, err, types.ErrContractNotFound) -} + t.Run("should swap if system contracts are deployed", func(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + chainID := getValidChainID(t) + + // fail if no system contract + _, err := k.CallUniswapV2RouterSwapExactTokensForTokens( + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + big.NewInt(1), + sample.EthAddress(), + sample.EthAddress(), + true, + ) + require.Error(t, err) + + // deploy system contracts and swap exact token for 1 token + tokenAmount := big.NewInt(1) + _, _, router, _, _ := deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) + + inzrc20 := deployZRC20(t, ctx, k, sdkk.EvmKeeper, chainID, "foo", sample.EthAddress().String(), "foo") + outzrc20 := deployZRC20(t, ctx, k, sdkk.EvmKeeper, chainID, "bar", sample.EthAddress().String(), "bar") + setupZRC20Pool(t, ctx, k, sdkk.BankKeeper, inzrc20) + setupZRC20Pool(t, ctx, k, sdkk.BankKeeper, outzrc20) + + amountToSwap, err := k.QueryUniswapV2RouterGetZRC4ToZRC4AmountsIn(ctx, tokenAmount, inzrc20, outzrc20) + require.NoError(t, err) + + _, err = k.DepositZRC20(ctx, inzrc20, types.ModuleAddressEVM, amountToSwap) + require.NoError(t, err) + k.CallZRC20Approve( + ctx, + types.ModuleAddressEVM, + inzrc20, + router, + amountToSwap, + false, + ) + + amounts, err := k.CallUniswapV2RouterSwapExactTokensForTokens( + ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, amountToSwap, inzrc20, outzrc20, true) + require.NoError(t, err) + require.Equal(t, 3, len(amounts)) + require.Equal(t, amounts[2], tokenAmount) + }) -func TestKeeper_CallUniswapV2RouterSwapExactTokensForTokensFails(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - chainID := getValidChainID(t) - - // deploy system contracts and swap fails because of missing balance - tokenAmount := big.NewInt(1) - deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) - - inzrc20 := deployZRC20(t, ctx, k, sdkk.EvmKeeper, chainID, "foo", sample.EthAddress().String(), "foo") - outzrc20 := deployZRC20(t, ctx, k, sdkk.EvmKeeper, chainID, "bar", sample.EthAddress().String(), "bar") - setupZRC20Pool(t, ctx, k, sdkk.BankKeeper, inzrc20) - setupZRC20Pool(t, ctx, k, sdkk.BankKeeper, outzrc20) - - amountToSwap, err := k.QueryUniswapV2RouterGetZRC4ToZRC4AmountsIn(ctx, tokenAmount, inzrc20, outzrc20) - require.NoError(t, err) - - _, err = k.CallUniswapV2RouterSwapExactTokensForTokens( - ctx, - types.ModuleAddressEVM, - types.ModuleAddressEVM, - amountToSwap, - inzrc20, - outzrc20, - true, - ) - require.ErrorIs(t, err, types.ErrContractCall) -} + t.Run("should fail if missing tokens balance", func(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + chainID := getValidChainID(t) + + // deploy system contracts and swap fails because of missing balance + tokenAmount := big.NewInt(1) + deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) + + inzrc20 := deployZRC20(t, ctx, k, sdkk.EvmKeeper, chainID, "foo", sample.EthAddress().String(), "foo") + outzrc20 := deployZRC20(t, ctx, k, sdkk.EvmKeeper, chainID, "bar", sample.EthAddress().String(), "bar") + setupZRC20Pool(t, ctx, k, sdkk.BankKeeper, inzrc20) + setupZRC20Pool(t, ctx, k, sdkk.BankKeeper, outzrc20) + + amountToSwap, err := k.QueryUniswapV2RouterGetZRC4ToZRC4AmountsIn(ctx, tokenAmount, inzrc20, outzrc20) + require.NoError(t, err) + + _, err = k.CallUniswapV2RouterSwapExactTokensForTokens( + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + amountToSwap, + inzrc20, + outzrc20, + true, + ) + require.ErrorIs(t, err, types.ErrContractCall) + }) -func TestKeeper_QueryUniswapV2RouterGetZRC4AmountsInFails(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + t.Run("should fail if wzeta not deployed", func(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + // fail if no system contract + _, err := k.CallUniswapV2RouterSwapExactTokensForTokens( + ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, big.NewInt(1), sample.EthAddress(), sample.EthAddress(), true) + require.Error(t, err) + + // deploy system contracts except router + deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ + DeployUniswapV2Router: true, + DeployWZeta: false, + DeployUniswapV2Factory: true, + }) + + _, err = k.CallUniswapV2RouterSwapExactTokensForTokens( + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + big.NewInt(1), + sample.EthAddress(), + sample.EthAddress(), + true, + ) + require.ErrorIs(t, err, types.ErrContractNotFound) + }) - deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) + t.Run("should fail if router not deployed", func(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + // fail if no system contract + _, err := k.CallUniswapV2RouterSwapExactTokensForTokens( + ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, big.NewInt(1), sample.EthAddress(), sample.EthAddress(), true) + require.Error(t, err) + + // deploy system contracts except router + deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ + DeployUniswapV2Router: false, + DeployWZeta: true, + DeployUniswapV2Factory: true, + }) + + _, err = k.CallUniswapV2RouterSwapExactTokensForTokens( + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + big.NewInt(1), + sample.EthAddress(), + sample.EthAddress(), + true, + ) + require.ErrorIs(t, err, types.ErrContractNotFound) + }) - _, err := k.QueryUniswapV2RouterGetZRC4AmountsIn(ctx, big.NewInt(1), sample.EthAddress()) - require.ErrorIs(t, err, types.ErrContractCall) } -func TestKeeper_QueryUniswapV2RouterGetZRC4AmountsInFailsIfWZetaContractNotSet(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) +func TestKeeper_QueryUniswapV2RouterGetZRC4AmountsIn(t *testing.T) { + t.Run("should fail if no amounts out", func(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) - deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ - DeployWZeta: false, - DeployUniswapV2Factory: true, - DeployUniswapV2Router: true, + _, err := k.QueryUniswapV2RouterGetZRC4AmountsIn(ctx, big.NewInt(1), sample.EthAddress()) + require.ErrorIs(t, err, types.ErrContractCall) }) - _, err := k.QueryUniswapV2RouterGetZRC4AmountsIn(ctx, big.NewInt(1), sample.EthAddress()) - require.ErrorIs(t, err, types.ErrContractNotFound) -} + t.Run("should fail if wzeta not deployed", func(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) -func TestKeeper_QueryUniswapV2RouterGetZRC4AmountsInFailsIfRouterContractNotSet(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ + DeployWZeta: false, + DeployUniswapV2Factory: true, + DeployUniswapV2Router: true, + }) - deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ - DeployWZeta: true, - DeployUniswapV2Factory: true, - DeployUniswapV2Router: false, + _, err := k.QueryUniswapV2RouterGetZRC4AmountsIn(ctx, big.NewInt(1), sample.EthAddress()) + require.ErrorIs(t, err, types.ErrContractNotFound) }) - _, err := k.QueryUniswapV2RouterGetZRC4AmountsIn(ctx, big.NewInt(1), sample.EthAddress()) - require.ErrorIs(t, err, types.ErrContractNotFound) -} - -func TestKeeper_QueryUniswapV2RouterGetZetaAmountsInFails(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + t.Run("should fail if router not deployed", func(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) + deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ + DeployWZeta: true, + DeployUniswapV2Factory: true, + DeployUniswapV2Router: false, + }) - _, err := k.QueryUniswapV2RouterGetZetaAmountsIn(ctx, big.NewInt(1), sample.EthAddress()) - require.ErrorIs(t, err, types.ErrContractCall) + _, err := k.QueryUniswapV2RouterGetZRC4AmountsIn(ctx, big.NewInt(1), sample.EthAddress()) + require.ErrorIs(t, err, types.ErrContractNotFound) + }) } -func TestKeeper_QueryUniswapV2RouterGetZetaAmountsInFailsIfWZetaContractNotSet(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) +func TestKeeper_QueryUniswapV2RouterGetZetaAmountsIn(t *testing.T) { + t.Run("should fail if no amounts out", func(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ - DeployWZeta: false, - DeployUniswapV2Factory: true, - DeployUniswapV2Router: true, + deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) + + _, err := k.QueryUniswapV2RouterGetZetaAmountsIn(ctx, big.NewInt(1), sample.EthAddress()) + require.ErrorIs(t, err, types.ErrContractCall) }) - _, err := k.QueryUniswapV2RouterGetZetaAmountsIn(ctx, big.NewInt(1), sample.EthAddress()) - require.ErrorIs(t, err, types.ErrContractNotFound) -} + t.Run("should fail if wzeta not deployed", func(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) -func TestKeeper_QueryUniswapV2RouterGetZetaAmountsInFailsIfRouterContractNotSet(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ + DeployWZeta: false, + DeployUniswapV2Factory: true, + DeployUniswapV2Router: true, + }) - deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ - DeployWZeta: true, - DeployUniswapV2Factory: true, - DeployUniswapV2Router: false, + _, err := k.QueryUniswapV2RouterGetZetaAmountsIn(ctx, big.NewInt(1), sample.EthAddress()) + require.ErrorIs(t, err, types.ErrContractNotFound) }) - _, err := k.QueryUniswapV2RouterGetZetaAmountsIn(ctx, big.NewInt(1), sample.EthAddress()) - require.ErrorIs(t, err, types.ErrContractNotFound) -} + t.Run("should fail if router not deployed", func(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) -func TestKeeper_QueryUniswapV2RouterGetZRC4ToZRC4AmountsInFails(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ + DeployWZeta: true, + DeployUniswapV2Factory: true, + DeployUniswapV2Router: false, + }) - deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) - - _, err := k.QueryUniswapV2RouterGetZRC4ToZRC4AmountsIn(ctx, big.NewInt(1), sample.EthAddress(), sample.EthAddress()) - require.ErrorIs(t, err, types.ErrContractCall) + _, err := k.QueryUniswapV2RouterGetZetaAmountsIn(ctx, big.NewInt(1), sample.EthAddress()) + require.ErrorIs(t, err, types.ErrContractNotFound) + }) } -func TestKeeper_QueryUniswapV2RouterGetZRC4ToZRC4AmountsInFailsIfWZetaContractNotSet(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) +func TestKeeper_QueryUniswapV2RouterGetZRC4ToZRC4AmountsIn(t *testing.T) { + t.Run("should fail if no amounts out", func(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ - DeployWZeta: false, - DeployUniswapV2Factory: true, - DeployUniswapV2Router: true, + deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) + + _, err := k.QueryUniswapV2RouterGetZRC4ToZRC4AmountsIn(ctx, big.NewInt(1), sample.EthAddress(), sample.EthAddress()) + require.ErrorIs(t, err, types.ErrContractCall) }) - _, err := k.QueryUniswapV2RouterGetZRC4ToZRC4AmountsIn(ctx, big.NewInt(1), sample.EthAddress(), sample.EthAddress()) - require.ErrorIs(t, err, types.ErrContractNotFound) -} + t.Run("should fail if wzeta not deployed", func(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) -func TestKeeper_QueryUniswapV2RouterGetZRC4ToZRC4AmountsInFailsIfRouterContractNotSet(t *testing.T) { - k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ + DeployWZeta: false, + DeployUniswapV2Factory: true, + DeployUniswapV2Router: true, + }) - deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ - DeployWZeta: true, - DeployUniswapV2Factory: true, - DeployUniswapV2Router: false, + _, err := k.QueryUniswapV2RouterGetZRC4ToZRC4AmountsIn(ctx, big.NewInt(1), sample.EthAddress(), sample.EthAddress()) + require.ErrorIs(t, err, types.ErrContractNotFound) }) - _, err := k.QueryUniswapV2RouterGetZRC4ToZRC4AmountsIn(ctx, big.NewInt(1), sample.EthAddress(), sample.EthAddress()) - require.ErrorIs(t, err, types.ErrContractNotFound) -} + t.Run("should fail if router not deployed", func(t *testing.T) { + k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + deploySystemContractsConfigurable(t, ctx, k, sdkk.EvmKeeper, &SystemContractDeployConfig{ + DeployWZeta: true, + DeployUniswapV2Factory: true, + DeployUniswapV2Router: false, + }) -func TestKeeper_CallZRC20BurnFails(t *testing.T) { - k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ - UseEVMMock: true, + _, err := k.QueryUniswapV2RouterGetZRC4ToZRC4AmountsIn(ctx, big.NewInt(1), sample.EthAddress(), sample.EthAddress()) + require.ErrorIs(t, err, types.ErrContractNotFound) }) - mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) +} - deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) +func TestKeeper_CallZRC20Burn(t *testing.T) { + t.Run("should fail if evm call fails", func(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - mockEVMKeeper.MockEVMFailCallOnce() - err := k.CallZRC20Burn(ctx, types.ModuleAddressEVM, sample.EthAddress(), big.NewInt(1), false) - require.ErrorIs(t, err, types.ErrContractCall) -} + deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) -func TestKeeper_CallZRC20ApproveFails(t *testing.T) { - k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ - UseEVMMock: true, + mockEVMKeeper.MockEVMFailCallOnce() + err := k.CallZRC20Burn(ctx, types.ModuleAddressEVM, sample.EthAddress(), big.NewInt(1), false) + require.ErrorIs(t, err, types.ErrContractCall) }) - mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) +} - deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) +func TestKeeper_CallZRC20Approve(t *testing.T) { + t.Run("should fail if evm call fails", func(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - mockEVMKeeper.MockEVMFailCallOnce() - err := k.CallZRC20Approve(ctx, types.ModuleAddressEVM, sample.EthAddress(), types.ModuleAddressEVM, big.NewInt(1), false) - require.ErrorIs(t, err, types.ErrContractCall) -} + deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) -func TestKeeper_CallZRC20DepositFails(t *testing.T) { - k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ - UseEVMMock: true, + mockEVMKeeper.MockEVMFailCallOnce() + err := k.CallZRC20Approve(ctx, types.ModuleAddressEVM, sample.EthAddress(), types.ModuleAddressEVM, big.NewInt(1), false) + require.ErrorIs(t, err, types.ErrContractCall) }) - mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) +} + +func TestKeeper_CallZRC20Deposit(t *testing.T) { + t.Run("should fail if evm call fails", func(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeperWithMocks(t, keepertest.FungibleMockOptions{ + UseEVMMock: true, + }) + mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) + deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) - mockEVMKeeper.MockEVMFailCallOnce() - err := k.CallZRC20Deposit(ctx, types.ModuleAddressEVM, sample.EthAddress(), types.ModuleAddressEVM, big.NewInt(1)) - require.ErrorIs(t, err, types.ErrContractCall) + mockEVMKeeper.MockEVMFailCallOnce() + err := k.CallZRC20Deposit(ctx, types.ModuleAddressEVM, sample.EthAddress(), types.ModuleAddressEVM, big.NewInt(1)) + require.ErrorIs(t, err, types.ErrContractCall) + }) } From 5341dbe007d7832f71e76762aa886fc68bf9bf02 Mon Sep 17 00:00:00 2001 From: skosito Date: Wed, 21 Feb 2024 11:56:44 +0100 Subject: [PATCH 16/18] Fix PR comments --- x/fungible/keeper/system_contract.go | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/x/fungible/keeper/system_contract.go b/x/fungible/keeper/system_contract.go index 65f4a4c169..af36727f54 100644 --- a/x/fungible/keeper/system_contract.go +++ b/x/fungible/keeper/system_contract.go @@ -6,7 +6,6 @@ import ( cosmoserrors "cosmossdk.io/errors" "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ethcommon "github.com/ethereum/go-ethereum/common" "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/systemcontract.sol" "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/wzeta.sol" @@ -88,8 +87,8 @@ func (k *Keeper) GetWZetaContractAddress(ctx sdk.Context) (ethcommon.Address, er return ethcommon.Address{}, cosmoserrors.Wrapf(types.ErrABIUnpack, "failed to unpack wZetaContractAddress: %s", err.Error()) } - if wzetaResponse.Value == ethcommon.HexToAddress("0x0") { - return ethcommon.Address{}, sdkerrors.Wrapf(types.ErrContractNotFound, "wzeta contract invalid address") + if wzetaResponse.Value == (ethcommon.Address{}) { + return ethcommon.Address{}, cosmoserrors.Wrapf(types.ErrContractNotFound, "wzeta contract invalid address") } return wzetaResponse.Value, nil } @@ -128,8 +127,8 @@ func (k *Keeper) GetUniswapV2FactoryAddress(ctx sdk.Context) (ethcommon.Address, return ethcommon.Address{}, cosmoserrors.Wrapf(types.ErrABIUnpack, "failed to unpack uniswapv2FactoryAddress: %s", err.Error()) } - if uniswapFactoryResponse.Value == ethcommon.HexToAddress("0x0") { - return ethcommon.Address{}, sdkerrors.Wrapf(types.ErrContractNotFound, "uniswap factory contract invalid address") + if uniswapFactoryResponse.Value == (ethcommon.Address{}) { + return ethcommon.Address{}, cosmoserrors.Wrapf(types.ErrContractNotFound, "uniswap factory contract invalid address") } return uniswapFactoryResponse.Value, nil } @@ -168,8 +167,8 @@ func (k *Keeper) GetUniswapV2Router02Address(ctx sdk.Context) (ethcommon.Address return ethcommon.Address{}, cosmoserrors.Wrapf(types.ErrABIUnpack, "failed to unpack uniswapv2Router02Address: %s", err.Error()) } - if routerResponse.Value == ethcommon.HexToAddress("0x0") { - return ethcommon.Address{}, sdkerrors.Wrapf(types.ErrContractNotFound, "uniswap router contract invalid address") + if routerResponse.Value == (ethcommon.Address{}) { + return ethcommon.Address{}, cosmoserrors.Wrapf(types.ErrContractNotFound, "uniswap router contract invalid address") } return routerResponse.Value, nil } @@ -277,8 +276,8 @@ func (k *Keeper) QuerySystemContractGasCoinZRC20(ctx sdk.Context, chainid *big.I if err := sysABI.UnpackIntoInterface(&zrc20Res, "gasCoinZRC20ByChainId", res.Ret); err != nil { return ethcommon.Address{}, cosmoserrors.Wrapf(types.ErrABIUnpack, "failed to unpack gasCoinZRC20ByChainId: %s", err.Error()) } - if zrc20Res.Value == ethcommon.HexToAddress("0x0") { - return ethcommon.Address{}, sdkerrors.Wrapf(types.ErrContractNotFound, "gas coin contract invalid address") + if zrc20Res.Value == (ethcommon.Address{}) { + return ethcommon.Address{}, cosmoserrors.Wrapf(types.ErrContractNotFound, "gas coin contract invalid address") } return zrc20Res.Value, nil } From 4099a2e81f41844e18f1923d85595933d32ef280 Mon Sep 17 00:00:00 2001 From: skosito Date: Wed, 21 Feb 2024 12:03:16 +0100 Subject: [PATCH 17/18] Cleanup deprecations --- app/ante/handler_options.go | 5 ++- app/app.go | 5 ++- .../keeper/msg_server_gas_price_voter.go | 4 +- .../keeper/msg_server_vote_inbound_tx.go | 6 +-- .../keeper/msg_server_vote_outbound_tx.go | 7 ++-- .../types/message_add_to_out_tx_tracker.go | 5 ++- x/crosschain/types/message_gas_price_voter.go | 5 ++- .../message_remove_from_out_tx_tracker.go | 5 ++- x/crosschain/types/message_tss_voter.go | 3 +- .../message_vote_on_observed_inbound_tx.go | 9 ++-- .../message_vote_on_observed_outbound_tx.go | 5 ++- x/crosschain/types/message_whitelist_erc20.go | 9 ++-- x/fungible/keeper/evm.go | 2 +- x/fungible/keeper/gas_coin_and_pool.go | 22 +++++----- x/fungible/keeper/gas_price.go | 41 ++++++++++--------- .../msg_server_deploy_fungible_coin_zrc20.go | 7 ++-- .../keeper/msg_server_remove_foreign_coin.go | 5 ++- .../msg_server_update_system_contract.go | 17 ++++---- .../message_deploy_fungible_coin_zrc20.go | 7 ++-- ...message_deploy_fungible_coin_zrc20_test.go | 3 +- .../types/message_deploy_system_contracts.go | 3 +- .../types/message_remove_foreign_coin.go | 3 +- .../types/message_update_system_contract.go | 5 ++- .../keeper/msg_server_add_blame_vote.go | 4 +- x/observer/types/message_add_blame_vote.go | 5 ++- x/observer/types/message_add_observer.go | 3 +- x/observer/types/message_update_keygen.go | 3 +- x/observer/types/message_update_observer.go | 3 +- 28 files changed, 112 insertions(+), 89 deletions(-) diff --git a/app/ante/handler_options.go b/app/ante/handler_options.go index e46f7b728e..4d116a581e 100644 --- a/app/ante/handler_options.go +++ b/app/ante/handler_options.go @@ -21,6 +21,7 @@ import ( observerkeeper "github.com/zeta-chain/zetacore/x/observer/keeper" + cosmoserrors "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/types/tx/signing" @@ -165,7 +166,7 @@ func (sud SetUpContextDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate // Set a gas meter with limit 0 as to prevent an infinite gas meter attack // during runTx. newCtx = SetGasMeter(simulate, ctx, 0) - return newCtx, sdkerrors.Wrap(sdkerrors.ErrTxDecode, "Tx must be GasTx") + return newCtx, cosmoserrors.Wrap(sdkerrors.ErrTxDecode, "Tx must be GasTx") } newCtx = SetGasMeter(simulate, ctx, gasTx.GetGas()) @@ -183,7 +184,7 @@ func (sud SetUpContextDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate "out of gas in location: %v; gasWanted: %d, gasUsed: %d", rType.Descriptor, gasTx.GetGas(), newCtx.GasMeter().GasConsumed()) - err = sdkerrors.Wrap(sdkerrors.ErrOutOfGas, log) + err = cosmoserrors.Wrap(sdkerrors.ErrOutOfGas, log) default: panic(r) } diff --git a/app/app.go b/app/app.go index c7c749cda3..63b889fa9c 100644 --- a/app/app.go +++ b/app/app.go @@ -6,6 +6,7 @@ import ( "os" "time" + cosmoserrors "cosmossdk.io/errors" "github.com/gorilla/mux" "github.com/rakyll/statik/fs" "github.com/spf13/cast" @@ -776,10 +777,10 @@ func initParamsKeeper(appCodec codec.BinaryCodec, legacyAmino *codec.LegacyAmino // VerifyAddressFormat verifies the address is compatible with ethereum func VerifyAddressFormat(bz []byte) error { if len(bz) == 0 { - return sdkerrors.Wrap(sdkerrors.ErrUnknownAddress, "invalid address; cannot be empty") + return cosmoserrors.Wrap(sdkerrors.ErrUnknownAddress, "invalid address; cannot be empty") } if len(bz) != AddrLen { - return sdkerrors.Wrapf( + return cosmoserrors.Wrapf( sdkerrors.ErrUnknownAddress, "invalid address length; got: %d, expect: %d", len(bz), AddrLen, ) diff --git a/x/crosschain/keeper/msg_server_gas_price_voter.go b/x/crosschain/keeper/msg_server_gas_price_voter.go index 2c56b3f266..db38b4c8f4 100644 --- a/x/crosschain/keeper/msg_server_gas_price_voter.go +++ b/x/crosschain/keeper/msg_server_gas_price_voter.go @@ -7,10 +7,10 @@ import ( "sort" "strconv" + cosmoserrors "cosmossdk.io/errors" "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/zeta-chain/zetacore/x/crosschain/types" observertypes "github.com/zeta-chain/zetacore/x/observer/types" ) @@ -31,7 +31,7 @@ func (k msgServer) GasPriceVoter(goCtx context.Context, msg *types.MsgGasPriceVo return nil, observertypes.ErrNotAuthorizedPolicy } if chain == nil { - return nil, sdkerrors.Wrap(types.ErrUnsupportedChain, fmt.Sprintf("ChainID : %d ", msg.ChainId)) + return nil, cosmoserrors.Wrap(types.ErrUnsupportedChain, fmt.Sprintf("ChainID : %d ", msg.ChainId)) } gasPrice, isFound := k.GetGasPrice(ctx, chain.ChainId) diff --git a/x/crosschain/keeper/msg_server_vote_inbound_tx.go b/x/crosschain/keeper/msg_server_vote_inbound_tx.go index ef98c85bf8..45af5ba0f6 100644 --- a/x/crosschain/keeper/msg_server_vote_inbound_tx.go +++ b/x/crosschain/keeper/msg_server_vote_inbound_tx.go @@ -4,9 +4,9 @@ import ( "context" "fmt" + cosmoserrors "cosmossdk.io/errors" errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/zeta-chain/zetacore/common" "github.com/zeta-chain/zetacore/x/crosschain/types" observerKeeper "github.com/zeta-chain/zetacore/x/observer/keeper" @@ -67,11 +67,11 @@ func (k msgServer) VoteOnObservedInboundTx(goCtx context.Context, msg *types.Msg // GetChainFromChainID makes sure we are getting only supported chains , if a chain support has been turned on using gov proposal, this function returns nil observationChain := k.zetaObserverKeeper.GetSupportedChainFromChainID(ctx, msg.SenderChainId) if observationChain == nil { - return nil, sdkerrors.Wrap(types.ErrUnsupportedChain, fmt.Sprintf("ChainID %d, Observation %s", msg.SenderChainId, observationType.String())) + return nil, cosmoserrors.Wrap(types.ErrUnsupportedChain, fmt.Sprintf("ChainID %d, Observation %s", msg.SenderChainId, observationType.String())) } receiverChain := k.zetaObserverKeeper.GetSupportedChainFromChainID(ctx, msg.ReceiverChain) if receiverChain == nil { - return nil, sdkerrors.Wrap(types.ErrUnsupportedChain, fmt.Sprintf("ChainID %d, Observation %s", msg.ReceiverChain, observationType.String())) + return nil, cosmoserrors.Wrap(types.ErrUnsupportedChain, fmt.Sprintf("ChainID %d, Observation %s", msg.ReceiverChain, observationType.String())) } tssPub := "" tss, tssFound := k.zetaObserverKeeper.GetTSS(ctx) diff --git a/x/crosschain/keeper/msg_server_vote_outbound_tx.go b/x/crosschain/keeper/msg_server_vote_outbound_tx.go index 17319d1f8a..72555df8cd 100644 --- a/x/crosschain/keeper/msg_server_vote_outbound_tx.go +++ b/x/crosschain/keeper/msg_server_vote_outbound_tx.go @@ -6,6 +6,7 @@ import ( "fmt" "math/big" + cosmoserrors "cosmossdk.io/errors" "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" @@ -81,11 +82,11 @@ func (k msgServer) VoteOnObservedOutboundTx(goCtx context.Context, msg *types.Ms // Check if CCTX exists cctx, found := k.GetCrossChainTx(ctx, msg.CctxHash) if !found { - return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf("CCTX %s does not exist", msg.CctxHash)) + return nil, cosmoserrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf("CCTX %s does not exist", msg.CctxHash)) } if cctx.GetCurrentOutTxParam().OutboundTxTssNonce != msg.OutTxTssNonce { - return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf("OutTxTssNonce %d does not match CCTX OutTxTssNonce %d", msg.OutTxTssNonce, cctx.GetCurrentOutTxParam().OutboundTxTssNonce)) + return nil, cosmoserrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf("OutTxTssNonce %d does not match CCTX OutTxTssNonce %d", msg.OutTxTssNonce, cctx.GetCurrentOutTxParam().OutboundTxTssNonce)) } ballotIndex := msg.Digest() @@ -117,7 +118,7 @@ func (k msgServer) VoteOnObservedOutboundTx(goCtx context.Context, msg *types.Ms log.Error().Msgf("VoteOnObservedOutboundTx: Mint mismatch: %s value received vs %s cctx amount", msg.ValueReceived, cctx.GetCurrentOutTxParam().Amount) - return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf("ValueReceived %s does not match sent value %s", msg.ValueReceived, cctx.GetCurrentOutTxParam().Amount)) + return nil, cosmoserrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf("ValueReceived %s does not match sent value %s", msg.ValueReceived, cctx.GetCurrentOutTxParam().Amount)) } } diff --git a/x/crosschain/types/message_add_to_out_tx_tracker.go b/x/crosschain/types/message_add_to_out_tx_tracker.go index 06716762a1..44d7b7f3e0 100644 --- a/x/crosschain/types/message_add_to_out_tx_tracker.go +++ b/x/crosschain/types/message_add_to_out_tx_tracker.go @@ -1,6 +1,7 @@ package types import ( + cosmoserrors "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/zeta-chain/zetacore/common" @@ -54,10 +55,10 @@ func (msg *MsgAddToOutTxTracker) GetSignBytes() []byte { func (msg *MsgAddToOutTxTracker) ValidateBasic() error { _, err := sdk.AccAddressFromBech32(msg.Creator) if err != nil { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err) + return cosmoserrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err) } if msg.ChainId < 0 { - return sdkerrors.Wrapf(ErrInvalidChainID, "chain id (%d)", msg.ChainId) + return cosmoserrors.Wrapf(ErrInvalidChainID, "chain id (%d)", msg.ChainId) } return nil } diff --git a/x/crosschain/types/message_gas_price_voter.go b/x/crosschain/types/message_gas_price_voter.go index 70e4738f91..a42d9b692e 100644 --- a/x/crosschain/types/message_gas_price_voter.go +++ b/x/crosschain/types/message_gas_price_voter.go @@ -1,6 +1,7 @@ package types import ( + cosmoserrors "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/zeta-chain/zetacore/common" @@ -42,10 +43,10 @@ func (msg *MsgGasPriceVoter) GetSignBytes() []byte { func (msg *MsgGasPriceVoter) ValidateBasic() error { _, err := sdk.AccAddressFromBech32(msg.Creator) if err != nil { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err) + return cosmoserrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err) } if msg.ChainId < 0 { - return sdkerrors.Wrapf(ErrInvalidChainID, "chain id (%d)", msg.ChainId) + return cosmoserrors.Wrapf(ErrInvalidChainID, "chain id (%d)", msg.ChainId) } return nil } diff --git a/x/crosschain/types/message_remove_from_out_tx_tracker.go b/x/crosschain/types/message_remove_from_out_tx_tracker.go index d1f3bca387..145d20a76c 100644 --- a/x/crosschain/types/message_remove_from_out_tx_tracker.go +++ b/x/crosschain/types/message_remove_from_out_tx_tracker.go @@ -1,6 +1,7 @@ package types import ( + cosmoserrors "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) @@ -41,10 +42,10 @@ func (msg *MsgRemoveFromOutTxTracker) GetSignBytes() []byte { func (msg *MsgRemoveFromOutTxTracker) ValidateBasic() error { _, err := sdk.AccAddressFromBech32(msg.Creator) if err != nil { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err) + return cosmoserrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err) } if msg.ChainId < 0 { - return sdkerrors.Wrapf(ErrInvalidChainID, "chain id (%d)", msg.ChainId) + return cosmoserrors.Wrapf(ErrInvalidChainID, "chain id (%d)", msg.ChainId) } return nil } diff --git a/x/crosschain/types/message_tss_voter.go b/x/crosschain/types/message_tss_voter.go index 683f792064..d88147ce5a 100644 --- a/x/crosschain/types/message_tss_voter.go +++ b/x/crosschain/types/message_tss_voter.go @@ -3,6 +3,7 @@ package types import ( "fmt" + cosmoserrors "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/zeta-chain/zetacore/common" @@ -43,7 +44,7 @@ func (msg *MsgCreateTSSVoter) GetSignBytes() []byte { func (msg *MsgCreateTSSVoter) ValidateBasic() error { _, err := sdk.AccAddressFromBech32(msg.Creator) if err != nil { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err) + return cosmoserrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err) } return nil } diff --git a/x/crosschain/types/message_vote_on_observed_inbound_tx.go b/x/crosschain/types/message_vote_on_observed_inbound_tx.go index b94b0567a4..251a8a8077 100644 --- a/x/crosschain/types/message_vote_on_observed_inbound_tx.go +++ b/x/crosschain/types/message_vote_on_observed_inbound_tx.go @@ -1,6 +1,7 @@ package types import ( + cosmoserrors "cosmossdk.io/errors" "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" @@ -74,19 +75,19 @@ func (msg *MsgVoteOnObservedInboundTx) GetSignBytes() []byte { func (msg *MsgVoteOnObservedInboundTx) ValidateBasic() error { _, err := sdk.AccAddressFromBech32(msg.Creator) if err != nil { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s): %s", err, msg.Creator) + return cosmoserrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s): %s", err, msg.Creator) } if msg.SenderChainId < 0 { - return sdkerrors.Wrapf(ErrInvalidChainID, "chain id (%d)", msg.SenderChainId) + return cosmoserrors.Wrapf(ErrInvalidChainID, "chain id (%d)", msg.SenderChainId) } if msg.ReceiverChain < 0 { - return sdkerrors.Wrapf(ErrInvalidChainID, "chain id (%d)", msg.ReceiverChain) + return cosmoserrors.Wrapf(ErrInvalidChainID, "chain id (%d)", msg.ReceiverChain) } if len(msg.Message) > MaxMessageLength { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, "message is too long: %d", len(msg.Message)) + return cosmoserrors.Wrapf(sdkerrors.ErrInvalidRequest, "message is too long: %d", len(msg.Message)) } return nil diff --git a/x/crosschain/types/message_vote_on_observed_outbound_tx.go b/x/crosschain/types/message_vote_on_observed_outbound_tx.go index bf940f6984..12d0276847 100644 --- a/x/crosschain/types/message_vote_on_observed_outbound_tx.go +++ b/x/crosschain/types/message_vote_on_observed_outbound_tx.go @@ -1,6 +1,7 @@ package types import ( + cosmoserrors "cosmossdk.io/errors" "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" @@ -64,10 +65,10 @@ func (msg *MsgVoteOnObservedOutboundTx) GetSignBytes() []byte { func (msg *MsgVoteOnObservedOutboundTx) ValidateBasic() error { _, err := sdk.AccAddressFromBech32(msg.Creator) if err != nil { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err) + return cosmoserrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err) } if msg.OutTxChain < 0 { - return sdkerrors.Wrapf(ErrInvalidChainID, "chain id (%d)", msg.OutTxChain) + return cosmoserrors.Wrapf(ErrInvalidChainID, "chain id (%d)", msg.OutTxChain) } return nil diff --git a/x/crosschain/types/message_whitelist_erc20.go b/x/crosschain/types/message_whitelist_erc20.go index a2cfd069e0..e2811287b7 100644 --- a/x/crosschain/types/message_whitelist_erc20.go +++ b/x/crosschain/types/message_whitelist_erc20.go @@ -1,6 +1,7 @@ package types import ( + cosmoserrors "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ethcommon "github.com/ethereum/go-ethereum/common" @@ -49,17 +50,17 @@ func (msg *MsgWhitelistERC20) GetSignBytes() []byte { func (msg *MsgWhitelistERC20) ValidateBasic() error { _, err := sdk.AccAddressFromBech32(msg.Creator) if err != nil { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err) + return cosmoserrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err) } // check if the system contract address is valid if ethcommon.HexToAddress(msg.Erc20Address) == (ethcommon.Address{}) { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid ERC20 contract address (%s)", msg.Erc20Address) + return cosmoserrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid ERC20 contract address (%s)", msg.Erc20Address) } if msg.Decimals > 128 { - return sdkerrors.Wrapf(types.ErrInvalidDecimals, "invalid decimals (%d)", msg.Decimals) + return cosmoserrors.Wrapf(types.ErrInvalidDecimals, "invalid decimals (%d)", msg.Decimals) } if msg.GasLimit <= 0 { - return sdkerrors.Wrapf(types.ErrInvalidGasLimit, "invalid gas limit (%d)", msg.GasLimit) + return cosmoserrors.Wrapf(types.ErrInvalidGasLimit, "invalid gas limit (%d)", msg.GasLimit) } return nil } diff --git a/x/fungible/keeper/evm.go b/x/fungible/keeper/evm.go index 53fe3c9859..04251028f0 100644 --- a/x/fungible/keeper/evm.go +++ b/x/fungible/keeper/evm.go @@ -432,7 +432,7 @@ func (k Keeper) QueryZRC20Data( zrc4ABI, err := zrc20.ZRC20MetaData.GetAbi() if err != nil { - return types.ZRC20Data{}, sdkerrors.Wrapf( + return types.ZRC20Data{}, cosmoserrors.Wrapf( types.ErrABIUnpack, "failed to get ABI: %s", err.Error(), ) } diff --git a/x/fungible/keeper/gas_coin_and_pool.go b/x/fungible/keeper/gas_coin_and_pool.go index 7540b90f69..7a847f3906 100644 --- a/x/fungible/keeper/gas_coin_and_pool.go +++ b/x/fungible/keeper/gas_coin_and_pool.go @@ -4,8 +4,8 @@ import ( "fmt" "math/big" + cosmoserrors "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ethcommon "github.com/ethereum/go-ethereum/common" systemcontract "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/systemcontract.sol" zrc20 "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/zrc20.sol" @@ -50,7 +50,7 @@ func (k Keeper) SetupChainGasCoinAndPool( zrc20Addr, err := k.DeployZRC20Contract(ctx, name, symbol, decimals, chain.ChainId, common.CoinType_Gas, "", transferGasLimit) if err != nil { - return ethcommon.Address{}, sdkerrors.Wrapf(err, "failed to DeployZRC20Contract") + return ethcommon.Address{}, cosmoserrors.Wrapf(err, "failed to DeployZRC20Contract") } ctx.EventManager().EmitEvent( sdk.NewEvent(sdk.EventTypeMessage, @@ -76,33 +76,33 @@ func (k Keeper) SetupChainGasCoinAndPool( } systemContractAddress, err := k.GetSystemContractAddress(ctx) if err != nil || systemContractAddress == (ethcommon.Address{}) { - return ethcommon.Address{}, sdkerrors.Wrapf(types.ErrContractNotFound, "system contract address invalid: %s", systemContractAddress) + return ethcommon.Address{}, cosmoserrors.Wrapf(types.ErrContractNotFound, "system contract address invalid: %s", systemContractAddress) } systemABI, err := systemcontract.SystemContractMetaData.GetAbi() if err != nil { - return ethcommon.Address{}, sdkerrors.Wrapf(err, "failed to get system contract abi") + return ethcommon.Address{}, cosmoserrors.Wrapf(err, "failed to get system contract abi") } _, err = k.CallEVM(ctx, *systemABI, types.ModuleAddressEVM, systemContractAddress, BigIntZero, nil, true, false, "setGasZetaPool", big.NewInt(chain.ChainId), zrc20Addr) if err != nil { - return ethcommon.Address{}, sdkerrors.Wrapf(err, "failed to CallEVM method setGasZetaPool(%d, %s)", chain.ChainId, zrc20Addr.String()) + return ethcommon.Address{}, cosmoserrors.Wrapf(err, "failed to CallEVM method setGasZetaPool(%d, %s)", chain.ChainId, zrc20Addr.String()) } // setup uniswap v2 pools gas/zeta routerAddress, err := k.GetUniswapV2Router02Address(ctx) if err != nil { - return ethcommon.Address{}, sdkerrors.Wrapf(err, "failed to GetUniswapV2Router02Address") + return ethcommon.Address{}, cosmoserrors.Wrapf(err, "failed to GetUniswapV2Router02Address") } routerABI, err := uniswapv2router02.UniswapV2Router02MetaData.GetAbi() if err != nil { - return ethcommon.Address{}, sdkerrors.Wrapf(err, "failed to get uniswap router abi") + return ethcommon.Address{}, cosmoserrors.Wrapf(err, "failed to get uniswap router abi") } ZRC20ABI, err := zrc20.ZRC20MetaData.GetAbi() if err != nil { - return ethcommon.Address{}, sdkerrors.Wrapf(err, "failed to GetAbi zrc20") + return ethcommon.Address{}, cosmoserrors.Wrapf(err, "failed to GetAbi zrc20") } _, err = k.CallEVM(ctx, *ZRC20ABI, types.ModuleAddressEVM, zrc20Addr, BigIntZero, nil, true, false, "approve", routerAddress, amount) if err != nil { - return ethcommon.Address{}, sdkerrors.Wrapf(err, "failed to CallEVM method approve(%s, %d)", routerAddress.String(), amount) + return ethcommon.Address{}, cosmoserrors.Wrapf(err, "failed to CallEVM method approve(%s, %d)", routerAddress.String(), amount) } //function addLiquidityETH( @@ -116,14 +116,14 @@ func (k Keeper) SetupChainGasCoinAndPool( res, err := k.CallEVM(ctx, *routerABI, types.ModuleAddressEVM, routerAddress, amountAZeta, big.NewInt(5_000_000), true, false, "addLiquidityETH", zrc20Addr, amount, BigIntZero, BigIntZero, types.ModuleAddressEVM, amountAZeta) if err != nil { - return ethcommon.Address{}, sdkerrors.Wrapf(err, "failed to CallEVM method addLiquidityETH(%s, %s)", zrc20Addr.String(), amountAZeta.String()) + return ethcommon.Address{}, cosmoserrors.Wrapf(err, "failed to CallEVM method addLiquidityETH(%s, %s)", zrc20Addr.String(), amountAZeta.String()) } AmountToken := new(*big.Int) AmountETH := new(*big.Int) Liquidity := new(*big.Int) err = routerABI.UnpackIntoInterface(&[]interface{}{AmountToken, AmountETH, Liquidity}, "addLiquidityETH", res.Ret) if err != nil { - return ethcommon.Address{}, sdkerrors.Wrapf(err, "failed to UnpackIntoInterface addLiquidityETH") + return ethcommon.Address{}, cosmoserrors.Wrapf(err, "failed to UnpackIntoInterface addLiquidityETH") } ctx.EventManager().EmitEvent( diff --git a/x/fungible/keeper/gas_price.go b/x/fungible/keeper/gas_price.go index 58ca702b69..68acdc98b9 100644 --- a/x/fungible/keeper/gas_price.go +++ b/x/fungible/keeper/gas_price.go @@ -3,9 +3,10 @@ package keeper import ( "math/big" + cosmoserrors "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/ethereum/go-ethereum/common" + ethcommon "github.com/ethereum/go-ethereum/common" systemcontract "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/systemcontract.sol" "github.com/zeta-chain/zetacore/x/fungible/types" ) @@ -13,26 +14,26 @@ import ( // SetGasPrice sets gas price on the system contract in zEVM; return the gasUsed and error code func (k Keeper) SetGasPrice(ctx sdk.Context, chainid *big.Int, gasPrice *big.Int) (uint64, error) { if gasPrice == nil { - return 0, sdkerrors.Wrapf(types.ErrNilGasPrice, "gas price param should be set") + return 0, cosmoserrors.Wrapf(types.ErrNilGasPrice, "gas price param should be set") } system, found := k.GetSystemContract(ctx) if !found { - return 0, sdkerrors.Wrapf(types.ErrContractNotFound, "system contract state variable not found") + return 0, cosmoserrors.Wrapf(types.ErrContractNotFound, "system contract state variable not found") } oracle := common.HexToAddress(system.SystemContract) - if oracle == common.HexToAddress("0x0") { - return 0, sdkerrors.Wrapf(types.ErrContractNotFound, "system contract invalid address") + if oracle == (ethcommon.Address{}) { + return 0, cosmoserrors.Wrapf(types.ErrContractNotFound, "system contract invalid address") } abi, err := systemcontract.SystemContractMetaData.GetAbi() if err != nil { - return 0, sdkerrors.Wrapf(types.ErrABIGet, "SystemContractMetaData") + return 0, cosmoserrors.Wrapf(types.ErrABIGet, "SystemContractMetaData") } res, err := k.CallEVM(ctx, *abi, types.ModuleAddressEVM, oracle, BigIntZero, big.NewInt(50_000), true, false, "setGasPrice", chainid, gasPrice) if err != nil { - return 0, sdkerrors.Wrapf(types.ErrContractCall, err.Error()) + return 0, cosmoserrors.Wrapf(types.ErrContractCall, err.Error()) } if res.Failed() { - return res.GasUsed, sdkerrors.Wrapf(types.ErrContractCall, "setGasPrice tx failed") + return res.GasUsed, cosmoserrors.Wrapf(types.ErrContractCall, "setGasPrice tx failed") } return res.GasUsed, nil @@ -41,22 +42,22 @@ func (k Keeper) SetGasPrice(ctx sdk.Context, chainid *big.Int, gasPrice *big.Int func (k Keeper) SetGasCoin(ctx sdk.Context, chainid *big.Int, address common.Address) error { system, found := k.GetSystemContract(ctx) if !found { - return sdkerrors.Wrapf(types.ErrContractNotFound, "system contract state variable not found") + return cosmoserrors.Wrapf(types.ErrContractNotFound, "system contract state variable not found") } oracle := common.HexToAddress(system.SystemContract) - if oracle == common.HexToAddress("0x0") { - return sdkerrors.Wrapf(types.ErrContractNotFound, "system contract invalid address") + if oracle == (ethcommon.Address{}) { + return cosmoserrors.Wrapf(types.ErrContractNotFound, "system contract invalid address") } abi, err := systemcontract.SystemContractMetaData.GetAbi() if err != nil { - return sdkerrors.Wrapf(types.ErrABIGet, "SystemContractMetaData") + return cosmoserrors.Wrapf(types.ErrABIGet, "SystemContractMetaData") } res, err := k.CallEVM(ctx, *abi, types.ModuleAddressEVM, oracle, BigIntZero, nil, true, false, "setGasCoinZRC20", chainid, address) if err != nil { - return sdkerrors.Wrapf(types.ErrContractCall, err.Error()) + return cosmoserrors.Wrapf(types.ErrContractCall, err.Error()) } if res.Failed() { - return sdkerrors.Wrapf(types.ErrContractCall, "setGasCoinZRC20 tx failed") + return cosmoserrors.Wrapf(types.ErrContractCall, "setGasCoinZRC20 tx failed") } return nil @@ -65,22 +66,22 @@ func (k Keeper) SetGasCoin(ctx sdk.Context, chainid *big.Int, address common.Add func (k Keeper) SetGasZetaPool(ctx sdk.Context, chainid *big.Int, pool common.Address) error { system, found := k.GetSystemContract(ctx) if !found { - return sdkerrors.Wrapf(types.ErrContractNotFound, "system contract state variable not found") + return cosmoserrors.Wrapf(types.ErrContractNotFound, "system contract state variable not found") } oracle := common.HexToAddress(system.SystemContract) - if oracle == common.HexToAddress("0x0") { - return sdkerrors.Wrapf(types.ErrContractNotFound, "system contract invalid address") + if oracle == (ethcommon.Address{}) { + return cosmoserrors.Wrapf(types.ErrContractNotFound, "system contract invalid address") } abi, err := systemcontract.SystemContractMetaData.GetAbi() if err != nil { - return sdkerrors.Wrapf(types.ErrABIGet, "SystemContractMetaData") + return cosmoserrors.Wrapf(types.ErrABIGet, "SystemContractMetaData") } res, err := k.CallEVM(ctx, *abi, types.ModuleAddressEVM, oracle, BigIntZero, nil, true, false, "setGasZetaPool", chainid, pool) if err != nil { - return sdkerrors.Wrapf(types.ErrContractCall, err.Error()) + return cosmoserrors.Wrapf(types.ErrContractCall, err.Error()) } if res.Failed() { - return sdkerrors.Wrapf(types.ErrContractCall, "setGasZetaPool tx failed") + return cosmoserrors.Wrapf(types.ErrContractCall, "setGasZetaPool tx failed") } return nil diff --git a/x/fungible/keeper/msg_server_deploy_fungible_coin_zrc20.go b/x/fungible/keeper/msg_server_deploy_fungible_coin_zrc20.go index 1bd16ce1a4..a490f060c6 100644 --- a/x/fungible/keeper/msg_server_deploy_fungible_coin_zrc20.go +++ b/x/fungible/keeper/msg_server_deploy_fungible_coin_zrc20.go @@ -4,6 +4,7 @@ import ( "context" "math/big" + cosmoserrors "cosmossdk.io/errors" "github.com/ethereum/go-ethereum/common" sdk "github.com/cosmos/cosmos-sdk/types" @@ -42,14 +43,14 @@ func (k msgServer) DeployFungibleCoinZRC20(goCtx context.Context, msg *types.Msg } if msg.Creator != k.observerKeeper.GetParams(ctx).GetAdminPolicyAccount(zetaObserverTypes.Policy_Type_group2) { - return nil, sdkerrors.Wrap(sdkerrors.ErrUnauthorized, "Deploy can only be executed by the correct policy account") + return nil, cosmoserrors.Wrap(sdkerrors.ErrUnauthorized, "Deploy can only be executed by the correct policy account") } if msg.CoinType == zetacommon.CoinType_Gas { // #nosec G701 always in range address, err = k.SetupChainGasCoinAndPool(ctx, msg.ForeignChainId, msg.Name, msg.Symbol, uint8(msg.Decimals), big.NewInt(msg.GasLimit)) if err != nil { - return nil, sdkerrors.Wrapf(err, "failed to setupChainGasCoinAndPool") + return nil, cosmoserrors.Wrapf(err, "failed to setupChainGasCoinAndPool") } } else { // #nosec G701 always in range @@ -74,7 +75,7 @@ func (k msgServer) DeployFungibleCoinZRC20(goCtx context.Context, msg *types.Msg }, ) if err != nil { - return nil, sdkerrors.Wrapf(err, "failed to emit event") + return nil, cosmoserrors.Wrapf(err, "failed to emit event") } return &types.MsgDeployFungibleCoinZRC20Response{ diff --git a/x/fungible/keeper/msg_server_remove_foreign_coin.go b/x/fungible/keeper/msg_server_remove_foreign_coin.go index ccab6eb9e2..a66f02a9c1 100644 --- a/x/fungible/keeper/msg_server_remove_foreign_coin.go +++ b/x/fungible/keeper/msg_server_remove_foreign_coin.go @@ -3,6 +3,7 @@ package keeper import ( "context" + cosmoserrors "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/zeta-chain/zetacore/x/fungible/types" @@ -16,12 +17,12 @@ import ( func (k msgServer) RemoveForeignCoin(goCtx context.Context, msg *types.MsgRemoveForeignCoin) (*types.MsgRemoveForeignCoinResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) if msg.Creator != k.observerKeeper.GetParams(ctx).GetAdminPolicyAccount(zetaObserverTypes.Policy_Type_group2) { - return nil, sdkerrors.Wrap(sdkerrors.ErrUnauthorized, "Removal can only be executed by the correct policy account") + return nil, cosmoserrors.Wrap(sdkerrors.ErrUnauthorized, "Removal can only be executed by the correct policy account") } index := msg.Name _, found := k.GetForeignCoins(ctx, index) if !found { - return nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, "foreign coin not found") + return nil, cosmoserrors.Wrapf(sdkerrors.ErrInvalidRequest, "foreign coin not found") } k.RemoveForeignCoins(ctx, index) return &types.MsgRemoveForeignCoinResponse{}, nil diff --git a/x/fungible/keeper/msg_server_update_system_contract.go b/x/fungible/keeper/msg_server_update_system_contract.go index a61ff78e97..1a5ce6dbc9 100644 --- a/x/fungible/keeper/msg_server_update_system_contract.go +++ b/x/fungible/keeper/msg_server_update_system_contract.go @@ -4,6 +4,7 @@ import ( "context" "math/big" + cosmoserrors "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ethcommon "github.com/ethereum/go-ethereum/common" @@ -18,21 +19,21 @@ import ( func (k msgServer) UpdateSystemContract(goCtx context.Context, msg *types.MsgUpdateSystemContract) (*types.MsgUpdateSystemContractResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) if msg.Creator != k.observerKeeper.GetParams(ctx).GetAdminPolicyAccount(zetaObserverTypes.Policy_Type_group2) { - return nil, sdkerrors.Wrap(sdkerrors.ErrUnauthorized, "Deploy can only be executed by the correct policy account") + return nil, cosmoserrors.Wrap(sdkerrors.ErrUnauthorized, "Deploy can only be executed by the correct policy account") } newSystemContractAddr := ethcommon.HexToAddress(msg.NewSystemContractAddress) if newSystemContractAddr == (ethcommon.Address{}) { - return nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid system contract address (%s)", msg.NewSystemContractAddress) + return nil, cosmoserrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid system contract address (%s)", msg.NewSystemContractAddress) } // update contracts zrc20ABI, err := zrc20.ZRC20MetaData.GetAbi() if err != nil { - return nil, sdkerrors.Wrapf(types.ErrABIGet, "failed to get zrc20 abi") + return nil, cosmoserrors.Wrapf(types.ErrABIGet, "failed to get zrc20 abi") } sysABI, err := systemcontract.SystemContractMetaData.GetAbi() if err != nil { - return nil, sdkerrors.Wrapf(types.ErrABIGet, "failed to get system contract abi") + return nil, cosmoserrors.Wrapf(types.ErrABIGet, "failed to get system contract abi") } foreignCoins := k.GetAllForeignCoins(ctx) tmpCtx, commit := ctx.CacheContext() @@ -44,16 +45,16 @@ func (k msgServer) UpdateSystemContract(goCtx context.Context, msg *types.MsgUpd } _, err = k.CallEVM(tmpCtx, *zrc20ABI, types.ModuleAddressEVM, zrc20Addr, BigIntZero, nil, true, false, "updateSystemContractAddress", newSystemContractAddr) if err != nil { - return nil, sdkerrors.Wrapf(types.ErrContractCall, "failed to call zrc20 contract method updateSystemContractAddress (%s)", err.Error()) + return nil, cosmoserrors.Wrapf(types.ErrContractCall, "failed to call zrc20 contract method updateSystemContractAddress (%s)", err.Error()) } if fcoin.CoinType == common.CoinType_Gas { _, err = k.CallEVM(tmpCtx, *sysABI, types.ModuleAddressEVM, newSystemContractAddr, BigIntZero, nil, true, false, "setGasCoinZRC20", big.NewInt(fcoin.ForeignChainId), zrc20Addr) if err != nil { - return nil, sdkerrors.Wrapf(types.ErrContractCall, "failed to call system contract method setGasCoinZRC20 (%s)", err.Error()) + return nil, cosmoserrors.Wrapf(types.ErrContractCall, "failed to call system contract method setGasCoinZRC20 (%s)", err.Error()) } _, err = k.CallEVM(tmpCtx, *sysABI, types.ModuleAddressEVM, newSystemContractAddr, BigIntZero, nil, true, false, "setGasZetaPool", big.NewInt(fcoin.ForeignChainId), zrc20Addr) if err != nil { - return nil, sdkerrors.Wrapf(types.ErrContractCall, "failed to call system contract method setGasZetaPool (%s)", err.Error()) + return nil, cosmoserrors.Wrapf(types.ErrContractCall, "failed to call system contract method setGasZetaPool (%s)", err.Error()) } } } @@ -75,7 +76,7 @@ func (k msgServer) UpdateSystemContract(goCtx context.Context, msg *types.MsgUpd ) if err != nil { k.Logger(ctx).Error("failed to emit event", "error", err.Error()) - return nil, sdkerrors.Wrapf(types.ErrEmitEvent, "failed to emit event (%s)", err.Error()) + return nil, cosmoserrors.Wrapf(types.ErrEmitEvent, "failed to emit event (%s)", err.Error()) } commit() return &types.MsgUpdateSystemContractResponse{}, nil diff --git a/x/fungible/types/message_deploy_fungible_coin_zrc20.go b/x/fungible/types/message_deploy_fungible_coin_zrc20.go index 6b23365001..1f695e63cb 100644 --- a/x/fungible/types/message_deploy_fungible_coin_zrc20.go +++ b/x/fungible/types/message_deploy_fungible_coin_zrc20.go @@ -1,6 +1,7 @@ package types import ( + cosmoserrors "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/zeta-chain/zetacore/common" @@ -47,14 +48,14 @@ func (msg *MsgDeployFungibleCoinZRC20) GetSignBytes() []byte { func (msg *MsgDeployFungibleCoinZRC20) ValidateBasic() error { _, err := sdk.AccAddressFromBech32(msg.Creator) if err != nil { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err) + return cosmoserrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err) } if msg.GasLimit < 0 { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidGasLimit, "invalid gas limit") + return cosmoserrors.Wrapf(sdkerrors.ErrInvalidGasLimit, "invalid gas limit") } if msg.Decimals > 77 { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, "decimals must be less than 78") + return cosmoserrors.Wrapf(sdkerrors.ErrInvalidRequest, "decimals must be less than 78") } return nil } diff --git a/x/fungible/types/message_deploy_fungible_coin_zrc20_test.go b/x/fungible/types/message_deploy_fungible_coin_zrc20_test.go index e107af7781..12e6e0750e 100644 --- a/x/fungible/types/message_deploy_fungible_coin_zrc20_test.go +++ b/x/fungible/types/message_deploy_fungible_coin_zrc20_test.go @@ -3,6 +3,7 @@ package types_test import ( "testing" + cosmoserrors "cosmossdk.io/errors" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/stretchr/testify/require" "github.com/zeta-chain/zetacore/testutil/sample" @@ -36,7 +37,7 @@ func TestMsgDeployFungibleCoinZRC4_ValidateBasic(t *testing.T) { Creator: sample.AccAddress(), Decimals: 78, }, - err: sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, "decimals must be less than 78"), + err: cosmoserrors.Wrapf(sdkerrors.ErrInvalidRequest, "decimals must be less than 78"), }, { name: "valid message", diff --git a/x/fungible/types/message_deploy_system_contracts.go b/x/fungible/types/message_deploy_system_contracts.go index 579df47a25..4c4515e856 100644 --- a/x/fungible/types/message_deploy_system_contracts.go +++ b/x/fungible/types/message_deploy_system_contracts.go @@ -1,6 +1,7 @@ package types import ( + cosmoserrors "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) @@ -39,7 +40,7 @@ func (msg *MsgDeploySystemContracts) GetSignBytes() []byte { func (msg *MsgDeploySystemContracts) ValidateBasic() error { _, err := sdk.AccAddressFromBech32(msg.Creator) if err != nil { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err) + return cosmoserrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err) } return nil } diff --git a/x/fungible/types/message_remove_foreign_coin.go b/x/fungible/types/message_remove_foreign_coin.go index 999b3364b1..0c7282dc4a 100644 --- a/x/fungible/types/message_remove_foreign_coin.go +++ b/x/fungible/types/message_remove_foreign_coin.go @@ -1,6 +1,7 @@ package types import ( + cosmoserrors "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) @@ -40,7 +41,7 @@ func (msg *MsgRemoveForeignCoin) GetSignBytes() []byte { func (msg *MsgRemoveForeignCoin) ValidateBasic() error { _, err := sdk.AccAddressFromBech32(msg.Creator) if err != nil { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err) + return cosmoserrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err) } return nil } diff --git a/x/fungible/types/message_update_system_contract.go b/x/fungible/types/message_update_system_contract.go index b6879f2ff6..2a347baada 100644 --- a/x/fungible/types/message_update_system_contract.go +++ b/x/fungible/types/message_update_system_contract.go @@ -1,6 +1,7 @@ package types import ( + cosmoserrors "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ethcommon "github.com/ethereum/go-ethereum/common" @@ -41,11 +42,11 @@ func (msg *MsgUpdateSystemContract) GetSignBytes() []byte { func (msg *MsgUpdateSystemContract) ValidateBasic() error { _, err := sdk.AccAddressFromBech32(msg.Creator) if err != nil { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err) + return cosmoserrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err) } // check if the system contract address is valid if ethcommon.HexToAddress(msg.NewSystemContractAddress) == (ethcommon.Address{}) { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid system contract address (%s)", msg.NewSystemContractAddress) + return cosmoserrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid system contract address (%s)", msg.NewSystemContractAddress) } return nil diff --git a/x/observer/keeper/msg_server_add_blame_vote.go b/x/observer/keeper/msg_server_add_blame_vote.go index 40f2fe54b0..6ff74146b6 100644 --- a/x/observer/keeper/msg_server_add_blame_vote.go +++ b/x/observer/keeper/msg_server_add_blame_vote.go @@ -4,8 +4,8 @@ import ( "context" "fmt" + cosmoserrors "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" crosschainTypes "github.com/zeta-chain/zetacore/x/crosschain/types" "github.com/zeta-chain/zetacore/x/observer/types" ) @@ -16,7 +16,7 @@ func (k msgServer) AddBlameVote(goCtx context.Context, vote *types.MsgAddBlameVo // GetChainFromChainID makes sure we are getting only supported chains , if a chain support has been turned on using gov proposal, this function returns nil observationChain := k.GetSupportedChainFromChainID(ctx, vote.ChainId) if observationChain == nil { - return nil, sdkerrors.Wrap(crosschainTypes.ErrUnsupportedChain, fmt.Sprintf("ChainID %d, Blame vote", vote.ChainId)) + return nil, cosmoserrors.Wrap(crosschainTypes.ErrUnsupportedChain, fmt.Sprintf("ChainID %d, Blame vote", vote.ChainId)) } // IsAuthorized does various checks against the list of observer mappers if ok := k.IsAuthorized(ctx, vote.Creator); !ok { diff --git a/x/observer/types/message_add_blame_vote.go b/x/observer/types/message_add_blame_vote.go index 1d9422f757..d10411f026 100644 --- a/x/observer/types/message_add_blame_vote.go +++ b/x/observer/types/message_add_blame_vote.go @@ -1,6 +1,7 @@ package types import ( + cosmoserrors "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/ethereum/go-ethereum/crypto" @@ -30,10 +31,10 @@ func (m *MsgAddBlameVote) Type() string { func (m *MsgAddBlameVote) ValidateBasic() error { _, err := sdk.AccAddressFromBech32(m.Creator) if err != nil { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err) + return cosmoserrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err) } if common.GetChainFromChainID(m.ChainId) == nil { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidChainID, "chain id (%d)", m.ChainId) + return cosmoserrors.Wrapf(sdkerrors.ErrInvalidChainID, "chain id (%d)", m.ChainId) } return nil } diff --git a/x/observer/types/message_add_observer.go b/x/observer/types/message_add_observer.go index 3c27255590..a045154c4f 100644 --- a/x/observer/types/message_add_observer.go +++ b/x/observer/types/message_add_observer.go @@ -1,6 +1,7 @@ package types import ( + cosmoserrors "cosmossdk.io/errors" errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" @@ -44,7 +45,7 @@ func (msg *MsgAddObserver) GetSignBytes() []byte { func (msg *MsgAddObserver) ValidateBasic() error { _, err := sdk.AccAddressFromBech32(msg.Creator) if err != nil { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err) + return cosmoserrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err) } _, err = sdk.AccAddressFromBech32(msg.ObserverAddress) if err != nil { diff --git a/x/observer/types/message_update_keygen.go b/x/observer/types/message_update_keygen.go index 561a9319ff..e13c83dd7a 100644 --- a/x/observer/types/message_update_keygen.go +++ b/x/observer/types/message_update_keygen.go @@ -1,6 +1,7 @@ package types import ( + cosmoserrors "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) @@ -40,7 +41,7 @@ func (msg *MsgUpdateKeygen) GetSignBytes() []byte { func (msg *MsgUpdateKeygen) ValidateBasic() error { _, err := sdk.AccAddressFromBech32(msg.Creator) if err != nil { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err) + return cosmoserrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err) } return nil } diff --git a/x/observer/types/message_update_observer.go b/x/observer/types/message_update_observer.go index e5b541859b..4384099f2e 100644 --- a/x/observer/types/message_update_observer.go +++ b/x/observer/types/message_update_observer.go @@ -1,6 +1,7 @@ package types import ( + cosmoserrors "cosmossdk.io/errors" errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" @@ -43,7 +44,7 @@ func (msg *MsgUpdateObserver) GetSignBytes() []byte { func (msg *MsgUpdateObserver) ValidateBasic() error { _, err := sdk.AccAddressFromBech32(msg.Creator) if err != nil { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err) + return cosmoserrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err) } _, err = sdk.AccAddressFromBech32(msg.OldObserverAddress) if err != nil { From b0c6b7b5ddb490ea0a19181e8ff4e1c479122812 Mon Sep 17 00:00:00 2001 From: skosito Date: Wed, 21 Feb 2024 15:17:42 +0100 Subject: [PATCH 18/18] Fix lint --- x/crosschain/keeper/msg_server_vote_inbound_tx.go | 3 +-- .../keeper/msg_server_vote_inbound_tx_test.go | 4 ++-- x/fungible/keeper/gas_price.go | 11 +++++------ x/observer/types/message_add_observer.go | 7 +++---- x/observer/types/message_update_observer.go | 9 ++++----- 5 files changed, 15 insertions(+), 19 deletions(-) diff --git a/x/crosschain/keeper/msg_server_vote_inbound_tx.go b/x/crosschain/keeper/msg_server_vote_inbound_tx.go index 45af5ba0f6..930bbd8421 100644 --- a/x/crosschain/keeper/msg_server_vote_inbound_tx.go +++ b/x/crosschain/keeper/msg_server_vote_inbound_tx.go @@ -5,7 +5,6 @@ import ( "fmt" cosmoserrors "cosmossdk.io/errors" - errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/zeta-chain/zetacore/common" "github.com/zeta-chain/zetacore/x/crosschain/types" @@ -93,7 +92,7 @@ func (k msgServer) VoteOnObservedInboundTx(goCtx context.Context, msg *types.Msg if isNew { // Check if the inbound has already been processed. if k.IsFinalizedInbound(ctx, msg.InTxHash, msg.SenderChainId, msg.EventIndex) { - return nil, errorsmod.Wrap(types.ErrObservedTxAlreadyFinalized, fmt.Sprintf("InTxHash:%s, SenderChainID:%d, EventIndex:%d", msg.InTxHash, msg.SenderChainId, msg.EventIndex)) + return nil, cosmoserrors.Wrap(types.ErrObservedTxAlreadyFinalized, fmt.Sprintf("InTxHash:%s, SenderChainID:%d, EventIndex:%d", msg.InTxHash, msg.SenderChainId, msg.EventIndex)) } observerKeeper.EmitEventBallotCreated(ctx, ballot, msg.InTxHash, observationChain.String()) } diff --git a/x/crosschain/keeper/msg_server_vote_inbound_tx_test.go b/x/crosschain/keeper/msg_server_vote_inbound_tx_test.go index 1a8c742c5b..1605a37e33 100644 --- a/x/crosschain/keeper/msg_server_vote_inbound_tx_test.go +++ b/x/crosschain/keeper/msg_server_vote_inbound_tx_test.go @@ -60,7 +60,7 @@ func TestKeeper_VoteOnObservedInboundTx(t *testing.T) { require.NoError(t, err) } ballot, _, _ := zk.ObserverKeeper.FindBallot(ctx, msg.Digest(), zk.ObserverKeeper.GetSupportedChainFromChainID(ctx, msg.SenderChainId), observerTypes.ObservationType_InBoundTx) - require.Equal(t, ballot.BallotStatus, observerTypes.BallotStatus_BallotFinalized_SuccessObservation) + require.Equal(t, ballot.BallotStatus, observertypes.BallotStatus_BallotFinalized_SuccessObservation) cctx, found := k.GetCrossChainTx(ctx, msg.Digest()) require.True(t, found) require.Equal(t, cctx.CctxStatus.Status, types.CctxStatus_OutboundMined) @@ -122,7 +122,7 @@ func TestNoDoubleEventProtections(t *testing.T) { // Check that the vote passed ballot, found := zk.ObserverKeeper.GetBallot(ctx, msg.Digest()) require.True(t, found) - require.Equal(t, ballot.BallotStatus, observerTypes.BallotStatus_BallotFinalized_SuccessObservation) + require.Equal(t, ballot.BallotStatus, observertypes.BallotStatus_BallotFinalized_SuccessObservation) //Perform the SAME event. Except, this time, we resubmit the event. msg2 := &types.MsgVoteOnObservedInboundTx{ Creator: validatorAddr, diff --git a/x/fungible/keeper/gas_price.go b/x/fungible/keeper/gas_price.go index 68acdc98b9..636cffeec9 100644 --- a/x/fungible/keeper/gas_price.go +++ b/x/fungible/keeper/gas_price.go @@ -5,7 +5,6 @@ import ( cosmoserrors "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/ethereum/go-ethereum/common" ethcommon "github.com/ethereum/go-ethereum/common" systemcontract "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/systemcontract.sol" "github.com/zeta-chain/zetacore/x/fungible/types" @@ -20,7 +19,7 @@ func (k Keeper) SetGasPrice(ctx sdk.Context, chainid *big.Int, gasPrice *big.Int if !found { return 0, cosmoserrors.Wrapf(types.ErrContractNotFound, "system contract state variable not found") } - oracle := common.HexToAddress(system.SystemContract) + oracle := ethcommon.HexToAddress(system.SystemContract) if oracle == (ethcommon.Address{}) { return 0, cosmoserrors.Wrapf(types.ErrContractNotFound, "system contract invalid address") } @@ -39,12 +38,12 @@ func (k Keeper) SetGasPrice(ctx sdk.Context, chainid *big.Int, gasPrice *big.Int return res.GasUsed, nil } -func (k Keeper) SetGasCoin(ctx sdk.Context, chainid *big.Int, address common.Address) error { +func (k Keeper) SetGasCoin(ctx sdk.Context, chainid *big.Int, address ethcommon.Address) error { system, found := k.GetSystemContract(ctx) if !found { return cosmoserrors.Wrapf(types.ErrContractNotFound, "system contract state variable not found") } - oracle := common.HexToAddress(system.SystemContract) + oracle := ethcommon.HexToAddress(system.SystemContract) if oracle == (ethcommon.Address{}) { return cosmoserrors.Wrapf(types.ErrContractNotFound, "system contract invalid address") } @@ -63,12 +62,12 @@ func (k Keeper) SetGasCoin(ctx sdk.Context, chainid *big.Int, address common.Add return nil } -func (k Keeper) SetGasZetaPool(ctx sdk.Context, chainid *big.Int, pool common.Address) error { +func (k Keeper) SetGasZetaPool(ctx sdk.Context, chainid *big.Int, pool ethcommon.Address) error { system, found := k.GetSystemContract(ctx) if !found { return cosmoserrors.Wrapf(types.ErrContractNotFound, "system contract state variable not found") } - oracle := common.HexToAddress(system.SystemContract) + oracle := ethcommon.HexToAddress(system.SystemContract) if oracle == (ethcommon.Address{}) { return cosmoserrors.Wrapf(types.ErrContractNotFound, "system contract invalid address") } diff --git a/x/observer/types/message_add_observer.go b/x/observer/types/message_add_observer.go index a045154c4f..991bb0afa1 100644 --- a/x/observer/types/message_add_observer.go +++ b/x/observer/types/message_add_observer.go @@ -2,7 +2,6 @@ package types import ( cosmoserrors "cosmossdk.io/errors" - errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/zeta-chain/zetacore/common" @@ -49,15 +48,15 @@ func (msg *MsgAddObserver) ValidateBasic() error { } _, err = sdk.AccAddressFromBech32(msg.ObserverAddress) if err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid observer address (%s)", err) + return cosmoserrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid observer address (%s)", err) } _, err = common.NewPubKey(msg.ZetaclientGranteePubkey) if err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidPubKey, "invalid zetaclient grantee pubkey (%s)", err) + return cosmoserrors.Wrapf(sdkerrors.ErrInvalidPubKey, "invalid zetaclient grantee pubkey (%s)", err) } _, err = common.GetAddressFromPubkeyString(msg.ZetaclientGranteePubkey) if err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidPubKey, "invalid zetaclient grantee pubkey (%s)", err) + return cosmoserrors.Wrapf(sdkerrors.ErrInvalidPubKey, "invalid zetaclient grantee pubkey (%s)", err) } return nil } diff --git a/x/observer/types/message_update_observer.go b/x/observer/types/message_update_observer.go index 4384099f2e..c6db5a1206 100644 --- a/x/observer/types/message_update_observer.go +++ b/x/observer/types/message_update_observer.go @@ -2,7 +2,6 @@ package types import ( cosmoserrors "cosmossdk.io/errors" - errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) @@ -48,17 +47,17 @@ func (msg *MsgUpdateObserver) ValidateBasic() error { } _, err = sdk.AccAddressFromBech32(msg.OldObserverAddress) if err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid old observer address (%s)", err) + return cosmoserrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid old observer address (%s)", err) } _, err = sdk.AccAddressFromBech32(msg.NewObserverAddress) if err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid new observer address (%s)", err) + return cosmoserrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid new observer address (%s)", err) } if msg.UpdateReason != ObserverUpdateReason_Tombstoned && msg.UpdateReason != ObserverUpdateReason_AdminUpdate { - return errorsmod.Wrapf(ErrUpdateObserver, "invalid update reason (%s)", msg.UpdateReason) + return cosmoserrors.Wrapf(ErrUpdateObserver, "invalid update reason (%s)", msg.UpdateReason) } if msg.UpdateReason == ObserverUpdateReason_Tombstoned && msg.OldObserverAddress != msg.Creator { - return errorsmod.Wrapf(ErrUpdateObserver, "invalid old observer address (%s)", msg.OldObserverAddress) + return cosmoserrors.Wrapf(ErrUpdateObserver, "invalid old observer address (%s)", msg.OldObserverAddress) } return nil }