From 3002441fa8b2eec74f370909ef8d2224ce08ec8a Mon Sep 17 00:00:00 2001 From: TimmyExogenous Date: Wed, 28 Feb 2024 17:56:24 +0800 Subject: [PATCH] fix the error for golangci-lint use shared test utils to refine the test codes fix the problem in tests caused by denom rename --- app/ethtest_helper.go | 2 +- app/export.go | 60 ++++- app/test_helpers.go | 8 +- go.mod | 2 + precompiles/delegation/delegation_test.go | 122 +++++---- precompiles/delegation/setup_test.go | 41 +--- precompiles/delegation/utils_test.go | 197 --------------- precompiles/deposit/deposit_integrate_test.go | 33 +-- precompiles/deposit/deposit_test.go | 46 ++-- precompiles/deposit/error.go | 2 +- precompiles/deposit/setup_test.go | 38 +-- precompiles/deposit/types.go | 17 +- precompiles/reward/reward_test.go | 44 ++-- precompiles/reward/setup_test.go | 39 +-- precompiles/reward/utils_test.go | 231 ----------------- precompiles/slash/setup_test.go | 39 +-- precompiles/slash/slash_test.go | 44 ++-- precompiles/slash/utils_test.go | 231 ----------------- precompiles/withdraw/setup_test.go | 39 +-- precompiles/withdraw/utils_test.go | 232 ------------------ precompiles/withdraw/withdraw.sol | 2 +- .../withdraw/withdraw_integrate_test.go | 10 +- precompiles/withdraw/withdraw_test.go | 44 ++-- testutil/abci.go | 26 +- testutil/ante.go | 2 +- testutil/contract.go | 16 +- testutil/fund.go | 6 +- testutil/integration.go | 12 +- testutil/network/network.go | 4 +- testutil/network/network_test.go | 4 +- testutil/staking-rewards.go | 10 +- testutil/tx/cosmos.go | 12 +- testutil/tx/eip712.go | 16 +- testutil/tx/eth.go | 14 +- .../utils_test.go => testutil/utils.go | 184 ++++++++------ utils/utils.go | 6 +- utils/utils_test.go | 24 +- x/delegation/client/cli/query.go | 2 +- x/delegation/keeper/delegation_op_test.go | 92 +++---- x/delegation/keeper/operator_info_test.go | 8 +- x/delegation/keeper/setup_test.go | 24 +- x/delegation/keeper/utils_test.go | 44 ---- x/deposit/keeper/deposit_test.go | 16 +- x/deposit/keeper/params_test.go | 6 +- x/deposit/keeper/setup_test.go | 23 +- x/deposit/keeper/utils_test.go | 36 --- x/evm/types/params.go | 30 ++- x/native_token/module.go | 6 +- x/native_token/types/keys.go | 4 +- x/restaking_assets_manage/client/cli/query.go | 4 +- .../keeper/client_chain_and_asset_test.go | 14 +- .../keeper/setup_test.go | 23 +- .../keeper/staker_asset_test.go | 54 ++-- .../keeper/utils_test.go | 36 --- x/restaking_assets_manage/types/general.go | 2 +- x/reward/keeper/claim_reward_test.go | 12 +- x/reward/keeper/params_test.go | 6 +- x/reward/keeper/setup_test.go | 23 +- x/reward/keeper/utils_test.go | 34 --- x/slash/keeper/execute_slash_test.go | 22 +- x/slash/keeper/params_test.go | 6 +- x/slash/keeper/setup_test.go | 23 +- x/slash/keeper/utils_test.go | 34 --- x/withdraw/client/cli/query.go | 1 - x/withdraw/client/cli/tx.go | 1 + x/withdraw/keeper/claim_withdraw_test.go | 22 +- x/withdraw/keeper/setup_test.go | 24 +- x/withdraw/keeper/utils_test.go | 34 --- x/withdraw/module.go | 10 +- 69 files changed, 681 insertions(+), 1854 deletions(-) delete mode 100644 precompiles/delegation/utils_test.go delete mode 100644 precompiles/reward/utils_test.go delete mode 100644 precompiles/slash/utils_test.go delete mode 100644 precompiles/withdraw/utils_test.go rename precompiles/deposit/utils_test.go => testutil/utils.go (53%) delete mode 100644 x/delegation/keeper/utils_test.go delete mode 100644 x/deposit/keeper/utils_test.go delete mode 100644 x/restaking_assets_manage/keeper/utils_test.go delete mode 100644 x/reward/keeper/utils_test.go delete mode 100644 x/slash/keeper/utils_test.go delete mode 100644 x/withdraw/keeper/utils_test.go diff --git a/app/ethtest_helper.go b/app/ethtest_helper.go index b0700ddf1..3c2599230 100644 --- a/app/ethtest_helper.go +++ b/app/ethtest_helper.go @@ -109,7 +109,7 @@ func NewTestGenesisState(codec codec.Codec) simapp.GenesisState { Coins: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100000000000000))), } - genesisState := NewDefaultGenesisState() + genesisState := NewDefaultGenesisState(codec) return genesisStateWithValSet(codec, genesisState, valSet, []authtypes.GenesisAccount{acc}, balance) } diff --git a/app/export.go b/app/export.go index 5cd4a8156..ed9e501c1 100644 --- a/app/export.go +++ b/app/export.go @@ -4,22 +4,74 @@ import ( "encoding/json" "fmt" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "cosmossdk.io/simapp" + + "github.com/ExocoreNetwork/exocore/utils" + tmproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/cosmos/cosmos-sdk/codec" servertypes "github.com/cosmos/cosmos-sdk/server/types" sdk "github.com/cosmos/cosmos-sdk/types" + crisistypes "github.com/cosmos/cosmos-sdk/x/crisis/types" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + govtypesv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" "github.com/cosmos/cosmos-sdk/x/staking" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + claimstypes "github.com/evmos/evmos/v14/x/claims/types" + evmtypes "github.com/evmos/evmos/v14/x/evm/types" + inflationtypes "github.com/evmos/evmos/v14/x/inflation/types" "github.com/evmos/evmos/v14/encoding" ) // NewDefaultGenesisState generates the default state for the application. -func NewDefaultGenesisState() simapp.GenesisState { +func NewDefaultGenesisState(cdc codec.Codec) simapp.GenesisState { encCfg := encoding.MakeConfig(ModuleBasics) - return ModuleBasics.DefaultGenesis(encCfg.Codec) + defaultGenesis := ModuleBasics.DefaultGenesis(encCfg.Codec) + + // staking module + stakingGenesis := stakingtypes.GenesisState{} + rawGenesis := defaultGenesis[stakingtypes.ModuleName] + cdc.MustUnmarshalJSON(rawGenesis, &stakingGenesis) + stakingGenesis.Params.BondDenom = utils.BaseDenom + defaultGenesis[stakingtypes.ModuleName] = cdc.MustMarshalJSON(&stakingGenesis) + + // crisis module + crisisGenesis := crisistypes.GenesisState{} + rawGenesis = defaultGenesis[crisistypes.ModuleName] + cdc.MustUnmarshalJSON(rawGenesis, &crisisGenesis) + crisisGenesis.ConstantFee.Denom = utils.BaseDenom + defaultGenesis[crisistypes.ModuleName] = cdc.MustMarshalJSON(&crisisGenesis) + + // gov module + govGenesis := govtypesv1.GenesisState{} + rawGenesis = defaultGenesis[govtypes.ModuleName] + cdc.MustUnmarshalJSON(rawGenesis, &govGenesis) + govGenesis.Params.MinDeposit[0].Denom = utils.BaseDenom + defaultGenesis[govtypes.ModuleName] = cdc.MustMarshalJSON(&govGenesis) + + // evm module + evmGenesis := evmtypes.GenesisState{} + rawGenesis = defaultGenesis[evmtypes.ModuleName] + cdc.MustUnmarshalJSON(rawGenesis, &evmGenesis) + evmGenesis.Params.EvmDenom = utils.BaseDenom + defaultGenesis[evmtypes.ModuleName] = cdc.MustMarshalJSON(&evmGenesis) + + // inflation module + inflationGenesis := inflationtypes.GenesisState{} + rawGenesis = defaultGenesis[inflationtypes.ModuleName] + cdc.MustUnmarshalJSON(rawGenesis, &inflationGenesis) + inflationGenesis.Params.MintDenom = utils.BaseDenom + defaultGenesis[inflationtypes.ModuleName] = cdc.MustMarshalJSON(&inflationGenesis) + + // claims module + claimsGenesis := claimstypes.GenesisState{} + rawGenesis = defaultGenesis[claimstypes.ModuleName] + cdc.MustUnmarshalJSON(rawGenesis, &claimsGenesis) + claimsGenesis.Params.ClaimsDenom = utils.BaseDenom + defaultGenesis[claimstypes.ModuleName] = cdc.MustMarshalJSON(&claimsGenesis) + + return defaultGenesis } // ExportAppStateAndValidators exports the state of the application for a genesis diff --git a/app/test_helpers.go b/app/test_helpers.go index 4af278b71..5fca3c7be 100644 --- a/app/test_helpers.go +++ b/app/test_helpers.go @@ -27,8 +27,8 @@ import ( "github.com/evmos/evmos/v14/encoding" feemarkettypes "github.com/evmos/evmos/v14/x/feemarket/types" - "github.com/evmos/evmos/v14/cmd/config" - "github.com/evmos/evmos/v14/utils" + "github.com/ExocoreNetwork/exocore/cmd/config" + "github.com/ExocoreNetwork/exocore/utils" ) func init() { @@ -106,7 +106,7 @@ func Setup( ) if !isCheckTx { // init chain must be called to stop deliverState from being nil - genesisState := NewDefaultGenesisState() + genesisState := NewDefaultGenesisState(app.appCodec) genesisState = GenesisStateWithValSet(app, genesisState, valSet, []authtypes.GenesisAccount{acc}, balance) // Verify feeMarket genesis @@ -218,6 +218,6 @@ func SetupTestingApp(chainID string, isPrintLog bool) func() (ibctesting.Testing simtestutil.NewAppOptionsWithFlagHome(DefaultNodeHome), baseapp.SetChainID(chainID), ) - return app, NewDefaultGenesisState() + return app, NewDefaultGenesisState(app.appCodec) } } diff --git a/go.mod b/go.mod index 79d900dff..be0eb43af 100644 --- a/go.mod +++ b/go.mod @@ -215,12 +215,14 @@ replace ( github.com/99designs/keyring => github.com/cosmos/keyring v1.2.0 // use Cosmos-SDK fork to enable Ledger functionality github.com/cosmos/cosmos-sdk => github.com/evmos/cosmos-sdk v0.47.4-evmos.2 + //github.com/cosmos/cosmos-sdk => ../cosmos-sdk //fix cosmos-sdk error github.com/cosmos/gogoproto => github.com/cosmos/gogoproto v1.4.10 // use Evmos geth fork github.com/ethereum/go-ethereum => github.com/evmos/go-ethereum v1.10.26-evmos-rc2 // use exocore fork of evmos github.com/evmos/evmos/v14 => github.com/ExocoreNetwork/evmos/v14 v14.1.1-0.20240205024453-5e8090e42ef4 + //github.com/evmos/evmos/v14 => ../ExocoreNetwork/evmos // Security Advisory https://github.com/advisories/GHSA-h395-qcrw-5vmq github.com/gin-gonic/gin => github.com/gin-gonic/gin v1.9.1 // replace broken goleveldb diff --git a/precompiles/delegation/delegation_test.go b/precompiles/delegation/delegation_test.go index cd869a26a..7d6931b33 100644 --- a/precompiles/delegation/delegation_test.go +++ b/precompiles/delegation/delegation_test.go @@ -1,7 +1,6 @@ package delegation_test import ( - "fmt" "math/big" "strings" @@ -24,7 +23,7 @@ import ( evmtypes "github.com/evmos/evmos/v14/x/evm/types" ) -func (s *PrecompileTestSuite) TestIsTransaction() { +func (s *DelegationPrecompileSuite) TestIsTransaction() { testCases := []struct { name string method string @@ -63,12 +62,12 @@ func paddingClientChainAddress(input []byte, outputLength int) []byte { } // TestRun tests DelegateToThroughClientChain method through calling Run function. -func (s *PrecompileTestSuite) TestRunDelegateToThroughClientChain() { +func (s *DelegationPrecompileSuite) TestRunDelegateToThroughClientChain() { // deposit params for test exoCoreLzAppAddress := "0x3fC91A3afd70395Cd496C647d5a6CC9D4B2b7FAD" exoCoreLzAppEventTopic := "0xc6a377bfc4eb120024a8ac08eef205be16b817020812c73223e81d1bdb9708ec" usdtAddress := common.FromHex("0xdAC17F958D2ee523a2206206994597C13D831ec7") - opAccAddr := "evmos1fl48vsnmsdzcv85q5d2q4z5ajdha8yu3h6cprl" + opAccAddr := "exo13h6xg79g82e2g2vhjwg7j4r2z2hlncelwutkjr" clientChainLzID := 101 lzNonce := 0 delegationAmount := big.NewInt(50) @@ -84,7 +83,7 @@ func (s *PrecompileTestSuite) TestRunDelegateToThroughClientChain() { AssetsAddress: usdtAddress, OpAmount: depositAmount, } - err := s.app.DepositKeeper.Deposit(s.ctx, params) + err := s.App.DepositKeeper.Deposit(s.Ctx, params) s.Require().NoError(err) } registerOperator := func() { @@ -94,27 +93,27 @@ func (s *PrecompileTestSuite) TestRunDelegateToThroughClientChain() { EarningsAddr: opAccAddr, }, } - _, err := s.app.DelegationKeeper.RegisterOperator(s.ctx, registerReq) + _, err := s.App.DelegationKeeper.RegisterOperator(s.Ctx, registerReq) s.NoError(err) } commonMalleate := func() (common.Address, []byte) { // prepare the call input for delegation test - valAddr, err := sdk.ValAddressFromBech32(s.validators[0].OperatorAddress) + valAddr, err := sdk.ValAddressFromBech32(s.Validators[0].OperatorAddress) s.Require().NoError(err) - val, _ := s.app.StakingKeeper.GetValidator(s.ctx, valAddr) + val, _ := s.App.StakingKeeper.GetValidator(s.Ctx, valAddr) coins := sdk.NewCoins(sdk.NewCoin(utils.BaseDenom, sdk.NewInt(1e18))) - s.app.DistrKeeper.AllocateTokensToValidator(s.ctx, val, sdk.NewDecCoinsFromCoins(coins...)) + s.App.DistrKeeper.AllocateTokensToValidator(s.Ctx, val, sdk.NewDecCoinsFromCoins(coins...)) input, err := s.precompile.Pack( delegation.MethodDelegateToThroughClientChain, uint16(clientChainLzID), uint64(lzNonce), assetAddr, - paddingClientChainAddress(s.address.Bytes(), types.GeneralClientChainAddrLength), + paddingClientChainAddress(s.Address.Bytes(), types.GeneralClientChainAddrLength), []byte(opAccAddr), delegationAmount, ) s.Require().NoError(err, "failed to pack input") - return s.address, input + return s.Address, input } successRet, err := s.precompile.Methods[delegation.MethodDelegateToThroughClientChain].Outputs.Pack(true) s.Require().NoError(err) @@ -143,7 +142,7 @@ func (s *PrecompileTestSuite) TestRunDelegateToThroughClientChain() { ExoCoreLzAppAddress: exoCoreLzAppAddress, ExoCoreLzAppEventTopic: exoCoreLzAppEventTopic, } - err := s.app.DepositKeeper.SetParams(s.ctx, depositModuleParam) + err := s.App.DepositKeeper.SetParams(s.Ctx, depositModuleParam) s.Require().NoError(err) return commonMalleate() }, @@ -155,10 +154,10 @@ func (s *PrecompileTestSuite) TestRunDelegateToThroughClientChain() { name: "fail - delegateToThroughClientChain transaction will fail because the delegated operator hasn't been registered", malleate: func() (common.Address, []byte) { depositModuleParam := &types3.Params{ - ExoCoreLzAppAddress: s.address.String(), + ExoCoreLzAppAddress: s.Address.String(), ExoCoreLzAppEventTopic: exoCoreLzAppEventTopic, } - err := s.app.DepositKeeper.SetParams(s.ctx, depositModuleParam) + err := s.App.DepositKeeper.SetParams(s.Ctx, depositModuleParam) s.Require().NoError(err) return commonMalleate() }, @@ -170,10 +169,10 @@ func (s *PrecompileTestSuite) TestRunDelegateToThroughClientChain() { name: "fail - delegateToThroughClientChain transaction will fail because the delegated asset hasn't been deposited", malleate: func() (common.Address, []byte) { depositModuleParam := &types3.Params{ - ExoCoreLzAppAddress: s.address.String(), + ExoCoreLzAppAddress: s.Address.String(), ExoCoreLzAppEventTopic: exoCoreLzAppEventTopic, } - err := s.app.DepositKeeper.SetParams(s.ctx, depositModuleParam) + err := s.App.DepositKeeper.SetParams(s.Ctx, depositModuleParam) s.Require().NoError(err) registerOperator() return commonMalleate() @@ -186,13 +185,13 @@ func (s *PrecompileTestSuite) TestRunDelegateToThroughClientChain() { name: "fail - delegateToThroughClientChain transaction will fail because the delegation amount is bigger than the canWithdraw amount", malleate: func() (common.Address, []byte) { depositModuleParam := &types3.Params{ - ExoCoreLzAppAddress: s.address.String(), + ExoCoreLzAppAddress: s.Address.String(), ExoCoreLzAppEventTopic: exoCoreLzAppEventTopic, } - err := s.app.DepositKeeper.SetParams(s.ctx, depositModuleParam) + err := s.App.DepositKeeper.SetParams(s.Ctx, depositModuleParam) s.Require().NoError(err) registerOperator() - depositAsset(s.address.Bytes(), sdkmath.NewIntFromBigInt(smallDepositAmount)) + depositAsset(s.Address.Bytes(), sdkmath.NewIntFromBigInt(smallDepositAmount)) return commonMalleate() }, readOnly: false, @@ -203,13 +202,13 @@ func (s *PrecompileTestSuite) TestRunDelegateToThroughClientChain() { name: "pass - delegateToThroughClientChain transaction", malleate: func() (common.Address, []byte) { depositModuleParam := &types3.Params{ - ExoCoreLzAppAddress: s.address.String(), + ExoCoreLzAppAddress: s.Address.String(), ExoCoreLzAppEventTopic: exoCoreLzAppEventTopic, } - err := s.app.DepositKeeper.SetParams(s.ctx, depositModuleParam) + err := s.App.DepositKeeper.SetParams(s.Ctx, depositModuleParam) s.Require().NoError(err) registerOperator() - depositAsset(s.address.Bytes(), sdkmath.NewIntFromBigInt(depositAmount)) + depositAsset(s.Address.Bytes(), sdkmath.NewIntFromBigInt(depositAmount)) return commonMalleate() }, returnBytes: successRet, @@ -224,7 +223,7 @@ func (s *PrecompileTestSuite) TestRunDelegateToThroughClientChain() { // setup basic test suite s.SetupTest() - baseFee := s.app.FeeMarketKeeper.GetBaseFee(s.ctx) + baseFee := s.App.FeeMarketKeeper.GetBaseFee(s.Ctx) // malleate testcase caller, input := tc.malleate() @@ -235,7 +234,7 @@ func (s *PrecompileTestSuite) TestRunDelegateToThroughClientChain() { contractAddr := contract.Address() // Build and sign Ethereum transaction txArgs := evmtypes.EvmTxArgs{ - ChainID: s.app.EvmKeeper.ChainID(), + ChainID: s.App.EvmKeeper.ChainID(), Nonce: 0, To: &contractAddr, Amount: nil, @@ -247,28 +246,28 @@ func (s *PrecompileTestSuite) TestRunDelegateToThroughClientChain() { } msgEthereumTx := evmtypes.NewTx(&txArgs) - msgEthereumTx.From = s.address.String() - err := msgEthereumTx.Sign(s.ethSigner, s.signer) + msgEthereumTx.From = s.Address.String() + err := msgEthereumTx.Sign(s.EthSigner, s.Signer) s.Require().NoError(err, "failed to sign Ethereum message") // Instantiate config - proposerAddress := s.ctx.BlockHeader().ProposerAddress - cfg, err := s.app.EvmKeeper.EVMConfig(s.ctx, proposerAddress, s.app.EvmKeeper.ChainID()) + proposerAddress := s.Ctx.BlockHeader().ProposerAddress + cfg, err := s.App.EvmKeeper.EVMConfig(s.Ctx, proposerAddress, s.App.EvmKeeper.ChainID()) s.Require().NoError(err, "failed to instantiate EVM config") - msg, err := msgEthereumTx.AsMessage(s.ethSigner, baseFee) + msg, err := msgEthereumTx.AsMessage(s.EthSigner, baseFee) s.Require().NoError(err, "failed to instantiate Ethereum message") // Create StateDB - s.stateDB = statedb.New(s.ctx, s.app.EvmKeeper, statedb.NewEmptyTxConfig(common.BytesToHash(s.ctx.HeaderHash().Bytes()))) + s.StateDB = statedb.New(s.Ctx, s.App.EvmKeeper, statedb.NewEmptyTxConfig(common.BytesToHash(s.Ctx.HeaderHash().Bytes()))) // Instantiate EVM - evm := s.app.EvmKeeper.NewEVM( - s.ctx, msg, cfg, nil, s.stateDB, + evm := s.App.EvmKeeper.NewEVM( + s.Ctx, msg, cfg, nil, s.StateDB, ) - params := s.app.EvmKeeper.GetParams(s.ctx) + params := s.App.EvmKeeper.GetParams(s.Ctx) activePrecompiles := params.GetActivePrecompilesAddrs() - precompileMap := s.app.EvmKeeper.Precompiles(activePrecompiles...) + precompileMap := s.App.EvmKeeper.Precompiles(activePrecompiles...) err = vm.ValidatePrecompiles(precompileMap, activePrecompiles) s.Require().NoError(err, "invalid precompiles", activePrecompiles) evm.WithPrecompiles(precompileMap, activePrecompiles) @@ -290,11 +289,11 @@ func (s *PrecompileTestSuite) TestRunDelegateToThroughClientChain() { } // TestRun tests DelegateToThroughClientChain method through calling Run function. -func (s *PrecompileTestSuite) TestRunUnDelegateFromThroughClientChain() { +func (s *DelegationPrecompileSuite) TestRunUnDelegateFromThroughClientChain() { // deposit params for test exoCoreLzAppEventTopic := "0xc6a377bfc4eb120024a8ac08eef205be16b817020812c73223e81d1bdb9708ec" usdtAddress := common.FromHex("0xdAC17F958D2ee523a2206206994597C13D831ec7") - operatorAddr := "evmos1fl48vsnmsdzcv85q5d2q4z5ajdha8yu3h6cprl" + operatorAddr := "exo13h6xg79g82e2g2vhjwg7j4r2z2hlncelwutkjr" clientChainLzID := 101 lzNonce := uint64(0) delegationAmount := big.NewInt(50) @@ -309,7 +308,7 @@ func (s *PrecompileTestSuite) TestRunUnDelegateFromThroughClientChain() { AssetsAddress: usdtAddress, OpAmount: depositAmount, } - err := s.app.DepositKeeper.Deposit(s.ctx, params) + err := s.App.DepositKeeper.Deposit(s.Ctx, params) s.Require().NoError(err) } @@ -326,7 +325,7 @@ func (s *PrecompileTestSuite) TestRunUnDelegateFromThroughClientChain() { opAccAddr, err := sdk.AccAddressFromBech32(operatorAddr) s.Require().NoError(err) delegateToParams.OperatorAddress = opAccAddr - err = s.app.DelegationKeeper.DelegateTo(s.ctx, delegateToParams) + err = s.App.DelegationKeeper.DelegateTo(s.Ctx, delegateToParams) s.Require().NoError(err) } registerOperator := func() { @@ -336,27 +335,27 @@ func (s *PrecompileTestSuite) TestRunUnDelegateFromThroughClientChain() { EarningsAddr: operatorAddr, }, } - _, err := s.app.DelegationKeeper.RegisterOperator(s.ctx, registerReq) + _, err := s.App.DelegationKeeper.RegisterOperator(s.Ctx, registerReq) s.NoError(err) } commonMalleate := func() (common.Address, []byte) { // prepare the call input for delegation test - valAddr, err := sdk.ValAddressFromBech32(s.validators[0].OperatorAddress) + valAddr, err := sdk.ValAddressFromBech32(s.Validators[0].OperatorAddress) s.Require().NoError(err) - val, _ := s.app.StakingKeeper.GetValidator(s.ctx, valAddr) + val, _ := s.App.StakingKeeper.GetValidator(s.Ctx, valAddr) coins := sdk.NewCoins(sdk.NewCoin(utils.BaseDenom, sdk.NewInt(1e18))) - s.app.DistrKeeper.AllocateTokensToValidator(s.ctx, val, sdk.NewDecCoinsFromCoins(coins...)) + s.App.DistrKeeper.AllocateTokensToValidator(s.Ctx, val, sdk.NewDecCoinsFromCoins(coins...)) input, err := s.precompile.Pack( delegation.MethodUndelegateFromThroughClientChain, uint16(clientChainLzID), lzNonce+1, assetAddr, - paddingClientChainAddress(s.address.Bytes(), types.GeneralClientChainAddrLength), + paddingClientChainAddress(s.Address.Bytes(), types.GeneralClientChainAddrLength), []byte(operatorAddr), delegationAmount, ) s.Require().NoError(err, "failed to pack input") - return s.address, input + return s.Address, input } successRet, err := s.precompile.Methods[delegation.MethodUndelegateFromThroughClientChain].Outputs.Pack(true) s.Require().NoError(err) @@ -373,14 +372,14 @@ func (s *PrecompileTestSuite) TestRunUnDelegateFromThroughClientChain() { name: "pass - undelegateFromThroughClientChain transaction", malleate: func() (common.Address, []byte) { depositModuleParam := &types3.Params{ - ExoCoreLzAppAddress: s.address.String(), + ExoCoreLzAppAddress: s.Address.String(), ExoCoreLzAppEventTopic: exoCoreLzAppEventTopic, } - err := s.app.DepositKeeper.SetParams(s.ctx, depositModuleParam) + err := s.App.DepositKeeper.SetParams(s.Ctx, depositModuleParam) s.Require().NoError(err) registerOperator() - depositAsset(s.address.Bytes(), sdkmath.NewIntFromBigInt(depositAmount)) - delegateAsset(s.address.Bytes(), sdkmath.NewIntFromBigInt(delegationAmount)) + depositAsset(s.Address.Bytes(), sdkmath.NewIntFromBigInt(depositAmount)) + delegateAsset(s.Address.Bytes(), sdkmath.NewIntFromBigInt(delegationAmount)) return commonMalleate() }, returnBytes: successRet, @@ -394,7 +393,7 @@ func (s *PrecompileTestSuite) TestRunUnDelegateFromThroughClientChain() { // setup basic test suite s.SetupTest() - baseFee := s.app.FeeMarketKeeper.GetBaseFee(s.ctx) + baseFee := s.App.FeeMarketKeeper.GetBaseFee(s.Ctx) // malleate testcase caller, input := tc.malleate() @@ -405,7 +404,7 @@ func (s *PrecompileTestSuite) TestRunUnDelegateFromThroughClientChain() { contractAddr := contract.Address() // Build and sign Ethereum transaction txArgs := evmtypes.EvmTxArgs{ - ChainID: s.app.EvmKeeper.ChainID(), + ChainID: s.App.EvmKeeper.ChainID(), Nonce: 0, To: &contractAddr, Amount: nil, @@ -417,30 +416,29 @@ func (s *PrecompileTestSuite) TestRunUnDelegateFromThroughClientChain() { } msgEthereumTx := evmtypes.NewTx(&txArgs) - msgEthereumTx.From = s.address.String() - err := msgEthereumTx.Sign(s.ethSigner, s.signer) + msgEthereumTx.From = s.Address.String() + err := msgEthereumTx.Sign(s.EthSigner, s.Signer) s.Require().NoError(err, "failed to sign Ethereum message") // Instantiate config - proposerAddress := s.ctx.BlockHeader().ProposerAddress - cfg, err := s.app.EvmKeeper.EVMConfig(s.ctx, proposerAddress, s.app.EvmKeeper.ChainID()) + proposerAddress := s.Ctx.BlockHeader().ProposerAddress + cfg, err := s.App.EvmKeeper.EVMConfig(s.Ctx, proposerAddress, s.App.EvmKeeper.ChainID()) s.Require().NoError(err, "failed to instantiate EVM config") - msg, err := msgEthereumTx.AsMessage(s.ethSigner, baseFee) + msg, err := msgEthereumTx.AsMessage(s.EthSigner, baseFee) s.Require().NoError(err, "failed to instantiate Ethereum message") // set txHash for delegation module - fmt.Println("the txHash is:", msgEthereumTx.Hash) - s.ctx = s.ctx.WithValue(delegation.CtxKeyTxHash, common.HexToHash(msgEthereumTx.Hash)) + s.Ctx = s.Ctx.WithValue(delegation.CtxKeyTxHash, common.HexToHash(msgEthereumTx.Hash)) // Create StateDB - s.stateDB = statedb.New(s.ctx, s.app.EvmKeeper, statedb.NewEmptyTxConfig(common.BytesToHash(s.ctx.HeaderHash().Bytes()))) + s.StateDB = statedb.New(s.Ctx, s.App.EvmKeeper, statedb.NewEmptyTxConfig(common.BytesToHash(s.Ctx.HeaderHash().Bytes()))) // Instantiate EVM - evm := s.app.EvmKeeper.NewEVM( - s.ctx, msg, cfg, nil, s.stateDB, + evm := s.App.EvmKeeper.NewEVM( + s.Ctx, msg, cfg, nil, s.StateDB, ) - params := s.app.EvmKeeper.GetParams(s.ctx) + params := s.App.EvmKeeper.GetParams(s.Ctx) activePrecompiles := params.GetActivePrecompilesAddrs() - precompileMap := s.app.EvmKeeper.Precompiles(activePrecompiles...) + precompileMap := s.App.EvmKeeper.Precompiles(activePrecompiles...) err = vm.ValidatePrecompiles(precompileMap, activePrecompiles) s.Require().NoError(err, "invalid precompiles", activePrecompiles) evm.WithPrecompiles(precompileMap, activePrecompiles) diff --git a/precompiles/delegation/setup_test.go b/precompiles/delegation/setup_test.go index 885171420..b5bec0e9b 100644 --- a/precompiles/delegation/setup_test.go +++ b/precompiles/delegation/setup_test.go @@ -1,50 +1,26 @@ package delegation_test import ( - "testing" - "github.com/ExocoreNetwork/exocore/precompiles/delegation" - - "github.com/evmos/evmos/v14/x/evm/statedb" + "github.com/ExocoreNetwork/exocore/testutil" + "testing" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - evmosapp "github.com/ExocoreNetwork/exocore/app" - tmtypes "github.com/cometbft/cometbft/types" - "github.com/cosmos/cosmos-sdk/crypto/keyring" - cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" - sdk "github.com/cosmos/cosmos-sdk/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/ethereum/go-ethereum/common" - ethtypes "github.com/ethereum/go-ethereum/core/types" - evmtypes "github.com/evmos/evmos/v14/x/evm/types" "github.com/stretchr/testify/suite" ) -var s *PrecompileTestSuite - -type PrecompileTestSuite struct { - suite.Suite +var s *DelegationPrecompileSuite - ctx sdk.Context - app *evmosapp.ExocoreApp - address common.Address - validators []stakingtypes.Validator - valSet *tmtypes.ValidatorSet - ethSigner ethtypes.Signer - privKey cryptotypes.PrivKey - signer keyring.Signer - bondDenom string +type DelegationPrecompileSuite struct { + testutil.BaseTestSuite precompile *delegation.Precompile - stateDB *statedb.StateDB - - queryClientEVM evmtypes.QueryClient } func TestPrecompileTestSuite(t *testing.T) { - s = new(PrecompileTestSuite) + s = new(DelegationPrecompileSuite) suite.Run(t, s) // Run Ginkgo integration tests @@ -52,6 +28,9 @@ func TestPrecompileTestSuite(t *testing.T) { RunSpecs(t, "Distribution Precompile Suite") } -func (s *PrecompileTestSuite) SetupTest() { +func (s *DelegationPrecompileSuite) SetupTest() { s.DoSetupTest() + precompile, err := delegation.NewPrecompile(s.App.StakingAssetsManageKeeper, s.App.DelegationKeeper, s.App.AuthzKeeper) + s.Require().NoError(err) + s.precompile = precompile } diff --git a/precompiles/delegation/utils_test.go b/precompiles/delegation/utils_test.go deleted file mode 100644 index f3130d62c..000000000 --- a/precompiles/delegation/utils_test.go +++ /dev/null @@ -1,197 +0,0 @@ -package delegation_test - -import ( - "encoding/json" - "time" - - "github.com/ExocoreNetwork/exocore/precompiles/delegation" - "github.com/ExocoreNetwork/exocore/testutil" - testutiltx "github.com/ExocoreNetwork/exocore/testutil/tx" - - evmosapp "github.com/ExocoreNetwork/exocore/app" - "github.com/ExocoreNetwork/exocore/utils" - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cometbft/cometbft/crypto/tmhash" - tmtypes "github.com/cometbft/cometbft/types" - "github.com/cosmos/cosmos-sdk/baseapp" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - "github.com/cosmos/cosmos-sdk/testutil/mock" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/ethereum/go-ethereum/common" - ethtypes "github.com/ethereum/go-ethereum/core/types" - cmn "github.com/evmos/evmos/v14/precompiles/common" - evmostypes "github.com/evmos/evmos/v14/types" - evmtypes "github.com/evmos/evmos/v14/x/evm/types" - inflationtypes "github.com/evmos/evmos/v14/x/inflation/types" -) - -// SetupWithGenesisValSet initializes a new EvmosApp with a validator set and genesis accounts -// that also act as delegators. For simplicity, each validator is bonded with a delegation -// of one consensus engine unit (10^6) in the default token of the simapp from first genesis -// account. A Nop logger is set in SimApp. -func (s *PrecompileTestSuite) SetupWithGenesisValSet(valSet *tmtypes.ValidatorSet, genAccs []authtypes.GenesisAccount, balances ...banktypes.Balance) { - appI, genesisState := evmosapp.SetupTestingApp(cmn.DefaultChainID, false)() - app, ok := appI.(*evmosapp.ExocoreApp) - s.Require().True(ok) - - // set genesis accounts - authGenesis := authtypes.NewGenesisState(authtypes.DefaultParams(), genAccs) - genesisState[authtypes.ModuleName] = app.AppCodec().MustMarshalJSON(authGenesis) - - validators := make([]stakingtypes.Validator, 0, len(valSet.Validators)) - delegations := make([]stakingtypes.Delegation, 0, len(valSet.Validators)) - - bondAmt := sdk.TokensFromConsensusPower(1, evmostypes.PowerReduction) - - for _, val := range valSet.Validators { - pk, err := cryptocodec.FromTmPubKeyInterface(val.PubKey) - s.Require().NoError(err) - pkAny, err := codectypes.NewAnyWithValue(pk) - s.Require().NoError(err) - validator := stakingtypes.Validator{ - OperatorAddress: sdk.ValAddress(val.Address).String(), - ConsensusPubkey: pkAny, - Jailed: false, - Status: stakingtypes.Bonded, - Tokens: bondAmt, - DelegatorShares: sdk.OneDec(), - Description: stakingtypes.Description{}, - UnbondingHeight: int64(0), - UnbondingTime: time.Unix(0, 0).UTC(), - Commission: stakingtypes.NewCommission(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), - MinSelfDelegation: sdk.ZeroInt(), - } - validators = append(validators, validator) - delegations = append(delegations, stakingtypes.NewDelegation(genAccs[0].GetAddress(), val.Address.Bytes(), sdk.OneDec())) - } - s.validators = validators - - // set validators and delegations - stakingParams := stakingtypes.DefaultParams() - // set bond demon to be aevmos - stakingParams.BondDenom = utils.BaseDenom - stakingGenesis := stakingtypes.NewGenesisState(stakingParams, validators, delegations) - genesisState[stakingtypes.ModuleName] = app.AppCodec().MustMarshalJSON(stakingGenesis) - - totalBondAmt := bondAmt.Add(bondAmt) - totalSupply := sdk.NewCoins() - for _, b := range balances { - // add genesis acc tokens and delegated tokens to total supply - totalSupply = totalSupply.Add(b.Coins.Add(sdk.NewCoin(utils.BaseDenom, totalBondAmt))...) - } - - // add bonded amount to bonded pool module account - balances = append(balances, banktypes.Balance{ - Address: authtypes.NewModuleAddress(stakingtypes.BondedPoolName).String(), - Coins: sdk.Coins{sdk.NewCoin(utils.BaseDenom, totalBondAmt)}, - }) - - // update total supply - bankGenesis := banktypes.NewGenesisState(banktypes.DefaultGenesisState().Params, balances, totalSupply, []banktypes.Metadata{}, []banktypes.SendEnabled{}) - genesisState[banktypes.ModuleName] = app.AppCodec().MustMarshalJSON(bankGenesis) - - stateBytes, err := json.MarshalIndent(genesisState, "", " ") - s.Require().NoError(err) - - // init chain will set the validator set and initialize the genesis accounts - app.InitChain( - abci.RequestInitChain{ - ChainId: cmn.DefaultChainID, - Validators: []abci.ValidatorUpdate{}, - ConsensusParams: evmosapp.DefaultConsensusParams, - AppStateBytes: stateBytes, - }, - ) - app.Commit() - - // instantiate new header - header := testutil.NewHeader( - 2, - time.Now().UTC(), - cmn.DefaultChainID, - sdk.ConsAddress(validators[0].GetOperator()), - tmhash.Sum([]byte("app")), - tmhash.Sum([]byte("validators")), - ) - - app.BeginBlock(abci.RequestBeginBlock{ - Header: header, - }) - - // create Context - s.ctx = app.BaseApp.NewContext(false, header) - s.app = app -} - -func (s *PrecompileTestSuite) DoSetupTest() { - // generate validator private/public key - privVal := mock.NewPV() - pubKey, err := privVal.GetPubKey() - s.Require().NoError(err) - - privVal2 := mock.NewPV() - pubKey2, err := privVal2.GetPubKey() - s.Require().NoError(err) - - // create validator set with two validators - validator := tmtypes.NewValidator(pubKey, 1) - validator2 := tmtypes.NewValidator(pubKey2, 2) - s.valSet = tmtypes.NewValidatorSet([]*tmtypes.Validator{validator, validator2}) - signers := make(map[string]tmtypes.PrivValidator) - signers[pubKey.Address().String()] = privVal - signers[pubKey2.Address().String()] = privVal2 - - // generate genesis account - addr, priv := testutiltx.NewAddrKey() - s.privKey = priv - s.address = addr - s.signer = testutiltx.NewSigner(priv) - - baseAcc := authtypes.NewBaseAccount(priv.PubKey().Address().Bytes(), priv.PubKey(), 0, 0) - - acc := &evmostypes.EthAccount{ - BaseAccount: baseAcc, - CodeHash: common.BytesToHash(evmtypes.EmptyCodeHash).Hex(), - } - - amount := sdk.TokensFromConsensusPower(5, evmostypes.PowerReduction) - - balance := banktypes.Balance{ - Address: acc.GetAddress().String(), - Coins: sdk.NewCoins(sdk.NewCoin(utils.BaseDenom, amount)), - } - - s.SetupWithGenesisValSet(s.valSet, []authtypes.GenesisAccount{acc}, balance) - - // bond denom - stakingParams := s.app.StakingKeeper.GetParams(s.ctx) - stakingParams.BondDenom = utils.BaseDenom - s.bondDenom = stakingParams.BondDenom - err = s.app.StakingKeeper.SetParams(s.ctx, stakingParams) - s.Require().NoError(err) - - s.ethSigner = ethtypes.LatestSignerForChainID(s.app.EvmKeeper.ChainID()) - - precompile, err := delegation.NewPrecompile(s.app.StakingAssetsManageKeeper, s.app.DelegationKeeper, s.app.AuthzKeeper) - s.Require().NoError(err) - s.precompile = precompile - - coins := sdk.NewCoins(sdk.NewCoin(utils.BaseDenom, sdk.NewInt(5000000000000000000))) - inflCoins := sdk.NewCoins(sdk.NewCoin(utils.BaseDenom, sdk.NewInt(2000000000000000000))) - distrCoins := sdk.NewCoins(sdk.NewCoin(utils.BaseDenom, sdk.NewInt(3000000000000000000))) - err = s.app.BankKeeper.MintCoins(s.ctx, inflationtypes.ModuleName, coins) - s.Require().NoError(err) - err = s.app.BankKeeper.SendCoinsFromModuleToModule(s.ctx, inflationtypes.ModuleName, authtypes.FeeCollectorName, inflCoins) - s.Require().NoError(err) - err = s.app.BankKeeper.SendCoinsFromModuleToModule(s.ctx, inflationtypes.ModuleName, distrtypes.ModuleName, distrCoins) - s.Require().NoError(err) - - queryHelperEvm := baseapp.NewQueryServerTestHelper(s.ctx, s.app.InterfaceRegistry()) - evmtypes.RegisterQueryServer(queryHelperEvm, s.app.EvmKeeper) - s.queryClientEVM = evmtypes.NewQueryClient(queryHelperEvm) -} diff --git a/precompiles/deposit/deposit_integrate_test.go b/precompiles/deposit/deposit_integrate_test.go index da95dee29..99ca68f2a 100644 --- a/precompiles/deposit/deposit_integrate_test.go +++ b/precompiles/deposit/deposit_integrate_test.go @@ -26,7 +26,7 @@ var ( passCheck testutil.LogCheckArgs ) -func (s *PrecompileTestSuite) TestCallDepositToFromEOA() { +func (s *DepositPrecompileSuite) TestCallDepositToFromEOA() { // deposit params for test exoCoreLzAppAddress := "0x3fC91A3afd70395Cd496C647d5a6CC9D4B2b7FAD" exoCoreLzAppEventTopic := "0xc6a377bfc4eb120024a8ac08eef205be16b817020812c73223e81d1bdb9708ec" @@ -36,7 +36,7 @@ func (s *PrecompileTestSuite) TestCallDepositToFromEOA() { } usdtAddress := paddingClientChainAddress(common.FromHex("0xdAC17F958D2ee523a2206206994597C13D831ec7"), types.GeneralClientChainAddrLength) clientChainLzID := 101 - stakerAddr := paddingClientChainAddress(s.address.Bytes(), types.GeneralClientChainAddrLength) + stakerAddr := paddingClientChainAddress(s.Address.Bytes(), types.GeneralClientChainAddrLength) opAmount := big.NewInt(100) assetAddr := usdtAddress method := "depositTo" @@ -47,7 +47,7 @@ func (s *PrecompileTestSuite) TestCallDepositToFromEOA() { defaultCallArgs = contracts.CallArgs{ ContractAddr: s.precompile.Address(), ContractABI: s.precompile.ABI, - PrivKey: s.privKey, + PrivKey: s.PrivKey, } defaultLogCheck = testutil.LogCheckArgs{ @@ -57,7 +57,7 @@ func (s *PrecompileTestSuite) TestCallDepositToFromEOA() { } prepareFunc := func(params *types3.Params, method string) contracts.CallArgs { - err := s.app.DepositKeeper.SetParams(s.ctx, params) + err := s.App.DepositKeeper.SetParams(s.Ctx, params) s.Require().NoError(err) defaultDepositArgs := defaultCallArgs.WithMethodName(method) return defaultDepositArgs.WithArgs( @@ -70,20 +70,20 @@ func (s *PrecompileTestSuite) TestCallDepositToFromEOA() { // test caller error beforeEach() setDepositToArgs := prepareFunc(&depositParams, method) - _, _, err := contracts.CallContractAndCheckLogs(s.ctx, s.app, setDepositToArgs, passCheck) + _, _, err := contracts.CallContractAndCheckLogs(s.Ctx, s.App, setDepositToArgs, passCheck) s.Require().ErrorContains(err, strings.Split(deposit.ErrContractCaller, ",")[0]) // test success beforeEach() - depositParams.ExoCoreLzAppAddress = s.address.String() + depositParams.ExoCoreLzAppAddress = s.Address.String() setDepositToArgs = prepareFunc(&depositParams, method) - _, ethRes, err := contracts.CallContractAndCheckLogs(s.ctx, s.app, setDepositToArgs, passCheck) + _, ethRes, err := contracts.CallContractAndCheckLogs(s.Ctx, s.App, setDepositToArgs, passCheck) successRet, err := s.precompile.Methods[deposit.MethodDepositTo].Outputs.Pack(true, opAmount) s.Require().NoError(err) s.Require().Equal(successRet, ethRes.Ret) } -func (s *PrecompileTestSuite) TestCallDepositToFromContract() { +func (s *DepositPrecompileSuite) TestCallDepositToFromContract() { // deposit params for test exoCoreLzAppAddress := "0x3fC91A3afd70395Cd496C647d5a6CC9D4B2b7FAD" exoCoreLzAppEventTopic := "0xc6a377bfc4eb120024a8ac08eef205be16b817020812c73223e81d1bdb9708ec" @@ -93,7 +93,7 @@ func (s *PrecompileTestSuite) TestCallDepositToFromContract() { } usdtAddress := paddingClientChainAddress(common.FromHex("0xdAC17F958D2ee523a2206206994597C13D831ec7"), types.GeneralClientChainAddrLength) clientChainLzID := 101 - stakerAddr := paddingClientChainAddress(s.address.Bytes(), types.GeneralClientChainAddrLength) + stakerAddr := paddingClientChainAddress(s.Address.Bytes(), types.GeneralClientChainAddrLength) opAmount := big.NewInt(100) assetAddr := usdtAddress @@ -107,8 +107,9 @@ func (s *PrecompileTestSuite) TestCallDepositToFromContract() { s.Require().NoError(err) // NextBlock the smart contract s.NextBlock() + // check contract was correctly deployed - cAcc := s.app.EvmKeeper.GetAccount(s.ctx, contractAddr) + cAcc := s.App.EvmKeeper.GetAccount(s.Ctx, contractAddr) s.Require().NotNil(cAcc) s.Require().True(cAcc.IsContract()) @@ -118,7 +119,7 @@ func (s *PrecompileTestSuite) TestCallDepositToFromContract() { defaultCallArgs = contracts.CallArgs{ ContractAddr: contractAddr, ContractABI: contracts.DepositCallerContract.ABI, - PrivKey: s.privKey, + PrivKey: s.PrivKey, } // default log check arguments @@ -127,7 +128,7 @@ func (s *PrecompileTestSuite) TestCallDepositToFromContract() { } prepareFunc := func(params *types3.Params, method string) contracts.CallArgs { - err := s.app.DepositKeeper.SetParams(s.ctx, params) + err := s.App.DepositKeeper.SetParams(s.Ctx, params) s.Require().NoError(err) defaultDepositArgs := defaultCallArgs.WithMethodName(method) return defaultDepositArgs.WithArgs( @@ -141,9 +142,9 @@ func (s *PrecompileTestSuite) TestCallDepositToFromContract() { beforeEach() depositParams.ExoCoreLzAppAddress = contractAddr.String() setDepositToArgs := prepareFunc(&depositParams, "testDepositTo") - _, _, err = contracts.CallContractAndCheckLogs(s.ctx, s.app, setDepositToArgs, passCheck) + _, _, err = contracts.CallContractAndCheckLogs(s.Ctx, s.App, setDepositToArgs, passCheck) s.Require().NoError(err) - //todo: need to find why the ethRet is nil when called by contract + // todo: need to find why the ethRet is nil when called by contract /* successRet, err := contracts.DepositCallerContract.ABI.Methods["testDepositTo"].Outputs.Pack(true, opAmount) s.Require().NoError(err) s.Require().Equal(successRet, ethRes.Ret)*/ @@ -153,7 +154,7 @@ func (s *PrecompileTestSuite) TestCallDepositToFromContract() { setDepositToArgs = prepareFunc(&depositParams, "testCallDepositToAndEmitEvent") // todo: need to check why can't get the ethereum log // eventCheck := passCheck.WithExpEvents("callDepositToResult") - _, _, err = contracts.CallContractAndCheckLogs(s.ctx, s.app, setDepositToArgs, passCheck) + _, _, err = contracts.CallContractAndCheckLogs(s.Ctx, s.App, setDepositToArgs, passCheck) s.Require().NoError(err) /* successRet, err = contracts.DepositCallerContract.ABI.Methods["testCallDepositToAndEmitEvent"].Outputs.Pack(true, opAmount) s.Require().NoError(err) @@ -165,7 +166,7 @@ func (s *PrecompileTestSuite) TestCallDepositToFromContract() { setDepositToArgs = prepareFunc(&depositParams, "testCallDepositToWithTryCatch") // eventCheck = passCheck.WithExpEvents("ErrorOccurred") // todo: need to check the ethereum log - _, _, err = contracts.CallContractAndCheckLogs(s.ctx, s.app, setDepositToArgs, passCheck) + _, _, err = contracts.CallContractAndCheckLogs(s.Ctx, s.App, setDepositToArgs, passCheck) s.Require().NoError(err) /* successRet, err = contracts.DepositCallerContract.ABI.Methods["testCallDepositToWithTryCatch"].Outputs.Pack(false, big.NewInt(0)) s.Require().NoError(err) diff --git a/precompiles/deposit/deposit_test.go b/precompiles/deposit/deposit_test.go index a2d33e405..afc4f3227 100644 --- a/precompiles/deposit/deposit_test.go +++ b/precompiles/deposit/deposit_test.go @@ -16,7 +16,7 @@ import ( evmtypes "github.com/evmos/evmos/v14/x/evm/types" ) -func (s *PrecompileTestSuite) TestIsTransaction() { +func (s *DepositPrecompileSuite) TestIsTransaction() { testCases := []struct { name string method string @@ -50,22 +50,22 @@ func paddingClientChainAddress(input []byte, outputLength int) []byte { } // TestRunDepositTo tests DepositTo method through calling Run function.. -func (s *PrecompileTestSuite) TestRunDepositTo() { +func (s *DepositPrecompileSuite) TestRunDepositTo() { // deposit params for test exoCoreLzAppAddress := "0x3fC91A3afd70395Cd496C647d5a6CC9D4B2b7FAD" exoCoreLzAppEventTopic := "0xc6a377bfc4eb120024a8ac08eef205be16b817020812c73223e81d1bdb9708ec" usdtAddress := paddingClientChainAddress(common.FromHex("0xdAC17F958D2ee523a2206206994597C13D831ec7"), types.GeneralClientChainAddrLength) usdcAddress := paddingClientChainAddress(common.FromHex("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"), types.GeneralClientChainAddrLength) clientChainLzID := 101 - stakerAddr := paddingClientChainAddress(s.address.Bytes(), types.GeneralClientChainAddrLength) + stakerAddr := paddingClientChainAddress(s.Address.Bytes(), types.GeneralClientChainAddrLength) opAmount := big.NewInt(100) assetAddr := usdtAddress commonMalleate := func() (common.Address, []byte) { - valAddr, err := sdk.ValAddressFromBech32(s.validators[0].OperatorAddress) + valAddr, err := sdk.ValAddressFromBech32(s.Validators[0].OperatorAddress) s.Require().NoError(err) - val, _ := s.app.StakingKeeper.GetValidator(s.ctx, valAddr) + val, _ := s.App.StakingKeeper.GetValidator(s.Ctx, valAddr) coins := sdk.NewCoins(sdk.NewCoin(utils.BaseDenom, sdk.NewInt(1e18))) - s.app.DistrKeeper.AllocateTokensToValidator(s.ctx, val, sdk.NewDecCoinsFromCoins(coins...)) + s.App.DistrKeeper.AllocateTokensToValidator(s.Ctx, val, sdk.NewDecCoinsFromCoins(coins...)) input, err := s.precompile.Pack( deposit.MethodDepositTo, uint16(clientChainLzID), @@ -74,7 +74,7 @@ func (s *PrecompileTestSuite) TestRunDepositTo() { opAmount, ) s.Require().NoError(err, "failed to pack input") - return s.address, input + return s.Address, input } successRet, err := s.precompile.Methods[deposit.MethodDepositTo].Outputs.Pack(true, opAmount) s.Require().NoError(err) @@ -103,7 +103,7 @@ func (s *PrecompileTestSuite) TestRunDepositTo() { ExoCoreLzAppAddress: exoCoreLzAppAddress, ExoCoreLzAppEventTopic: exoCoreLzAppEventTopic, } - err := s.app.DepositKeeper.SetParams(s.ctx, depositModuleParam) + err := s.App.DepositKeeper.SetParams(s.Ctx, depositModuleParam) s.Require().NoError(err) return commonMalleate() }, @@ -115,10 +115,10 @@ func (s *PrecompileTestSuite) TestRunDepositTo() { name: "fail - depositTo transaction will fail because the staked asset hasn't been registered", malleate: func() (common.Address, []byte) { depositModuleParam := &types3.Params{ - ExoCoreLzAppAddress: s.address.String(), + ExoCoreLzAppAddress: s.Address.String(), ExoCoreLzAppEventTopic: exoCoreLzAppEventTopic, } - err := s.app.DepositKeeper.SetParams(s.ctx, depositModuleParam) + err := s.App.DepositKeeper.SetParams(s.Ctx, depositModuleParam) s.Require().NoError(err) assetAddr = usdcAddress return commonMalleate() @@ -131,11 +131,11 @@ func (s *PrecompileTestSuite) TestRunDepositTo() { name: "pass - depositTo transaction", malleate: func() (common.Address, []byte) { depositModuleParam := &types3.Params{ - ExoCoreLzAppAddress: s.address.String(), + ExoCoreLzAppAddress: s.Address.String(), ExoCoreLzAppEventTopic: exoCoreLzAppEventTopic, } assetAddr = usdtAddress - err := s.app.DepositKeeper.SetParams(s.ctx, depositModuleParam) + err := s.App.DepositKeeper.SetParams(s.Ctx, depositModuleParam) s.Require().NoError(err) return commonMalleate() }, @@ -151,7 +151,7 @@ func (s *PrecompileTestSuite) TestRunDepositTo() { // setup basic test suite s.SetupTest() - baseFee := s.app.FeeMarketKeeper.GetBaseFee(s.ctx) + baseFee := s.App.FeeMarketKeeper.GetBaseFee(s.Ctx) // malleate testcase caller, input := tc.malleate() @@ -162,7 +162,7 @@ func (s *PrecompileTestSuite) TestRunDepositTo() { contractAddr := contract.Address() // Build and sign Ethereum transaction txArgs := evmtypes.EvmTxArgs{ - ChainID: s.app.EvmKeeper.ChainID(), + ChainID: s.App.EvmKeeper.ChainID(), Nonce: 0, To: &contractAddr, Amount: nil, @@ -174,26 +174,26 @@ func (s *PrecompileTestSuite) TestRunDepositTo() { } msgEthereumTx := evmtypes.NewTx(&txArgs) - msgEthereumTx.From = s.address.String() - err := msgEthereumTx.Sign(s.ethSigner, s.signer) + msgEthereumTx.From = s.Address.String() + err := msgEthereumTx.Sign(s.EthSigner, s.Signer) s.Require().NoError(err, "failed to sign Ethereum message") // Instantiate config - proposerAddress := s.ctx.BlockHeader().ProposerAddress - cfg, err := s.app.EvmKeeper.EVMConfig(s.ctx, proposerAddress, s.app.EvmKeeper.ChainID()) + proposerAddress := s.Ctx.BlockHeader().ProposerAddress + cfg, err := s.App.EvmKeeper.EVMConfig(s.Ctx, proposerAddress, s.App.EvmKeeper.ChainID()) s.Require().NoError(err, "failed to instantiate EVM config") - msg, err := msgEthereumTx.AsMessage(s.ethSigner, baseFee) + msg, err := msgEthereumTx.AsMessage(s.EthSigner, baseFee) s.Require().NoError(err, "failed to instantiate Ethereum message") // Instantiate EVM - evm := s.app.EvmKeeper.NewEVM( - s.ctx, msg, cfg, nil, s.stateDB, + evm := s.App.EvmKeeper.NewEVM( + s.Ctx, msg, cfg, nil, s.StateDB, ) - params := s.app.EvmKeeper.GetParams(s.ctx) + params := s.App.EvmKeeper.GetParams(s.Ctx) activePrecompiles := params.GetActivePrecompilesAddrs() - precompileMap := s.app.EvmKeeper.Precompiles(activePrecompiles...) + precompileMap := s.App.EvmKeeper.Precompiles(activePrecompiles...) err = vm.ValidatePrecompiles(precompileMap, activePrecompiles) s.Require().NoError(err, "invalid precompiles", activePrecompiles) evm.WithPrecompiles(precompileMap, activePrecompiles) diff --git a/precompiles/deposit/error.go b/precompiles/deposit/error.go index 268df762a..3bce6ea7e 100644 --- a/precompiles/deposit/error.go +++ b/precompiles/deposit/error.go @@ -1,7 +1,7 @@ package deposit const ( - ErrContractInputParaOrType = "the contract input parameter type or value error,arg index:%d, type is:%s,value:%v" + ErrContractInputParaOrType = "the contract input parameter type or value error,arg index:%d, expected type is:%s,value:%v" ErrContractCaller = "the caller doesn't have the permission to call this function,caller:%s,need:%s" ErrInputClientChainAddrLength = "the length of input client chain addr doesn't match,input:%d,need:%d" ) diff --git a/precompiles/deposit/setup_test.go b/precompiles/deposit/setup_test.go index 7c0783634..a489fe03d 100644 --- a/precompiles/deposit/setup_test.go +++ b/precompiles/deposit/setup_test.go @@ -1,50 +1,27 @@ package deposit_test import ( + "github.com/ExocoreNetwork/exocore/testutil" "testing" "github.com/ExocoreNetwork/exocore/precompiles/deposit" - "github.com/evmos/evmos/v14/x/evm/statedb" - . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - evmosapp "github.com/ExocoreNetwork/exocore/app" - tmtypes "github.com/cometbft/cometbft/types" - "github.com/cosmos/cosmos-sdk/crypto/keyring" - cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" - sdk "github.com/cosmos/cosmos-sdk/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/ethereum/go-ethereum/common" - ethtypes "github.com/ethereum/go-ethereum/core/types" - evmtypes "github.com/evmos/evmos/v14/x/evm/types" "github.com/stretchr/testify/suite" ) -var s *PrecompileTestSuite - -type PrecompileTestSuite struct { - suite.Suite +var s *DepositPrecompileSuite - ctx sdk.Context - app *evmosapp.ExocoreApp - address common.Address - validators []stakingtypes.Validator - valSet *tmtypes.ValidatorSet - ethSigner ethtypes.Signer - privKey cryptotypes.PrivKey - signer keyring.Signer - bondDenom string +type DepositPrecompileSuite struct { + testutil.BaseTestSuite precompile *deposit.Precompile - stateDB *statedb.StateDB - - queryClientEVM evmtypes.QueryClient } func TestPrecompileTestSuite(t *testing.T) { - s = new(PrecompileTestSuite) + s = new(DepositPrecompileSuite) suite.Run(t, s) // Run Ginkgo integration tests @@ -52,6 +29,9 @@ func TestPrecompileTestSuite(t *testing.T) { RunSpecs(t, "Distribution Precompile Suite") } -func (s *PrecompileTestSuite) SetupTest() { +func (s *DepositPrecompileSuite) SetupTest() { s.DoSetupTest() + precompile, err := deposit.NewPrecompile(s.App.StakingAssetsManageKeeper, s.App.DepositKeeper, s.App.AuthzKeeper) + s.Require().NoError(err) + s.precompile = precompile } diff --git a/precompiles/deposit/types.go b/precompiles/deposit/types.go index dddc870f9..140677bfd 100644 --- a/precompiles/deposit/types.go +++ b/precompiles/deposit/types.go @@ -1,25 +1,24 @@ package deposit import ( - "fmt" "math/big" - "reflect" sdkmath "cosmossdk.io/math" "github.com/ExocoreNetwork/exocore/x/deposit/keeper" "github.com/ExocoreNetwork/exocore/x/restaking_assets_manage/types" sdk "github.com/cosmos/cosmos-sdk/types" cmn "github.com/evmos/evmos/v14/precompiles/common" + "golang.org/x/xerrors" ) func (p Precompile) GetDepositToParamsFromInputs(ctx sdk.Context, args []interface{}) (*keeper.DepositParams, error) { if len(args) != 4 { - return nil, fmt.Errorf(cmn.ErrInvalidNumberOfArgs, 4, len(args)) + return nil, xerrors.Errorf(cmn.ErrInvalidNumberOfArgs, 4, len(args)) } depositParams := &keeper.DepositParams{} clientChainLzID, ok := args[0].(uint16) if !ok { - return nil, fmt.Errorf(ErrContractInputParaOrType, 0, reflect.TypeOf(args[0]), clientChainLzID) + return nil, xerrors.Errorf(ErrContractInputParaOrType, 0, "uint16", clientChainLzID) } depositParams.ClientChainLzID = uint64(clientChainLzID) @@ -32,25 +31,25 @@ func (p Precompile) GetDepositToParamsFromInputs(ctx sdk.Context, args []interfa // the length of client chain address inputted by caller is 32, so we need to check the length and remove the padding according to the actual length. assetAddr, ok := args[1].([]byte) if !ok || assetAddr == nil { - return nil, fmt.Errorf(ErrContractInputParaOrType, 1, reflect.TypeOf(args[0]), assetAddr) + return nil, xerrors.Errorf(ErrContractInputParaOrType, 1, "[]byte", assetAddr) } if len(assetAddr) != types.GeneralAssetsAddrLength { - return nil, fmt.Errorf(ErrInputClientChainAddrLength, len(assetAddr), types.GeneralClientChainAddrLength) + return nil, xerrors.Errorf(ErrInputClientChainAddrLength, len(assetAddr), types.GeneralClientChainAddrLength) } depositParams.AssetsAddress = assetAddr[:clientChainAddrLength] stakerAddr, ok := args[2].([]byte) if !ok || stakerAddr == nil { - return nil, fmt.Errorf(ErrContractInputParaOrType, 2, reflect.TypeOf(args[0]), stakerAddr) + return nil, xerrors.Errorf(ErrContractInputParaOrType, 2, "[]byte", stakerAddr) } if len(stakerAddr) != types.GeneralClientChainAddrLength { - return nil, fmt.Errorf(ErrInputClientChainAddrLength, len(assetAddr), types.GeneralClientChainAddrLength) + return nil, xerrors.Errorf(ErrInputClientChainAddrLength, len(assetAddr), types.GeneralClientChainAddrLength) } depositParams.StakerAddress = stakerAddr[:clientChainAddrLength] opAmount, ok := args[3].(*big.Int) if !ok || opAmount == nil || opAmount.Cmp(big.NewInt(0)) == 0 { - return nil, fmt.Errorf(ErrContractInputParaOrType, 3, reflect.TypeOf(args[0]), opAmount) + return nil, xerrors.Errorf(ErrContractInputParaOrType, 3, "*big.Int", opAmount) } depositParams.OpAmount = sdkmath.NewIntFromBigInt(opAmount) diff --git a/precompiles/reward/reward_test.go b/precompiles/reward/reward_test.go index 3306dba68..ccc2f0483 100644 --- a/precompiles/reward/reward_test.go +++ b/precompiles/reward/reward_test.go @@ -17,7 +17,7 @@ import ( evmtypes "github.com/evmos/evmos/v14/x/evm/types" ) -func (s *PrecompileTestSuite) TestIsTransaction() { +func (s *RewardPrecompileTestSuite) TestIsTransaction() { testCases := []struct { name string method string @@ -51,7 +51,7 @@ func paddingClientChainAddress(input []byte, outputLength int) []byte { } // TestRun tests the precompiled Run method reward. -func (s *PrecompileTestSuite) TestRunRewardThroughClientChain() { +func (s *RewardPrecompileTestSuite) TestRunRewardThroughClientChain() { // deposit params for test exoCoreLzAppEventTopic := "0xc6a377bfc4eb120024a8ac08eef205be16b817020812c73223e81d1bdb9708ec" usdtAddress := common.FromHex("0xdAC17F958D2ee523a2206206994597C13D831ec7") @@ -68,7 +68,7 @@ func (s *PrecompileTestSuite) TestRunRewardThroughClientChain() { AssetsAddress: usdtAddress, OpAmount: depositAmount, } - err := s.app.DepositKeeper.Deposit(s.ctx, params) + err := s.App.DepositKeeper.Deposit(s.Ctx, params) s.Require().NoError(err) } @@ -78,11 +78,11 @@ func (s *PrecompileTestSuite) TestRunRewardThroughClientChain() { reward.MethodReward, uint16(clientChainLzID), assetAddr, - paddingClientChainAddress(s.address.Bytes(), types.GeneralClientChainAddrLength), + paddingClientChainAddress(s.Address.Bytes(), types.GeneralClientChainAddrLength), withdrawAmount, ) s.Require().NoError(err, "failed to pack input") - return s.address, input + return s.Address, input } successRet, err := s.precompile.Methods[reward.MethodReward].Outputs.Pack(true, new(big.Int).Add(depositAmount, withdrawAmount)) s.Require().NoError(err) @@ -98,17 +98,17 @@ func (s *PrecompileTestSuite) TestRunRewardThroughClientChain() { name: "pass - reward via pre-compiles", malleate: func() (common.Address, []byte) { depositModuleParam := &depositParams.Params{ - ExoCoreLzAppAddress: s.address.String(), + ExoCoreLzAppAddress: s.Address.String(), ExoCoreLzAppEventTopic: exoCoreLzAppEventTopic, } - err := s.app.DepositKeeper.SetParams(s.ctx, depositModuleParam) + err := s.App.DepositKeeper.SetParams(s.Ctx, depositModuleParam) s.Require().NoError(err) - depositAsset(s.address.Bytes(), sdkmath.NewIntFromBigInt(depositAmount)) + depositAsset(s.Address.Bytes(), sdkmath.NewIntFromBigInt(depositAmount)) rewardModuleParam := &rewardParams.Params{ - ExoCoreLzAppAddress: s.address.String(), + ExoCoreLzAppAddress: s.Address.String(), ExoCoreLzAppEventTopic: exoCoreLzAppEventTopic, } - err = s.app.RewardKeeper.SetParams(s.ctx, rewardModuleParam) + err = s.App.RewardKeeper.SetParams(s.Ctx, rewardModuleParam) s.Require().NoError(err) return commonMalleate() }, @@ -123,7 +123,7 @@ func (s *PrecompileTestSuite) TestRunRewardThroughClientChain() { // setup basic test suite s.SetupTest() - baseFee := s.app.FeeMarketKeeper.GetBaseFee(s.ctx) + baseFee := s.App.FeeMarketKeeper.GetBaseFee(s.Ctx) // malleate testcase caller, input := tc.malleate() @@ -134,7 +134,7 @@ func (s *PrecompileTestSuite) TestRunRewardThroughClientChain() { contractAddr := contract.Address() // Build and sign Ethereum transaction txArgs := evmtypes.EvmTxArgs{ - ChainID: s.app.EvmKeeper.ChainID(), + ChainID: s.App.EvmKeeper.ChainID(), Nonce: 0, To: &contractAddr, Amount: nil, @@ -146,27 +146,27 @@ func (s *PrecompileTestSuite) TestRunRewardThroughClientChain() { } msgEthereumTx := evmtypes.NewTx(&txArgs) - msgEthereumTx.From = s.address.String() - err := msgEthereumTx.Sign(s.ethSigner, s.signer) + msgEthereumTx.From = s.Address.String() + err := msgEthereumTx.Sign(s.EthSigner, s.Signer) s.Require().NoError(err, "failed to sign Ethereum message") // Instantiate config - proposerAddress := s.ctx.BlockHeader().ProposerAddress - cfg, err := s.app.EvmKeeper.EVMConfig(s.ctx, proposerAddress, s.app.EvmKeeper.ChainID()) + proposerAddress := s.Ctx.BlockHeader().ProposerAddress + cfg, err := s.App.EvmKeeper.EVMConfig(s.Ctx, proposerAddress, s.App.EvmKeeper.ChainID()) s.Require().NoError(err, "failed to instantiate EVM config") - msg, err := msgEthereumTx.AsMessage(s.ethSigner, baseFee) + msg, err := msgEthereumTx.AsMessage(s.EthSigner, baseFee) s.Require().NoError(err, "failed to instantiate Ethereum message") // Create StateDB - s.stateDB = statedb.New(s.ctx, s.app.EvmKeeper, statedb.NewEmptyTxConfig(common.BytesToHash(s.ctx.HeaderHash().Bytes()))) + s.StateDB = statedb.New(s.Ctx, s.App.EvmKeeper, statedb.NewEmptyTxConfig(common.BytesToHash(s.Ctx.HeaderHash().Bytes()))) // Instantiate EVM - evm := s.app.EvmKeeper.NewEVM( - s.ctx, msg, cfg, nil, s.stateDB, + evm := s.App.EvmKeeper.NewEVM( + s.Ctx, msg, cfg, nil, s.StateDB, ) - params := s.app.EvmKeeper.GetParams(s.ctx) + params := s.App.EvmKeeper.GetParams(s.Ctx) activePrecompiles := params.GetActivePrecompilesAddrs() - precompileMap := s.app.EvmKeeper.Precompiles(activePrecompiles...) + precompileMap := s.App.EvmKeeper.Precompiles(activePrecompiles...) err = vm.ValidatePrecompiles(precompileMap, activePrecompiles) s.Require().NoError(err, "invalid precompiles", activePrecompiles) evm.WithPrecompiles(precompileMap, activePrecompiles) diff --git a/precompiles/reward/setup_test.go b/precompiles/reward/setup_test.go index e8db9fdbb..9b444815e 100644 --- a/precompiles/reward/setup_test.go +++ b/precompiles/reward/setup_test.go @@ -1,50 +1,26 @@ package reward_test import ( + "github.com/ExocoreNetwork/exocore/testutil" "testing" "github.com/ExocoreNetwork/exocore/precompiles/reward" - "github.com/evmos/evmos/v14/x/evm/statedb" - . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - evmosapp "github.com/ExocoreNetwork/exocore/app" - tmtypes "github.com/cometbft/cometbft/types" - "github.com/cosmos/cosmos-sdk/crypto/keyring" - cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" - sdk "github.com/cosmos/cosmos-sdk/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/ethereum/go-ethereum/common" - ethtypes "github.com/ethereum/go-ethereum/core/types" - evmtypes "github.com/evmos/evmos/v14/x/evm/types" "github.com/stretchr/testify/suite" ) -var s *PrecompileTestSuite - -type PrecompileTestSuite struct { - suite.Suite - - ctx sdk.Context - app *evmosapp.ExocoreApp - address common.Address - validators []stakingtypes.Validator - valSet *tmtypes.ValidatorSet - ethSigner ethtypes.Signer - privKey cryptotypes.PrivKey - signer keyring.Signer - bondDenom string +var s *RewardPrecompileTestSuite +type RewardPrecompileTestSuite struct { + testutil.BaseTestSuite precompile *reward.Precompile - stateDB *statedb.StateDB - - queryClientEVM evmtypes.QueryClient } func TestPrecompileTestSuite(t *testing.T) { - s = new(PrecompileTestSuite) + s = new(RewardPrecompileTestSuite) suite.Run(t, s) // Run Ginkgo integration tests @@ -52,6 +28,9 @@ func TestPrecompileTestSuite(t *testing.T) { RunSpecs(t, "Reward Precompile Suite") } -func (s *PrecompileTestSuite) SetupTest() { +func (s *RewardPrecompileTestSuite) SetupTest() { s.DoSetupTest() + precompile, err := reward.NewPrecompile(s.App.StakingAssetsManageKeeper, s.App.RewardKeeper, s.App.AuthzKeeper) + s.Require().NoError(err) + s.precompile = precompile } diff --git a/precompiles/reward/utils_test.go b/precompiles/reward/utils_test.go deleted file mode 100644 index 61a8dc469..000000000 --- a/precompiles/reward/utils_test.go +++ /dev/null @@ -1,231 +0,0 @@ -package reward_test - -import ( - "encoding/json" - "time" - - evmosapp "github.com/ExocoreNetwork/exocore/app" - "github.com/ExocoreNetwork/exocore/precompiles/reward" - "github.com/ExocoreNetwork/exocore/utils" - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cometbft/cometbft/crypto/tmhash" - tmtypes "github.com/cometbft/cometbft/types" - "github.com/cosmos/cosmos-sdk/baseapp" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - "github.com/cosmos/cosmos-sdk/testutil/mock" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/ethereum/go-ethereum/common" - ethtypes "github.com/ethereum/go-ethereum/core/types" - cmn "github.com/evmos/evmos/v14/precompiles/common" - "github.com/evmos/evmos/v14/precompiles/testutil/contracts" - "github.com/evmos/evmos/v14/precompiles/vesting/testdata" - evmosutil "github.com/evmos/evmos/v14/testutil" - evmosutiltx "github.com/evmos/evmos/v14/testutil/tx" - evmostypes "github.com/evmos/evmos/v14/types" - "github.com/evmos/evmos/v14/x/evm/statedb" - evmtypes "github.com/evmos/evmos/v14/x/evm/types" - inflationtypes "github.com/evmos/evmos/v14/x/inflation/types" -) - -// SetupWithGenesisValSet initializes a new EvmosApp with a validator set and genesis accounts -// that also act as delegators. For simplicity, each validator is bonded with a delegation -// of one consensus engine unit (10^6) in the default token of the simapp from first genesis -// account. A Nop logger is set in SimApp. -func (s *PrecompileTestSuite) SetupWithGenesisValSet(valSet *tmtypes.ValidatorSet, genAccs []authtypes.GenesisAccount, balances ...banktypes.Balance) { - appI, genesisState := evmosapp.SetupTestingApp(cmn.DefaultChainID, false)() - app, ok := appI.(*evmosapp.ExocoreApp) - s.Require().True(ok) - - // set genesis accounts - authGenesis := authtypes.NewGenesisState(authtypes.DefaultParams(), genAccs) - genesisState[authtypes.ModuleName] = app.AppCodec().MustMarshalJSON(authGenesis) - - validators := make([]stakingtypes.Validator, 0, len(valSet.Validators)) - delegations := make([]stakingtypes.Delegation, 0, len(valSet.Validators)) - - bondAmt := sdk.TokensFromConsensusPower(1, evmostypes.PowerReduction) - - for _, val := range valSet.Validators { - pk, err := cryptocodec.FromTmPubKeyInterface(val.PubKey) - s.Require().NoError(err) - pkAny, err := codectypes.NewAnyWithValue(pk) - s.Require().NoError(err) - validator := stakingtypes.Validator{ - OperatorAddress: sdk.ValAddress(val.Address).String(), - ConsensusPubkey: pkAny, - Jailed: false, - Status: stakingtypes.Bonded, - Tokens: bondAmt, - DelegatorShares: sdk.OneDec(), - Description: stakingtypes.Description{}, - UnbondingHeight: int64(0), - UnbondingTime: time.Unix(0, 0).UTC(), - Commission: stakingtypes.NewCommission(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), - MinSelfDelegation: sdk.ZeroInt(), - } - validators = append(validators, validator) - delegations = append(delegations, stakingtypes.NewDelegation(genAccs[0].GetAddress(), val.Address.Bytes(), sdk.OneDec())) - } - s.validators = validators - - // set validators and delegations - stakingParams := stakingtypes.DefaultParams() - // set bond demon to be aevmos - stakingParams.BondDenom = utils.BaseDenom - stakingGenesis := stakingtypes.NewGenesisState(stakingParams, validators, delegations) - genesisState[stakingtypes.ModuleName] = app.AppCodec().MustMarshalJSON(stakingGenesis) - - totalBondAmt := bondAmt.Add(bondAmt) - totalSupply := sdk.NewCoins() - for _, b := range balances { - // add genesis acc tokens and delegated tokens to total supply - totalSupply = totalSupply.Add(b.Coins.Add(sdk.NewCoin(utils.BaseDenom, totalBondAmt))...) - } - - // add bonded amount to bonded pool module account - balances = append(balances, banktypes.Balance{ - Address: authtypes.NewModuleAddress(stakingtypes.BondedPoolName).String(), - Coins: sdk.Coins{sdk.NewCoin(utils.BaseDenom, totalBondAmt)}, - }) - - // update total supply - bankGenesis := banktypes.NewGenesisState(banktypes.DefaultGenesisState().Params, balances, totalSupply, []banktypes.Metadata{}, []banktypes.SendEnabled{}) - genesisState[banktypes.ModuleName] = app.AppCodec().MustMarshalJSON(bankGenesis) - - stateBytes, err := json.MarshalIndent(genesisState, "", " ") - s.Require().NoError(err) - - // init chain will set the validator set and initialize the genesis accounts - app.InitChain( - abci.RequestInitChain{ - ChainId: cmn.DefaultChainID, - Validators: []abci.ValidatorUpdate{}, - ConsensusParams: evmosapp.DefaultConsensusParams, - AppStateBytes: stateBytes, - }, - ) - app.Commit() - - // instantiate new header - header := evmosutil.NewHeader( - 2, - time.Now().UTC(), - cmn.DefaultChainID, - sdk.ConsAddress(validators[0].GetOperator()), - tmhash.Sum([]byte("app")), - tmhash.Sum([]byte("validators")), - ) - - app.BeginBlock(abci.RequestBeginBlock{ - Header: header, - }) - - // create Context - s.ctx = app.BaseApp.NewContext(false, header) - s.app = app -} - -func (s *PrecompileTestSuite) DoSetupTest() { - // generate validator private/public key - privVal := mock.NewPV() - pubKey, err := privVal.GetPubKey() - s.Require().NoError(err) - - privVal2 := mock.NewPV() - pubKey2, err := privVal2.GetPubKey() - s.Require().NoError(err) - - // create validator set with two validators - validator := tmtypes.NewValidator(pubKey, 1) - validator2 := tmtypes.NewValidator(pubKey2, 2) - s.valSet = tmtypes.NewValidatorSet([]*tmtypes.Validator{validator, validator2}) - signers := make(map[string]tmtypes.PrivValidator) - signers[pubKey.Address().String()] = privVal - signers[pubKey2.Address().String()] = privVal2 - - // generate genesis account - addr, priv := evmosutiltx.NewAddrKey() - s.privKey = priv - s.address = addr - s.signer = evmosutiltx.NewSigner(priv) - - baseAcc := authtypes.NewBaseAccount(priv.PubKey().Address().Bytes(), priv.PubKey(), 0, 0) - - acc := &evmostypes.EthAccount{ - BaseAccount: baseAcc, - CodeHash: common.BytesToHash(evmtypes.EmptyCodeHash).Hex(), - } - - amount := sdk.TokensFromConsensusPower(5, evmostypes.PowerReduction) - - balance := banktypes.Balance{ - Address: acc.GetAddress().String(), - Coins: sdk.NewCoins(sdk.NewCoin(utils.BaseDenom, amount)), - } - - s.SetupWithGenesisValSet(s.valSet, []authtypes.GenesisAccount{acc}, balance) - - // Create StateDB - s.stateDB = statedb.New(s.ctx, s.app.EvmKeeper, statedb.NewEmptyTxConfig(common.BytesToHash(s.ctx.HeaderHash().Bytes()))) - - // bond denom - stakingParams := s.app.StakingKeeper.GetParams(s.ctx) - stakingParams.BondDenom = utils.BaseDenom - s.bondDenom = stakingParams.BondDenom - err = s.app.StakingKeeper.SetParams(s.ctx, stakingParams) - s.Require().NoError(err) - - s.ethSigner = ethtypes.LatestSignerForChainID(s.app.EvmKeeper.ChainID()) - - precompile, err := reward.NewPrecompile(s.app.StakingAssetsManageKeeper, s.app.RewardKeeper, s.app.AuthzKeeper) - s.Require().NoError(err) - s.precompile = precompile - - coins := sdk.NewCoins(sdk.NewCoin(utils.BaseDenom, sdk.NewInt(5000000000000000000))) - inflCoins := sdk.NewCoins(sdk.NewCoin(utils.BaseDenom, sdk.NewInt(2000000000000000000))) - distrCoins := sdk.NewCoins(sdk.NewCoin(utils.BaseDenom, sdk.NewInt(3000000000000000000))) - err = s.app.BankKeeper.MintCoins(s.ctx, inflationtypes.ModuleName, coins) - s.Require().NoError(err) - err = s.app.BankKeeper.SendCoinsFromModuleToModule(s.ctx, inflationtypes.ModuleName, authtypes.FeeCollectorName, inflCoins) - s.Require().NoError(err) - err = s.app.BankKeeper.SendCoinsFromModuleToModule(s.ctx, inflationtypes.ModuleName, distrtypes.ModuleName, distrCoins) - s.Require().NoError(err) - - queryHelperEvm := baseapp.NewQueryServerTestHelper(s.ctx, s.app.InterfaceRegistry()) - evmtypes.RegisterQueryServer(queryHelperEvm, s.app.EvmKeeper) - s.queryClientEVM = evmtypes.NewQueryClient(queryHelperEvm) -} - -// CallType is a struct that represents the type of call to be made to -// precompile - either direct or through a smart contract. -type CallType struct { - // name is the name of the call type - name string - // directCall is true if the call is to be made directly to precompile - directCall bool -} - -// BuildCallArgs builds the call arguments for the integration test suite -// depending on the type of interaction. -func (s *PrecompileTestSuite) BuildCallArgs( - callType CallType, - contractAddr common.Address, -) contracts.CallArgs { - callArgs := contracts.CallArgs{ - PrivKey: s.privKey, - } - if callType.directCall { - callArgs.ContractABI = s.precompile.ABI - callArgs.ContractAddr = s.precompile.Address() - } else { - callArgs.ContractAddr = contractAddr - callArgs.ContractABI = testdata.VestingCallerContract.ABI - } - - return callArgs -} diff --git a/precompiles/slash/setup_test.go b/precompiles/slash/setup_test.go index bd7eaf1b3..dcae7c8ee 100644 --- a/precompiles/slash/setup_test.go +++ b/precompiles/slash/setup_test.go @@ -1,50 +1,26 @@ package slash_test import ( + "github.com/ExocoreNetwork/exocore/testutil" "testing" "github.com/ExocoreNetwork/exocore/precompiles/slash" - "github.com/evmos/evmos/v14/x/evm/statedb" - . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - evmosapp "github.com/ExocoreNetwork/exocore/app" - tmtypes "github.com/cometbft/cometbft/types" - "github.com/cosmos/cosmos-sdk/crypto/keyring" - cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" - sdk "github.com/cosmos/cosmos-sdk/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/ethereum/go-ethereum/common" - ethtypes "github.com/ethereum/go-ethereum/core/types" - evmtypes "github.com/evmos/evmos/v14/x/evm/types" "github.com/stretchr/testify/suite" ) -var s *PrecompileTestSuite - -type PrecompileTestSuite struct { - suite.Suite - - ctx sdk.Context - app *evmosapp.ExocoreApp - address common.Address - validators []stakingtypes.Validator - valSet *tmtypes.ValidatorSet - ethSigner ethtypes.Signer - privKey cryptotypes.PrivKey - signer keyring.Signer - bondDenom string +var s *SlashPrecompileTestSuite +type SlashPrecompileTestSuite struct { + testutil.BaseTestSuite precompile *slash.Precompile - stateDB *statedb.StateDB - - queryClientEVM evmtypes.QueryClient } func TestPrecompileTestSuite(t *testing.T) { - s = new(PrecompileTestSuite) + s = new(SlashPrecompileTestSuite) suite.Run(t, s) // Run Ginkgo integration tests @@ -52,6 +28,9 @@ func TestPrecompileTestSuite(t *testing.T) { RunSpecs(t, "Slash Precompile Suite") } -func (s *PrecompileTestSuite) SetupTest() { +func (s *SlashPrecompileTestSuite) SetupTest() { s.DoSetupTest() + precompile, err := slash.NewPrecompile(s.App.StakingAssetsManageKeeper, s.App.ExoSlashKeeper, s.App.AuthzKeeper) + s.Require().NoError(err) + s.precompile = precompile } diff --git a/precompiles/slash/slash_test.go b/precompiles/slash/slash_test.go index 6d653dab6..2538a6a70 100644 --- a/precompiles/slash/slash_test.go +++ b/precompiles/slash/slash_test.go @@ -17,7 +17,7 @@ import ( evmtypes "github.com/evmos/evmos/v14/x/evm/types" ) -func (s *PrecompileTestSuite) TestIsTransaction() { +func (s *SlashPrecompileTestSuite) TestIsTransaction() { testCases := []struct { name string method string @@ -51,7 +51,7 @@ func paddingClientChainAddress(input []byte, outputLength int) []byte { } // TestRun tests the precompiles Run method submitSlash. -func (s *PrecompileTestSuite) TestRunSlash() { +func (s *SlashPrecompileTestSuite) TestRunSlash() { // deposit params for test exoCoreLzAppEventTopic := "0xc6a377bfc4eb120024a8ac08eef205be16b817020812c73223e81d1bdb9708ec" usdtAddress := common.FromHex("0xdAC17F958D2ee523a2206206994597C13D831ec7") @@ -68,7 +68,7 @@ func (s *PrecompileTestSuite) TestRunSlash() { AssetsAddress: usdtAddress, OpAmount: depositAmount, } - err := s.app.DepositKeeper.Deposit(s.ctx, params) + err := s.App.DepositKeeper.Deposit(s.Ctx, params) s.Require().NoError(err) } @@ -78,7 +78,7 @@ func (s *PrecompileTestSuite) TestRunSlash() { slash.MethodSlash, uint16(clientChainLzID), assetAddr, - paddingClientChainAddress(s.address.Bytes(), types.GeneralClientChainAddrLength), + paddingClientChainAddress(s.Address.Bytes(), types.GeneralClientChainAddrLength), slashAmount, common.FromHex("0x2E756b8faBeA234b9900767b69D6387400CDC396"), common.FromHex("0xceb69f6342ece283b2f5c9088ff249b5d0ae66ea"), @@ -86,7 +86,7 @@ func (s *PrecompileTestSuite) TestRunSlash() { "slash", ) s.Require().NoError(err, "failed to pack input") - return s.address, input + return s.Address, input } successRet, err := s.precompile.Methods[slash.MethodSlash].Outputs.Pack(true) s.Require().NoError(err) @@ -102,17 +102,17 @@ func (s *PrecompileTestSuite) TestRunSlash() { name: "pass - slash via pre-compiles", malleate: func() (common.Address, []byte) { depositModuleParam := &depositParams.Params{ - ExoCoreLzAppAddress: s.address.String(), + ExoCoreLzAppAddress: s.Address.String(), ExoCoreLzAppEventTopic: exoCoreLzAppEventTopic, } - err := s.app.DepositKeeper.SetParams(s.ctx, depositModuleParam) + err := s.App.DepositKeeper.SetParams(s.Ctx, depositModuleParam) s.Require().NoError(err) - depositAsset(s.address.Bytes(), sdkmath.NewIntFromBigInt(depositAmount)) + depositAsset(s.Address.Bytes(), sdkmath.NewIntFromBigInt(depositAmount)) slashModuleParam := &slashParams.Params{ - ExoCoreLzAppAddress: s.address.String(), + ExoCoreLzAppAddress: s.Address.String(), ExoCoreLzAppEventTopic: exoCoreLzAppEventTopic, } - err = s.app.ExoSlashKeeper.SetParams(s.ctx, slashModuleParam) + err = s.App.ExoSlashKeeper.SetParams(s.Ctx, slashModuleParam) s.Require().NoError(err) return commonMalleate() }, @@ -127,7 +127,7 @@ func (s *PrecompileTestSuite) TestRunSlash() { // setup basic test suite s.SetupTest() - baseFee := s.app.FeeMarketKeeper.GetBaseFee(s.ctx) + baseFee := s.App.FeeMarketKeeper.GetBaseFee(s.Ctx) // malleate testcase caller, input := tc.malleate() @@ -138,7 +138,7 @@ func (s *PrecompileTestSuite) TestRunSlash() { contractAddr := contract.Address() // Build and sign Ethereum transaction txArgs := evmtypes.EvmTxArgs{ - ChainID: s.app.EvmKeeper.ChainID(), + ChainID: s.App.EvmKeeper.ChainID(), Nonce: 0, To: &contractAddr, Amount: nil, @@ -150,27 +150,27 @@ func (s *PrecompileTestSuite) TestRunSlash() { } msgEthereumTx := evmtypes.NewTx(&txArgs) - msgEthereumTx.From = s.address.String() - err := msgEthereumTx.Sign(s.ethSigner, s.signer) + msgEthereumTx.From = s.Address.String() + err := msgEthereumTx.Sign(s.EthSigner, s.Signer) s.Require().NoError(err, "failed to sign Ethereum message") // Instantiate config - proposerAddress := s.ctx.BlockHeader().ProposerAddress - cfg, err := s.app.EvmKeeper.EVMConfig(s.ctx, proposerAddress, s.app.EvmKeeper.ChainID()) + proposerAddress := s.Ctx.BlockHeader().ProposerAddress + cfg, err := s.App.EvmKeeper.EVMConfig(s.Ctx, proposerAddress, s.App.EvmKeeper.ChainID()) s.Require().NoError(err, "failed to instantiate EVM config") - msg, err := msgEthereumTx.AsMessage(s.ethSigner, baseFee) + msg, err := msgEthereumTx.AsMessage(s.EthSigner, baseFee) s.Require().NoError(err, "failed to instantiate Ethereum message") // Create StateDB - s.stateDB = statedb.New(s.ctx, s.app.EvmKeeper, statedb.NewEmptyTxConfig(common.BytesToHash(s.ctx.HeaderHash().Bytes()))) + s.StateDB = statedb.New(s.Ctx, s.App.EvmKeeper, statedb.NewEmptyTxConfig(common.BytesToHash(s.Ctx.HeaderHash().Bytes()))) // Instantiate EVM - evm := s.app.EvmKeeper.NewEVM( - s.ctx, msg, cfg, nil, s.stateDB, + evm := s.App.EvmKeeper.NewEVM( + s.Ctx, msg, cfg, nil, s.StateDB, ) - params := s.app.EvmKeeper.GetParams(s.ctx) + params := s.App.EvmKeeper.GetParams(s.Ctx) activePrecompiles := params.GetActivePrecompilesAddrs() - precompileMap := s.app.EvmKeeper.Precompiles(activePrecompiles...) + precompileMap := s.App.EvmKeeper.Precompiles(activePrecompiles...) err = vm.ValidatePrecompiles(precompileMap, activePrecompiles) s.Require().NoError(err, "invalid precompiles", activePrecompiles) evm.WithPrecompiles(precompileMap, activePrecompiles) diff --git a/precompiles/slash/utils_test.go b/precompiles/slash/utils_test.go deleted file mode 100644 index 47ba515ab..000000000 --- a/precompiles/slash/utils_test.go +++ /dev/null @@ -1,231 +0,0 @@ -package slash_test - -import ( - "encoding/json" - "time" - - evmosapp "github.com/ExocoreNetwork/exocore/app" - "github.com/ExocoreNetwork/exocore/precompiles/slash" - "github.com/ExocoreNetwork/exocore/utils" - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cometbft/cometbft/crypto/tmhash" - tmtypes "github.com/cometbft/cometbft/types" - "github.com/cosmos/cosmos-sdk/baseapp" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - "github.com/cosmos/cosmos-sdk/testutil/mock" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/ethereum/go-ethereum/common" - ethtypes "github.com/ethereum/go-ethereum/core/types" - cmn "github.com/evmos/evmos/v14/precompiles/common" - "github.com/evmos/evmos/v14/precompiles/testutil/contracts" - "github.com/evmos/evmos/v14/precompiles/vesting/testdata" - evmosutil "github.com/evmos/evmos/v14/testutil" - evmosutiltx "github.com/evmos/evmos/v14/testutil/tx" - evmostypes "github.com/evmos/evmos/v14/types" - "github.com/evmos/evmos/v14/x/evm/statedb" - evmtypes "github.com/evmos/evmos/v14/x/evm/types" - inflationtypes "github.com/evmos/evmos/v14/x/inflation/types" -) - -// SetupWithGenesisValSet initializes a new EvmosApp with a validator set and genesis accounts -// that also act as delegators. For simplicity, each validator is bonded with a delegation -// of one consensus engine unit (10^6) in the default token of the simapp from first genesis -// account. A Nop logger is set in SimApp. -func (s *PrecompileTestSuite) SetupWithGenesisValSet(valSet *tmtypes.ValidatorSet, genAccs []authtypes.GenesisAccount, balances ...banktypes.Balance) { - appI, genesisState := evmosapp.SetupTestingApp(cmn.DefaultChainID, false)() - app, ok := appI.(*evmosapp.ExocoreApp) - s.Require().True(ok) - - // set genesis accounts - authGenesis := authtypes.NewGenesisState(authtypes.DefaultParams(), genAccs) - genesisState[authtypes.ModuleName] = app.AppCodec().MustMarshalJSON(authGenesis) - - validators := make([]stakingtypes.Validator, 0, len(valSet.Validators)) - delegations := make([]stakingtypes.Delegation, 0, len(valSet.Validators)) - - bondAmt := sdk.TokensFromConsensusPower(1, evmostypes.PowerReduction) - - for _, val := range valSet.Validators { - pk, err := cryptocodec.FromTmPubKeyInterface(val.PubKey) - s.Require().NoError(err) - pkAny, err := codectypes.NewAnyWithValue(pk) - s.Require().NoError(err) - validator := stakingtypes.Validator{ - OperatorAddress: sdk.ValAddress(val.Address).String(), - ConsensusPubkey: pkAny, - Jailed: false, - Status: stakingtypes.Bonded, - Tokens: bondAmt, - DelegatorShares: sdk.OneDec(), - Description: stakingtypes.Description{}, - UnbondingHeight: int64(0), - UnbondingTime: time.Unix(0, 0).UTC(), - Commission: stakingtypes.NewCommission(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), - MinSelfDelegation: sdk.ZeroInt(), - } - validators = append(validators, validator) - delegations = append(delegations, stakingtypes.NewDelegation(genAccs[0].GetAddress(), val.Address.Bytes(), sdk.OneDec())) - } - s.validators = validators - - // set validators and delegations - stakingParams := stakingtypes.DefaultParams() - // set bond demon to be aevmos - stakingParams.BondDenom = utils.BaseDenom - stakingGenesis := stakingtypes.NewGenesisState(stakingParams, validators, delegations) - genesisState[stakingtypes.ModuleName] = app.AppCodec().MustMarshalJSON(stakingGenesis) - - totalBondAmt := bondAmt.Add(bondAmt) - totalSupply := sdk.NewCoins() - for _, b := range balances { - // add genesis acc tokens and delegated tokens to total supply - totalSupply = totalSupply.Add(b.Coins.Add(sdk.NewCoin(utils.BaseDenom, totalBondAmt))...) - } - - // add bonded amount to bonded pool module account - balances = append(balances, banktypes.Balance{ - Address: authtypes.NewModuleAddress(stakingtypes.BondedPoolName).String(), - Coins: sdk.Coins{sdk.NewCoin(utils.BaseDenom, totalBondAmt)}, - }) - - // update total supply - bankGenesis := banktypes.NewGenesisState(banktypes.DefaultGenesisState().Params, balances, totalSupply, []banktypes.Metadata{}, []banktypes.SendEnabled{}) - genesisState[banktypes.ModuleName] = app.AppCodec().MustMarshalJSON(bankGenesis) - - stateBytes, err := json.MarshalIndent(genesisState, "", " ") - s.Require().NoError(err) - - // init chain will set the validator set and initialize the genesis accounts - app.InitChain( - abci.RequestInitChain{ - ChainId: cmn.DefaultChainID, - Validators: []abci.ValidatorUpdate{}, - ConsensusParams: evmosapp.DefaultConsensusParams, - AppStateBytes: stateBytes, - }, - ) - app.Commit() - - // instantiate new header - header := evmosutil.NewHeader( - 2, - time.Now().UTC(), - cmn.DefaultChainID, - sdk.ConsAddress(validators[0].GetOperator()), - tmhash.Sum([]byte("app")), - tmhash.Sum([]byte("validators")), - ) - - app.BeginBlock(abci.RequestBeginBlock{ - Header: header, - }) - - // create Context - s.ctx = app.BaseApp.NewContext(false, header) - s.app = app -} - -func (s *PrecompileTestSuite) DoSetupTest() { - // generate validator private/public key - privVal := mock.NewPV() - pubKey, err := privVal.GetPubKey() - s.Require().NoError(err) - - privVal2 := mock.NewPV() - pubKey2, err := privVal2.GetPubKey() - s.Require().NoError(err) - - // create validator set with two validators - validator := tmtypes.NewValidator(pubKey, 1) - validator2 := tmtypes.NewValidator(pubKey2, 2) - s.valSet = tmtypes.NewValidatorSet([]*tmtypes.Validator{validator, validator2}) - signers := make(map[string]tmtypes.PrivValidator) - signers[pubKey.Address().String()] = privVal - signers[pubKey2.Address().String()] = privVal2 - - // generate genesis account - addr, priv := evmosutiltx.NewAddrKey() - s.privKey = priv - s.address = addr - s.signer = evmosutiltx.NewSigner(priv) - - baseAcc := authtypes.NewBaseAccount(priv.PubKey().Address().Bytes(), priv.PubKey(), 0, 0) - - acc := &evmostypes.EthAccount{ - BaseAccount: baseAcc, - CodeHash: common.BytesToHash(evmtypes.EmptyCodeHash).Hex(), - } - - amount := sdk.TokensFromConsensusPower(5, evmostypes.PowerReduction) - - balance := banktypes.Balance{ - Address: acc.GetAddress().String(), - Coins: sdk.NewCoins(sdk.NewCoin(utils.BaseDenom, amount)), - } - - s.SetupWithGenesisValSet(s.valSet, []authtypes.GenesisAccount{acc}, balance) - - // Create StateDB - s.stateDB = statedb.New(s.ctx, s.app.EvmKeeper, statedb.NewEmptyTxConfig(common.BytesToHash(s.ctx.HeaderHash().Bytes()))) - - // bond denom - stakingParams := s.app.StakingKeeper.GetParams(s.ctx) - stakingParams.BondDenom = utils.BaseDenom - s.bondDenom = stakingParams.BondDenom - err = s.app.StakingKeeper.SetParams(s.ctx, stakingParams) - s.Require().NoError(err) - - s.ethSigner = ethtypes.LatestSignerForChainID(s.app.EvmKeeper.ChainID()) - - precompile, err := slash.NewPrecompile(s.app.StakingAssetsManageKeeper, s.app.ExoSlashKeeper, s.app.AuthzKeeper) - s.Require().NoError(err) - s.precompile = precompile - - coins := sdk.NewCoins(sdk.NewCoin(utils.BaseDenom, sdk.NewInt(5000000000000000000))) - inflCoins := sdk.NewCoins(sdk.NewCoin(utils.BaseDenom, sdk.NewInt(2000000000000000000))) - distrCoins := sdk.NewCoins(sdk.NewCoin(utils.BaseDenom, sdk.NewInt(3000000000000000000))) - err = s.app.BankKeeper.MintCoins(s.ctx, inflationtypes.ModuleName, coins) - s.Require().NoError(err) - err = s.app.BankKeeper.SendCoinsFromModuleToModule(s.ctx, inflationtypes.ModuleName, authtypes.FeeCollectorName, inflCoins) - s.Require().NoError(err) - err = s.app.BankKeeper.SendCoinsFromModuleToModule(s.ctx, inflationtypes.ModuleName, distrtypes.ModuleName, distrCoins) - s.Require().NoError(err) - - queryHelperEvm := baseapp.NewQueryServerTestHelper(s.ctx, s.app.InterfaceRegistry()) - evmtypes.RegisterQueryServer(queryHelperEvm, s.app.EvmKeeper) - s.queryClientEVM = evmtypes.NewQueryClient(queryHelperEvm) -} - -// CallType is a struct that represents the type of call to be made to -// precompile - either direct or through a smart contract. -type CallType struct { - // name is the name of the call type - name string - // directCall is true if the call is to be made directly to precompile - directCall bool -} - -// BuildCallArgs builds the call arguments for the integration test suite -// depending on the type of interaction. -func (s *PrecompileTestSuite) BuildCallArgs( - callType CallType, - contractAddr common.Address, -) contracts.CallArgs { - callArgs := contracts.CallArgs{ - PrivKey: s.privKey, - } - if callType.directCall { - callArgs.ContractABI = s.precompile.ABI - callArgs.ContractAddr = s.precompile.Address() - } else { - callArgs.ContractAddr = contractAddr - callArgs.ContractABI = testdata.VestingCallerContract.ABI - } - - return callArgs -} diff --git a/precompiles/withdraw/setup_test.go b/precompiles/withdraw/setup_test.go index 7465b97d7..259b6c0b5 100644 --- a/precompiles/withdraw/setup_test.go +++ b/precompiles/withdraw/setup_test.go @@ -1,50 +1,26 @@ package withdraw_test import ( + "github.com/ExocoreNetwork/exocore/testutil" "testing" "github.com/ExocoreNetwork/exocore/precompiles/withdraw" - "github.com/evmos/evmos/v14/x/evm/statedb" - . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - evmosapp "github.com/ExocoreNetwork/exocore/app" - tmtypes "github.com/cometbft/cometbft/types" - "github.com/cosmos/cosmos-sdk/crypto/keyring" - cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" - sdk "github.com/cosmos/cosmos-sdk/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/ethereum/go-ethereum/common" - ethtypes "github.com/ethereum/go-ethereum/core/types" - evmtypes "github.com/evmos/evmos/v14/x/evm/types" "github.com/stretchr/testify/suite" ) -var s *PrecompileTestSuite - -type PrecompileTestSuite struct { - suite.Suite - - ctx sdk.Context - app *evmosapp.ExocoreApp - address common.Address - validators []stakingtypes.Validator - valSet *tmtypes.ValidatorSet - ethSigner ethtypes.Signer - privKey cryptotypes.PrivKey - signer keyring.Signer - bondDenom string +var s *WithdrawPrecompileTestSuite +type WithdrawPrecompileTestSuite struct { + testutil.BaseTestSuite precompile *withdraw.Precompile - stateDB *statedb.StateDB - - queryClientEVM evmtypes.QueryClient } func TestPrecompileTestSuite(t *testing.T) { - s = new(PrecompileTestSuite) + s = new(WithdrawPrecompileTestSuite) suite.Run(t, s) // Run Ginkgo integration tests @@ -52,6 +28,9 @@ func TestPrecompileTestSuite(t *testing.T) { RunSpecs(t, "Withdraw Precompile Suite") } -func (s *PrecompileTestSuite) SetupTest() { +func (s *WithdrawPrecompileTestSuite) SetupTest() { s.DoSetupTest() + precompile, err := withdraw.NewPrecompile(s.App.StakingAssetsManageKeeper, s.App.WithdrawKeeper, s.App.AuthzKeeper) + s.Require().NoError(err) + s.precompile = precompile } diff --git a/precompiles/withdraw/utils_test.go b/precompiles/withdraw/utils_test.go deleted file mode 100644 index 2ce50f587..000000000 --- a/precompiles/withdraw/utils_test.go +++ /dev/null @@ -1,232 +0,0 @@ -package withdraw_test - -import ( - "encoding/json" - "time" - - evmosapp "github.com/ExocoreNetwork/exocore/app" - "github.com/ExocoreNetwork/exocore/precompiles/withdraw" - testutiltx "github.com/ExocoreNetwork/exocore/testutil/tx" - "github.com/ExocoreNetwork/exocore/utils" - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cometbft/cometbft/crypto/tmhash" - tmtypes "github.com/cometbft/cometbft/types" - "github.com/cosmos/cosmos-sdk/baseapp" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - "github.com/cosmos/cosmos-sdk/testutil/mock" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/ethereum/go-ethereum/common" - ethtypes "github.com/ethereum/go-ethereum/core/types" - cmn "github.com/evmos/evmos/v14/precompiles/common" - "github.com/evmos/evmos/v14/precompiles/testutil/contracts" - "github.com/evmos/evmos/v14/precompiles/vesting/testdata" - evmosutil "github.com/evmos/evmos/v14/testutil" - evmosutiltx "github.com/evmos/evmos/v14/testutil/tx" - evmostypes "github.com/evmos/evmos/v14/types" - "github.com/evmos/evmos/v14/x/evm/statedb" - evmtypes "github.com/evmos/evmos/v14/x/evm/types" - inflationtypes "github.com/evmos/evmos/v14/x/inflation/types" -) - -// SetupWithGenesisValSet initializes a new EvmosApp with a validator set and genesis accounts -// that also act as delegators. For simplicity, each validator is bonded with a delegation -// of one consensus engine unit (10^6) in the default token of the simapp from first genesis -// account. A Nop logger is set in SimApp. -func (s *PrecompileTestSuite) SetupWithGenesisValSet(valSet *tmtypes.ValidatorSet, genAccs []authtypes.GenesisAccount, balances ...banktypes.Balance) { - appI, genesisState := evmosapp.SetupTestingApp(cmn.DefaultChainID, false)() - app, ok := appI.(*evmosapp.ExocoreApp) - s.Require().True(ok) - - // set genesis accounts - authGenesis := authtypes.NewGenesisState(authtypes.DefaultParams(), genAccs) - genesisState[authtypes.ModuleName] = app.AppCodec().MustMarshalJSON(authGenesis) - - validators := make([]stakingtypes.Validator, 0, len(valSet.Validators)) - delegations := make([]stakingtypes.Delegation, 0, len(valSet.Validators)) - - bondAmt := sdk.TokensFromConsensusPower(1, evmostypes.PowerReduction) - - for _, val := range valSet.Validators { - pk, err := cryptocodec.FromTmPubKeyInterface(val.PubKey) - s.Require().NoError(err) - pkAny, err := codectypes.NewAnyWithValue(pk) - s.Require().NoError(err) - validator := stakingtypes.Validator{ - OperatorAddress: sdk.ValAddress(val.Address).String(), - ConsensusPubkey: pkAny, - Jailed: false, - Status: stakingtypes.Bonded, - Tokens: bondAmt, - DelegatorShares: sdk.OneDec(), - Description: stakingtypes.Description{}, - UnbondingHeight: int64(0), - UnbondingTime: time.Unix(0, 0).UTC(), - Commission: stakingtypes.NewCommission(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), - MinSelfDelegation: sdk.ZeroInt(), - } - validators = append(validators, validator) - delegations = append(delegations, stakingtypes.NewDelegation(genAccs[0].GetAddress(), val.Address.Bytes(), sdk.OneDec())) - } - s.validators = validators - - // set validators and delegations - stakingParams := stakingtypes.DefaultParams() - // set bond demon to be aevmos - stakingParams.BondDenom = utils.BaseDenom - stakingGenesis := stakingtypes.NewGenesisState(stakingParams, validators, delegations) - genesisState[stakingtypes.ModuleName] = app.AppCodec().MustMarshalJSON(stakingGenesis) - - totalBondAmt := bondAmt.Add(bondAmt) - totalSupply := sdk.NewCoins() - for _, b := range balances { - // add genesis acc tokens and delegated tokens to total supply - totalSupply = totalSupply.Add(b.Coins.Add(sdk.NewCoin(utils.BaseDenom, totalBondAmt))...) - } - - // add bonded amount to bonded pool module account - balances = append(balances, banktypes.Balance{ - Address: authtypes.NewModuleAddress(stakingtypes.BondedPoolName).String(), - Coins: sdk.Coins{sdk.NewCoin(utils.BaseDenom, totalBondAmt)}, - }) - - // update total supply - bankGenesis := banktypes.NewGenesisState(banktypes.DefaultGenesisState().Params, balances, totalSupply, []banktypes.Metadata{}, []banktypes.SendEnabled{}) - genesisState[banktypes.ModuleName] = app.AppCodec().MustMarshalJSON(bankGenesis) - - stateBytes, err := json.MarshalIndent(genesisState, "", " ") - s.Require().NoError(err) - - // init chain will set the validator set and initialize the genesis accounts - app.InitChain( - abci.RequestInitChain{ - ChainId: cmn.DefaultChainID, - Validators: []abci.ValidatorUpdate{}, - ConsensusParams: evmosapp.DefaultConsensusParams, - AppStateBytes: stateBytes, - }, - ) - app.Commit() - - // instantiate new header - header := evmosutil.NewHeader( - 2, - time.Now().UTC(), - cmn.DefaultChainID, - sdk.ConsAddress(validators[0].GetOperator()), - tmhash.Sum([]byte("app")), - tmhash.Sum([]byte("validators")), - ) - - app.BeginBlock(abci.RequestBeginBlock{ - Header: header, - }) - - // create Context - s.ctx = app.BaseApp.NewContext(false, header) - s.app = app -} - -func (s *PrecompileTestSuite) DoSetupTest() { - // generate validator private/public key - privVal := mock.NewPV() - pubKey, err := privVal.GetPubKey() - s.Require().NoError(err) - - privVal2 := mock.NewPV() - pubKey2, err := privVal2.GetPubKey() - s.Require().NoError(err) - - // create validator set with two validators - validator := tmtypes.NewValidator(pubKey, 1) - validator2 := tmtypes.NewValidator(pubKey2, 2) - s.valSet = tmtypes.NewValidatorSet([]*tmtypes.Validator{validator, validator2}) - signers := make(map[string]tmtypes.PrivValidator) - signers[pubKey.Address().String()] = privVal - signers[pubKey2.Address().String()] = privVal2 - - // generate genesis account - addr, priv := testutiltx.NewAddrKey() - s.privKey = priv - s.address = addr - s.signer = evmosutiltx.NewSigner(priv) - - baseAcc := authtypes.NewBaseAccount(priv.PubKey().Address().Bytes(), priv.PubKey(), 0, 0) - - acc := &evmostypes.EthAccount{ - BaseAccount: baseAcc, - CodeHash: common.BytesToHash(evmtypes.EmptyCodeHash).Hex(), - } - - amount := sdk.TokensFromConsensusPower(5, evmostypes.PowerReduction) - - balance := banktypes.Balance{ - Address: acc.GetAddress().String(), - Coins: sdk.NewCoins(sdk.NewCoin(utils.BaseDenom, amount)), - } - - s.SetupWithGenesisValSet(s.valSet, []authtypes.GenesisAccount{acc}, balance) - - // Create StateDB - s.stateDB = statedb.New(s.ctx, s.app.EvmKeeper, statedb.NewEmptyTxConfig(common.BytesToHash(s.ctx.HeaderHash().Bytes()))) - - // bond denom - stakingParams := s.app.StakingKeeper.GetParams(s.ctx) - stakingParams.BondDenom = utils.BaseDenom - s.bondDenom = stakingParams.BondDenom - err = s.app.StakingKeeper.SetParams(s.ctx, stakingParams) - s.Require().NoError(err) - - s.ethSigner = ethtypes.LatestSignerForChainID(s.app.EvmKeeper.ChainID()) - - precompile, err := withdraw.NewPrecompile(s.app.StakingAssetsManageKeeper, s.app.WithdrawKeeper, s.app.AuthzKeeper) - s.Require().NoError(err) - s.precompile = precompile - - coins := sdk.NewCoins(sdk.NewCoin(utils.BaseDenom, sdk.NewInt(5000000000000000000))) - inflCoins := sdk.NewCoins(sdk.NewCoin(utils.BaseDenom, sdk.NewInt(2000000000000000000))) - distrCoins := sdk.NewCoins(sdk.NewCoin(utils.BaseDenom, sdk.NewInt(3000000000000000000))) - err = s.app.BankKeeper.MintCoins(s.ctx, inflationtypes.ModuleName, coins) - s.Require().NoError(err) - err = s.app.BankKeeper.SendCoinsFromModuleToModule(s.ctx, inflationtypes.ModuleName, authtypes.FeeCollectorName, inflCoins) - s.Require().NoError(err) - err = s.app.BankKeeper.SendCoinsFromModuleToModule(s.ctx, inflationtypes.ModuleName, distrtypes.ModuleName, distrCoins) - s.Require().NoError(err) - - queryHelperEvm := baseapp.NewQueryServerTestHelper(s.ctx, s.app.InterfaceRegistry()) - evmtypes.RegisterQueryServer(queryHelperEvm, s.app.EvmKeeper) - s.queryClientEVM = evmtypes.NewQueryClient(queryHelperEvm) -} - -// CallType is a struct that represents the type of call to be made to -// precompile - either direct or through a smart contract. -type CallType struct { - // name is the name of the call type - name string - // directCall is true if the call is to be made directly to precompile - directCall bool -} - -// BuildCallArgs builds the call arguments for the integration test suite -// depending on the type of interaction. -func (s *PrecompileTestSuite) BuildCallArgs( - callType CallType, - contractAddr common.Address, -) contracts.CallArgs { - callArgs := contracts.CallArgs{ - PrivKey: s.privKey, - } - if callType.directCall { - callArgs.ContractABI = s.precompile.ABI - callArgs.ContractAddr = s.precompile.Address() - } else { - callArgs.ContractAddr = contractAddr - callArgs.ContractABI = testdata.VestingCallerContract.ABI - } - - return callArgs -} diff --git a/precompiles/withdraw/withdraw.sol b/precompiles/withdraw/withdraw.sol index afd90b908..79e6c25b5 100644 --- a/precompiles/withdraw/withdraw.sol +++ b/precompiles/withdraw/withdraw.sol @@ -16,7 +16,7 @@ interface IWithdraw { /// TRANSACTIONS /// @dev withdraw To the staker, that will change the state in withdraw module /// Note that this address cannot be a module account. -/// @param clientChainLzID The lzId of client chain +/// @param clientChainLzID The LzID of client chain /// @param assetsAddress The client chain asset Address /// @param withdrawAddress The withdraw address /// @param opAmount The withdraw amount diff --git a/precompiles/withdraw/withdraw_integrate_test.go b/precompiles/withdraw/withdraw_integrate_test.go index a9566ab19..239c9d0f9 100644 --- a/precompiles/withdraw/withdraw_integrate_test.go +++ b/precompiles/withdraw/withdraw_integrate_test.go @@ -26,7 +26,7 @@ var ( passCheck testutil.LogCheckArgs ) -func (s *PrecompileTestSuite) TestCallWithdrawFromEOA() { +func (s *WithdrawPrecompileTestSuite) TestCallWithdrawFromEOA() { // withdraw params for test exoCoreLzAppAddress := "0x3fC91A3afd70395Cd496C647d5a6CC9D4B2b7FAD" exoCoreLzAppEventTopic := "0xc6a377bfc4eb120024a8ac08eef205be16b817020812c73223e81d1bdb9708ec" @@ -36,7 +36,7 @@ func (s *PrecompileTestSuite) TestCallWithdrawFromEOA() { } usdtAddress := paddingClientChainAddress(common.FromHex("0xdAC17F958D2ee523a2206206994597C13D831ec7"), types.GeneralClientChainAddrLength) clientChainLzID := 101 - stakerAddr := paddingClientChainAddress(s.address.Bytes(), types.GeneralClientChainAddrLength) + stakerAddr := paddingClientChainAddress(s.Address.Bytes(), types.GeneralClientChainAddrLength) opAmount := big.NewInt(100) assetAddr := usdtAddress method := "withdrawPrinciple" @@ -47,7 +47,7 @@ func (s *PrecompileTestSuite) TestCallWithdrawFromEOA() { defaultCallArgs = contracts.CallArgs{ ContractAddr: s.precompile.Address(), ContractABI: s.precompile.ABI, - PrivKey: s.privKey, + PrivKey: s.PrivKey, } defaultLogCheck = testutil.LogCheckArgs{ @@ -57,7 +57,7 @@ func (s *PrecompileTestSuite) TestCallWithdrawFromEOA() { } prepareFunc := func(params *deposittype.Params, method string) contracts.CallArgs { - err := s.app.DepositKeeper.SetParams(s.ctx, params) + err := s.App.DepositKeeper.SetParams(s.Ctx, params) s.Require().NoError(err) defaultWithdrawArgs := defaultCallArgs.WithMethodName(method) return defaultWithdrawArgs.WithArgs( @@ -69,6 +69,6 @@ func (s *PrecompileTestSuite) TestCallWithdrawFromEOA() { beforeEach() setWithdrawArgs := prepareFunc(¶ms, method) - _, _, err := contracts.CallContractAndCheckLogs(s.ctx, s.app, setWithdrawArgs, passCheck) + _, _, err := contracts.CallContractAndCheckLogs(s.Ctx, s.App, setWithdrawArgs, passCheck) s.Require().ErrorContains(err, strings.Split(withdraw.ErrContractCaller, ",")[0]) } diff --git a/precompiles/withdraw/withdraw_test.go b/precompiles/withdraw/withdraw_test.go index 0ac0e40c9..38545e324 100644 --- a/precompiles/withdraw/withdraw_test.go +++ b/precompiles/withdraw/withdraw_test.go @@ -16,7 +16,7 @@ import ( evmtypes "github.com/evmos/evmos/v14/x/evm/types" ) -func (s *PrecompileTestSuite) TestIsTransaction() { +func (s *WithdrawPrecompileTestSuite) TestIsTransaction() { testCases := []struct { name string method string @@ -49,10 +49,10 @@ func paddingClientChainAddress(input []byte, outputLength int) []byte { return input } -func (s *PrecompileTestSuite) TestRequiredGas() { +func (s *WithdrawPrecompileTestSuite) TestRequiredGas() { clientChainLzID := 101 usdtAddress := paddingClientChainAddress(common.FromHex("0xdAC17F958D2ee523a2206206994597C13D831ec7"), types.GeneralClientChainAddrLength) - withdrawAddr := paddingClientChainAddress(s.address.Bytes(), types.GeneralClientChainAddrLength) + withdrawAddr := paddingClientChainAddress(s.Address.Bytes(), types.GeneralClientChainAddrLength) opAmount := big.NewInt(100) assetAddr := usdtAddress @@ -92,7 +92,7 @@ func (s *PrecompileTestSuite) TestRequiredGas() { } // TestRun tests the precompiled Run method withdraw. -func (s *PrecompileTestSuite) TestRunWithdrawThroughClientChain() { +func (s *WithdrawPrecompileTestSuite) TestRunWithdrawThroughClientChain() { // deposit params for test exoCoreLzAppEventTopic := "0xc6a377bfc4eb120024a8ac08eef205be16b817020812c73223e81d1bdb9708ec" usdtAddress := common.FromHex("0xdAC17F958D2ee523a2206206994597C13D831ec7") @@ -109,7 +109,7 @@ func (s *PrecompileTestSuite) TestRunWithdrawThroughClientChain() { AssetsAddress: usdtAddress, OpAmount: depositAmount, } - err := s.app.DepositKeeper.Deposit(s.ctx, params) + err := s.App.DepositKeeper.Deposit(s.Ctx, params) s.Require().NoError(err) } @@ -119,11 +119,11 @@ func (s *PrecompileTestSuite) TestRunWithdrawThroughClientChain() { withdraw.MethodWithdraw, uint16(clientChainLzID), assetAddr, - paddingClientChainAddress(s.address.Bytes(), types.GeneralClientChainAddrLength), + paddingClientChainAddress(s.Address.Bytes(), types.GeneralClientChainAddrLength), withdrawAmount, ) s.Require().NoError(err, "failed to pack input") - return s.address, input + return s.Address, input } successRet, err := s.precompile.Methods[withdraw.MethodWithdraw].Outputs.Pack(true, new(big.Int).Sub(depositAmount, withdrawAmount)) s.Require().NoError(err) @@ -139,12 +139,12 @@ func (s *PrecompileTestSuite) TestRunWithdrawThroughClientChain() { name: "pass - withdraw via pre-compiles", malleate: func() (common.Address, []byte) { depositModuleParam := &depositparams.Params{ - ExoCoreLzAppAddress: s.address.String(), + ExoCoreLzAppAddress: s.Address.String(), ExoCoreLzAppEventTopic: exoCoreLzAppEventTopic, } - err := s.app.DepositKeeper.SetParams(s.ctx, depositModuleParam) + err := s.App.DepositKeeper.SetParams(s.Ctx, depositModuleParam) s.Require().NoError(err) - depositAsset(s.address.Bytes(), sdkmath.NewIntFromBigInt(depositAmount)) + depositAsset(s.Address.Bytes(), sdkmath.NewIntFromBigInt(depositAmount)) return commonMalleate() }, returnBytes: successRet, @@ -158,7 +158,7 @@ func (s *PrecompileTestSuite) TestRunWithdrawThroughClientChain() { // setup basic test suite s.SetupTest() - baseFee := s.app.FeeMarketKeeper.GetBaseFee(s.ctx) + baseFee := s.App.FeeMarketKeeper.GetBaseFee(s.Ctx) // malleate testcase caller, input := tc.malleate() @@ -169,7 +169,7 @@ func (s *PrecompileTestSuite) TestRunWithdrawThroughClientChain() { contractAddr := contract.Address() // Build and sign Ethereum transaction txArgs := evmtypes.EvmTxArgs{ - ChainID: s.app.EvmKeeper.ChainID(), + ChainID: s.App.EvmKeeper.ChainID(), Nonce: 0, To: &contractAddr, Amount: nil, @@ -181,27 +181,27 @@ func (s *PrecompileTestSuite) TestRunWithdrawThroughClientChain() { } msgEthereumTx := evmtypes.NewTx(&txArgs) - msgEthereumTx.From = s.address.String() - err := msgEthereumTx.Sign(s.ethSigner, s.signer) + msgEthereumTx.From = s.Address.String() + err := msgEthereumTx.Sign(s.EthSigner, s.Signer) s.Require().NoError(err, "failed to sign Ethereum message") // Instantiate config - proposerAddress := s.ctx.BlockHeader().ProposerAddress - cfg, err := s.app.EvmKeeper.EVMConfig(s.ctx, proposerAddress, s.app.EvmKeeper.ChainID()) + proposerAddress := s.Ctx.BlockHeader().ProposerAddress + cfg, err := s.App.EvmKeeper.EVMConfig(s.Ctx, proposerAddress, s.App.EvmKeeper.ChainID()) s.Require().NoError(err, "failed to instantiate EVM config") - msg, err := msgEthereumTx.AsMessage(s.ethSigner, baseFee) + msg, err := msgEthereumTx.AsMessage(s.EthSigner, baseFee) s.Require().NoError(err, "failed to instantiate Ethereum message") // Create StateDB - s.stateDB = statedb.New(s.ctx, s.app.EvmKeeper, statedb.NewEmptyTxConfig(common.BytesToHash(s.ctx.HeaderHash().Bytes()))) + s.StateDB = statedb.New(s.Ctx, s.App.EvmKeeper, statedb.NewEmptyTxConfig(common.BytesToHash(s.Ctx.HeaderHash().Bytes()))) // Instantiate EVM - evm := s.app.EvmKeeper.NewEVM( - s.ctx, msg, cfg, nil, s.stateDB, + evm := s.App.EvmKeeper.NewEVM( + s.Ctx, msg, cfg, nil, s.StateDB, ) - params := s.app.EvmKeeper.GetParams(s.ctx) + params := s.App.EvmKeeper.GetParams(s.Ctx) activePrecompiles := params.GetActivePrecompilesAddrs() - precompileMap := s.app.EvmKeeper.Precompiles(activePrecompiles...) + precompileMap := s.App.EvmKeeper.Precompiles(activePrecompiles...) err = vm.ValidatePrecompiles(precompileMap, activePrecompiles) s.Require().NoError(err, "invalid precompiles", activePrecompiles) evm.WithPrecompiles(precompileMap, activePrecompiles) diff --git a/testutil/abci.go b/testutil/abci.go index 304468daa..51061fd20 100644 --- a/testutil/abci.go +++ b/testutil/abci.go @@ -57,7 +57,7 @@ func CommitAndCreateNewCtx(ctx sdk.Context, app *app.ExocoreApp, t time.Duration // DeliverTx delivers a cosmos tx for a given set of msgs func DeliverTx( ctx sdk.Context, - appEvmos *app.ExocoreApp, + appExocore *app.ExocoreApp, priv cryptotypes.PrivKey, gasPrice *sdkmath.Int, msgs ...sdk.Msg, @@ -65,7 +65,7 @@ func DeliverTx( txConfig := encoding.MakeConfig(app.ModuleBasics).TxConfig tx, err := tx.PrepareCosmosTx( ctx, - appEvmos, + appExocore, tx.CosmosTxArgs{ TxCfg: txConfig, Priv: priv, @@ -78,7 +78,7 @@ func DeliverTx( if err != nil { return abci.ResponseDeliverTx{}, err } - return BroadcastTxBytes(appEvmos, txConfig.TxEncoder(), tx) + return BroadcastTxBytes(appExocore, txConfig.TxEncoder(), tx) } // DeliverEthTx generates and broadcasts a Cosmos Tx populated with MsgEthereumTx messages. @@ -112,18 +112,18 @@ func DeliverEthTx( // otherwise, it will assume the messages have already been signed. It does not check if the Eth tx is // successful or not. func DeliverEthTxWithoutCheck( - appEvmos *app.ExocoreApp, + appExocore *app.ExocoreApp, priv cryptotypes.PrivKey, msgs ...sdk.Msg, ) (abci.ResponseDeliverTx, error) { txConfig := encoding.MakeConfig(app.ModuleBasics).TxConfig - tx, err := tx.PrepareEthTx(txConfig, appEvmos, priv, msgs...) + tx, err := tx.PrepareEthTx(txConfig, appExocore, priv, msgs...) if err != nil { return abci.ResponseDeliverTx{}, err } - res, err := BroadcastTxBytes(appEvmos, txConfig.TxEncoder(), tx) + res, err := BroadcastTxBytes(appExocore, txConfig.TxEncoder(), tx) if err != nil { return abci.ResponseDeliverTx{}, err } @@ -134,7 +134,7 @@ func DeliverEthTxWithoutCheck( // CheckTx checks a cosmos tx for a given set of msgs func CheckTx( ctx sdk.Context, - appEvmos *app.ExocoreApp, + appExocore *app.ExocoreApp, priv cryptotypes.PrivKey, gasPrice *sdkmath.Int, msgs ...sdk.Msg, @@ -143,7 +143,7 @@ func CheckTx( tx, err := tx.PrepareCosmosTx( ctx, - appEvmos, + appExocore, tx.CosmosTxArgs{ TxCfg: txConfig, Priv: priv, @@ -156,25 +156,25 @@ func CheckTx( if err != nil { return abci.ResponseCheckTx{}, err } - return checkTxBytes(appEvmos, txConfig.TxEncoder(), tx) + return checkTxBytes(appExocore, txConfig.TxEncoder(), tx) } // CheckEthTx checks a Ethereum tx for a given set of msgs func CheckEthTx( - appEvmos *app.ExocoreApp, + appExocore *app.ExocoreApp, priv cryptotypes.PrivKey, msgs ...sdk.Msg, ) (abci.ResponseCheckTx, error) { txConfig := encoding.MakeConfig(app.ModuleBasics).TxConfig - tx, err := tx.PrepareEthTx(txConfig, appEvmos, priv, msgs...) + tx, err := tx.PrepareEthTx(txConfig, appExocore, priv, msgs...) if err != nil { return abci.ResponseCheckTx{}, err } - return checkTxBytes(appEvmos, txConfig.TxEncoder(), tx) + return checkTxBytes(appExocore, txConfig.TxEncoder(), tx) } -// BroadcastTxBytes encodes a transaction and calls DeliverTx on the app. +// BroadcastTxBytes encodes a transaction and calls DeliverTx on the App. func BroadcastTxBytes(app *app.ExocoreApp, txEncoder sdk.TxEncoder, tx sdk.Tx) (abci.ResponseDeliverTx, error) { // bz are bytes to be broadcasted over the network bz, err := txEncoder(tx) diff --git a/testutil/ante.go b/testutil/ante.go index 22032f884..f9fdfa990 100644 --- a/testutil/ante.go +++ b/testutil/ante.go @@ -10,7 +10,7 @@ import ( // the next function in the AnteHandler chain. // // It can be used in unit tests when calling a decorator's AnteHandle method, e.g. -// `dec.AnteHandle(ctx, tx, false, NextFn)` +// `dec.AnteHandle(Ctx, tx, false, NextFn)` func NextFn(ctx sdk.Context, _ sdk.Tx, _ bool) (sdk.Context, error) { return ctx, nil } diff --git a/testutil/contract.go b/testutil/contract.go index 27ac88ba6..8ea51b668 100644 --- a/testutil/contract.go +++ b/testutil/contract.go @@ -23,7 +23,7 @@ import ( // ContractArgs are the params used for calling a smart contract. type ContractArgs struct { - // Addr is the address of the contract to call. + // Addr is the Address of the contract to call. Addr common.Address // ABI is the ABI of the contract to call. ABI abi.ABI @@ -39,7 +39,7 @@ type ContractCallArgs struct { Contract ContractArgs // Nonce is the nonce to use for the transaction. Nonce *big.Int - // Amount is the aevmos amount to send in the transaction. + // Amount is the aexo amount to send in the transaction. Amount *big.Int // GasLimit to use for the transaction GasLimit uint64 @@ -51,15 +51,15 @@ type ContractCallArgs struct { // compiled contract data and constructor arguments func DeployContract( ctx sdk.Context, - evmosApp *app.ExocoreApp, + exocoreApp *app.ExocoreApp, priv cryptotypes.PrivKey, queryClientEvm evm.QueryClient, contract evm.CompiledContract, constructorArgs ...interface{}, ) (common.Address, error) { - chainID := evmosApp.EvmKeeper.ChainID() + chainID := exocoreApp.EvmKeeper.ChainID() from := common.BytesToAddress(priv.PubKey().Address().Bytes()) - nonce := evmosApp.EvmKeeper.GetNonce(ctx, from) + nonce := exocoreApp.EvmKeeper.GetNonce(ctx, from) ctorArgs, err := contract.ABI.Pack("", constructorArgs...) if err != nil { @@ -76,19 +76,19 @@ func DeployContract( ChainID: chainID, Nonce: nonce, GasLimit: gas, - GasFeeCap: evmosApp.FeeMarketKeeper.GetBaseFee(ctx), + GasFeeCap: exocoreApp.FeeMarketKeeper.GetBaseFee(ctx), GasTipCap: big.NewInt(1), Input: data, Accesses: ðtypes.AccessList{}, }) msgEthereumTx.From = from.String() - res, err := DeliverEthTx(evmosApp, priv, msgEthereumTx) + res, err := DeliverEthTx(exocoreApp, priv, msgEthereumTx) if err != nil { return common.Address{}, err } - if _, err := CheckEthTxResponse(res, evmosApp.AppCodec()); err != nil { + if _, err := CheckEthTxResponse(res, exocoreApp.AppCodec()); err != nil { return common.Address{}, err } diff --git a/testutil/fund.go b/testutil/fund.go index dfc19878e..459bcde83 100644 --- a/testutil/fund.go +++ b/testutil/fund.go @@ -1,14 +1,14 @@ package testutil import ( + "github.com/ExocoreNetwork/exocore/utils" sdk "github.com/cosmos/cosmos-sdk/types" bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - "github.com/evmos/evmos/v14/utils" inflationtypes "github.com/evmos/evmos/v14/x/inflation/types" ) // FundAccount is a utility function that funds an account by minting and -// sending the coins to the address. +// sending the coins to the Address. func FundAccount(ctx sdk.Context, bankKeeper bankkeeper.Keeper, addr sdk.AccAddress, amounts sdk.Coins) error { if err := bankKeeper.MintCoins(ctx, inflationtypes.ModuleName, amounts); err != nil { return err @@ -27,7 +27,7 @@ func FundAccountWithBaseDenom(ctx sdk.Context, bankKeeper bankkeeper.Keeper, add } // FundModuleAccount is a utility function that funds a module account by -// minting and sending the coins to the address. +// minting and sending the coins to the Address. func FundModuleAccount(ctx sdk.Context, bankKeeper bankkeeper.Keeper, recipientMod string, amounts sdk.Coins) error { if err := bankKeeper.MintCoins(ctx, inflationtypes.ModuleName, amounts); err != nil { return err diff --git a/testutil/integration.go b/testutil/integration.go index e795a1d13..dfaa91a96 100644 --- a/testutil/integration.go +++ b/testutil/integration.go @@ -18,7 +18,7 @@ import ( // event. func SubmitProposal( ctx sdk.Context, - appEvmos *app.ExocoreApp, + appExocore *app.ExocoreApp, pk *ethsecp256k1.PrivKey, content govv1beta1.Content, eventNum int, @@ -31,7 +31,7 @@ func SubmitProposal( if err != nil { return id, err } - res, err := DeliverTx(ctx, appEvmos, pk, nil, msg) + res, err := DeliverTx(ctx, appExocore, pk, nil, msg) if err != nil { return id, err } @@ -47,7 +47,7 @@ func SubmitProposal( // Delegate delivers a delegate tx func Delegate( ctx sdk.Context, - appEvmos *app.ExocoreApp, + appExocore *app.ExocoreApp, priv *ethsecp256k1.PrivKey, delegateAmount sdk.Coin, validator stakingtypes.Validator, @@ -60,13 +60,13 @@ func Delegate( } delegateMsg := stakingtypes.NewMsgDelegate(accountAddress, val, delegateAmount) - return DeliverTx(ctx, appEvmos, priv, nil, delegateMsg) + return DeliverTx(ctx, appExocore, priv, nil, delegateMsg) } // Vote delivers a vote tx with the VoteOption "yes" func Vote( ctx sdk.Context, - appEvmos *app.ExocoreApp, + appExocore *app.ExocoreApp, priv *ethsecp256k1.PrivKey, proposalID uint64, voteOption govv1beta1.VoteOption, @@ -74,5 +74,5 @@ func Vote( accountAddress := sdk.AccAddress(priv.PubKey().Address().Bytes()) voteMsg := govv1beta1.NewMsgVote(accountAddress, proposalID, voteOption) - return DeliverTx(ctx, appEvmos, priv, nil, voteMsg) + return DeliverTx(ctx, appExocore, priv, nil, voteMsg) } diff --git a/testutil/network/network.go b/testutil/network/network.go index 85593918e..513e044d1 100644 --- a/testutil/network/network.go +++ b/testutil/network/network.go @@ -99,7 +99,7 @@ type Config struct { // testing requirements. func DefaultConfig() Config { encCfg := encoding.MakeConfig(app.ModuleBasics) - chainID := fmt.Sprintf("evmos_%d-1", tmrand.Int63n(9999999999999)+1) + chainID := fmt.Sprintf("exocore_%d-1", tmrand.Int63n(9999999999999)+1) return Config{ Codec: encCfg.Codec, TxConfig: encCfg.TxConfig, @@ -111,7 +111,7 @@ func DefaultConfig() Config { TimeoutCommit: 3 * time.Second, ChainID: chainID, NumValidators: 4, - BondDenom: "aevmos", + BondDenom: "aexo", MinGasPrices: fmt.Sprintf("0.000006%s", evmostypes.AttoEvmos), AccountTokens: sdk.TokensFromConsensusPower(1000000000000000000, evmostypes.PowerReduction), StakingTokens: sdk.TokensFromConsensusPower(500000000000000000, evmostypes.PowerReduction), diff --git a/testutil/network/network_test.go b/testutil/network/network_test.go index 2844a9cc6..e412fef33 100644 --- a/testutil/network/network_test.go +++ b/testutil/network/network_test.go @@ -14,7 +14,7 @@ import ( "github.com/ethereum/go-ethereum/ethclient" "github.com/evmos/evmos/v14/server/config" - evmosnetwork "github.com/ExocoreNetwork/exocore/testutil/network" + exocorenetwork "github.com/ExocoreNetwork/exocore/testutil/network" ) type IntegrationTestSuite struct { @@ -27,7 +27,7 @@ func (s *IntegrationTestSuite) SetupSuite() { s.T().Log("setting up integration test suite") var err error - cfg := evmosnetwork.DefaultConfig() + cfg := exocorenetwork.DefaultConfig() cfg.JSONRPCAddress = config.DefaultJSONRPCAddress cfg.NumValidators = 1 diff --git a/testutil/staking-rewards.go b/testutil/staking-rewards.go index 070ad7554..ac6cabefa 100644 --- a/testutil/staking-rewards.go +++ b/testutil/staking-rewards.go @@ -7,6 +7,7 @@ import ( sdkmath "cosmossdk.io/math" "github.com/ExocoreNetwork/exocore/app" testutiltx "github.com/ExocoreNetwork/exocore/testutil/tx" + "github.com/ExocoreNetwork/exocore/utils" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -16,7 +17,6 @@ import ( stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" teststaking "github.com/cosmos/cosmos-sdk/x/staking/testutil" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/evmos/evmos/v14/utils" "github.com/stretchr/testify/require" ) @@ -44,7 +44,7 @@ func CreateValidator(ctx sdk.Context, t *testing.T, pubKey cryptotypes.PubKey, s // such that the given amount of tokens is outstanding as a staking reward for the account. // // The setup is done in the following way: -// - Fund the account with the given address with the given balance. +// - Fund the account with the given Address with the given balance. // - If the given balance is zero, the account will be created with zero balance. // // For every reward defined in the rewards argument, the following steps are executed: @@ -54,7 +54,7 @@ func CreateValidator(ctx sdk.Context, t *testing.T, pubKey cryptotypes.PubKey, s // The function returns the updated context along with a potential error. func PrepareAccountsForDelegationRewards(t *testing.T, ctx sdk.Context, app *app.ExocoreApp, addr sdk.AccAddress, balance sdkmath.Int, rewards ...sdkmath.Int) (sdk.Context, error) { // Calculate the necessary amount of tokens to fund the account in order for the desired residual balance to - // be left after creating validators and delegating to them. + // be left after creating Validators and delegating to them. totalRewards := sdk.ZeroInt() for _, reward := range rewards { totalRewards = totalRewards.Add(reward) @@ -112,7 +112,7 @@ func PrepareAccountsForDelegationRewards(t *testing.T, ctx sdk.Context, app *app stakingHelper.Denom = utils.BaseDenom valAddr := sdk.ValAddress(addr2.Bytes()) - // self-delegate the same amount of tokens as the delegate address also stakes + // self-delegate the same amount of tokens as the delegate Address also stakes // this ensures, that the delegation rewards are 50% of the total rewards stakingHelper.CreateValidator(valAddr, privKey.PubKey(), reward, true) stakingHelper.Delegate(addr, valAddr, reward) @@ -131,7 +131,7 @@ func PrepareAccountsForDelegationRewards(t *testing.T, ctx sdk.Context, app *app } // GetTotalDelegationRewards returns the total delegation rewards that are currently -// outstanding for the given address. +// outstanding for the given Address. func GetTotalDelegationRewards(ctx sdk.Context, distributionKeeper distributionkeeper.Keeper, addr sdk.AccAddress) (sdk.DecCoins, error) { querier := distributionkeeper.NewQuerier(distributionKeeper) resp, err := querier.DelegationTotalRewards( diff --git a/testutil/tx/cosmos.go b/testutil/tx/cosmos.go index ee9dee3c3..9051dd01b 100644 --- a/testutil/tx/cosmos.go +++ b/testutil/tx/cosmos.go @@ -12,7 +12,7 @@ import ( authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing" "github.com/ExocoreNetwork/exocore/app" - "github.com/evmos/evmos/v14/utils" + "github.com/ExocoreNetwork/exocore/utils" ) var ( @@ -44,7 +44,7 @@ type CosmosTxArgs struct { // It returns the signed transaction and an error func PrepareCosmosTx( ctx sdk.Context, - appEvmos *app.ExocoreApp, + appExocore *app.ExocoreApp, args CosmosTxArgs, ) (authsigning.Tx, error) { txBuilder := args.TxCfg.NewTxBuilder() @@ -67,7 +67,7 @@ func PrepareCosmosTx( return signCosmosTx( ctx, - appEvmos, + appExocore, args, txBuilder, ) @@ -77,12 +77,12 @@ func PrepareCosmosTx( // the provided private key func signCosmosTx( ctx sdk.Context, - appEvmos *app.ExocoreApp, + appExocore *app.ExocoreApp, args CosmosTxArgs, txBuilder client.TxBuilder, ) (authsigning.Tx, error) { addr := sdk.AccAddress(args.Priv.PubKey().Address().Bytes()) - seq, err := appEvmos.AccountKeeper.GetSequence(ctx, addr) + seq, err := appExocore.AccountKeeper.GetSequence(ctx, addr) if err != nil { return nil, err } @@ -105,7 +105,7 @@ func signCosmosTx( } // Second round: all signer infos are set, so each signer can sign. - accNumber := appEvmos.AccountKeeper.GetAccount(ctx, addr).GetAccountNumber() + accNumber := appExocore.AccountKeeper.GetAccount(ctx, addr).GetAccountNumber() signerData := authsigning.SignerData{ ChainID: args.ChainID, AccountNumber: accNumber, diff --git a/testutil/tx/eip712.go b/testutil/tx/eip712.go index 65a6a37b3..e845453c3 100644 --- a/testutil/tx/eip712.go +++ b/testutil/tx/eip712.go @@ -50,12 +50,12 @@ type legacyWeb3ExtensionArgs struct { // It returns the signed transaction and an error func CreateEIP712CosmosTx( ctx sdk.Context, - appEvmos *app.ExocoreApp, + appExocore *app.ExocoreApp, args EIP712TxArgs, ) (sdk.Tx, error) { builder, err := PrepareEIP712CosmosTx( ctx, - appEvmos, + appExocore, args, ) return builder.GetTx(), err @@ -66,7 +66,7 @@ func CreateEIP712CosmosTx( // It returns the tx builder with the signed transaction and an error func PrepareEIP712CosmosTx( ctx sdk.Context, - appEvmos *app.ExocoreApp, + appExocore *app.ExocoreApp, args EIP712TxArgs, ) (client.TxBuilder, error) { txArgs := args.CosmosTxArgs @@ -78,9 +78,9 @@ func PrepareEIP712CosmosTx( chainIDNum := pc.Uint64() from := sdk.AccAddress(txArgs.Priv.PubKey().Address().Bytes()) - accNumber := appEvmos.AccountKeeper.GetAccount(ctx, from).GetAccountNumber() + accNumber := appExocore.AccountKeeper.GetAccount(ctx, from).GetAccountNumber() - nonce, err := appEvmos.AccountKeeper.GetSequence(ctx, from) + nonce, err := appExocore.AccountKeeper.GetSequence(ctx, from) if err != nil { return nil, err } @@ -117,7 +117,7 @@ func PrepareEIP712CosmosTx( return signCosmosEIP712Tx( ctx, - appEvmos, + appExocore, args, builder, chainIDNum, @@ -129,7 +129,7 @@ func PrepareEIP712CosmosTx( // the provided private key and the typed data func signCosmosEIP712Tx( ctx sdk.Context, - appEvmos *app.ExocoreApp, + appExocore *app.ExocoreApp, args EIP712TxArgs, builder authtx.ExtensionOptionsTxBuilder, chainID uint64, @@ -138,7 +138,7 @@ func signCosmosEIP712Tx( priv := args.CosmosTxArgs.Priv from := sdk.AccAddress(priv.PubKey().Address().Bytes()) - nonce, err := appEvmos.AccountKeeper.GetSequence(ctx, from) + nonce, err := appExocore.AccountKeeper.GetSequence(ctx, from) if err != nil { return nil, err } diff --git a/testutil/tx/eth.go b/testutil/tx/eth.go index 0bf8afb5f..84aec52c2 100644 --- a/testutil/tx/eth.go +++ b/testutil/tx/eth.go @@ -26,13 +26,13 @@ import ( // It returns the signed transaction and an error func PrepareEthTx( txCfg client.TxConfig, - appEvmos *app.ExocoreApp, + appExocore *app.ExocoreApp, priv cryptotypes.PrivKey, msgs ...sdk.Msg, ) (authsigning.Tx, error) { txBuilder := txCfg.NewTxBuilder() - signer := ethtypes.LatestSignerForChainID(appEvmos.EvmKeeper.ChainID()) + signer := ethtypes.LatestSignerForChainID(appExocore.EvmKeeper.ChainID()) txFee := sdk.Coins{} txGasLimit := uint64(0) @@ -89,7 +89,7 @@ func PrepareEthTx( // Should this not be the case, just pass in zero. func CreateEthTx( ctx sdk.Context, - appEvmos *app.ExocoreApp, + appExocore *app.ExocoreApp, privKey cryptotypes.PrivKey, from sdk.AccAddress, dest sdk.AccAddress, @@ -98,17 +98,17 @@ func CreateEthTx( ) (*evmtypes.MsgEthereumTx, error) { toAddr := common.BytesToAddress(dest.Bytes()) fromAddr := common.BytesToAddress(from.Bytes()) - chainID := appEvmos.EvmKeeper.ChainID() + chainID := appExocore.EvmKeeper.ChainID() // When we send multiple Ethereum Tx's in one Cosmos Tx, we need to increment the nonce for each one. - nonce := appEvmos.EvmKeeper.GetNonce(ctx, fromAddr) + uint64(nonceIncrement) + nonce := appExocore.EvmKeeper.GetNonce(ctx, fromAddr) + uint64(nonceIncrement) evmTxParams := &evmtypes.EvmTxArgs{ ChainID: chainID, Nonce: nonce, To: &toAddr, Amount: amount, GasLimit: 100000, - GasFeeCap: appEvmos.FeeMarketKeeper.GetBaseFee(ctx), + GasFeeCap: appExocore.FeeMarketKeeper.GetBaseFee(ctx), GasTipCap: big.NewInt(1), Accesses: ðtypes.AccessList{}, } @@ -117,7 +117,7 @@ func CreateEthTx( // If we are creating multiple eth Tx's with different senders, we need to sign here rather than later. if privKey != nil { - signer := ethtypes.LatestSignerForChainID(appEvmos.EvmKeeper.ChainID()) + signer := ethtypes.LatestSignerForChainID(appExocore.EvmKeeper.ChainID()) err := msgEthereumTx.Sign(signer, NewSigner(privKey)) if err != nil { return nil, err diff --git a/precompiles/deposit/utils_test.go b/testutil/utils.go similarity index 53% rename from precompiles/deposit/utils_test.go rename to testutil/utils.go index 31af57c34..d7a973841 100644 --- a/precompiles/deposit/utils_test.go +++ b/testutil/utils.go @@ -1,44 +1,80 @@ -package deposit_test +package testutil import ( "encoding/json" "time" - "github.com/ExocoreNetwork/exocore/precompiles/deposit" - "github.com/ExocoreNetwork/exocore/testutil" + "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/crypto/keyring" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" + "github.com/evmos/evmos/v14/testutil" + "github.com/stretchr/testify/suite" + "golang.org/x/exp/rand" + testutiltx "github.com/ExocoreNetwork/exocore/testutil/tx" - evmosapp "github.com/ExocoreNetwork/exocore/app" + exocoreapp "github.com/ExocoreNetwork/exocore/app" "github.com/ExocoreNetwork/exocore/utils" abci "github.com/cometbft/cometbft/abci/types" "github.com/cometbft/cometbft/crypto/tmhash" tmtypes "github.com/cometbft/cometbft/types" - "github.com/cosmos/cosmos-sdk/baseapp" codectypes "github.com/cosmos/cosmos-sdk/codec/types" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" + "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" "github.com/cosmos/cosmos-sdk/testutil/mock" sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/ethereum/go-ethereum/common" ethtypes "github.com/ethereum/go-ethereum/core/types" - cmn "github.com/evmos/evmos/v14/precompiles/common" evmostypes "github.com/evmos/evmos/v14/types" "github.com/evmos/evmos/v14/x/evm/statedb" evmtypes "github.com/evmos/evmos/v14/x/evm/types" - inflationtypes "github.com/evmos/evmos/v14/x/inflation/types" ) +type BaseTestSuite struct { + suite.Suite + + Ctx sdk.Context + App *exocoreapp.ExocoreApp + Address common.Address + AccAddress sdk.AccAddress + + Validators []stakingtypes.Validator + ValSet *tmtypes.ValidatorSet + EthSigner ethtypes.Signer + PrivKey cryptotypes.PrivKey + Signer keyring.Signer + BondDenom string + StateDB *statedb.StateDB + QueryClientEVM evmtypes.QueryClient + + // needed by test + /* operatorAddr sdk.AccAddress + avsAddr string + assetID string + stakerID string + assetAddr common.Address + assetDecimal uint32 + clientChainLzID uint64 + depositAmount sdkmath.Int + delegationAmount sdkmath.Int + updatedAmountForOptIn sdkmath.Int*/ +} + +func (suite *BaseTestSuite) SetupTest() { + suite.DoSetupTest() +} + // SetupWithGenesisValSet initializes a new EvmosApp with a validator set and genesis accounts // that also act as delegators. For simplicity, each validator is bonded with a delegation // of one consensus engine unit (10^6) in the default token of the simapp from first genesis // account. A Nop logger is set in SimApp. -func (s *PrecompileTestSuite) SetupWithGenesisValSet(valSet *tmtypes.ValidatorSet, genAccs []authtypes.GenesisAccount, balances ...banktypes.Balance) { - appI, genesisState := evmosapp.SetupTestingApp(cmn.DefaultChainID, false)() - app, ok := appI.(*evmosapp.ExocoreApp) - s.Require().True(ok) +func (suite *BaseTestSuite) SetupWithGenesisValSet(valSet *tmtypes.ValidatorSet, genAccs []authtypes.GenesisAccount, balances ...banktypes.Balance) { + appI, genesisState := exocoreapp.SetupTestingApp(utils.DefaultChainID, false)() + app, ok := appI.(*exocoreapp.ExocoreApp) + suite.Require().True(ok) // set genesis accounts authGenesis := authtypes.NewGenesisState(authtypes.DefaultParams(), genAccs) @@ -51,9 +87,9 @@ func (s *PrecompileTestSuite) SetupWithGenesisValSet(valSet *tmtypes.ValidatorSe for _, val := range valSet.Validators { pk, err := cryptocodec.FromTmPubKeyInterface(val.PubKey) - s.Require().NoError(err) + suite.Require().NoError(err) pkAny, err := codectypes.NewAnyWithValue(pk) - s.Require().NoError(err) + suite.Require().NoError(err) validator := stakingtypes.Validator{ OperatorAddress: sdk.ValAddress(val.Address).String(), ConsensusPubkey: pkAny, @@ -70,9 +106,9 @@ func (s *PrecompileTestSuite) SetupWithGenesisValSet(valSet *tmtypes.ValidatorSe validators = append(validators, validator) delegations = append(delegations, stakingtypes.NewDelegation(genAccs[0].GetAddress(), val.Address.Bytes(), sdk.OneDec())) } - s.validators = validators + suite.Validators = validators - // set validators and delegations + // set Validators and delegations stakingParams := stakingtypes.DefaultParams() // set bond demon to be aevmos stakingParams.BondDenom = utils.BaseDenom @@ -97,14 +133,14 @@ func (s *PrecompileTestSuite) SetupWithGenesisValSet(valSet *tmtypes.ValidatorSe genesisState[banktypes.ModuleName] = app.AppCodec().MustMarshalJSON(bankGenesis) stateBytes, err := json.MarshalIndent(genesisState, "", " ") - s.Require().NoError(err) + suite.Require().NoError(err) // init chain will set the validator set and initialize the genesis accounts app.InitChain( abci.RequestInitChain{ - ChainId: cmn.DefaultChainID, + ChainId: utils.DefaultChainID, Validators: []abci.ValidatorUpdate{}, - ConsensusParams: evmosapp.DefaultConsensusParams, + ConsensusParams: exocoreapp.DefaultConsensusParams, AppStateBytes: stateBytes, }, ) @@ -114,107 +150,109 @@ func (s *PrecompileTestSuite) SetupWithGenesisValSet(valSet *tmtypes.ValidatorSe header := testutil.NewHeader( 2, time.Now().UTC(), - cmn.DefaultChainID, + utils.DefaultChainID, sdk.ConsAddress(validators[0].GetOperator()), - tmhash.Sum([]byte("app")), - tmhash.Sum([]byte("validators")), + tmhash.Sum([]byte("App")), + tmhash.Sum([]byte("Validators")), ) app.BeginBlock(abci.RequestBeginBlock{ Header: header, }) - // create Context - s.ctx = app.BaseApp.NewContext(false, header) - s.app = app + // need to create UncachedContext when retrieving historical state + suite.Ctx = app.BaseApp.NewUncachedContext(false, header) + suite.App = app } -func (s *PrecompileTestSuite) DoSetupTest() { +func (suite *BaseTestSuite) DoSetupTest() { // generate validator private/public key privVal := mock.NewPV() pubKey, err := privVal.GetPubKey() - s.Require().NoError(err) + suite.Require().NoError(err) privVal2 := mock.NewPV() pubKey2, err := privVal2.GetPubKey() - s.Require().NoError(err) + suite.Require().NoError(err) - // create validator set with two validators + // create validator set with two Validators validator := tmtypes.NewValidator(pubKey, 1) validator2 := tmtypes.NewValidator(pubKey2, 2) - s.valSet = tmtypes.NewValidatorSet([]*tmtypes.Validator{validator, validator2}) + suite.ValSet = tmtypes.NewValidatorSet([]*tmtypes.Validator{validator, validator2}) signers := make(map[string]tmtypes.PrivValidator) signers[pubKey.Address().String()] = privVal signers[pubKey2.Address().String()] = privVal2 + // create AccAddress for test + pubBz := make([]byte, ed25519.PubKeySize) + pub := &ed25519.PubKey{Key: pubBz} + _, err = rand.Read(pub.Key) + suite.Require().NoError(err) + suite.AccAddress = sdk.AccAddress(pub.Address()) + // generate genesis account addr, priv := testutiltx.NewAddrKey() - s.privKey = priv - s.address = addr - s.signer = testutiltx.NewSigner(priv) - + suite.PrivKey = priv + suite.Address = addr + suite.Signer = testutiltx.NewSigner(priv) baseAcc := authtypes.NewBaseAccount(priv.PubKey().Address().Bytes(), priv.PubKey(), 0, 0) - acc := &evmostypes.EthAccount{ BaseAccount: baseAcc, CodeHash: common.BytesToHash(evmtypes.EmptyCodeHash).Hex(), } - + // set amount for genesis account amount := sdk.TokensFromConsensusPower(5, evmostypes.PowerReduction) - balance := banktypes.Balance{ Address: acc.GetAddress().String(), Coins: sdk.NewCoins(sdk.NewCoin(utils.BaseDenom, amount)), } - s.SetupWithGenesisValSet(s.valSet, []authtypes.GenesisAccount{acc}, balance) + // Initialize an ExocoreApp for test + suite.SetupWithGenesisValSet(suite.ValSet, []authtypes.GenesisAccount{acc}, balance) // Create StateDB - s.stateDB = statedb.New(s.ctx, s.app.EvmKeeper, statedb.NewEmptyTxConfig(common.BytesToHash(s.ctx.HeaderHash().Bytes()))) + suite.StateDB = statedb.New(suite.Ctx, suite.App.EvmKeeper, statedb.NewEmptyTxConfig(common.BytesToHash(suite.Ctx.HeaderHash().Bytes()))) // bond denom - stakingParams := s.app.StakingKeeper.GetParams(s.ctx) - stakingParams.BondDenom = utils.BaseDenom - s.bondDenom = stakingParams.BondDenom - err = s.app.StakingKeeper.SetParams(s.ctx, stakingParams) - s.Require().NoError(err) - - s.ethSigner = ethtypes.LatestSignerForChainID(s.app.EvmKeeper.ChainID()) - - precompile, err := deposit.NewPrecompile(s.app.StakingAssetsManageKeeper, s.app.DepositKeeper, s.app.AuthzKeeper) - s.Require().NoError(err) - s.precompile = precompile - - coins := sdk.NewCoins(sdk.NewCoin(utils.BaseDenom, sdk.NewInt(5000000000000000000))) - inflCoins := sdk.NewCoins(sdk.NewCoin(utils.BaseDenom, sdk.NewInt(2000000000000000000))) - distrCoins := sdk.NewCoins(sdk.NewCoin(utils.BaseDenom, sdk.NewInt(3000000000000000000))) - err = s.app.BankKeeper.MintCoins(s.ctx, inflationtypes.ModuleName, coins) - s.Require().NoError(err) - err = s.app.BankKeeper.SendCoinsFromModuleToModule(s.ctx, inflationtypes.ModuleName, authtypes.FeeCollectorName, inflCoins) - s.Require().NoError(err) - err = s.app.BankKeeper.SendCoinsFromModuleToModule(s.ctx, inflationtypes.ModuleName, distrtypes.ModuleName, distrCoins) - s.Require().NoError(err) - - queryHelperEvm := baseapp.NewQueryServerTestHelper(s.ctx, s.app.InterfaceRegistry()) - evmtypes.RegisterQueryServer(queryHelperEvm, s.app.EvmKeeper) - s.queryClientEVM = evmtypes.NewQueryClient(queryHelperEvm) + /* stakingParams := suite.App.StakingKeeper.GetParams(suite.Ctx) + stakingParams.BondDenom = utils.BaseDenom + suite.BondDenom = stakingParams.BondDenom + err = suite.App.StakingKeeper.SetParams(suite.Ctx, stakingParams) + suite.Require().NoError(err)*/ + + suite.BondDenom = utils.BaseDenom + suite.EthSigner = ethtypes.LatestSignerForChainID(suite.App.EvmKeeper.ChainID()) + + queryHelperEvm := baseapp.NewQueryServerTestHelper(suite.Ctx, suite.App.InterfaceRegistry()) + evmtypes.RegisterQueryServer(queryHelperEvm, suite.App.EvmKeeper) + suite.QueryClientEVM = evmtypes.NewQueryClient(queryHelperEvm) + + /* coins := sdk.NewCoins(sdk.NewCoin(utils.BaseDenom, sdk.NewInt(5000000000000000000))) + inflCoins := sdk.NewCoins(sdk.NewCoin(utils.BaseDenom, sdk.NewInt(2000000000000000000))) + distrCoins := sdk.NewCoins(sdk.NewCoin(utils.BaseDenom, sdk.NewInt(3000000000000000000))) + err = suite.App.BankKeeper.MintCoins(suite.Ctx, inflationtypes.ModuleName, coins) + suite.Require().NoError(err) + err = suite.App.BankKeeper.SendCoinsFromModuleToModule(suite.Ctx, inflationtypes.ModuleName, authtypes.FeeCollectorName, inflCoins) + suite.Require().NoError(err) + err = suite.App.BankKeeper.SendCoinsFromModuleToModule(suite.Ctx, inflationtypes.ModuleName, distrtypes.ModuleName, distrCoins) + suite.Require().NoError(err)*/ } // DeployContract deploys a contract that calls the deposit precompile's methods for testing purposes. -func (s *PrecompileTestSuite) DeployContract(contract evmtypes.CompiledContract) (addr common.Address, err error) { - addr, err = testutil.DeployContract( - s.ctx, - s.app, - s.privKey, - s.queryClientEVM, +func (suite *BaseTestSuite) DeployContract(contract evmtypes.CompiledContract) (addr common.Address, err error) { + addr, err = DeployContract( + suite.Ctx, + suite.App, + suite.PrivKey, + suite.QueryClientEVM, contract, ) return } // NextBlock commits the current block and sets up the next block. -func (s *PrecompileTestSuite) NextBlock() { +func (suite *BaseTestSuite) NextBlock() { var err error - s.ctx, err = testutil.CommitAndCreateNewCtx(s.ctx, s.app, time.Second, s.valSet) - s.Require().NoError(err) + suite.Ctx, err = CommitAndCreateNewCtx(suite.Ctx, suite.App, time.Second, suite.ValSet) + suite.Require().NoError(err) } diff --git a/utils/utils.go b/utils/utils.go index 121c91017..cbbc672ec 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -20,6 +20,8 @@ const ( // TestnetChainID defines the Evmos EIP155 chain ID for testnet // TODO: the testnet chainid is still under consideration and need to be finalized later TestnetChainID = "exocoretestnet_233" + // DefaultChainID is the standard chain id used for testing purposes + DefaultChainID = MainnetChainID + "-1" // BaseDenom defines the Evmos mainnet denomination BaseDenom = "aexo" ) @@ -62,11 +64,11 @@ func IsSupportedKey(pubkey cryptotypes.PubKey) bool { } } -// GetEvmosAddressFromBech32 returns the sdk.Account address of given address, +// GetExocoreAddressFromBech32 returns the sdk.Account address of given address, // while also changing bech32 human readable prefix (HRP) to the value set on // the global sdk.Config (eg: `evmos`). // The function fails if the provided bech32 address is invalid. -func GetEvmosAddressFromBech32(address string) (sdk.AccAddress, error) { +func GetExocoreAddressFromBech32(address string) (sdk.AccAddress, error) { bech32Prefix := strings.SplitN(address, "1", 2)[0] if bech32Prefix == address { return nil, errorsmod.Wrapf(errortypes.ErrInvalidAddress, "invalid bech32 address: %s", address) diff --git a/utils/utils_test.go b/utils/utils_test.go index f3e547835..5240ce5a0 100644 --- a/utils/utils_test.go +++ b/utils/utils_test.go @@ -17,7 +17,7 @@ import ( func init() { cfg := sdk.GetConfig() - cfg.SetBech32PrefixForAccount("evmos", "evmospub") + cfg.SetBech32PrefixForAccount("exo", "exopub") } func TestIsSupportedKeys(t *testing.T) { @@ -73,7 +73,7 @@ func TestIsSupportedKeys(t *testing.T) { } } -func TestGetEvmosAddressFromBech32(t *testing.T) { +func TestGetExocoreAddressFromBech32(t *testing.T) { testCases := []struct { name string address string @@ -88,38 +88,38 @@ func TestGetEvmosAddressFromBech32(t *testing.T) { }, { "invalid bech32 address", - "evmos", + "exocore", "", true, }, { "invalid address bytes", - "evmos1123", + "exocore1123", "", true, }, { - "evmos address", - "evmos1qql8ag4cluz6r4dz28p3w00dnc9w8ueuafmxps", - "evmos1qql8ag4cluz6r4dz28p3w00dnc9w8ueuafmxps", + "exocore address", + "exo13h6xg79g82e2g2vhjwg7j4r2z2hlncelwutkjr", + "exo13h6xg79g82e2g2vhjwg7j4r2z2hlncelwutkjr", false, }, { "cosmos address", "cosmos1qql8ag4cluz6r4dz28p3w00dnc9w8ueulg2gmc", - "evmos1qql8ag4cluz6r4dz28p3w00dnc9w8ueuafmxps", + "exo1qql8ag4cluz6r4dz28p3w00dnc9w8ueu83talg", false, }, { "osmosis address", "osmo1qql8ag4cluz6r4dz28p3w00dnc9w8ueuhnecd2", - "evmos1qql8ag4cluz6r4dz28p3w00dnc9w8ueuafmxps", + "exo1qql8ag4cluz6r4dz28p3w00dnc9w8ueu83talg", false, }, } for _, tc := range testCases { - addr, err := GetEvmosAddressFromBech32(tc.address) + addr, err := GetExocoreAddressFromBech32(tc.address) if tc.expError { require.Error(t, err, tc.name) } else { @@ -129,7 +129,7 @@ func TestGetEvmosAddressFromBech32(t *testing.T) { } } -func TestEvmosCoinDenom(t *testing.T) { +func TestExocoreCoinDenom(t *testing.T) { testCases := []struct { name string denom string @@ -137,7 +137,7 @@ func TestEvmosCoinDenom(t *testing.T) { }{ { "valid denom - native coin", - "aevmos", + "aexo", false, }, { diff --git a/x/delegation/client/cli/query.go b/x/delegation/client/cli/query.go index 6cc258196..ead51495b 100644 --- a/x/delegation/client/cli/query.go +++ b/x/delegation/client/cli/query.go @@ -34,7 +34,7 @@ func GetQueryCmd() *cobra.Command { // QuerySingleDelegationInfo queries the single delegation info func QuerySingleDelegationInfo() *cobra.Command { cmd := &cobra.Command{ - Use: "QuerySingleDelegationInfo clientChainId stakerAddr assetAddr operatorAddr", + Use: "QuerySingleDelegationInfo clientChainID stakerAddr assetAddr operatorAddr", Short: "Get single delegation info", Long: "Get single delegation info", Args: cobra.ExactArgs(4), diff --git a/x/delegation/keeper/delegation_op_test.go b/x/delegation/keeper/delegation_op_test.go index 3cf6f8d07..33ed6d3e0 100644 --- a/x/delegation/keeper/delegation_op_test.go +++ b/x/delegation/keeper/delegation_op_test.go @@ -11,33 +11,33 @@ import ( "github.com/ethereum/go-ethereum/common" ) -func (suite *KeeperTestSuite) TestDelegateTo() { +func (suite *DelegationTestSuite) TestDelegateTo() { usdtAddress := common.HexToAddress("0xdAC17F958D2ee523a2206206994597C13D831ec7") clientChainLzID := uint64(101) depositEvent := &keeper.DepositParams{ ClientChainLzID: clientChainLzID, Action: types.Deposit, - StakerAddress: suite.address[:], + StakerAddress: suite.Address[:], OpAmount: sdkmath.NewInt(100), } depositEvent.AssetsAddress = usdtAddress[:] - err := suite.app.DepositKeeper.Deposit(suite.ctx, depositEvent) + err := suite.App.DepositKeeper.Deposit(suite.Ctx, depositEvent) suite.NoError(err) - opAccAddr, err := sdk.AccAddressFromBech32("evmos1fl48vsnmsdzcv85q5d2q4z5ajdha8yu3h6cprl") + opAccAddr, err := sdk.AccAddressFromBech32("exo13h6xg79g82e2g2vhjwg7j4r2z2hlncelwutkjr") suite.NoError(err) delegationParams := &keeper2.DelegationOrUndelegationParams{ ClientChainLzID: clientChainLzID, Action: types.DelegateTo, AssetsAddress: usdtAddress[:], OperatorAddress: opAccAddr, - StakerAddress: suite.address[:], + StakerAddress: suite.Address[:], OpAmount: sdkmath.NewInt(50), LzNonce: 0, TxHash: common.HexToHash("0x24c4a315d757249c12a7a1d7b6fb96261d49deee26f06a3e1787d008b445c3ac"), } - err = suite.app.DelegationKeeper.DelegateTo(suite.ctx, delegationParams) + err = suite.App.DelegationKeeper.DelegateTo(suite.Ctx, delegationParams) suite.EqualError(err, delegationtype.ErrOperatorNotExist.Error()) registerReq := &delegationtype.RegisterOperatorReq{ @@ -46,15 +46,15 @@ func (suite *KeeperTestSuite) TestDelegateTo() { EarningsAddr: opAccAddr.String(), }, } - _, err = suite.app.DelegationKeeper.RegisterOperator(suite.ctx, registerReq) + _, err = suite.App.DelegationKeeper.RegisterOperator(suite.Ctx, registerReq) suite.NoError(err) - err = suite.app.DelegationKeeper.DelegateTo(suite.ctx, delegationParams) + err = suite.App.DelegationKeeper.DelegateTo(suite.Ctx, delegationParams) suite.NoError(err) // check delegation states stakerID, assetID := types.GetStakeIDAndAssetID(delegationParams.ClientChainLzID, delegationParams.StakerAddress, delegationParams.AssetsAddress) - restakerState, err := suite.app.StakingAssetsManageKeeper.GetStakerSpecifiedAssetInfo(suite.ctx, stakerID, assetID) + restakerState, err := suite.App.StakingAssetsManageKeeper.GetStakerSpecifiedAssetInfo(suite.Ctx, stakerID, assetID) suite.NoError(err) suite.Equal(types.StakerSingleAssetOrChangeInfo{ TotalDepositAmountOrWantChangeValue: depositEvent.OpAmount, @@ -62,7 +62,7 @@ func (suite *KeeperTestSuite) TestDelegateTo() { WaitUndelegationAmountOrWantChangeValue: sdkmath.NewInt(0), }, *restakerState) - operatorState, err := suite.app.StakingAssetsManageKeeper.GetOperatorSpecifiedAssetInfo(suite.ctx, opAccAddr, assetID) + operatorState, err := suite.App.StakingAssetsManageKeeper.GetOperatorSpecifiedAssetInfo(suite.Ctx, opAccAddr, assetID) suite.NoError(err) suite.Equal(types.OperatorSingleAssetOrChangeInfo{ TotalAmountOrWantChangeValue: delegationParams.OpAmount, @@ -70,40 +70,40 @@ func (suite *KeeperTestSuite) TestDelegateTo() { WaitUndelegationAmountOrWantChangeValue: sdkmath.NewInt(0), }, *operatorState) - specifiedDelegationAmount, err := suite.app.DelegationKeeper.GetSingleDelegationInfo(suite.ctx, stakerID, assetID, opAccAddr.String()) + specifiedDelegationAmount, err := suite.App.DelegationKeeper.GetSingleDelegationInfo(suite.Ctx, stakerID, assetID, opAccAddr.String()) suite.NoError(err) suite.Equal(delegationtype.DelegationAmounts{ CanUndelegationAmount: delegationParams.OpAmount, WaitUndelegationAmount: sdkmath.NewInt(0), }, *specifiedDelegationAmount) - totalDelegationAmount, err := suite.app.DelegationKeeper.GetStakerDelegationTotalAmount(suite.ctx, stakerID, assetID) + totalDelegationAmount, err := suite.App.DelegationKeeper.GetStakerDelegationTotalAmount(suite.Ctx, stakerID, assetID) suite.NoError(err) suite.Equal(delegationParams.OpAmount, totalDelegationAmount) } -func (suite *KeeperTestSuite) TestUndelegateFrom() { +func (suite *DelegationTestSuite) TestUndelegateFrom() { usdtAddress := common.HexToAddress("0xdAC17F958D2ee523a2206206994597C13D831ec7") clientChainLzID := uint64(101) depositEvent := &keeper.DepositParams{ ClientChainLzID: clientChainLzID, Action: types.Deposit, - StakerAddress: suite.address[:], + StakerAddress: suite.Address[:], OpAmount: sdkmath.NewInt(100), } depositEvent.AssetsAddress = usdtAddress[:] - err := suite.app.DepositKeeper.Deposit(suite.ctx, depositEvent) + err := suite.App.DepositKeeper.Deposit(suite.Ctx, depositEvent) suite.NoError(err) - opAccAddr, err := sdk.AccAddressFromBech32("evmos1fl48vsnmsdzcv85q5d2q4z5ajdha8yu3h6cprl") + opAccAddr, err := sdk.AccAddressFromBech32("exo13h6xg79g82e2g2vhjwg7j4r2z2hlncelwutkjr") suite.NoError(err) delegationEvent := &keeper2.DelegationOrUndelegationParams{ ClientChainLzID: clientChainLzID, Action: types.DelegateTo, AssetsAddress: usdtAddress[:], OperatorAddress: opAccAddr, - StakerAddress: suite.address[:], + StakerAddress: suite.Address[:], OpAmount: sdkmath.NewInt(50), LzNonce: 0, TxHash: common.HexToHash("0x24c4a315d757249c12a7a1d7b6fb96261d49deee26f06a3e1787d008b445c3ac"), @@ -114,20 +114,20 @@ func (suite *KeeperTestSuite) TestUndelegateFrom() { EarningsAddr: opAccAddr.String(), }, } - _, err = suite.app.DelegationKeeper.RegisterOperator(suite.ctx, registerReq) + _, err = suite.App.DelegationKeeper.RegisterOperator(suite.Ctx, registerReq) suite.NoError(err) - err = suite.app.DelegationKeeper.DelegateTo(suite.ctx, delegationEvent) + err = suite.App.DelegationKeeper.DelegateTo(suite.Ctx, delegationEvent) suite.NoError(err) // test Undelegation delegationEvent.LzNonce = 1 - err = suite.app.DelegationKeeper.UndelegateFrom(suite.ctx, delegationEvent) + err = suite.App.DelegationKeeper.UndelegateFrom(suite.Ctx, delegationEvent) suite.NoError(err) // check state stakerID, assetID := types.GetStakeIDAndAssetID(delegationEvent.ClientChainLzID, delegationEvent.StakerAddress, delegationEvent.AssetsAddress) - restakerState, err := suite.app.StakingAssetsManageKeeper.GetStakerSpecifiedAssetInfo(suite.ctx, stakerID, assetID) + restakerState, err := suite.App.StakingAssetsManageKeeper.GetStakerSpecifiedAssetInfo(suite.Ctx, stakerID, assetID) suite.NoError(err) suite.Equal(types.StakerSingleAssetOrChangeInfo{ TotalDepositAmountOrWantChangeValue: depositEvent.OpAmount, @@ -135,7 +135,7 @@ func (suite *KeeperTestSuite) TestUndelegateFrom() { WaitUndelegationAmountOrWantChangeValue: delegationEvent.OpAmount, }, *restakerState) - operatorState, err := suite.app.StakingAssetsManageKeeper.GetOperatorSpecifiedAssetInfo(suite.ctx, opAccAddr, assetID) + operatorState, err := suite.App.StakingAssetsManageKeeper.GetOperatorSpecifiedAssetInfo(suite.Ctx, opAccAddr, assetID) suite.NoError(err) suite.Equal(types.OperatorSingleAssetOrChangeInfo{ TotalAmountOrWantChangeValue: delegationEvent.OpAmount, @@ -143,18 +143,18 @@ func (suite *KeeperTestSuite) TestUndelegateFrom() { WaitUndelegationAmountOrWantChangeValue: delegationEvent.OpAmount, }, *operatorState) - specifiedDelegationAmount, err := suite.app.DelegationKeeper.GetSingleDelegationInfo(suite.ctx, stakerID, assetID, opAccAddr.String()) + specifiedDelegationAmount, err := suite.App.DelegationKeeper.GetSingleDelegationInfo(suite.Ctx, stakerID, assetID, opAccAddr.String()) suite.NoError(err) suite.Equal(delegationtype.DelegationAmounts{ CanUndelegationAmount: sdkmath.NewInt(0), WaitUndelegationAmount: delegationEvent.OpAmount, }, *specifiedDelegationAmount) - totalDelegationAmount, err := suite.app.DelegationKeeper.GetStakerDelegationTotalAmount(suite.ctx, stakerID, assetID) + totalDelegationAmount, err := suite.App.DelegationKeeper.GetStakerDelegationTotalAmount(suite.Ctx, stakerID, assetID) suite.NoError(err) suite.Equal(delegationEvent.OpAmount, totalDelegationAmount) - records, err := suite.app.DelegationKeeper.GetStakerUndelegationRecords(suite.ctx, stakerID, assetID, keeper2.PendingRecords) + records, err := suite.App.DelegationKeeper.GetStakerUndelegationRecords(suite.Ctx, stakerID, assetID, keeper2.PendingRecords) suite.NoError(err) suite.Equal(1, len(records)) UndelegationRecord := &delegationtype.UndelegationRecord{ @@ -163,7 +163,7 @@ func (suite *KeeperTestSuite) TestUndelegateFrom() { OperatorAddr: delegationEvent.OperatorAddress.String(), TxHash: delegationEvent.TxHash.String(), IsPending: true, - BlockNumber: uint64(suite.ctx.BlockHeight()), + BlockNumber: uint64(suite.Ctx.BlockHeight()), LzTxNonce: delegationEvent.LzNonce, Amount: delegationEvent.OpAmount, ActualCompletedAmount: sdkmath.NewInt(0), @@ -171,35 +171,35 @@ func (suite *KeeperTestSuite) TestUndelegateFrom() { UndelegationRecord.CompleteBlockNumber = UndelegationRecord.BlockNumber + delegationtype.CanUndelegationDelayHeight suite.Equal(UndelegationRecord, records[0]) - suite.ctx.Logger().Info("the complete block number is:", "height", UndelegationRecord.CompleteBlockNumber) - waitUndelegationRecords, err := suite.app.DelegationKeeper.GetWaitCompleteUndelegationRecords(suite.ctx, UndelegationRecord.CompleteBlockNumber) + suite.Ctx.Logger().Info("the complete block number is:", "height", UndelegationRecord.CompleteBlockNumber) + waitUndelegationRecords, err := suite.App.DelegationKeeper.GetWaitCompleteUndelegationRecords(suite.Ctx, UndelegationRecord.CompleteBlockNumber) suite.NoError(err) suite.Equal(1, len(waitUndelegationRecords)) suite.Equal(UndelegationRecord, waitUndelegationRecords[0]) } -func (suite *KeeperTestSuite) TestCompleteUndelegation() { +func (suite *DelegationTestSuite) TestCompleteUndelegation() { usdtAddress := common.HexToAddress("0xdAC17F958D2ee523a2206206994597C13D831ec7") clientChainLzID := uint64(101) depositEvent := &keeper.DepositParams{ ClientChainLzID: clientChainLzID, Action: types.Deposit, - StakerAddress: suite.address[:], + StakerAddress: suite.Address[:], OpAmount: sdkmath.NewInt(100), } depositEvent.AssetsAddress = usdtAddress[:] - err := suite.app.DepositKeeper.Deposit(suite.ctx, depositEvent) + err := suite.App.DepositKeeper.Deposit(suite.Ctx, depositEvent) suite.NoError(err) - opAccAddr, err := sdk.AccAddressFromBech32("evmos1fl48vsnmsdzcv85q5d2q4z5ajdha8yu3h6cprl") + opAccAddr, err := sdk.AccAddressFromBech32("exo13h6xg79g82e2g2vhjwg7j4r2z2hlncelwutkjr") suite.NoError(err) delegationEvent := &keeper2.DelegationOrUndelegationParams{ ClientChainLzID: clientChainLzID, Action: types.DelegateTo, AssetsAddress: usdtAddress[:], OperatorAddress: opAccAddr, - StakerAddress: suite.address[:], + StakerAddress: suite.Address[:], OpAmount: sdkmath.NewInt(50), LzNonce: 0, TxHash: common.HexToHash("0x24c4a315d757249c12a7a1d7b6fb96261d49deee26f06a3e1787d008b445c3ac"), @@ -210,26 +210,26 @@ func (suite *KeeperTestSuite) TestCompleteUndelegation() { EarningsAddr: opAccAddr.String(), }, } - _, err = suite.app.DelegationKeeper.RegisterOperator(suite.ctx, registerReq) + _, err = suite.App.DelegationKeeper.RegisterOperator(suite.Ctx, registerReq) suite.NoError(err) - err = suite.app.DelegationKeeper.DelegateTo(suite.ctx, delegationEvent) + err = suite.App.DelegationKeeper.DelegateTo(suite.Ctx, delegationEvent) suite.NoError(err) delegationEvent.LzNonce = 1 - err = suite.app.DelegationKeeper.UndelegateFrom(suite.ctx, delegationEvent) + err = suite.App.DelegationKeeper.UndelegateFrom(suite.Ctx, delegationEvent) suite.NoError(err) - UndelegateHeight := suite.ctx.BlockHeight() - suite.ctx.Logger().Info("the ctx block height is:", "height", UndelegateHeight) + UndelegateHeight := suite.Ctx.BlockHeight() + suite.Ctx.Logger().Info("the ctx block height is:", "height", UndelegateHeight) // test complete Undelegation completeBlockNumber := UndelegateHeight + int64(delegationtype.CanUndelegationDelayHeight) - suite.ctx = suite.ctx.WithBlockHeight(completeBlockNumber) - suite.app.DelegationKeeper.EndBlock(suite.ctx, abci.RequestEndBlock{}) + suite.Ctx = suite.Ctx.WithBlockHeight(completeBlockNumber) + suite.App.DelegationKeeper.EndBlock(suite.Ctx, abci.RequestEndBlock{}) // check state stakerID, assetID := types.GetStakeIDAndAssetID(delegationEvent.ClientChainLzID, delegationEvent.StakerAddress, delegationEvent.AssetsAddress) - restakerState, err := suite.app.StakingAssetsManageKeeper.GetStakerSpecifiedAssetInfo(suite.ctx, stakerID, assetID) + restakerState, err := suite.App.StakingAssetsManageKeeper.GetStakerSpecifiedAssetInfo(suite.Ctx, stakerID, assetID) suite.NoError(err) suite.Equal(types.StakerSingleAssetOrChangeInfo{ TotalDepositAmountOrWantChangeValue: depositEvent.OpAmount, @@ -237,7 +237,7 @@ func (suite *KeeperTestSuite) TestCompleteUndelegation() { WaitUndelegationAmountOrWantChangeValue: sdkmath.NewInt(0), }, *restakerState) - operatorState, err := suite.app.StakingAssetsManageKeeper.GetOperatorSpecifiedAssetInfo(suite.ctx, opAccAddr, assetID) + operatorState, err := suite.App.StakingAssetsManageKeeper.GetOperatorSpecifiedAssetInfo(suite.Ctx, opAccAddr, assetID) suite.NoError(err) suite.Equal(types.OperatorSingleAssetOrChangeInfo{ TotalAmountOrWantChangeValue: sdkmath.NewInt(0), @@ -245,18 +245,18 @@ func (suite *KeeperTestSuite) TestCompleteUndelegation() { WaitUndelegationAmountOrWantChangeValue: sdkmath.NewInt(0), }, *operatorState) - specifiedDelegationAmount, err := suite.app.DelegationKeeper.GetSingleDelegationInfo(suite.ctx, stakerID, assetID, opAccAddr.String()) + specifiedDelegationAmount, err := suite.App.DelegationKeeper.GetSingleDelegationInfo(suite.Ctx, stakerID, assetID, opAccAddr.String()) suite.NoError(err) suite.Equal(delegationtype.DelegationAmounts{ CanUndelegationAmount: sdkmath.NewInt(0), WaitUndelegationAmount: sdkmath.NewInt(0), }, *specifiedDelegationAmount) - totalDelegationAmount, err := suite.app.DelegationKeeper.GetStakerDelegationTotalAmount(suite.ctx, stakerID, assetID) + totalDelegationAmount, err := suite.App.DelegationKeeper.GetStakerDelegationTotalAmount(suite.Ctx, stakerID, assetID) suite.NoError(err) suite.Equal(sdkmath.NewInt(0), totalDelegationAmount) - records, err := suite.app.DelegationKeeper.GetStakerUndelegationRecords(suite.ctx, stakerID, assetID, keeper2.CompletedRecords) + records, err := suite.App.DelegationKeeper.GetStakerUndelegationRecords(suite.Ctx, stakerID, assetID, keeper2.CompletedRecords) suite.NoError(err) suite.Equal(1, len(records)) UndelegationRecord := &delegationtype.UndelegationRecord{ @@ -273,7 +273,7 @@ func (suite *KeeperTestSuite) TestCompleteUndelegation() { } suite.Equal(UndelegationRecord, records[0]) - waitUndelegationRecords, err := suite.app.DelegationKeeper.GetWaitCompleteUndelegationRecords(suite.ctx, UndelegationRecord.CompleteBlockNumber) + waitUndelegationRecords, err := suite.App.DelegationKeeper.GetWaitCompleteUndelegationRecords(suite.Ctx, UndelegationRecord.CompleteBlockNumber) suite.NoError(err) suite.Equal(1, len(waitUndelegationRecords)) suite.Equal(UndelegationRecord, waitUndelegationRecords[0]) diff --git a/x/delegation/keeper/operator_info_test.go b/x/delegation/keeper/operator_info_test.go index aec84310d..d0b3b1df6 100644 --- a/x/delegation/keeper/operator_info_test.go +++ b/x/delegation/keeper/operator_info_test.go @@ -2,9 +2,9 @@ package keeper_test import delegationtype "github.com/ExocoreNetwork/exocore/x/delegation/types" -func (suite *KeeperTestSuite) TestOperatorInfo() { +func (suite *DelegationTestSuite) TestOperatorInfo() { info := &delegationtype.OperatorInfo{ - EarningsAddr: suite.accAddress.String(), + EarningsAddr: suite.AccAddress.String(), ApproveAddr: "", OperatorMetaInfo: "test operator", ClientChainEarningsAddr: &delegationtype.ClientChainEarningAddrList{ @@ -13,10 +13,10 @@ func (suite *KeeperTestSuite) TestOperatorInfo() { }, }, } - err := suite.app.DelegationKeeper.SetOperatorInfo(suite.ctx, suite.accAddress.String(), info) + err := suite.App.DelegationKeeper.SetOperatorInfo(suite.Ctx, suite.AccAddress.String(), info) suite.NoError(err) - getOperatorInfo, err := suite.app.DelegationKeeper.GetOperatorInfo(suite.ctx, suite.accAddress.String()) + getOperatorInfo, err := suite.App.DelegationKeeper.GetOperatorInfo(suite.Ctx, suite.AccAddress.String()) suite.NoError(err) suite.Equal(*info, *getOperatorInfo) } diff --git a/x/delegation/keeper/setup_test.go b/x/delegation/keeper/setup_test.go index ce52efbcb..c139e4874 100644 --- a/x/delegation/keeper/setup_test.go +++ b/x/delegation/keeper/setup_test.go @@ -1,33 +1,23 @@ package keeper_test import ( + "github.com/ExocoreNetwork/exocore/testutil" "testing" - "github.com/ExocoreNetwork/exocore/app" - "github.com/cosmos/cosmos-sdk/crypto/keyring" - "github.com/ethereum/go-ethereum/common" - . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/suite" ) -type KeeperTestSuite struct { - suite.Suite - - ctx sdk.Context - app *app.ExocoreApp - address common.Address - signer keyring.Signer - accAddress sdk.AccAddress +type DelegationTestSuite struct { + testutil.BaseTestSuite } -var s *KeeperTestSuite +var s *DelegationTestSuite func TestKeeperTestSuite(t *testing.T) { - s = new(KeeperTestSuite) + s = new(DelegationTestSuite) suite.Run(t, s) // Run Ginkgo integration tests @@ -35,6 +25,6 @@ func TestKeeperTestSuite(t *testing.T) { RunSpecs(t, "Keeper Suite") } -func (suite *KeeperTestSuite) SetupTest() { - suite.DoSetupTest(suite.T()) +func (suite *DelegationTestSuite) SetupTest() { + suite.DoSetupTest() } diff --git a/x/delegation/keeper/utils_test.go b/x/delegation/keeper/utils_test.go deleted file mode 100644 index 8abc9db4a..000000000 --- a/x/delegation/keeper/utils_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package keeper_test - -import ( - "time" - - "github.com/ExocoreNetwork/exocore/app" - "github.com/ExocoreNetwork/exocore/utils" - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/ethereum/go-ethereum/common" - "github.com/evmos/evmos/v14/crypto/ethsecp256k1" - "github.com/evmos/evmos/v14/testutil" - utiltx "github.com/evmos/evmos/v14/testutil/tx" - feemarkettypes "github.com/evmos/evmos/v14/x/feemarket/types" - "github.com/stretchr/testify/require" - "golang.org/x/exp/rand" -) - -// Test helpers -func (suite *KeeperTestSuite) DoSetupTest(t require.TestingT) { - // account key - priv, err := ethsecp256k1.GenerateKey() - require.NoError(t, err) - suite.address = common.BytesToAddress(priv.PubKey().Address().Bytes()) - suite.signer = utiltx.NewSigner(priv) - - // accAddress - pubBz := make([]byte, ed25519.PubKeySize) - pub := &ed25519.PubKey{Key: pubBz} - rand.Read(pub.Key) - suite.accAddress = sdk.AccAddress(pub.Address()) - - // consensus key - privCons, err := ethsecp256k1.GenerateKey() - require.NoError(t, err) - consAddress := sdk.ConsAddress(privCons.PubKey().Address()) - - chainID := utils.TestnetChainID + "-1" - suite.app = app.Setup(false, feemarkettypes.DefaultGenesisState(), chainID, false) - header := testutil.NewHeader( - 1, time.Now().UTC(), chainID, consAddress, nil, nil, - ) - suite.ctx = suite.app.BaseApp.NewContext(false, header) -} diff --git a/x/deposit/keeper/deposit_test.go b/x/deposit/keeper/deposit_test.go index 46f9e51d0..41c87e024 100644 --- a/x/deposit/keeper/deposit_test.go +++ b/x/deposit/keeper/deposit_test.go @@ -8,33 +8,33 @@ import ( "github.com/ethereum/go-ethereum/common" ) -func (suite *KeeperTestSuite) TestDeposit() { +func (suite *DepositTestSuite) TestDeposit() { usdtAddress := common.HexToAddress("0xdAC17F958D2ee523a2206206994597C13D831ec7") usdcAddress := common.HexToAddress("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48") params := &keeper.DepositParams{ ClientChainLzID: 101, Action: types.Deposit, - StakerAddress: suite.address[:], + StakerAddress: suite.Address[:], OpAmount: sdkmath.NewInt(100), } // test the case that the deposit asset hasn't registered params.AssetsAddress = usdcAddress[:] - err := suite.app.DepositKeeper.Deposit(suite.ctx, params) + err := suite.App.DepositKeeper.Deposit(suite.Ctx, params) suite.ErrorContains(err, deposittype.ErrDepositAssetNotExist.Error()) - assets, err := suite.app.StakingAssetsManageKeeper.GetAllStakingAssetsInfo(suite.ctx) + assets, err := suite.App.StakingAssetsManageKeeper.GetAllStakingAssetsInfo(suite.Ctx) suite.NoError(err) - suite.app.Logger().Info("the assets is:", "assets", assets) + suite.App.Logger().Info("the assets is:", "assets", assets) // test the normal case params.AssetsAddress = usdtAddress[:] - err = suite.app.DepositKeeper.Deposit(suite.ctx, params) + err = suite.App.DepositKeeper.Deposit(suite.Ctx, params) suite.NoError(err) // check state after deposit stakerID, assetID := types.GetStakeIDAndAssetID(params.ClientChainLzID, params.StakerAddress, params.AssetsAddress) - info, err := suite.app.StakingAssetsManageKeeper.GetStakerSpecifiedAssetInfo(suite.ctx, stakerID, assetID) + info, err := suite.App.StakingAssetsManageKeeper.GetStakerSpecifiedAssetInfo(suite.Ctx, stakerID, assetID) suite.NoError(err) suite.Equal(types.StakerSingleAssetOrChangeInfo{ TotalDepositAmountOrWantChangeValue: params.OpAmount, @@ -42,7 +42,7 @@ func (suite *KeeperTestSuite) TestDeposit() { WaitUndelegationAmountOrWantChangeValue: sdkmath.NewInt(0), }, *info) - assetInfo, err := suite.app.StakingAssetsManageKeeper.GetStakingAssetInfo(suite.ctx, assetID) + assetInfo, err := suite.App.StakingAssetsManageKeeper.GetStakingAssetInfo(suite.Ctx, assetID) suite.NoError(err) suite.Equal(params.OpAmount, assetInfo.StakingTotalAmount) } diff --git a/x/deposit/keeper/params_test.go b/x/deposit/keeper/params_test.go index f40415fff..016486003 100644 --- a/x/deposit/keeper/params_test.go +++ b/x/deposit/keeper/params_test.go @@ -4,15 +4,15 @@ import ( deposittype "github.com/ExocoreNetwork/exocore/x/deposit/types" ) -func (suite *KeeperTestSuite) TestParams() { +func (suite *DepositTestSuite) TestParams() { params := &deposittype.Params{ ExoCoreLzAppAddress: "0x3fC91A3afd70395Cd496C647d5a6CC9D4B2b7FAD", ExoCoreLzAppEventTopic: "0xc6a377bfc4eb120024a8ac08eef205be16b817020812c73223e81d1bdb9708ec", } - err := suite.app.DepositKeeper.SetParams(suite.ctx, params) + err := suite.App.DepositKeeper.SetParams(suite.Ctx, params) suite.NoError(err) - getParams, err := suite.app.DepositKeeper.GetParams(suite.ctx) + getParams, err := suite.App.DepositKeeper.GetParams(suite.Ctx) suite.NoError(err) suite.Equal(*params, *getParams) } diff --git a/x/deposit/keeper/setup_test.go b/x/deposit/keeper/setup_test.go index 13bd11a79..c6b43ccc3 100644 --- a/x/deposit/keeper/setup_test.go +++ b/x/deposit/keeper/setup_test.go @@ -1,32 +1,23 @@ package keeper_test import ( + "github.com/ExocoreNetwork/exocore/testutil" "testing" - "github.com/ExocoreNetwork/exocore/app" - "github.com/cosmos/cosmos-sdk/crypto/keyring" - "github.com/ethereum/go-ethereum/common" - . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/suite" ) -type KeeperTestSuite struct { - suite.Suite - - ctx sdk.Context - app *app.ExocoreApp - address common.Address - signer keyring.Signer +type DepositTestSuite struct { + testutil.BaseTestSuite } -var s *KeeperTestSuite +var s *DepositTestSuite func TestKeeperTestSuite(t *testing.T) { - s = new(KeeperTestSuite) + s = new(DepositTestSuite) suite.Run(t, s) // Run Ginkgo integration tests @@ -34,6 +25,6 @@ func TestKeeperTestSuite(t *testing.T) { RunSpecs(t, "Keeper Suite") } -func (suite *KeeperTestSuite) SetupTest() { - suite.DoSetupTest(suite.T()) +func (suite *DepositTestSuite) SetupTest() { + suite.DoSetupTest() } diff --git a/x/deposit/keeper/utils_test.go b/x/deposit/keeper/utils_test.go deleted file mode 100644 index 8116e8070..000000000 --- a/x/deposit/keeper/utils_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package keeper_test - -import ( - "time" - - "github.com/ExocoreNetwork/exocore/app" - "github.com/ExocoreNetwork/exocore/utils" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/ethereum/go-ethereum/common" - "github.com/evmos/evmos/v14/crypto/ethsecp256k1" - "github.com/evmos/evmos/v14/testutil" - utiltx "github.com/evmos/evmos/v14/testutil/tx" - feemarkettypes "github.com/evmos/evmos/v14/x/feemarket/types" - "github.com/stretchr/testify/require" -) - -// Test helpers -func (suite *KeeperTestSuite) DoSetupTest(t require.TestingT) { - // account key - priv, err := ethsecp256k1.GenerateKey() - require.NoError(t, err) - suite.address = common.BytesToAddress(priv.PubKey().Address().Bytes()) - suite.signer = utiltx.NewSigner(priv) - - // consensus key - privCons, err := ethsecp256k1.GenerateKey() - require.NoError(t, err) - consAddress := sdk.ConsAddress(privCons.PubKey().Address()) - - chainID := utils.TestnetChainID + "-1" - suite.app = app.Setup(false, feemarkettypes.DefaultGenesisState(), chainID, false) - header := testutil.NewHeader( - 1, time.Now().UTC(), chainID, consAddress, nil, nil, - ) - suite.ctx = suite.app.BaseApp.NewContext(false, header) -} diff --git a/x/evm/types/params.go b/x/evm/types/params.go index d0419b159..0dcacfceb 100644 --- a/x/evm/types/params.go +++ b/x/evm/types/params.go @@ -1,22 +1,26 @@ package types import ( - utils "github.com/ExocoreNetwork/exocore/utils" + "github.com/ExocoreNetwork/exocore/utils" evmtype "github.com/evmos/evmos/v14/x/evm/types" ) // ExocoreAvailableEVMExtensions defines the default active precompiles -var ExocoreAvailableEVMExtensions = []string{ - "0x0000000000000000000000000000000000000800", // Staking precompile - "0x0000000000000000000000000000000000000801", // Distribution precompile - "0x0000000000000000000000000000000000000802", // ICS20 transfer precompile - "0x0000000000000000000000000000000000000803", // Vesting precompile - "0x0000000000000000000000000000000000000804", // deposit precompile - "0x0000000000000000000000000000000000000805", // delegation precompile - "0x0000000000000000000000000000000000000806", // reward precompile - "0x0000000000000000000000000000000000000807", // slash precompile - "0x0000000000000000000000000000000000000808", // withdraw precompile -} +var ( + // DefaultEVMDenom defines the default EVM denomination on Exocore + DefaultEVMDenom = utils.BaseDenom + ExocoreAvailableEVMExtensions = []string{ + "0x0000000000000000000000000000000000000800", // Staking precompile + "0x0000000000000000000000000000000000000801", // Distribution precompile + "0x0000000000000000000000000000000000000802", // ICS20 transfer precompile + "0x0000000000000000000000000000000000000803", // Vesting precompile + "0x0000000000000000000000000000000000000804", // deposit precompile + "0x0000000000000000000000000000000000000805", // delegation precompile + "0x0000000000000000000000000000000000000806", // reward precompile + "0x0000000000000000000000000000000000000807", // slash precompile + "0x0000000000000000000000000000000000000808", // withdraw precompile + } +) // ExocoreEvmDefaultParams returns default evm parameters // ExtraEIPs is empty to prevent overriding the latest hard fork instruction set @@ -24,7 +28,7 @@ var ExocoreAvailableEVMExtensions = []string{ // from the EVM configuration. func ExocoreEvmDefaultParams() evmtype.Params { return evmtype.Params{ - EvmDenom: utils.BaseDenom, + EvmDenom: DefaultEVMDenom, EnableCreate: evmtype.DefaultEnableCreate, EnableCall: evmtype.DefaultEnableCall, ChainConfig: evmtype.DefaultChainConfig(), diff --git a/x/native_token/module.go b/x/native_token/module.go index 4ad59d5b4..08a16273a 100644 --- a/x/native_token/module.go +++ b/x/native_token/module.go @@ -85,9 +85,9 @@ type IDeposit interface { PostTxProcessing(ctx sdk.Context, msg core.Message, receipt *ethtypes.Receipt) error // SetReStakerExoCoreAddr handle the SetReStakerExoCoreAddr txs from msg service - SetReStakerExoCoreAddr(ctx context.Context, reStakerId string) (err error) - GetReStakerExoCoreAddr(reStakerId string) (addr sdk.Address, err error) + SetReStakerExoCoreAddr(ctx context.Context, reStakerID string) (err error) + GetReStakerExoCoreAddr(reStakerID string) (addr sdk.Address, err error) // Deposit internal func for PostTxProcessing - Deposit(reStakerId string, assetsInfo map[string]math.Uint) error + Deposit(reStakerID string, assetsInfo map[string]math.Uint) error } diff --git a/x/native_token/types/keys.go b/x/native_token/types/keys.go index 5835491f9..bcc3947a5 100644 --- a/x/native_token/types/keys.go +++ b/x/native_token/types/keys.go @@ -28,6 +28,6 @@ const ( prefixReStakerExocoreAddr = iota + 1 ) -// KeyPrefixReStakerExoCoreAddr reStakerId = clientChainAddr+'_'+ExoCoreChainIndex -// KeyPrefixReStakerExoCoreAddr key-value: reStakerId->exoCoreAddr +// KeyPrefixReStakerExoCoreAddr reStakerID = clientChainAddr+'_'+ExoCoreChainIndex +// KeyPrefixReStakerExoCoreAddr key-value: reStakerID->exoCoreAddr var KeyPrefixReStakerExoCoreAddr = []byte{prefixReStakerExocoreAddr} diff --git a/x/restaking_assets_manage/client/cli/query.go b/x/restaking_assets_manage/client/cli/query.go index cce124677..a3d0e1a0f 100644 --- a/x/restaking_assets_manage/client/cli/query.go +++ b/x/restaking_assets_manage/client/cli/query.go @@ -190,7 +190,7 @@ func QueStakerAssetInfos() *cobra.Command { // QueStakerSpecifiedAssetAmount queries staker specified asset info func QueStakerSpecifiedAssetAmount() *cobra.Command { cmd := &cobra.Command{ - Use: "QueStakerSpecifiedAssetAmount clientChainId stakerAddr assetAddr", + Use: "QueStakerSpecifiedAssetAmount clientChainID stakerAddr assetAddr", Short: "Get staker specified asset state", Long: "Get staker specified asset state", Args: cobra.ExactArgs(3), @@ -254,7 +254,7 @@ func QueOperatorAssetInfos() *cobra.Command { // QueOperatorSpecifiedAssetAmount queries specified operator asset info func QueOperatorSpecifiedAssetAmount() *cobra.Command { cmd := &cobra.Command{ - Use: "QueOperatorSpecifiedAssetAmount operatorAddr clientChainId assetAddr", + Use: "QueOperatorSpecifiedAssetAmount operatorAddr clientChainID assetAddr", Short: "Get operator specified asset state", Long: "Get operator specified asset state", Args: cobra.ExactArgs(3), diff --git a/x/restaking_assets_manage/keeper/client_chain_and_asset_test.go b/x/restaking_assets_manage/keeper/client_chain_and_asset_test.go index a776ee0a4..83e1b2e30 100644 --- a/x/restaking_assets_manage/keeper/client_chain_and_asset_test.go +++ b/x/restaking_assets_manage/keeper/client_chain_and_asset_test.go @@ -5,29 +5,29 @@ import ( "github.com/ExocoreNetwork/exocore/x/restaking_assets_manage/types" ) -func (suite *KeeperTestSuite) TestGenesisClientChainAndAssetInfo() { +func (suite *StakingAssetsTestSuite) TestGenesisClientChainAndAssetInfo() { defaultGensisState := restaking_assets_manage.DefaultGenesisState() // test the client chains getting - clientChains, err := suite.app.StakingAssetsManageKeeper.GetAllClientChainInfo(suite.ctx) + clientChains, err := suite.App.StakingAssetsManageKeeper.GetAllClientChainInfo(suite.Ctx) suite.NoError(err) - suite.ctx.Logger().Info("the clientChains is:", "info", clientChains) + suite.Ctx.Logger().Info("the clientChains is:", "info", clientChains) for _, clientChain := range defaultGensisState.DefaultSupportedClientChains { info, ok := clientChains[clientChain.LayerZeroChainID] suite.True(ok) suite.Equal(info, clientChain) } - chainInfo, err := suite.app.StakingAssetsManageKeeper.GetClientChainInfoByIndex(suite.ctx, 101) + chainInfo, err := suite.App.StakingAssetsManageKeeper.GetClientChainInfoByIndex(suite.Ctx, 101) suite.NoError(err) suite.Equal(clientChains[101], chainInfo) // test the client chain assets getting - assets, err := suite.app.StakingAssetsManageKeeper.GetAllStakingAssetsInfo(suite.ctx) + assets, err := suite.App.StakingAssetsManageKeeper.GetAllStakingAssetsInfo(suite.Ctx) suite.NoError(err) for _, asset := range defaultGensisState.DefaultSupportedClientChainTokens { _, assetID := types.GetStakeIDAndAssetIDFromStr(asset.LayerZeroChainID, "", asset.Address) - suite.ctx.Logger().Info("the asset id is:", "assetID", assetID) + suite.Ctx.Logger().Info("the asset id is:", "assetID", assetID) info, ok := assets[assetID] suite.True(ok) suite.Equal(asset, info.AssetBasicInfo) @@ -35,7 +35,7 @@ func (suite *KeeperTestSuite) TestGenesisClientChainAndAssetInfo() { usdtAsset := defaultGensisState.DefaultSupportedClientChainTokens[0] _, assetID := types.GetStakeIDAndAssetIDFromStr(usdtAsset.LayerZeroChainID, "", usdtAsset.Address) - assetInfo, err := suite.app.StakingAssetsManageKeeper.GetStakingAssetInfo(suite.ctx, assetID) + assetInfo, err := suite.App.StakingAssetsManageKeeper.GetStakingAssetInfo(suite.Ctx, assetID) suite.NoError(err) suite.Equal(usdtAsset, assetInfo.AssetBasicInfo) } diff --git a/x/restaking_assets_manage/keeper/setup_test.go b/x/restaking_assets_manage/keeper/setup_test.go index 13bd11a79..21d80f32f 100644 --- a/x/restaking_assets_manage/keeper/setup_test.go +++ b/x/restaking_assets_manage/keeper/setup_test.go @@ -1,32 +1,23 @@ package keeper_test import ( + "github.com/ExocoreNetwork/exocore/testutil" "testing" - "github.com/ExocoreNetwork/exocore/app" - "github.com/cosmos/cosmos-sdk/crypto/keyring" - "github.com/ethereum/go-ethereum/common" - . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/suite" ) -type KeeperTestSuite struct { - suite.Suite - - ctx sdk.Context - app *app.ExocoreApp - address common.Address - signer keyring.Signer +type StakingAssetsTestSuite struct { + testutil.BaseTestSuite } -var s *KeeperTestSuite +var s *StakingAssetsTestSuite func TestKeeperTestSuite(t *testing.T) { - s = new(KeeperTestSuite) + s = new(StakingAssetsTestSuite) suite.Run(t, s) // Run Ginkgo integration tests @@ -34,6 +25,6 @@ func TestKeeperTestSuite(t *testing.T) { RunSpecs(t, "Keeper Suite") } -func (suite *KeeperTestSuite) SetupTest() { - suite.DoSetupTest(suite.T()) +func (suite *StakingAssetsTestSuite) SetupTest() { + suite.DoSetupTest() } diff --git a/x/restaking_assets_manage/keeper/staker_asset_test.go b/x/restaking_assets_manage/keeper/staker_asset_test.go index 9d8232c32..563166d72 100644 --- a/x/restaking_assets_manage/keeper/staker_asset_test.go +++ b/x/restaking_assets_manage/keeper/staker_asset_test.go @@ -8,20 +8,20 @@ import ( restakingtype "github.com/ExocoreNetwork/exocore/x/restaking_assets_manage/types" ) -func (suite *KeeperTestSuite) TestUpdateStakerAssetsState() { - stakerID := fmt.Sprintf("%s_%s", suite.address, "0") - ethUniAssetId := fmt.Sprintf("%s_%s", "0x1f9840a85d5af5bf1d1762f925bdaddc4201f984", "101") +func (suite *StakingAssetsTestSuite) TestUpdateStakerAssetsState() { + stakerID := fmt.Sprintf("%s_%s", suite.Address, "0") + ethUniAssetID := fmt.Sprintf("%s_%s", "0x1f9840a85d5af5bf1d1762f925bdaddc4201f984", "101") ethUniInitialChangeValue := restakingtype.StakerSingleAssetOrChangeInfo{ TotalDepositAmountOrWantChangeValue: math.NewInt(1000), CanWithdrawAmountOrWantChangeValue: math.NewInt(1000), } // test the initial storage of statker assets state - err := suite.app.StakingAssetsManageKeeper.UpdateStakerAssetState(suite.ctx, stakerID, ethUniAssetId, ethUniInitialChangeValue) + err := suite.App.StakingAssetsManageKeeper.UpdateStakerAssetState(suite.Ctx, stakerID, ethUniAssetID, ethUniInitialChangeValue) suite.Require().NoError(err) // test that the retrieved value is correct - getInfo, err := suite.app.StakingAssetsManageKeeper.GetStakerSpecifiedAssetInfo(suite.ctx, stakerID, ethUniAssetId) + getInfo, err := suite.App.StakingAssetsManageKeeper.GetStakerSpecifiedAssetInfo(suite.Ctx, stakerID, ethUniAssetID) suite.Require().NoError(err) suite.Require().True(ethUniInitialChangeValue.TotalDepositAmountOrWantChangeValue.Equal(getInfo.TotalDepositAmountOrWantChangeValue)) suite.Require().True(ethUniInitialChangeValue.CanWithdrawAmountOrWantChangeValue.Equal(getInfo.CanWithdrawAmountOrWantChangeValue)) @@ -29,16 +29,16 @@ func (suite *KeeperTestSuite) TestUpdateStakerAssetsState() { // test ErrInputUpdateStateIsZero /* ethUniInitialChangeValue.TotalDepositAmountOrWantChangeValue = math.NewInt(0) ethUniInitialChangeValue.CanWithdrawAmountOrWantChangeValue = math.NewInt(0) - err = suite.app.StakingAssetsManageKeeper.UpdateStakerAssetState(suite.ctx, stakerID, ethUniAssetId, ethUniInitialChangeValue) - suite.Require().Error(err, types2.ErrInputUpdateStateIsZero)*/ + err = suite.App.StakingAssetsManageKeeper.UpdateStakerAssetState(suite.Ctx, stakerID, ethUniAssetID, ethUniInitialChangeValue) + suite.Require().Error(err, restakingtype.ErrInputUpdateStateIsZero)*/ // test valid increase of staker asset state ethUniInitialChangeValue.TotalDepositAmountOrWantChangeValue = math.NewInt(500) ethUniInitialChangeValue.CanWithdrawAmountOrWantChangeValue = math.NewInt(500) - err = suite.app.StakingAssetsManageKeeper.UpdateStakerAssetState(suite.ctx, stakerID, ethUniAssetId, ethUniInitialChangeValue) + err = suite.App.StakingAssetsManageKeeper.UpdateStakerAssetState(suite.Ctx, stakerID, ethUniAssetID, ethUniInitialChangeValue) suite.Require().NoError(err) - getInfo, err = suite.app.StakingAssetsManageKeeper.GetStakerSpecifiedAssetInfo(suite.ctx, stakerID, ethUniAssetId) + getInfo, err = suite.App.StakingAssetsManageKeeper.GetStakerSpecifiedAssetInfo(suite.Ctx, stakerID, ethUniAssetID) suite.Require().NoError(err) suite.Require().True(getInfo.TotalDepositAmountOrWantChangeValue.Equal(math.NewInt(1500))) suite.Require().True(getInfo.CanWithdrawAmountOrWantChangeValue.Equal(math.NewInt(1500))) @@ -46,9 +46,9 @@ func (suite *KeeperTestSuite) TestUpdateStakerAssetsState() { // test valid decrease of staker asset state ethUniInitialChangeValue.TotalDepositAmountOrWantChangeValue = math.NewInt(-500) ethUniInitialChangeValue.CanWithdrawAmountOrWantChangeValue = math.NewInt(-500) - err = suite.app.StakingAssetsManageKeeper.UpdateStakerAssetState(suite.ctx, stakerID, ethUniAssetId, ethUniInitialChangeValue) + err = suite.App.StakingAssetsManageKeeper.UpdateStakerAssetState(suite.Ctx, stakerID, ethUniAssetID, ethUniInitialChangeValue) suite.Require().NoError(err) - getInfo, err = suite.app.StakingAssetsManageKeeper.GetStakerSpecifiedAssetInfo(suite.ctx, stakerID, ethUniAssetId) + getInfo, err = suite.App.StakingAssetsManageKeeper.GetStakerSpecifiedAssetInfo(suite.Ctx, stakerID, ethUniAssetID) suite.Require().NoError(err) suite.Require().True(getInfo.TotalDepositAmountOrWantChangeValue.Equal(math.NewInt(1000))) suite.Require().True(getInfo.CanWithdrawAmountOrWantChangeValue.Equal(math.NewInt(1000))) @@ -56,40 +56,40 @@ func (suite *KeeperTestSuite) TestUpdateStakerAssetsState() { // test the decreased amount is bigger than original state ethUniInitialChangeValue.TotalDepositAmountOrWantChangeValue = math.NewInt(-2000) ethUniInitialChangeValue.CanWithdrawAmountOrWantChangeValue = math.NewInt(-500) - err = suite.app.StakingAssetsManageKeeper.UpdateStakerAssetState(suite.ctx, stakerID, ethUniAssetId, ethUniInitialChangeValue) + err = suite.App.StakingAssetsManageKeeper.UpdateStakerAssetState(suite.Ctx, stakerID, ethUniAssetID, ethUniInitialChangeValue) suite.Require().Error(err, restakingtype.ErrSubAmountIsMoreThanOrigin) - getInfo, err = suite.app.StakingAssetsManageKeeper.GetStakerSpecifiedAssetInfo(suite.ctx, stakerID, ethUniAssetId) + getInfo, err = suite.App.StakingAssetsManageKeeper.GetStakerSpecifiedAssetInfo(suite.Ctx, stakerID, ethUniAssetID) suite.Require().NoError(err) suite.Require().True(getInfo.TotalDepositAmountOrWantChangeValue.Equal(math.NewInt(1000))) suite.Require().True(getInfo.CanWithdrawAmountOrWantChangeValue.Equal(math.NewInt(1000))) ethUniInitialChangeValue.TotalDepositAmountOrWantChangeValue = math.NewInt(-500) ethUniInitialChangeValue.CanWithdrawAmountOrWantChangeValue = math.NewInt(-2000) - err = suite.app.StakingAssetsManageKeeper.UpdateStakerAssetState(suite.ctx, stakerID, ethUniAssetId, ethUniInitialChangeValue) + err = suite.App.StakingAssetsManageKeeper.UpdateStakerAssetState(suite.Ctx, stakerID, ethUniAssetID, ethUniInitialChangeValue) suite.Require().Error(err, restakingtype.ErrSubAmountIsMoreThanOrigin) - getInfo, err = suite.app.StakingAssetsManageKeeper.GetStakerSpecifiedAssetInfo(suite.ctx, stakerID, ethUniAssetId) + getInfo, err = suite.App.StakingAssetsManageKeeper.GetStakerSpecifiedAssetInfo(suite.Ctx, stakerID, ethUniAssetID) suite.Require().NoError(err) suite.Require().True(getInfo.TotalDepositAmountOrWantChangeValue.Equal(math.NewInt(1000))) suite.Require().True(getInfo.CanWithdrawAmountOrWantChangeValue.Equal(math.NewInt(1000))) // test the storage of multiple assets state - ethUsdtAssetId := fmt.Sprintf("%s_%s", "0xdac17f958d2ee523a2206206994597c13d831ec7", "101") + ethUsdtAssetID := fmt.Sprintf("%s_%s", "0xdac17f958d2ee523a2206206994597c13d831ec7", "101") ethUsdtInitialChangeValue := restakingtype.StakerSingleAssetOrChangeInfo{ TotalDepositAmountOrWantChangeValue: math.NewInt(2000), CanWithdrawAmountOrWantChangeValue: math.NewInt(2000), } - err = suite.app.StakingAssetsManageKeeper.UpdateStakerAssetState(suite.ctx, stakerID, ethUsdtAssetId, ethUsdtInitialChangeValue) + err = suite.App.StakingAssetsManageKeeper.UpdateStakerAssetState(suite.Ctx, stakerID, ethUsdtAssetID, ethUsdtInitialChangeValue) suite.Require().NoError(err) - getInfo, err = suite.app.StakingAssetsManageKeeper.GetStakerSpecifiedAssetInfo(suite.ctx, stakerID, ethUsdtAssetId) + getInfo, err = suite.App.StakingAssetsManageKeeper.GetStakerSpecifiedAssetInfo(suite.Ctx, stakerID, ethUsdtAssetID) suite.Require().NoError(err) suite.Require().True(getInfo.TotalDepositAmountOrWantChangeValue.Equal(math.NewInt(2000))) suite.Require().True(getInfo.CanWithdrawAmountOrWantChangeValue.Equal(math.NewInt(2000))) } -func (suite *KeeperTestSuite) TestGetStakerAssetInfos() { - stakerID := fmt.Sprintf("%s_%s", suite.address, "0") - ethUniAssetId := fmt.Sprintf("%s_%s", "0x1f9840a85d5af5bf1d1762f925bdaddc4201f984", "101") - ethUsdtAssetId := fmt.Sprintf("%s_%s", "0xdac17f958d2ee523a2206206994597c13d831ec7", "101") +func (suite *StakingAssetsTestSuite) TestGetStakerAssetInfos() { + stakerID := fmt.Sprintf("%s_%s", suite.Address, "0") + ethUniAssetID := fmt.Sprintf("%s_%s", "0x1f9840a85d5af5bf1d1762f925bdaddc4201f984", "101") + ethUsdtAssetID := fmt.Sprintf("%s_%s", "0xdac17f958d2ee523a2206206994597c13d831ec7", "101") ethUniInitialChangeValue := restakingtype.StakerSingleAssetOrChangeInfo{ TotalDepositAmountOrWantChangeValue: math.NewInt(1000), CanWithdrawAmountOrWantChangeValue: math.NewInt(1000), @@ -98,20 +98,20 @@ func (suite *KeeperTestSuite) TestGetStakerAssetInfos() { TotalDepositAmountOrWantChangeValue: math.NewInt(2000), CanWithdrawAmountOrWantChangeValue: math.NewInt(2000), } - err := suite.app.StakingAssetsManageKeeper.UpdateStakerAssetState(suite.ctx, stakerID, ethUniAssetId, ethUniInitialChangeValue) + err := suite.App.StakingAssetsManageKeeper.UpdateStakerAssetState(suite.Ctx, stakerID, ethUniAssetID, ethUniInitialChangeValue) suite.Require().NoError(err) - err = suite.app.StakingAssetsManageKeeper.UpdateStakerAssetState(suite.ctx, stakerID, ethUsdtAssetId, ethUsdtInitialChangeValue) + err = suite.App.StakingAssetsManageKeeper.UpdateStakerAssetState(suite.Ctx, stakerID, ethUsdtAssetID, ethUsdtInitialChangeValue) suite.Require().NoError(err) // test get all assets state of staker - assetsInfo, err := suite.app.StakingAssetsManageKeeper.GetStakerAssetInfos(suite.ctx, stakerID) + assetsInfo, err := suite.App.StakingAssetsManageKeeper.GetStakerAssetInfos(suite.Ctx, stakerID) suite.Require().NoError(err) - uniState, isExist := assetsInfo[ethUniAssetId] + uniState, isExist := assetsInfo[ethUniAssetID] suite.Require().True(isExist) suite.Require().True(uniState.TotalDepositAmountOrWantChangeValue.Equal(math.NewInt(1000))) suite.Require().True(uniState.CanWithdrawAmountOrWantChangeValue.Equal(math.NewInt(1000))) - usdtState, isExist := assetsInfo[ethUsdtAssetId] + usdtState, isExist := assetsInfo[ethUsdtAssetID] suite.Require().True(isExist) suite.Require().True(usdtState.TotalDepositAmountOrWantChangeValue.Equal(math.NewInt(2000))) suite.Require().True(usdtState.CanWithdrawAmountOrWantChangeValue.Equal(math.NewInt(2000))) diff --git a/x/restaking_assets_manage/keeper/utils_test.go b/x/restaking_assets_manage/keeper/utils_test.go deleted file mode 100644 index 8116e8070..000000000 --- a/x/restaking_assets_manage/keeper/utils_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package keeper_test - -import ( - "time" - - "github.com/ExocoreNetwork/exocore/app" - "github.com/ExocoreNetwork/exocore/utils" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/ethereum/go-ethereum/common" - "github.com/evmos/evmos/v14/crypto/ethsecp256k1" - "github.com/evmos/evmos/v14/testutil" - utiltx "github.com/evmos/evmos/v14/testutil/tx" - feemarkettypes "github.com/evmos/evmos/v14/x/feemarket/types" - "github.com/stretchr/testify/require" -) - -// Test helpers -func (suite *KeeperTestSuite) DoSetupTest(t require.TestingT) { - // account key - priv, err := ethsecp256k1.GenerateKey() - require.NoError(t, err) - suite.address = common.BytesToAddress(priv.PubKey().Address().Bytes()) - suite.signer = utiltx.NewSigner(priv) - - // consensus key - privCons, err := ethsecp256k1.GenerateKey() - require.NoError(t, err) - consAddress := sdk.ConsAddress(privCons.PubKey().Address()) - - chainID := utils.TestnetChainID + "-1" - suite.app = app.Setup(false, feemarkettypes.DefaultGenesisState(), chainID, false) - header := testutil.NewHeader( - 1, time.Now().UTC(), chainID, consAddress, nil, nil, - ) - suite.ctx = suite.app.BaseApp.NewContext(false, header) -} diff --git a/x/restaking_assets_manage/types/general.go b/x/restaking_assets_manage/types/general.go index 75f92a609..1d2e39dd2 100644 --- a/x/restaking_assets_manage/types/general.go +++ b/x/restaking_assets_manage/types/general.go @@ -15,7 +15,7 @@ const ( ClientChainLzIDIndexInTopics = 0 LzNonceIndexInTopics = 2 - ExoCoreOperatorAddrLength = 44 + ExoCoreOperatorAddrLength = 42 ) type GeneralAssetsAddr [32]byte diff --git a/x/reward/keeper/claim_reward_test.go b/x/reward/keeper/claim_reward_test.go index d2caf5818..c2bda596b 100644 --- a/x/reward/keeper/claim_reward_test.go +++ b/x/reward/keeper/claim_reward_test.go @@ -8,29 +8,29 @@ import ( "github.com/ethereum/go-ethereum/common" ) -func (suite *KeeperTestSuite) TestClaimWithdrawRequest() { +func (suite *RewardTestSuite) TestClaimWithdrawRequest() { usdtAddress := common.HexToAddress("0xdAC17F958D2ee523a2206206994597C13D831ec7") usdcAddress := common.HexToAddress("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48") event := &keeper.RewardParams{ ClientChainLzID: 101, Action: types.WithDrawReward, - WithdrawRewardAddress: suite.address[:], + WithdrawRewardAddress: suite.Address[:], OpAmount: sdkmath.NewInt(10), } // test the case that the deposit asset hasn't registered event.AssetsAddress = usdcAddress[:] - err := suite.app.RewardKeeper.RewardForWithdraw(suite.ctx, event) + err := suite.App.RewardKeeper.RewardForWithdraw(suite.Ctx, event) suite.ErrorContains(err, rewardtype.ErrRewardAssetNotExist.Error()) // test the normal case event.AssetsAddress = usdtAddress[:] - err = suite.app.RewardKeeper.RewardForWithdraw(suite.ctx, event) + err = suite.App.RewardKeeper.RewardForWithdraw(suite.Ctx, event) suite.NoError(err) // check state after reward stakerID, assetID := types.GetStakeIDAndAssetID(event.ClientChainLzID, event.WithdrawRewardAddress, event.AssetsAddress) - info, err := suite.app.StakingAssetsManageKeeper.GetStakerSpecifiedAssetInfo(suite.ctx, stakerID, assetID) + info, err := suite.App.StakingAssetsManageKeeper.GetStakerSpecifiedAssetInfo(suite.Ctx, stakerID, assetID) suite.NoError(err) suite.Equal(types.StakerSingleAssetOrChangeInfo{ TotalDepositAmountOrWantChangeValue: sdkmath.NewInt(10), @@ -38,7 +38,7 @@ func (suite *KeeperTestSuite) TestClaimWithdrawRequest() { WaitUndelegationAmountOrWantChangeValue: sdkmath.NewInt(0), }, *info) - assetInfo, err := suite.app.StakingAssetsManageKeeper.GetStakingAssetInfo(suite.ctx, assetID) + assetInfo, err := suite.App.StakingAssetsManageKeeper.GetStakingAssetInfo(suite.Ctx, assetID) suite.NoError(err) suite.Equal(sdkmath.NewInt(10), assetInfo.StakingTotalAmount) } diff --git a/x/reward/keeper/params_test.go b/x/reward/keeper/params_test.go index 5de13d449..3dfa1fd9e 100644 --- a/x/reward/keeper/params_test.go +++ b/x/reward/keeper/params_test.go @@ -4,15 +4,15 @@ import ( rewardtype "github.com/ExocoreNetwork/exocore/x/reward/types" ) -func (suite *KeeperTestSuite) TestParams() { +func (suite *RewardTestSuite) TestParams() { params := &rewardtype.Params{ ExoCoreLzAppAddress: "0x3fC91A3afd70395Cd496C647d5a6CC9D4B2b7FAD", ExoCoreLzAppEventTopic: "0xc6a377bfc4eb120024a8ac08eef205be16b817020812c73223e81d1bdb9708ec", } - err := suite.app.RewardKeeper.SetParams(suite.ctx, params) + err := suite.App.RewardKeeper.SetParams(suite.Ctx, params) suite.NoError(err) - getParams, err := suite.app.RewardKeeper.GetParams(suite.ctx) + getParams, err := suite.App.RewardKeeper.GetParams(suite.Ctx) suite.NoError(err) suite.Equal(*params, *getParams) } diff --git a/x/reward/keeper/setup_test.go b/x/reward/keeper/setup_test.go index f8d0365c3..1927a5b17 100644 --- a/x/reward/keeper/setup_test.go +++ b/x/reward/keeper/setup_test.go @@ -1,6 +1,7 @@ package keeper_test import ( + "github.com/ExocoreNetwork/exocore/testutil" "testing" //nolint:revive // dot imports are fine for Ginkgo @@ -8,27 +9,17 @@ import ( //nolint:revive // dot imports are fine for Ginkgo . "github.com/onsi/gomega" - "github.com/ExocoreNetwork/exocore/app" - "github.com/cosmos/cosmos-sdk/crypto/keyring" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/suite" ) -type KeeperTestSuite struct { - suite.Suite - - ctx sdk.Context - app *app.ExocoreApp - address common.Address - - signer keyring.Signer +type RewardTestSuite struct { + testutil.BaseTestSuite } -var s *KeeperTestSuite +var s *RewardTestSuite func TestKeeperTestSuite(t *testing.T) { - s = new(KeeperTestSuite) + s = new(RewardTestSuite) suite.Run(t, s) // Run Ginkgo integration tests @@ -37,6 +28,6 @@ func TestKeeperTestSuite(t *testing.T) { } // SetupTest setup test environment, it uses`require.TestingT` to support both `testing.T` and `testing.B`. -func (suite *KeeperTestSuite) SetupTest() { - suite.DoSetupTest(suite.T()) +func (suite *RewardTestSuite) SetupTest() { + suite.DoSetupTest() } diff --git a/x/reward/keeper/utils_test.go b/x/reward/keeper/utils_test.go deleted file mode 100644 index 8dcb23033..000000000 --- a/x/reward/keeper/utils_test.go +++ /dev/null @@ -1,34 +0,0 @@ -package keeper_test - -import ( - "time" - - "github.com/ExocoreNetwork/exocore/app" - "github.com/ExocoreNetwork/exocore/utils" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/ethereum/go-ethereum/common" - "github.com/evmos/evmos/v14/crypto/ethsecp256k1" - "github.com/evmos/evmos/v14/testutil" - utiltx "github.com/evmos/evmos/v14/testutil/tx" - "github.com/stretchr/testify/require" -) - -func (suite *KeeperTestSuite) DoSetupTest(t require.TestingT) { - // account key - priv, err := ethsecp256k1.GenerateKey() - require.NoError(t, err) - suite.address = common.BytesToAddress(priv.PubKey().Address().Bytes()) - suite.signer = utiltx.NewSigner(priv) - - // consensus key - privCons, err := ethsecp256k1.GenerateKey() - require.NoError(t, err) - consAddress := sdk.ConsAddress(privCons.PubKey().Address()) - - chainID := utils.TestnetChainID + "-1" - suite.app = app.Setup(false, nil, chainID, false) - header := testutil.NewHeader( - 1, time.Now().UTC(), chainID, consAddress, nil, nil, - ) - suite.ctx = suite.app.BaseApp.NewContext(false, header) -} diff --git a/x/slash/keeper/execute_slash_test.go b/x/slash/keeper/execute_slash_test.go index 0986a2ac7..a222f02b0 100644 --- a/x/slash/keeper/execute_slash_test.go +++ b/x/slash/keeper/execute_slash_test.go @@ -9,39 +9,39 @@ import ( "github.com/ethereum/go-ethereum/common" ) -func (suite *KeeperTestSuite) TestSlash() { +func (suite *SlashTestSuite) TestSlash() { usdtAddress := common.HexToAddress("0xdAC17F958D2ee523a2206206994597C13D831ec7") usdcAddress := common.HexToAddress("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48") event := &keeper.SlashParams{ ClientChainLzID: 101, Action: types.Slash, - StakerAddress: suite.address[:], + StakerAddress: suite.Address[:], OpAmount: sdkmath.NewInt(90), } depositEvent := &depositKeeper.DepositParams{ ClientChainLzID: 101, Action: types.Deposit, - StakerAddress: suite.address[:], + StakerAddress: suite.Address[:], OpAmount: sdkmath.NewInt(100), } // deposit firstly depositEvent.AssetsAddress = usdtAddress[:] - err := suite.app.DepositKeeper.Deposit(suite.ctx, depositEvent) + err := suite.App.DepositKeeper.Deposit(suite.Ctx, depositEvent) suite.NoError(err) // test the case that the slash hasn't registered event.AssetsAddress = usdcAddress[:] - err = suite.app.ExoSlashKeeper.Slash(suite.ctx, event) + err = suite.App.ExoSlashKeeper.Slash(suite.Ctx, event) suite.ErrorContains(err, slashtype.ErrSlashAssetNotExist.Error()) - assets, err := suite.app.StakingAssetsManageKeeper.GetAllStakingAssetsInfo(suite.ctx) + assets, err := suite.App.StakingAssetsManageKeeper.GetAllStakingAssetsInfo(suite.Ctx) suite.NoError(err) - suite.app.Logger().Info("the assets is:", "assets", assets) + suite.App.Logger().Info("the assets is:", "assets", assets) stakerID, assetID := types.GetStakeIDAndAssetID(depositEvent.ClientChainLzID, depositEvent.StakerAddress, depositEvent.AssetsAddress) - info, err := suite.app.StakingAssetsManageKeeper.GetStakerSpecifiedAssetInfo(suite.ctx, stakerID, assetID) + info, err := suite.App.StakingAssetsManageKeeper.GetStakerSpecifiedAssetInfo(suite.Ctx, stakerID, assetID) suite.NoError(err) suite.Equal(types.StakerSingleAssetOrChangeInfo{ TotalDepositAmountOrWantChangeValue: depositEvent.OpAmount, @@ -51,12 +51,12 @@ func (suite *KeeperTestSuite) TestSlash() { // test the normal case event.AssetsAddress = usdtAddress[:] - err = suite.app.ExoSlashKeeper.Slash(suite.ctx, event) + err = suite.App.ExoSlashKeeper.Slash(suite.Ctx, event) suite.NoError(err) // check state after slash stakerID, assetID = types.GetStakeIDAndAssetID(event.ClientChainLzID, event.StakerAddress, event.AssetsAddress) - info, err = suite.app.StakingAssetsManageKeeper.GetStakerSpecifiedAssetInfo(suite.ctx, stakerID, assetID) + info, err = suite.App.StakingAssetsManageKeeper.GetStakerSpecifiedAssetInfo(suite.Ctx, stakerID, assetID) suite.NoError(err) suite.Equal(types.StakerSingleAssetOrChangeInfo{ TotalDepositAmountOrWantChangeValue: sdkmath.NewInt(10), @@ -64,7 +64,7 @@ func (suite *KeeperTestSuite) TestSlash() { WaitUndelegationAmountOrWantChangeValue: sdkmath.NewInt(0), }, *info) - assetInfo, err := suite.app.StakingAssetsManageKeeper.GetStakingAssetInfo(suite.ctx, assetID) + assetInfo, err := suite.App.StakingAssetsManageKeeper.GetStakingAssetInfo(suite.Ctx, assetID) suite.NoError(err) suite.Equal(sdkmath.NewInt(10), assetInfo.StakingTotalAmount) } diff --git a/x/slash/keeper/params_test.go b/x/slash/keeper/params_test.go index c89f832aa..4d4342717 100644 --- a/x/slash/keeper/params_test.go +++ b/x/slash/keeper/params_test.go @@ -4,15 +4,15 @@ import ( slashtype "github.com/ExocoreNetwork/exocore/x/slash/types" ) -func (suite *KeeperTestSuite) TestParams() { +func (suite *SlashTestSuite) TestParams() { params := &slashtype.Params{ ExoCoreLzAppAddress: "0x3fC91A3afd70395Cd496C647d5a6CC9D4B2b7FAD", ExoCoreLzAppEventTopic: "0xc6a377bfc4eb120024a8ac08eef205be16b817020812c73223e81d1bdb9708ec", } - err := suite.app.ExoSlashKeeper.SetParams(suite.ctx, params) + err := suite.App.ExoSlashKeeper.SetParams(suite.Ctx, params) suite.NoError(err) - getParams, err := suite.app.ExoSlashKeeper.GetParams(suite.ctx) + getParams, err := suite.App.ExoSlashKeeper.GetParams(suite.Ctx) suite.NoError(err) suite.Equal(*params, *getParams) } diff --git a/x/slash/keeper/setup_test.go b/x/slash/keeper/setup_test.go index f8d0365c3..cf45470b0 100644 --- a/x/slash/keeper/setup_test.go +++ b/x/slash/keeper/setup_test.go @@ -1,6 +1,7 @@ package keeper_test import ( + "github.com/ExocoreNetwork/exocore/testutil" "testing" //nolint:revive // dot imports are fine for Ginkgo @@ -8,27 +9,17 @@ import ( //nolint:revive // dot imports are fine for Ginkgo . "github.com/onsi/gomega" - "github.com/ExocoreNetwork/exocore/app" - "github.com/cosmos/cosmos-sdk/crypto/keyring" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/suite" ) -type KeeperTestSuite struct { - suite.Suite - - ctx sdk.Context - app *app.ExocoreApp - address common.Address - - signer keyring.Signer +type SlashTestSuite struct { + testutil.BaseTestSuite } -var s *KeeperTestSuite +var s *SlashTestSuite func TestKeeperTestSuite(t *testing.T) { - s = new(KeeperTestSuite) + s = new(SlashTestSuite) suite.Run(t, s) // Run Ginkgo integration tests @@ -37,6 +28,6 @@ func TestKeeperTestSuite(t *testing.T) { } // SetupTest setup test environment, it uses`require.TestingT` to support both `testing.T` and `testing.B`. -func (suite *KeeperTestSuite) SetupTest() { - suite.DoSetupTest(suite.T()) +func (suite *SlashTestSuite) SetupTest() { + suite.DoSetupTest() } diff --git a/x/slash/keeper/utils_test.go b/x/slash/keeper/utils_test.go deleted file mode 100644 index 8dcb23033..000000000 --- a/x/slash/keeper/utils_test.go +++ /dev/null @@ -1,34 +0,0 @@ -package keeper_test - -import ( - "time" - - "github.com/ExocoreNetwork/exocore/app" - "github.com/ExocoreNetwork/exocore/utils" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/ethereum/go-ethereum/common" - "github.com/evmos/evmos/v14/crypto/ethsecp256k1" - "github.com/evmos/evmos/v14/testutil" - utiltx "github.com/evmos/evmos/v14/testutil/tx" - "github.com/stretchr/testify/require" -) - -func (suite *KeeperTestSuite) DoSetupTest(t require.TestingT) { - // account key - priv, err := ethsecp256k1.GenerateKey() - require.NoError(t, err) - suite.address = common.BytesToAddress(priv.PubKey().Address().Bytes()) - suite.signer = utiltx.NewSigner(priv) - - // consensus key - privCons, err := ethsecp256k1.GenerateKey() - require.NoError(t, err) - consAddress := sdk.ConsAddress(privCons.PubKey().Address()) - - chainID := utils.TestnetChainID + "-1" - suite.app = app.Setup(false, nil, chainID, false) - header := testutil.NewHeader( - 1, time.Now().UTC(), chainID, consAddress, nil, nil, - ) - suite.ctx = suite.app.BaseApp.NewContext(false, header) -} diff --git a/x/withdraw/client/cli/query.go b/x/withdraw/client/cli/query.go index 229a8827e..523254dd8 100644 --- a/x/withdraw/client/cli/query.go +++ b/x/withdraw/client/cli/query.go @@ -2,7 +2,6 @@ package cli import ( "fmt" - // "strings" "github.com/spf13/cobra" diff --git a/x/withdraw/client/cli/tx.go b/x/withdraw/client/cli/tx.go index cca9df077..ac1e77b6a 100644 --- a/x/withdraw/client/cli/tx.go +++ b/x/withdraw/client/cli/tx.go @@ -2,6 +2,7 @@ package cli import ( "fmt" + "github.com/ExocoreNetwork/exocore/x/withdraw/types" "github.com/spf13/cobra" diff --git a/x/withdraw/keeper/claim_withdraw_test.go b/x/withdraw/keeper/claim_withdraw_test.go index d1457d887..f40e3a31c 100644 --- a/x/withdraw/keeper/claim_withdraw_test.go +++ b/x/withdraw/keeper/claim_withdraw_test.go @@ -9,39 +9,39 @@ import ( "github.com/ethereum/go-ethereum/common" ) -func (suite *KeeperTestSuite) TestClaimWithdrawRequest() { +func (suite *WithdrawTestSuite) TestClaimWithdrawRequest() { usdtAddress := common.HexToAddress("0xdAC17F958D2ee523a2206206994597C13D831ec7") usdcAddress := common.HexToAddress("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48") event := &keeper.WithdrawParams{ ClientChainLzID: 101, Action: types.WithdrawPrinciple, - WithdrawAddress: suite.address[:], + WithdrawAddress: suite.Address[:], OpAmount: sdkmath.NewInt(90), } depositEvent := &depositKeeper.DepositParams{ ClientChainLzID: 101, Action: types.Deposit, - StakerAddress: suite.address[:], + StakerAddress: suite.Address[:], OpAmount: sdkmath.NewInt(100), } // deposit firstly depositEvent.AssetsAddress = usdtAddress[:] - err := suite.app.DepositKeeper.Deposit(suite.ctx, depositEvent) + err := suite.App.DepositKeeper.Deposit(suite.Ctx, depositEvent) suite.NoError(err) // test the case that the withdraw asset hasn't registered event.AssetsAddress = usdcAddress[:] - err = suite.app.WithdrawKeeper.Withdraw(suite.ctx, event) + err = suite.App.WithdrawKeeper.Withdraw(suite.Ctx, event) suite.ErrorContains(err, withdrawtype.ErrWithdrawAssetNotExist.Error()) - assets, err := suite.app.StakingAssetsManageKeeper.GetAllStakingAssetsInfo(suite.ctx) + assets, err := suite.App.StakingAssetsManageKeeper.GetAllStakingAssetsInfo(suite.Ctx) suite.NoError(err) - suite.app.Logger().Info("the assets is:", "assets", assets) + suite.App.Logger().Info("the assets is:", "assets", assets) stakerID, assetID := types.GetStakeIDAndAssetID(depositEvent.ClientChainLzID, depositEvent.StakerAddress, depositEvent.AssetsAddress) - info, err := suite.app.StakingAssetsManageKeeper.GetStakerSpecifiedAssetInfo(suite.ctx, stakerID, assetID) + info, err := suite.App.StakingAssetsManageKeeper.GetStakerSpecifiedAssetInfo(suite.Ctx, stakerID, assetID) suite.NoError(err) suite.Equal(types.StakerSingleAssetOrChangeInfo{ TotalDepositAmountOrWantChangeValue: depositEvent.OpAmount, @@ -50,12 +50,12 @@ func (suite *KeeperTestSuite) TestClaimWithdrawRequest() { }, *info) // test the normal case event.AssetsAddress = usdtAddress[:] - err = suite.app.WithdrawKeeper.Withdraw(suite.ctx, event) + err = suite.App.WithdrawKeeper.Withdraw(suite.Ctx, event) suite.NoError(err) // check state after withdraw stakerID, assetID = types.GetStakeIDAndAssetID(event.ClientChainLzID, event.WithdrawAddress, event.AssetsAddress) - info, err = suite.app.StakingAssetsManageKeeper.GetStakerSpecifiedAssetInfo(suite.ctx, stakerID, assetID) + info, err = suite.App.StakingAssetsManageKeeper.GetStakerSpecifiedAssetInfo(suite.Ctx, stakerID, assetID) suite.NoError(err) suite.Equal(types.StakerSingleAssetOrChangeInfo{ TotalDepositAmountOrWantChangeValue: sdkmath.NewInt(10), @@ -63,7 +63,7 @@ func (suite *KeeperTestSuite) TestClaimWithdrawRequest() { WaitUndelegationAmountOrWantChangeValue: sdkmath.NewInt(0), }, *info) - assetInfo, err := suite.app.StakingAssetsManageKeeper.GetStakingAssetInfo(suite.ctx, assetID) + assetInfo, err := suite.App.StakingAssetsManageKeeper.GetStakingAssetInfo(suite.Ctx, assetID) suite.NoError(err) suite.Equal(sdkmath.NewInt(10), assetInfo.StakingTotalAmount) } diff --git a/x/withdraw/keeper/setup_test.go b/x/withdraw/keeper/setup_test.go index f8d0365c3..9dd0c641a 100644 --- a/x/withdraw/keeper/setup_test.go +++ b/x/withdraw/keeper/setup_test.go @@ -1,34 +1,24 @@ package keeper_test import ( + "github.com/ExocoreNetwork/exocore/testutil" "testing" //nolint:revive // dot imports are fine for Ginkgo . "github.com/onsi/ginkgo/v2" //nolint:revive // dot imports are fine for Ginkgo . "github.com/onsi/gomega" - - "github.com/ExocoreNetwork/exocore/app" - "github.com/cosmos/cosmos-sdk/crypto/keyring" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/suite" ) -type KeeperTestSuite struct { - suite.Suite - - ctx sdk.Context - app *app.ExocoreApp - address common.Address - - signer keyring.Signer +type WithdrawTestSuite struct { + testutil.BaseTestSuite } -var s *KeeperTestSuite +var s *WithdrawTestSuite func TestKeeperTestSuite(t *testing.T) { - s = new(KeeperTestSuite) + s = new(WithdrawTestSuite) suite.Run(t, s) // Run Ginkgo integration tests @@ -37,6 +27,6 @@ func TestKeeperTestSuite(t *testing.T) { } // SetupTest setup test environment, it uses`require.TestingT` to support both `testing.T` and `testing.B`. -func (suite *KeeperTestSuite) SetupTest() { - suite.DoSetupTest(suite.T()) +func (suite *WithdrawTestSuite) SetupTest() { + suite.DoSetupTest() } diff --git a/x/withdraw/keeper/utils_test.go b/x/withdraw/keeper/utils_test.go deleted file mode 100644 index 8dcb23033..000000000 --- a/x/withdraw/keeper/utils_test.go +++ /dev/null @@ -1,34 +0,0 @@ -package keeper_test - -import ( - "time" - - "github.com/ExocoreNetwork/exocore/app" - "github.com/ExocoreNetwork/exocore/utils" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/ethereum/go-ethereum/common" - "github.com/evmos/evmos/v14/crypto/ethsecp256k1" - "github.com/evmos/evmos/v14/testutil" - utiltx "github.com/evmos/evmos/v14/testutil/tx" - "github.com/stretchr/testify/require" -) - -func (suite *KeeperTestSuite) DoSetupTest(t require.TestingT) { - // account key - priv, err := ethsecp256k1.GenerateKey() - require.NoError(t, err) - suite.address = common.BytesToAddress(priv.PubKey().Address().Bytes()) - suite.signer = utiltx.NewSigner(priv) - - // consensus key - privCons, err := ethsecp256k1.GenerateKey() - require.NoError(t, err) - consAddress := sdk.ConsAddress(privCons.PubKey().Address()) - - chainID := utils.TestnetChainID + "-1" - suite.app = app.Setup(false, nil, chainID, false) - header := testutil.NewHeader( - 1, time.Now().UTC(), chainID, consAddress, nil, nil, - ) - suite.ctx = suite.app.BaseApp.NewContext(false, header) -} diff --git a/x/withdraw/module.go b/x/withdraw/module.go index 0a0b3c92e..5b28f8ba2 100644 --- a/x/withdraw/module.go +++ b/x/withdraw/module.go @@ -45,13 +45,13 @@ func (AppModuleBasic) Name() string { } // RegisterLegacyAminoCodec registers the amino codec for the module, which is used to marshal and unmarshal structs to/from []byte in order to persist them in the module's KVStore -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {} +func (AppModuleBasic) RegisterLegacyAminoCodec(_ *codec.LegacyAmino) {} // RegisterInterfaces registers a module's interface types and their concrete implementations as proto.Message -func (a AppModuleBasic) RegisterInterfaces(reg cdctypes.InterfaceRegistry) {} +func (a AppModuleBasic) RegisterInterfaces(_ cdctypes.InterfaceRegistry) {} // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the module -func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) {} +func (AppModuleBasic) RegisterGRPCGatewayRoutes(_ client.Context, _ *runtime.ServeMux) {} // GetTxCmd returns the root Tx command for the module. The subcommands of this root command are used by end-users to generate new transactions containing messages defined in the module func (a AppModuleBasic) GetTxCmd() *cobra.Command { @@ -85,9 +85,9 @@ func NewAppModule( } // RegisterServices registers a gRPC query service to respond to the module-specific gRPC queries -func (am AppModule) RegisterServices(cfg module.Configurator) { +func (am AppModule) RegisterServices(_ module.Configurator) { // types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) - //types.RegisterQueryServer(cfg.QueryServer(), am.keeper) + // types.RegisterQueryServer(cfg.QueryServer(), am.keeper) } // RegisterInvariants registers the invariants of the module. If an invariant deviates from its predicted value, the InvariantRegistry triggers appropriate logic (most often the chain will be halted)