Skip to content

Commit

Permalink
test: abci tests and restructure test directory (#120)
Browse files Browse the repository at this point in the history
* Restructure test folder

* Change test package path and add more checks

* Add unpack interface for any type

* Remove unused check

* Change round int to truncate int and resolve decimal when dividing

* Fix type and lint errors

* Add check error when burn remaining coin

* remove debug code

---------

Co-authored-by: Hieu Vu <[email protected]>
  • Loading branch information
neitdung and catShaark authored Jan 29, 2024
1 parent 619dbf6 commit 4a8d70c
Show file tree
Hide file tree
Showing 31 changed files with 277 additions and 132 deletions.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
"os"
"path/filepath"

"github.com/realio-tech/multi-staking-module/testing/simapp"
"github.com/realio-tech/multi-staking-module/test/simapp"
"github.com/spf13/cast"
"github.com/spf13/cobra"
tmcfg "github.com/tendermint/tendermint/config"
Expand Down
File renamed without changes.
4 changes: 2 additions & 2 deletions testing/simapp/simd/main.go → test/simapp/simd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ package main
import (
"os"

"github.com/realio-tech/multi-staking-module/testing/simapp"
"github.com/realio-tech/multi-staking-module/testing/simapp/simd/cmd"
"github.com/realio-tech/multi-staking-module/test/simapp"
"github.com/realio-tech/multi-staking-module/test/simapp/simd/cmd"

"github.com/cosmos/cosmos-sdk/server"
svrcmd "github.com/cosmos/cosmos-sdk/server/cmd"
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,6 @@ func genesisStateWithValSet(app *SimApp, genesisState GenesisState, valSet *tmty
Commission: stakingtypes.NewCommission(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()),
MinSelfDelegation: sdk.ZeroInt(),
}

validators = append(validators, validator)
delegations = append(delegations, stakingtypes.NewDelegation(genAcc.GetAddress(), val.Address.Bytes(), sdk.OneDec()))

Expand All @@ -178,6 +177,7 @@ func genesisStateWithValSet(app *SimApp, genesisState GenesisState, valSet *tmty
ValidatorMultiStakingCoins: validatorMsCoins,
StakingGenesisState: *stakingGenesis,
}

genesisState[multistakingtypes.ModuleName] = app.AppCodec().MustMarshalJSON(&multistakingGenesis)

balances = append(balances, banktypes.Balance{
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
2 changes: 1 addition & 1 deletion testutil/address.go → test/test_util.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package testutil
package test

import (
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
Expand Down
27 changes: 0 additions & 27 deletions testutil/context.go

This file was deleted.

5 changes: 4 additions & 1 deletion x/multi-staking/keeper/abci.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,10 @@ func (k Keeper) BurnUnbondedCoinAndUnlockedMultiStakingCoin(
}
// burn remaining coin in unlock
remaningCoin := unlockEntry.UnlockingCoin.ToCoin().Sub(unlockedCoin)
k.bankKeeper.BurnCoins(ctx, types.ModuleName, sdk.NewCoins(remaningCoin))
err = k.bankKeeper.BurnCoins(ctx, types.ModuleName, sdk.NewCoins(remaningCoin))
if err != nil {
return sdk.Coin{}, err
}

err = k.UnescrowCoinTo(ctx, multiStakerAddr, unlockedCoin)
if err != nil {
Expand Down
108 changes: 108 additions & 0 deletions x/multi-staking/keeper/abci_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
package keeper_test

import (
"time"

"github.com/stretchr/testify/require"

"cosmossdk.io/math"

sdk "github.com/cosmos/cosmos-sdk/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)

func (suite *KeeperTestSuite) TestMsUnlockEndBlocker() {
// val A
// delegate to val A with X ario
// undelegate from val A
// val A got slash
// nextblock
// check A balance has X ario/ zero stake

testCases := []struct {
name string
lockAmount math.Int
slashFactor sdk.Dec
}{
{
name: "no slashing",
lockAmount: math.NewInt(3788),
slashFactor: sdk.ZeroDec(),
},
{
name: "slash half of lock coin",
lockAmount: math.NewInt(123),
slashFactor: sdk.MustNewDecFromStr("0.5"),
},
{
name: "slash all of lock coin",
lockAmount: math.NewInt(19090),
slashFactor: sdk.ZeroDec(),
},
}

for _, tc := range testCases {
tc := tc
suite.Run(tc.name, func() {
// height 1
suite.SetupTest()

vals := suite.app.StakingKeeper.GetAllValidators(suite.ctx)
val := vals[0]

msDenom := suite.msKeeper.GetValidatorMultiStakingCoin(suite.ctx, val.GetOperator())

msCoin := sdk.NewCoin(msDenom, tc.lockAmount)

msStaker := suite.CreateAndFundAccount(sdk.NewCoins(msCoin))

delegateMsg := &stakingtypes.MsgDelegate{
DelegatorAddress: msStaker.String(),
ValidatorAddress: val.OperatorAddress,
Amount: msCoin,
}
_, err := suite.msgServer.Delegate(suite.ctx, delegateMsg)
suite.NoError(err)

// height 2
suite.NextBlock(time.Second)

if !tc.slashFactor.IsZero() {
val, found := suite.app.StakingKeeper.GetValidator(suite.ctx, val.GetOperator())
require.True(suite.T(), found)

slashedPow := suite.app.StakingKeeper.TokensToConsensusPower(suite.ctx, val.Tokens)

valConsAddr, err := val.GetConsAddr()
require.NoError(suite.T(), err)

// height 3
suite.NextBlock(time.Second)

suite.app.SlashingKeeper.Slash(suite.ctx, valConsAddr, tc.slashFactor, slashedPow, 2)
} else {
// height 3
suite.NextBlock(time.Second)
}

undelegateMsg := stakingtypes.MsgUndelegate{
DelegatorAddress: msStaker.String(),
ValidatorAddress: val.OperatorAddress,
Amount: msCoin,
}

_, err = suite.msgServer.Undelegate(suite.ctx, &undelegateMsg)
suite.NoError(err)

// pass unbonding period
suite.NextBlock(time.Duration(1000000000000000000))
suite.NextBlock(time.Duration(1))

unlockAmount := suite.app.BankKeeper.GetBalance(suite.ctx, msStaker, msDenom).Amount

expectedUnlockAmount := sdk.NewDecFromInt(tc.lockAmount).Mul(sdk.OneDec().Sub(tc.slashFactor)).TruncateInt()

suite.True(SoftEqualInt(unlockAmount, expectedUnlockAmount) || DiffLTEThanOne(unlockAmount, expectedUnlockAmount))
})
}
}
13 changes: 6 additions & 7 deletions x/multi-staking/keeper/invartiants_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package keeper_test
import (
"time"

"github.com/realio-tech/multi-staking-module/testutil"
"github.com/realio-tech/multi-staking-module/test"
"github.com/realio-tech/multi-staking-module/x/multi-staking/keeper"
"github.com/realio-tech/multi-staking-module/x/multi-staking/types"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
Expand All @@ -14,8 +14,8 @@ import (
)

func (suite *KeeperTestSuite) TestModuleAccountInvariants() {
delAddr := testutil.GenAddress()
priv, valAddr := testutil.GenValAddressWithPrivKey()
delAddr := test.GenAddress()
priv, valAddr := test.GenValAddressWithPrivKey()
valPubKey := priv.PubKey()

testCases := []struct {
Expand Down Expand Up @@ -72,7 +72,7 @@ func (suite *KeeperTestSuite) TestModuleAccountInvariants() {
{
name: "Success BeginRedelegate",
malleate: func() {
priv, valAddr2 := testutil.GenValAddressWithPrivKey()
priv, valAddr2 := test.GenValAddressWithPrivKey()
valPubKey2 := priv.PubKey()
bondAmount := sdk.NewCoin(MultiStakingDenomA, sdk.NewInt(500))
createMsg2 := stakingtypes.MsgCreateValidator{
Expand Down Expand Up @@ -132,8 +132,7 @@ func (suite *KeeperTestSuite) TestModuleAccountInvariants() {
suite.SetupTest() // reset

valCoins := sdk.NewCoins(sdk.NewCoin(MultiStakingDenomA, sdk.NewInt(10000)), sdk.NewCoin(MultiStakingDenomB, sdk.NewInt(10000)))
err := suite.FundAccount(delAddr, valCoins)
suite.Require().NoError(err)
suite.FundAccount(delAddr, valCoins)

suite.msKeeper.SetBondWeight(suite.ctx, MultiStakingDenomA, sdk.MustNewDecFromStr("0.3"))
bondAmount := sdk.NewCoin(MultiStakingDenomA, sdk.NewInt(3001))
Expand All @@ -157,7 +156,7 @@ func (suite *KeeperTestSuite) TestModuleAccountInvariants() {
Value: bondAmount,
}

_, err = suite.msgServer.CreateValidator(suite.ctx, &msg)
_, err := suite.msgServer.CreateValidator(suite.ctx, &msg)
suite.Require().NoError(err)

tc.malleate()
Expand Down
19 changes: 18 additions & 1 deletion x/multi-staking/keeper/keeper.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package keeper

import (
"fmt"
"time"

"github.com/realio-tech/multi-staking-module/x/multi-staking/types"
"github.com/tendermint/tendermint/libs/log"
Expand Down Expand Up @@ -44,9 +45,25 @@ func (k Keeper) Logger(ctx sdk.Context) log.Logger {
return ctx.Logger().With("module", "x/"+types.ModuleName)
}

func (k Keeper) DequeueAllMatureUBDQueue(ctx sdk.Context, currTime time.Time) (matureUnbonds []stakingtypes.DVPair) {
// gets an iterator for all timeslices from time 0 until the current Blockheader time
unbondingTimesliceIterator := k.stakingKeeper.UBDQueueIterator(ctx, currTime)
defer unbondingTimesliceIterator.Close()

for ; unbondingTimesliceIterator.Valid(); unbondingTimesliceIterator.Next() {
timeslice := stakingtypes.DVPairs{}
value := unbondingTimesliceIterator.Value()
k.cdc.MustUnmarshal(value, &timeslice)

matureUnbonds = append(matureUnbonds, timeslice.Pairs...)
}

return matureUnbonds
}

func (k Keeper) GetMatureUnbondingDelegations(ctx sdk.Context) []stakingtypes.UnbondingDelegation {
var matureUnbondingDelegations []stakingtypes.UnbondingDelegation
matureUnbonds := k.stakingKeeper.DequeueAllMatureUBDQueue(ctx, ctx.BlockHeader().Time)
matureUnbonds := k.DequeueAllMatureUBDQueue(ctx, ctx.BlockHeader().Time)
for _, dvPair := range matureUnbonds {
delAddr, valAddr, err := types.AccAddrAndValAddrFromStrings(dvPair.DelegatorAddress, dvPair.ValidatorAddress)
if err != nil {
Expand Down
Loading

0 comments on commit 4a8d70c

Please sign in to comment.