feat: decouple x/distribution from simapp (#12334)

* feat: decouple `x/distribution` from simapp

* updates
This commit is contained in:
Julien Robert
2022-06-22 21:43:33 +02:00
committed by GitHub
parent 6559c7ac82
commit d07d35f29e
39 changed files with 915 additions and 575 deletions
+4 -3
View File
@@ -49,9 +49,10 @@ Ref: https://keepachangelog.com/en/1.0.0/
### API Breaking Changes
* (simapp) [#12312](https:12278//github.com/cosmos/cosmos-sdk/pull/12312) Move `simapp.EmptyAppOptions` to `simtestutil.EmptyAppOptions` (`testutil/sims`)
* (simapp) [#12312](https:12278//github.com/cosmos/cosmos-sdk/pull/12312) Remove `skipUpgradeHeights map[int64]bool` and `homePath string` from `NewSimApp` constructor as per migration of `x/upgrade` to app-wiring.
* (testutil) [#12278](https:12278//github.com/cosmos/cosmos-sdk/pull/12278) Move all functions from `simapp/helpers` to `testutil/sims`
* (simapp) [#XXXXX](https://github.com/cosmos/cosmos-sdk/pull/XXXXX) Move `simapp.ConvertAddrsToValAddrs` and `simapp.CreateTestPubKeys ` to respectively `simtestutil.ConvertAddrsToValAddrs` and `simtestutil.CreateTestPubKeys` (`testutil/sims`)
* (simapp) [#12312](https://github.com/cosmos/cosmos-sdk/pull/12312) Move `simapp.EmptyAppOptions` to `simtestutil.EmptyAppOptions` (`testutil/sims`)
* (simapp) [#12312](https://github.com/cosmos/cosmos-sdk/pull/12312) Remove `skipUpgradeHeights map[int64]bool` and `homePath string` from `NewSimApp` constructor as per migration of `x/upgrade` to app-wiring.
* (testutil) [#12278](https://github.com/cosmos/cosmos-sdk/pull/12278) Move all functions from `simapp/helpers` to `testutil/sims`
* (testutil) [#12233](https://github.com/cosmos/cosmos-sdk/pull/12233) Move `simapp.TestAddr` to `simtestutil.TestAddr` (`testutil/sims`)
* (x/staking) [#12102](https://github.com/cosmos/cosmos-sdk/pull/12102) Staking keeper now is passed by reference instead of copy. Keeper's SetHooks no longer returns keeper. It updates the keeper in place instead.
* (linting) [#12141](https://github.com/cosmos/cosmos-sdk/pull/12141) Fix usability related linting for database. This means removing the infix Prefix from `prefix.NewPrefixWriter` and such so that it is `prefix.NewWriter` and making `db.DBConnection` and such into `db.Connection`
+12 -19
View File
@@ -2,25 +2,18 @@ package params
// Default simulation operation weights for messages and gov proposals
const (
DefaultWeightMsgSend int = 100
DefaultWeightMsgMultiSend int = 10
DefaultWeightMsgSetWithdrawAddress int = 50
DefaultWeightMsgWithdrawDelegationReward int = 50
DefaultWeightMsgWithdrawValidatorCommission int = 50
DefaultWeightMsgFundCommunityPool int = 50
DefaultWeightMsgDeposit int = 100
DefaultWeightMsgVote int = 67
DefaultWeightMsgVoteWeighted int = 33
DefaultWeightMsgUnjail int = 100
DefaultWeightMsgCreateValidator int = 100
DefaultWeightMsgEditValidator int = 5
DefaultWeightMsgDelegate int = 100
DefaultWeightMsgUndelegate int = 100
DefaultWeightMsgBeginRedelegate int = 100
DefaultWeightMsgCancelUnbondingDelegation int = 100
DefaultWeightCommunitySpendProposal int = 5
DefaultWeightTextProposal int = 5
DefaultWeightMsgSend int = 100
DefaultWeightMsgMultiSend int = 10
DefaultWeightMsgDeposit int = 100
DefaultWeightMsgVote int = 67
DefaultWeightMsgVoteWeighted int = 33
DefaultWeightMsgUnjail int = 100
DefaultWeightMsgCreateValidator int = 100
DefaultWeightMsgEditValidator int = 5
DefaultWeightMsgDelegate int = 100
DefaultWeightMsgUndelegate int = 100
DefaultWeightMsgBeginRedelegate int = 100
DefaultWeightMsgCancelUnbondingDelegation int = 100
// feegrant
DefaultWeightGrantAllowance int = 100
-45
View File
@@ -1,11 +1,8 @@
package simapp
import (
"bytes"
"context"
"encoding/hex"
"encoding/json"
"strconv"
"testing"
"github.com/stretchr/testify/require"
@@ -19,7 +16,6 @@ import (
"cosmossdk.io/math"
bam "github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/crypto/keys/ed25519"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
"github.com/cosmos/cosmos-sdk/depinject"
@@ -28,7 +24,6 @@ import (
"github.com/cosmos/cosmos-sdk/testutil/mock"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/errors"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
@@ -247,17 +242,6 @@ func initAccountWithCoins(app *SimApp, ctx sdk.Context, addr sdk.AccAddress, coi
}
}
// ConvertAddrsToValAddrs converts the provided addresses to ValAddress.
func ConvertAddrsToValAddrs(addrs []sdk.AccAddress) []sdk.ValAddress {
valAddrs := make([]sdk.ValAddress, len(addrs))
for i, addr := range addrs {
valAddrs[i] = sdk.ValAddress(addr)
}
return valAddrs
}
// CheckBalance checks the balance of an account.
func CheckBalance(t *testing.T, app *SimApp, addr sdk.AccAddress, balances sdk.Coins) {
ctxCheck := app.BaseApp.NewContext(true, tmproto.Header{})
@@ -347,35 +331,6 @@ func incrementAllSequenceNumbers(initSeqNums []uint64) {
}
}
// CreateTestPubKeys returns a total of numPubKeys public keys in ascending order.
func CreateTestPubKeys(numPubKeys int) []cryptotypes.PubKey {
var publicKeys []cryptotypes.PubKey
var buffer bytes.Buffer
// start at 10 to avoid changing 1 to 01, 2 to 02, etc
for i := 100; i < (numPubKeys + 100); i++ {
numString := strconv.Itoa(i)
buffer.WriteString("0B485CFC0EECC619440448436F8FC9DF40566F2369E72400281454CB552AF") // base pubkey string
buffer.WriteString(numString) // adding on final two digits to make pubkeys unique
publicKeys = append(publicKeys, NewPubKeyFromHex(buffer.String()))
buffer.Reset()
}
return publicKeys
}
// NewPubKeyFromHex returns a PubKey from a hex string.
func NewPubKeyFromHex(pk string) (res cryptotypes.PubKey) {
pkBytes, err := hex.DecodeString(pk)
if err != nil {
panic(err)
}
if len(pkBytes) != ed25519.PubKeySize {
panic(errors.Wrap(errors.ErrInvalidPubKey, "invalid pubkey size"))
}
return &ed25519.PubKey{Key: pkBytes}
}
// ModuleAccountAddrs provides a list of blocked module accounts from configuration in app.yaml
//
// Ported from SimApp
+49
View File
@@ -2,12 +2,15 @@ package sims
import (
"bytes"
"encoding/hex"
"fmt"
"strconv"
"cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/crypto/keys/ed25519"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/errors"
bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper"
minttypes "github.com/cosmos/cosmos-sdk/x/mint/types"
stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
@@ -15,6 +18,12 @@ import (
type GenerateAccountStrategy func(int) []sdk.AccAddress
// AddTestAddrs constructs and returns accNum amount of accounts with an
// initial balance of accAmt in random order
func AddTestAddrs(bankKeeper bankkeeper.Keeper, stakingKeeper *stakingkeeper.Keeper, ctx sdk.Context, accNum int, accAmt math.Int) []sdk.AccAddress {
return addTestAddrs(bankKeeper, stakingKeeper, ctx, accNum, accAmt, CreateRandomAccounts)
}
// AddTestAddrsIncremental constructs and returns accNum amount of accounts with an initial balance of accAmt in random order
func AddTestAddrsIncremental(bankKeeper bankkeeper.Keeper, stakingKeeper *stakingkeeper.Keeper, ctx sdk.Context, accNum int, accAmt math.Int) []sdk.AccAddress {
return addTestAddrs(bankKeeper, stakingKeeper, ctx, accNum, accAmt, CreateIncrementalAccounts)
@@ -94,3 +103,43 @@ func TestAddr(addr string, bech string) (sdk.AccAddress, error) {
return res, nil
}
// ConvertAddrsToValAddrs converts the provided addresses to ValAddress.
func ConvertAddrsToValAddrs(addrs []sdk.AccAddress) []sdk.ValAddress {
valAddrs := make([]sdk.ValAddress, len(addrs))
for i, addr := range addrs {
valAddrs[i] = sdk.ValAddress(addr)
}
return valAddrs
}
// CreateTestPubKeys returns a total of numPubKeys public keys in ascending order.
func CreateTestPubKeys(numPubKeys int) []cryptotypes.PubKey {
var publicKeys []cryptotypes.PubKey
var buffer bytes.Buffer
// start at 10 to avoid changing 1 to 01, 2 to 02, etc
for i := 100; i < (numPubKeys + 100); i++ {
numString := strconv.Itoa(i)
buffer.WriteString("0B485CFC0EECC619440448436F8FC9DF40566F2369E72400281454CB552AF") // base pubkey string
buffer.WriteString(numString) // adding on final two digits to make pubkeys unique
publicKeys = append(publicKeys, NewPubKeyFromHex(buffer.String()))
buffer.Reset()
}
return publicKeys
}
// NewPubKeyFromHex returns a PubKey from a hex string.
func NewPubKeyFromHex(pk string) (res cryptotypes.PubKey) {
pkBytes, err := hex.DecodeString(pk)
if err != nil {
panic(err)
}
if len(pkBytes) != ed25519.PubKeySize {
panic(errors.Wrap(errors.ErrInvalidPubKey, "invalid pubkey size"))
}
return &ed25519.PubKey{Key: pkBytes}
}
+3 -2
View File
@@ -9,6 +9,7 @@ import (
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/cosmos/cosmos-sdk/simapp"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
@@ -648,8 +649,8 @@ func dirtyTrackingFields(ctx sdk.Context, vesting exported.VestingAccount, app *
func createValidator(t *testing.T, ctx sdk.Context, app *simapp.SimApp, powers int64) (sdk.AccAddress, sdk.ValAddress) {
valTokens := sdk.TokensFromConsensusPower(powers, sdk.DefaultPowerReduction)
addrs := simapp.AddTestAddrsIncremental(app, ctx, 1, valTokens)
valAddrs := simapp.ConvertAddrsToValAddrs(addrs)
pks := simapp.CreateTestPubKeys(1)
valAddrs := simtestutil.ConvertAddrsToValAddrs(addrs)
pks := simtestutil.CreateTestPubKeys(1)
cdc := simapp.MakeTestEncodingConfig().Codec
app.StakingKeeper = stakingkeeper.NewKeeper(
+26 -9
View File
@@ -5,8 +5,12 @@ import (
"github.com/cosmos/cosmos-sdk/crypto/keys/ed25519"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
"github.com/cosmos/cosmos-sdk/simapp"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper"
"github.com/cosmos/cosmos-sdk/x/distribution/keeper"
"github.com/cosmos/cosmos-sdk/x/distribution/testutil"
stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
"github.com/cosmos/cosmos-sdk/x/staking/teststaking"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/stretchr/testify/require"
@@ -33,10 +37,23 @@ type validator struct {
// Context in https://github.com/cosmos/cosmos-sdk/issues/9161
func TestVerifyProposerRewardAssignement(t *testing.T) {
app := simapp.Setup(t, false)
var (
bankKeeper bankkeeper.Keeper
stakingKeeper *stakingkeeper.Keeper
distrKeeper keeper.Keeper
)
app, err := simtestutil.Setup(testutil.AppConfig,
&bankKeeper,
&stakingKeeper,
&distrKeeper,
)
require.NoError(t, err)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
addrs := simapp.AddTestAddrsIncremental(app, ctx, totalValidators, valTokens)
tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper)
addrs := simtestutil.AddTestAddrsIncremental(bankKeeper, stakingKeeper, ctx, totalValidators, valTokens)
tstaking := teststaking.NewHelper(t, ctx, stakingKeeper)
tstaking.Commission = validatorCommissionRates
// create validators
@@ -51,10 +68,10 @@ func TestVerifyProposerRewardAssignement(t *testing.T) {
require.NotEmpty(t, app.Commit())
// verify validators lists
require.Len(t, app.StakingKeeper.GetAllValidators(ctx), totalValidators)
require.Len(t, stakingKeeper.GetAllValidators(ctx), totalValidators)
for i, val := range validators {
// verify all validator exists
require.NotNil(t, app.StakingKeeper.ValidatorByConsAddr(ctx, sdk.GetConsAddress(val.pubkey)))
require.NotNil(t, stakingKeeper.ValidatorByConsAddr(ctx, sdk.GetConsAddress(val.pubkey)))
// populate last commit info
voteInfos := []abci.VoteInfo{}
@@ -99,9 +116,9 @@ func TestVerifyProposerRewardAssignement(t *testing.T) {
})
require.NotEmpty(t, app.Commit())
rewardsValidatorBeforeLazyValidator := app.DistrKeeper.GetValidatorOutstandingRewardsCoins(ctx, validators[lazyValidatorIdx+1].addr)
rewardsLazyValidator := app.DistrKeeper.GetValidatorOutstandingRewardsCoins(ctx, validators[lazyValidatorIdx].addr)
rewardsValidatorAfterLazyValidator := app.DistrKeeper.GetValidatorOutstandingRewardsCoins(ctx, validators[lazyValidatorIdx+1].addr)
rewardsValidatorBeforeLazyValidator := distrKeeper.GetValidatorOutstandingRewardsCoins(ctx, validators[lazyValidatorIdx+1].addr)
rewardsLazyValidator := distrKeeper.GetValidatorOutstandingRewardsCoins(ctx, validators[lazyValidatorIdx].addr)
rewardsValidatorAfterLazyValidator := distrKeeper.GetValidatorOutstandingRewardsCoins(ctx, validators[lazyValidatorIdx+1].addr)
require.True(t, rewardsLazyValidator[0].Amount.LT(rewardsValidatorAfterLazyValidator[0].Amount))
require.Equal(t, rewardsValidatorBeforeLazyValidator, rewardsValidatorAfterLazyValidator)
}
+14 -14
View File
@@ -5,15 +5,14 @@ import (
"github.com/spf13/pflag"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
"github.com/cosmos/cosmos-sdk/simapp/params"
"github.com/cosmos/cosmos-sdk/testutil"
sdktestutil "github.com/cosmos/cosmos-sdk/testutil"
"github.com/cosmos/cosmos-sdk/testutil/testdata"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/assert"
"github.com/cosmos/cosmos-sdk/client"
sdk "github.com/cosmos/cosmos-sdk/types"
)
@@ -22,7 +21,7 @@ func Test_splitAndCall_NoMessages(t *testing.T) {
clientCtx := client.Context{}
err := newSplitAndApply(nil, clientCtx, nil, nil, 10)
assert.NoError(t, err, "")
require.NoError(t, err, "")
}
func Test_splitAndCall_Splitting(t *testing.T) {
@@ -47,27 +46,28 @@ func Test_splitAndCall_Splitting(t *testing.T) {
func(clientCtx client.Context, fs *pflag.FlagSet, msgs ...sdk.Msg) error {
callCount++
assert.NotNil(t, clientCtx)
assert.NotNil(t, msgs)
require.NotNil(t, clientCtx)
require.NotNil(t, msgs)
if callCount < 3 {
assert.Equal(t, len(msgs), 2)
require.Equal(t, len(msgs), 2)
} else {
assert.Equal(t, len(msgs), 1)
require.Equal(t, len(msgs), 1)
}
return nil
},
clientCtx, nil, msgs, chunkSize)
assert.NoError(t, err, "")
assert.Equal(t, 3, callCount)
require.NoError(t, err, "")
require.Equal(t, 3, callCount)
}
func TestParseProposal(t *testing.T) {
encodingConfig := params.MakeTestEncodingConfig()
interfaceRegistry := types.NewInterfaceRegistry()
cdc := codec.NewProtoCodec(interfaceRegistry)
okJSON := testutil.WriteToNewTempFile(t, `
okJSON := sdktestutil.WriteToNewTempFile(t, `
{
"title": "Community Pool Spend",
"description": "Pay me some Atoms!",
@@ -77,7 +77,7 @@ func TestParseProposal(t *testing.T) {
}
`)
proposal, err := ParseCommunityPoolSpendProposalWithDeposit(encodingConfig.Codec, okJSON.Name())
proposal, err := ParseCommunityPoolSpendProposalWithDeposit(cdc, okJSON.Name())
require.NoError(t, err)
require.Equal(t, "Community Pool Spend", proposal.Title)
@@ -6,12 +6,13 @@ import (
"github.com/gogo/protobuf/proto"
"github.com/stretchr/testify/suite"
"github.com/cosmos/cosmos-sdk/testutil"
sdktestutil "github.com/cosmos/cosmos-sdk/testutil"
"github.com/cosmos/cosmos-sdk/testutil/network"
"github.com/cosmos/cosmos-sdk/testutil/rest"
sdk "github.com/cosmos/cosmos-sdk/types"
grpctypes "github.com/cosmos/cosmos-sdk/types/grpc"
"github.com/cosmos/cosmos-sdk/types/query"
"github.com/cosmos/cosmos-sdk/x/distribution/testutil"
"github.com/cosmos/cosmos-sdk/x/distribution/types"
)
@@ -25,11 +26,11 @@ type GRPCQueryTestSuite struct {
func (s *GRPCQueryTestSuite) SetupSuite() {
s.T().Log("setting up integration test suite")
cfg := network.DefaultConfig()
cfg, err := network.DefaultConfigWithAppConfig(testutil.AppConfig)
s.Require().NoError(err)
cfg.NumValidators = 1
s.cfg = cfg
var err error
s.network, err = network.New(s.T(), s.T().TempDir(), cfg)
s.Require().NoError(err)
@@ -115,7 +116,7 @@ func (s *GRPCQueryTestSuite) TestQueryOutstandingRewardsGRPC() {
for _, tc := range testCases {
tc := tc
resp, err := testutil.GetRequestWithHeaders(tc.url, tc.headers)
resp, err := sdktestutil.GetRequestWithHeaders(tc.url, tc.headers)
s.Run(tc.name, func() {
if tc.expErr {
s.Require().Error(val.ClientCtx.Codec.UnmarshalJSON(resp, tc.respType))
@@ -169,7 +170,7 @@ func (s *GRPCQueryTestSuite) TestQueryValidatorCommissionGRPC() {
for _, tc := range testCases {
tc := tc
resp, err := testutil.GetRequestWithHeaders(tc.url, tc.headers)
resp, err := sdktestutil.GetRequestWithHeaders(tc.url, tc.headers)
s.Run(tc.name, func() {
if tc.expErr {
s.Require().Error(val.ClientCtx.Codec.UnmarshalJSON(resp, tc.respType))
@@ -303,7 +304,7 @@ func (s *GRPCQueryTestSuite) TestQueryDelegatorRewardsGRPC() {
for _, tc := range testCases {
tc := tc
resp, err := testutil.GetRequestWithHeaders(tc.url, tc.headers)
resp, err := sdktestutil.GetRequestWithHeaders(tc.url, tc.headers)
s.Run(tc.name, func() {
if tc.expErr {
@@ -452,7 +453,7 @@ func (s *GRPCQueryTestSuite) TestQueryValidatorCommunityPoolGRPC() {
for _, tc := range testCases {
tc := tc
resp, err := testutil.GetRequestWithHeaders(tc.url, tc.headers)
resp, err := sdktestutil.GetRequestWithHeaders(tc.url, tc.headers)
s.Run(tc.name, func() {
if tc.expErr {
+8 -4
View File
@@ -11,11 +11,12 @@ import (
tmcli "github.com/tendermint/tendermint/libs/cli"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/testutil"
sdktestutil "github.com/cosmos/cosmos-sdk/testutil"
clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli"
"github.com/cosmos/cosmos-sdk/testutil/network"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/distribution/client/cli"
"github.com/cosmos/cosmos-sdk/x/distribution/testutil"
distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types"
minttypes "github.com/cosmos/cosmos-sdk/x/mint/types"
)
@@ -38,7 +39,8 @@ func NewIntegrationTestSuite(cfg network.Config) *IntegrationTestSuite {
func (s *IntegrationTestSuite) SetupSuite() {
s.T().Log("setting up integration test suite")
cfg := network.DefaultConfig()
cfg, err := network.DefaultConfigWithAppConfig(testutil.AppConfig)
s.Require().NoError(err)
cfg.NumValidators = 1
s.cfg = cfg
@@ -751,6 +753,8 @@ func (s *IntegrationTestSuite) TestNewFundCommunityPoolCmd() {
}
func (s *IntegrationTestSuite) TestGetCmdSubmitProposal() {
s.T().Skip() // TODO to re-enable in #12274
val := s.network.Validators[0]
invalidProp := `{
"title": "",
@@ -769,7 +773,7 @@ func (s *IntegrationTestSuite) TestGetCmdSubmitProposal() {
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()),
}
invalidPropFile := testutil.WriteToNewTempFile(s.T(), invalidProp)
invalidPropFile := sdktestutil.WriteToNewTempFile(s.T(), invalidProp)
cmd := cli.NewFundCommunityPoolCmd()
out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, args)
s.Require().NoError(err)
@@ -786,7 +790,7 @@ func (s *IntegrationTestSuite) TestGetCmdSubmitProposal() {
"deposit": "%s"
}`, val.Address.String(), sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(5431)), sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(5431)))
validPropFile := testutil.WriteToNewTempFile(s.T(), validProp)
validPropFile := sdktestutil.WriteToNewTempFile(s.T(), validProp)
testCases := []struct {
name string
args []string
@@ -12,6 +12,7 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types"
banktestutil "github.com/cosmos/cosmos-sdk/x/bank/client/testutil"
"github.com/cosmos/cosmos-sdk/x/distribution/client/cli"
"github.com/cosmos/cosmos-sdk/x/distribution/testutil"
stakingcli "github.com/cosmos/cosmos-sdk/x/staking/client/cli"
"github.com/stretchr/testify/suite"
)
@@ -24,7 +25,8 @@ type WithdrawAllTestSuite struct {
}
func (s *WithdrawAllTestSuite) SetupSuite() {
cfg := network.DefaultConfig()
cfg, err := network.DefaultConfigWithAppConfig(testutil.AppConfig)
s.Require().NoError(err)
cfg.NumValidators = 2
s.cfg = cfg
+98 -53
View File
@@ -7,54 +7,85 @@ import (
abci "github.com/tendermint/tendermint/abci/types"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/cosmos/cosmos-sdk/simapp"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper"
"github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/cosmos/cosmos-sdk/x/bank/testutil"
bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper"
banktestutil "github.com/cosmos/cosmos-sdk/x/bank/testutil"
"github.com/cosmos/cosmos-sdk/x/distribution/keeper"
"github.com/cosmos/cosmos-sdk/x/distribution/testutil"
disttypes "github.com/cosmos/cosmos-sdk/x/distribution/types"
stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
"github.com/cosmos/cosmos-sdk/x/staking/teststaking"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)
func TestAllocateTokensToValidatorWithCommission(t *testing.T) {
app := simapp.Setup(t, false)
var (
bankKeeper bankkeeper.Keeper
distrKeeper keeper.Keeper
stakingKeeper *stakingkeeper.Keeper
)
app, err := simtestutil.Setup(testutil.AppConfig,
&bankKeeper,
&distrKeeper,
&stakingKeeper,
)
require.NoError(t, err)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
addrs := simapp.AddTestAddrs(app, ctx, 3, sdk.NewInt(1234))
valAddrs := simapp.ConvertAddrsToValAddrs(addrs)
tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper)
addrs := simtestutil.AddTestAddrs(bankKeeper, stakingKeeper, ctx, 3, sdk.NewInt(1234))
valAddrs := simtestutil.ConvertAddrsToValAddrs(addrs)
tstaking := teststaking.NewHelper(t, ctx, stakingKeeper)
// create validator with 50% commission
tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0))
tstaking.CreateValidator(sdk.ValAddress(addrs[0]), valConsPk1, sdk.NewInt(100), true)
val := app.StakingKeeper.Validator(ctx, valAddrs[0])
val := stakingKeeper.Validator(ctx, valAddrs[0])
// allocate tokens
tokens := sdk.DecCoins{
{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(10)},
}
app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens)
distrKeeper.AllocateTokensToValidator(ctx, val, tokens)
// check commission
expected := sdk.DecCoins{
{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(5)},
}
require.Equal(t, expected, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, val.GetOperator()).Commission)
require.Equal(t, expected, distrKeeper.GetValidatorAccumulatedCommission(ctx, val.GetOperator()).Commission)
// check current rewards
require.Equal(t, expected, app.DistrKeeper.GetValidatorCurrentRewards(ctx, val.GetOperator()).Rewards)
require.Equal(t, expected, distrKeeper.GetValidatorCurrentRewards(ctx, val.GetOperator()).Rewards)
}
func TestAllocateTokensToManyValidators(t *testing.T) {
app := simapp.Setup(t, false)
var (
accountKeeper authkeeper.AccountKeeper
bankKeeper bankkeeper.Keeper
distrKeeper keeper.Keeper
stakingKeeper *stakingkeeper.Keeper
)
app, err := simtestutil.Setup(testutil.AppConfig,
&accountKeeper,
&bankKeeper,
&distrKeeper,
&stakingKeeper,
)
require.NoError(t, err)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
// reset fee pool
app.DistrKeeper.SetFeePool(ctx, disttypes.InitialFeePool())
distrKeeper.SetFeePool(ctx, disttypes.InitialFeePool())
addrs := simapp.AddTestAddrs(app, ctx, 2, sdk.NewInt(1234))
valAddrs := simapp.ConvertAddrsToValAddrs(addrs)
tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper)
addrs := simtestutil.AddTestAddrs(bankKeeper, stakingKeeper, ctx, 2, sdk.NewInt(1234))
valAddrs := simtestutil.ConvertAddrsToValAddrs(addrs)
tstaking := teststaking.NewHelper(t, ctx, stakingKeeper)
// create validator with 50% commission
tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0))
@@ -74,23 +105,23 @@ func TestAllocateTokensToManyValidators(t *testing.T) {
}
// assert initial state: zero outstanding rewards, zero community pool, zero commission, zero current rewards
require.True(t, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[0]).Rewards.IsZero())
require.True(t, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[1]).Rewards.IsZero())
require.True(t, app.DistrKeeper.GetFeePool(ctx).CommunityPool.IsZero())
require.True(t, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission.IsZero())
require.True(t, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[1]).Commission.IsZero())
require.True(t, app.DistrKeeper.GetValidatorCurrentRewards(ctx, valAddrs[0]).Rewards.IsZero())
require.True(t, app.DistrKeeper.GetValidatorCurrentRewards(ctx, valAddrs[1]).Rewards.IsZero())
require.True(t, distrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[0]).Rewards.IsZero())
require.True(t, distrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[1]).Rewards.IsZero())
require.True(t, distrKeeper.GetFeePool(ctx).CommunityPool.IsZero())
require.True(t, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission.IsZero())
require.True(t, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[1]).Commission.IsZero())
require.True(t, distrKeeper.GetValidatorCurrentRewards(ctx, valAddrs[0]).Rewards.IsZero())
require.True(t, distrKeeper.GetValidatorCurrentRewards(ctx, valAddrs[1]).Rewards.IsZero())
// allocate tokens as if both had voted and second was proposer
fees := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)))
feeCollector := app.AccountKeeper.GetModuleAccount(ctx, types.FeeCollectorName)
feeCollector := accountKeeper.GetModuleAccount(ctx, types.FeeCollectorName)
require.NotNil(t, feeCollector)
// fund fee collector
require.NoError(t, testutil.FundModuleAccount(app.BankKeeper, ctx, feeCollector.GetName(), fees))
require.NoError(t, banktestutil.FundModuleAccount(bankKeeper, ctx, feeCollector.GetName(), fees))
app.AccountKeeper.SetAccount(ctx, feeCollector)
accountKeeper.SetAccount(ctx, feeCollector)
votes := []abci.VoteInfo{
{
@@ -102,33 +133,47 @@ func TestAllocateTokensToManyValidators(t *testing.T) {
SignedLastBlock: true,
},
}
app.DistrKeeper.AllocateTokens(ctx, 200, 200, valConsAddr2, votes)
distrKeeper.AllocateTokens(ctx, 200, 200, valConsAddr2, votes)
// 98 outstanding rewards (100 less 2 to community pool)
require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(465, 1)}}, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[0]).Rewards)
require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(515, 1)}}, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[1]).Rewards)
require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(465, 1)}}, distrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[0]).Rewards)
require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(515, 1)}}, distrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[1]).Rewards)
// 2 community pool coins
require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(2)}}, app.DistrKeeper.GetFeePool(ctx).CommunityPool)
require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(2)}}, distrKeeper.GetFeePool(ctx).CommunityPool)
// 50% commission for first proposer, (0.5 * 93%) * 100 / 2 = 23.25
require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(2325, 2)}}, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission)
require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(2325, 2)}}, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission)
// zero commission for second proposer
require.True(t, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[1]).Commission.IsZero())
require.True(t, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[1]).Commission.IsZero())
// just staking.proportional for first proposer less commission = (0.5 * 93%) * 100 / 2 = 23.25
require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(2325, 2)}}, app.DistrKeeper.GetValidatorCurrentRewards(ctx, valAddrs[0]).Rewards)
require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(2325, 2)}}, distrKeeper.GetValidatorCurrentRewards(ctx, valAddrs[0]).Rewards)
// proposer reward + staking.proportional for second proposer = (5 % + 0.5 * (93%)) * 100 = 51.5
require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(515, 1)}}, app.DistrKeeper.GetValidatorCurrentRewards(ctx, valAddrs[1]).Rewards)
require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(515, 1)}}, distrKeeper.GetValidatorCurrentRewards(ctx, valAddrs[1]).Rewards)
}
func TestAllocateTokensTruncation(t *testing.T) {
app := simapp.Setup(t, false)
var (
accountKeeper authkeeper.AccountKeeper
bankKeeper bankkeeper.Keeper
distrKeeper keeper.Keeper
stakingKeeper *stakingkeeper.Keeper
)
app, err := simtestutil.Setup(testutil.AppConfig,
&accountKeeper,
&bankKeeper,
&distrKeeper,
&stakingKeeper,
)
require.NoError(t, err)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
// reset fee pool
app.DistrKeeper.SetFeePool(ctx, disttypes.InitialFeePool())
distrKeeper.SetFeePool(ctx, disttypes.InitialFeePool())
addrs := simapp.AddTestAddrs(app, ctx, 3, sdk.NewInt(1234))
valAddrs := simapp.ConvertAddrsToValAddrs(addrs)
tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper)
addrs := simtestutil.AddTestAddrs(bankKeeper, stakingKeeper, ctx, 3, sdk.NewInt(1234))
valAddrs := simtestutil.ConvertAddrsToValAddrs(addrs)
tstaking := teststaking.NewHelper(t, ctx, stakingKeeper)
// create validator with 10% commission
tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(1, 1), sdk.NewDecWithPrec(1, 1), sdk.NewDec(0))
@@ -156,24 +201,24 @@ func TestAllocateTokensTruncation(t *testing.T) {
}
// assert initial state: zero outstanding rewards, zero community pool, zero commission, zero current rewards
require.True(t, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[0]).Rewards.IsZero())
require.True(t, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[1]).Rewards.IsZero())
require.True(t, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[1]).Rewards.IsZero())
require.True(t, app.DistrKeeper.GetFeePool(ctx).CommunityPool.IsZero())
require.True(t, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission.IsZero())
require.True(t, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[1]).Commission.IsZero())
require.True(t, app.DistrKeeper.GetValidatorCurrentRewards(ctx, valAddrs[0]).Rewards.IsZero())
require.True(t, app.DistrKeeper.GetValidatorCurrentRewards(ctx, valAddrs[1]).Rewards.IsZero())
require.True(t, distrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[0]).Rewards.IsZero())
require.True(t, distrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[1]).Rewards.IsZero())
require.True(t, distrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[1]).Rewards.IsZero())
require.True(t, distrKeeper.GetFeePool(ctx).CommunityPool.IsZero())
require.True(t, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission.IsZero())
require.True(t, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[1]).Commission.IsZero())
require.True(t, distrKeeper.GetValidatorCurrentRewards(ctx, valAddrs[0]).Rewards.IsZero())
require.True(t, distrKeeper.GetValidatorCurrentRewards(ctx, valAddrs[1]).Rewards.IsZero())
// allocate tokens as if both had voted and second was proposer
fees := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(634195840)))
feeCollector := app.AccountKeeper.GetModuleAccount(ctx, types.FeeCollectorName)
feeCollector := accountKeeper.GetModuleAccount(ctx, types.FeeCollectorName)
require.NotNil(t, feeCollector)
require.NoError(t, testutil.FundModuleAccount(app.BankKeeper, ctx, feeCollector.GetName(), fees))
require.NoError(t, banktestutil.FundModuleAccount(bankKeeper, ctx, feeCollector.GetName(), fees))
app.AccountKeeper.SetAccount(ctx, feeCollector)
accountKeeper.SetAccount(ctx, feeCollector)
votes := []abci.VoteInfo{
{
@@ -189,9 +234,9 @@ func TestAllocateTokensTruncation(t *testing.T) {
SignedLastBlock: true,
},
}
app.DistrKeeper.AllocateTokens(ctx, 31, 31, sdk.ConsAddress(valConsPk2.Address()), votes)
distrKeeper.AllocateTokens(ctx, 31, 31, sdk.ConsAddress(valConsPk2.Address()), votes)
require.True(t, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[0]).Rewards.IsValid())
require.True(t, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[1]).Rewards.IsValid())
require.True(t, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[2]).Rewards.IsValid())
require.True(t, distrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[0]).Rewards.IsValid())
require.True(t, distrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[1]).Rewards.IsValid())
require.True(t, distrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[2]).Rewards.IsValid())
}
+2 -2
View File
@@ -1,14 +1,14 @@
package keeper_test
import (
"github.com/cosmos/cosmos-sdk/simapp"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/cosmos/cosmos-sdk/x/distribution/types"
)
var (
PKS = simapp.CreateTestPubKeys(5)
PKS = simtestutil.CreateTestPubKeys(5)
valConsPk1 = PKS[0]
valConsPk2 = PKS[1]
+298 -179
View File
@@ -6,49 +6,66 @@ import (
"github.com/stretchr/testify/require"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/cosmos/cosmos-sdk/simapp"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/bank/testutil"
authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper"
bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper"
banktestutil "github.com/cosmos/cosmos-sdk/x/bank/testutil"
"github.com/cosmos/cosmos-sdk/x/distribution/keeper"
"github.com/cosmos/cosmos-sdk/x/distribution/testutil"
"github.com/cosmos/cosmos-sdk/x/staking"
stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
"github.com/cosmos/cosmos-sdk/x/staking/teststaking"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)
func TestCalculateRewardsBasic(t *testing.T) {
app := simapp.Setup(t, false)
var (
bankKeeper bankkeeper.Keeper
distrKeeper keeper.Keeper
stakingKeeper *stakingkeeper.Keeper
)
app, err := simtestutil.Setup(testutil.AppConfig,
&bankKeeper,
&distrKeeper,
&stakingKeeper,
)
require.NoError(t, err)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
app.DistrKeeper.DeleteAllValidatorHistoricalRewards(ctx)
distrKeeper.DeleteAllValidatorHistoricalRewards(ctx)
tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper)
tstaking := teststaking.NewHelper(t, ctx, stakingKeeper)
addr := simapp.AddTestAddrs(app, ctx, 2, sdk.NewInt(1000))
valAddrs := simapp.ConvertAddrsToValAddrs(addr)
addr := simtestutil.AddTestAddrs(bankKeeper, stakingKeeper, ctx, 2, sdk.NewInt(1000))
valAddrs := simtestutil.ConvertAddrsToValAddrs(addr)
// create validator with 50% commission
tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0))
tstaking.CreateValidator(valAddrs[0], valConsPk1, sdk.NewInt(100), true)
// end block to bond validator and start new block
staking.EndBlocker(ctx, app.StakingKeeper)
staking.EndBlocker(ctx, stakingKeeper)
ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1)
tstaking.Ctx = ctx
// fetch validator and delegation
val := app.StakingKeeper.Validator(ctx, valAddrs[0])
del := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0])
val := stakingKeeper.Validator(ctx, valAddrs[0])
del := stakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0])
// historical count should be 2 (once for validator init, once for delegation init)
require.Equal(t, uint64(2), app.DistrKeeper.GetValidatorHistoricalReferenceCount(ctx))
require.Equal(t, uint64(2), distrKeeper.GetValidatorHistoricalReferenceCount(ctx))
// end period
endingPeriod := app.DistrKeeper.IncrementValidatorPeriod(ctx, val)
endingPeriod := distrKeeper.IncrementValidatorPeriod(ctx, val)
// historical count should be 2 still
require.Equal(t, uint64(2), app.DistrKeeper.GetValidatorHistoricalReferenceCount(ctx))
require.Equal(t, uint64(2), distrKeeper.GetValidatorHistoricalReferenceCount(ctx))
// calculate delegation rewards
rewards := app.DistrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod)
rewards := distrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod)
// rewards should be zero
require.True(t, rewards.IsZero())
@@ -56,28 +73,40 @@ func TestCalculateRewardsBasic(t *testing.T) {
// allocate some rewards
initial := int64(10)
tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial)}}
app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens)
distrKeeper.AllocateTokensToValidator(ctx, val, tokens)
// end period
endingPeriod = app.DistrKeeper.IncrementValidatorPeriod(ctx, val)
endingPeriod = distrKeeper.IncrementValidatorPeriod(ctx, val)
// calculate delegation rewards
rewards = app.DistrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod)
rewards = distrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod)
// rewards should be half the tokens
require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial / 2)}}, rewards)
// commission should be the other half
require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial / 2)}}, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission)
require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial / 2)}}, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission)
}
func TestCalculateRewardsAfterSlash(t *testing.T) {
app := simapp.Setup(t, false)
var (
bankKeeper bankkeeper.Keeper
distrKeeper keeper.Keeper
stakingKeeper *stakingkeeper.Keeper
)
app, err := simtestutil.Setup(testutil.AppConfig,
&bankKeeper,
&distrKeeper,
&stakingKeeper,
)
require.NoError(t, err)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
addr := simapp.AddTestAddrs(app, ctx, 2, sdk.NewInt(100000000))
valAddrs := simapp.ConvertAddrsToValAddrs(addr)
tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper)
addr := simtestutil.AddTestAddrs(bankKeeper, stakingKeeper, ctx, 2, sdk.NewInt(100000000))
valAddrs := simtestutil.ConvertAddrsToValAddrs(addr)
tstaking := teststaking.NewHelper(t, ctx, stakingKeeper)
// create validator with 50% commission
tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0))
@@ -85,20 +114,20 @@ func TestCalculateRewardsAfterSlash(t *testing.T) {
tstaking.CreateValidatorWithValPower(valAddrs[0], valConsPk1, valPower, true)
// end block to bond validator
staking.EndBlocker(ctx, app.StakingKeeper)
staking.EndBlocker(ctx, stakingKeeper)
// next block
ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1)
// fetch validator and delegation
val := app.StakingKeeper.Validator(ctx, valAddrs[0])
del := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0])
val := stakingKeeper.Validator(ctx, valAddrs[0])
del := stakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0])
// end period
endingPeriod := app.DistrKeeper.IncrementValidatorPeriod(ctx, val)
endingPeriod := distrKeeper.IncrementValidatorPeriod(ctx, val)
// calculate delegation rewards
rewards := app.DistrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod)
rewards := distrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod)
// rewards should be zero
require.True(t, rewards.IsZero())
@@ -107,40 +136,52 @@ func TestCalculateRewardsAfterSlash(t *testing.T) {
ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3)
// slash the validator by 50%
app.StakingKeeper.Slash(ctx, valConsAddr1, ctx.BlockHeight(), valPower, sdk.NewDecWithPrec(5, 1))
stakingKeeper.Slash(ctx, valConsAddr1, ctx.BlockHeight(), valPower, sdk.NewDecWithPrec(5, 1))
// retrieve validator
val = app.StakingKeeper.Validator(ctx, valAddrs[0])
val = stakingKeeper.Validator(ctx, valAddrs[0])
// increase block height
ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3)
// allocate some rewards
initial := app.StakingKeeper.TokensFromConsensusPower(ctx, 10)
initial := stakingKeeper.TokensFromConsensusPower(ctx, 10)
tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecFromInt(initial)}}
app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens)
distrKeeper.AllocateTokensToValidator(ctx, val, tokens)
// end period
endingPeriod = app.DistrKeeper.IncrementValidatorPeriod(ctx, val)
endingPeriod = distrKeeper.IncrementValidatorPeriod(ctx, val)
// calculate delegation rewards
rewards = app.DistrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod)
rewards = distrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod)
// rewards should be half the tokens
require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecFromInt(initial.QuoRaw(2))}}, rewards)
// commission should be the other half
require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecFromInt(initial.QuoRaw(2))}},
app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission)
distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission)
}
func TestCalculateRewardsAfterManySlashes(t *testing.T) {
app := simapp.Setup(t, false)
var (
bankKeeper bankkeeper.Keeper
distrKeeper keeper.Keeper
stakingKeeper *stakingkeeper.Keeper
)
app, err := simtestutil.Setup(testutil.AppConfig,
&bankKeeper,
&distrKeeper,
&stakingKeeper,
)
require.NoError(t, err)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper)
addr := simapp.AddTestAddrs(app, ctx, 2, sdk.NewInt(100000000))
valAddrs := simapp.ConvertAddrsToValAddrs(addr)
tstaking := teststaking.NewHelper(t, ctx, stakingKeeper)
addr := simtestutil.AddTestAddrs(bankKeeper, stakingKeeper, ctx, 2, sdk.NewInt(100000000))
valAddrs := simtestutil.ConvertAddrsToValAddrs(addr)
// create validator with 50% commission
valPower := int64(100)
@@ -148,20 +189,20 @@ func TestCalculateRewardsAfterManySlashes(t *testing.T) {
tstaking.CreateValidatorWithValPower(valAddrs[0], valConsPk1, valPower, true)
// end block to bond validator
staking.EndBlocker(ctx, app.StakingKeeper)
staking.EndBlocker(ctx, stakingKeeper)
// next block
ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1)
// fetch validator and delegation
val := app.StakingKeeper.Validator(ctx, valAddrs[0])
del := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0])
val := stakingKeeper.Validator(ctx, valAddrs[0])
del := stakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0])
// end period
endingPeriod := app.DistrKeeper.IncrementValidatorPeriod(ctx, val)
endingPeriod := distrKeeper.IncrementValidatorPeriod(ctx, val)
// calculate delegation rewards
rewards := app.DistrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod)
rewards := distrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod)
// rewards should be zero
require.True(t, rewards.IsZero())
@@ -170,124 +211,150 @@ func TestCalculateRewardsAfterManySlashes(t *testing.T) {
ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3)
// slash the validator by 50%
app.StakingKeeper.Slash(ctx, valConsAddr1, ctx.BlockHeight(), valPower, sdk.NewDecWithPrec(5, 1))
stakingKeeper.Slash(ctx, valConsAddr1, ctx.BlockHeight(), valPower, sdk.NewDecWithPrec(5, 1))
// fetch the validator again
val = app.StakingKeeper.Validator(ctx, valAddrs[0])
val = stakingKeeper.Validator(ctx, valAddrs[0])
// increase block height
ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3)
// allocate some rewards
initial := app.StakingKeeper.TokensFromConsensusPower(ctx, 10)
initial := stakingKeeper.TokensFromConsensusPower(ctx, 10)
tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecFromInt(initial)}}
app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens)
distrKeeper.AllocateTokensToValidator(ctx, val, tokens)
// slash the validator by 50% again
app.StakingKeeper.Slash(ctx, valConsAddr1, ctx.BlockHeight(), valPower/2, sdk.NewDecWithPrec(5, 1))
stakingKeeper.Slash(ctx, valConsAddr1, ctx.BlockHeight(), valPower/2, sdk.NewDecWithPrec(5, 1))
// fetch the validator again
val = app.StakingKeeper.Validator(ctx, valAddrs[0])
val = stakingKeeper.Validator(ctx, valAddrs[0])
// increase block height
ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3)
// allocate some more rewards
app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens)
distrKeeper.AllocateTokensToValidator(ctx, val, tokens)
// end period
endingPeriod = app.DistrKeeper.IncrementValidatorPeriod(ctx, val)
endingPeriod = distrKeeper.IncrementValidatorPeriod(ctx, val)
// calculate delegation rewards
rewards = app.DistrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod)
rewards = distrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod)
// rewards should be half the tokens
require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecFromInt(initial)}}, rewards)
// commission should be the other half
require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecFromInt(initial)}},
app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission)
distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission)
}
func TestCalculateRewardsMultiDelegator(t *testing.T) {
app := simapp.Setup(t, false)
var (
bankKeeper bankkeeper.Keeper
distrKeeper keeper.Keeper
stakingKeeper *stakingkeeper.Keeper
)
app, err := simtestutil.Setup(testutil.AppConfig,
&bankKeeper,
&distrKeeper,
&stakingKeeper,
)
require.NoError(t, err)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper)
addr := simapp.AddTestAddrs(app, ctx, 2, sdk.NewInt(100000000))
valAddrs := simapp.ConvertAddrsToValAddrs(addr)
tstaking := teststaking.NewHelper(t, ctx, stakingKeeper)
addr := simtestutil.AddTestAddrs(bankKeeper, stakingKeeper, ctx, 2, sdk.NewInt(100000000))
valAddrs := simtestutil.ConvertAddrsToValAddrs(addr)
// create validator with 50% commission
tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0))
tstaking.CreateValidator(valAddrs[0], valConsPk1, sdk.NewInt(100), true)
// end block to bond validator
staking.EndBlocker(ctx, app.StakingKeeper)
staking.EndBlocker(ctx, stakingKeeper)
// next block
ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1)
// fetch validator and delegation
val := app.StakingKeeper.Validator(ctx, valAddrs[0])
del1 := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0])
val := stakingKeeper.Validator(ctx, valAddrs[0])
del1 := stakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0])
// allocate some rewards
initial := int64(20)
tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial)}}
app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens)
distrKeeper.AllocateTokensToValidator(ctx, val, tokens)
// second delegation
tstaking.Ctx = ctx
tstaking.Delegate(sdk.AccAddress(valAddrs[1]), valAddrs[0], sdk.NewInt(100))
del2 := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[1]), valAddrs[0])
del2 := stakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[1]), valAddrs[0])
// fetch updated validator
val = app.StakingKeeper.Validator(ctx, valAddrs[0])
val = stakingKeeper.Validator(ctx, valAddrs[0])
// end block
staking.EndBlocker(ctx, app.StakingKeeper)
staking.EndBlocker(ctx, stakingKeeper)
// next block
ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1)
// allocate some more rewards
app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens)
distrKeeper.AllocateTokensToValidator(ctx, val, tokens)
// end period
endingPeriod := app.DistrKeeper.IncrementValidatorPeriod(ctx, val)
endingPeriod := distrKeeper.IncrementValidatorPeriod(ctx, val)
// calculate delegation rewards for del1
rewards := app.DistrKeeper.CalculateDelegationRewards(ctx, val, del1, endingPeriod)
rewards := distrKeeper.CalculateDelegationRewards(ctx, val, del1, endingPeriod)
// rewards for del1 should be 3/4 initial
require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial * 3 / 4)}}, rewards)
// calculate delegation rewards for del2
rewards = app.DistrKeeper.CalculateDelegationRewards(ctx, val, del2, endingPeriod)
rewards = distrKeeper.CalculateDelegationRewards(ctx, val, del2, endingPeriod)
// rewards for del2 should be 1/4 initial
require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial * 1 / 4)}}, rewards)
// commission should be equal to initial (50% twice)
require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial)}}, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission)
require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial)}}, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission)
}
func TestWithdrawDelegationRewardsBasic(t *testing.T) {
app := simapp.Setup(t, false)
var (
accountKeeper authkeeper.AccountKeeper
bankKeeper bankkeeper.Keeper
distrKeeper keeper.Keeper
stakingKeeper *stakingkeeper.Keeper
)
app, err := simtestutil.Setup(testutil.AppConfig,
&accountKeeper,
&bankKeeper,
&distrKeeper,
&stakingKeeper,
)
require.NoError(t, err)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
app.DistrKeeper.DeleteAllValidatorHistoricalRewards(ctx)
distrKeeper.DeleteAllValidatorHistoricalRewards(ctx)
balancePower := int64(1000)
balanceTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, balancePower)
addr := simapp.AddTestAddrs(app, ctx, 1, sdk.NewInt(1000000000))
valAddrs := simapp.ConvertAddrsToValAddrs(addr)
tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper)
balanceTokens := stakingKeeper.TokensFromConsensusPower(ctx, balancePower)
addr := simtestutil.AddTestAddrs(bankKeeper, stakingKeeper, ctx, 1, sdk.NewInt(1000000000))
valAddrs := simtestutil.ConvertAddrsToValAddrs(addr)
tstaking := teststaking.NewHelper(t, ctx, stakingKeeper)
// set module account coins
distrAcc := app.DistrKeeper.GetDistributionAccount(ctx)
require.NoError(t, testutil.FundModuleAccount(app.BankKeeper, ctx, distrAcc.GetName(), sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, balanceTokens))))
app.AccountKeeper.SetModuleAccount(ctx, distrAcc)
distrAcc := distrKeeper.GetDistributionAccount(ctx)
require.NoError(t, banktestutil.FundModuleAccount(bankKeeper, ctx, distrAcc.GetName(), sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, balanceTokens))))
accountKeeper.SetModuleAccount(ctx, distrAcc)
// create validator with 50% commission
power := int64(100)
@@ -298,60 +365,72 @@ func TestWithdrawDelegationRewardsBasic(t *testing.T) {
expTokens := balanceTokens.Sub(valTokens)
require.Equal(t,
sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, expTokens)},
app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(valAddrs[0])),
bankKeeper.GetAllBalances(ctx, sdk.AccAddress(valAddrs[0])),
)
// end block to bond validator
staking.EndBlocker(ctx, app.StakingKeeper)
staking.EndBlocker(ctx, stakingKeeper)
// next block
ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1)
// fetch validator and delegation
val := app.StakingKeeper.Validator(ctx, valAddrs[0])
val := stakingKeeper.Validator(ctx, valAddrs[0])
// allocate some rewards
initial := app.StakingKeeper.TokensFromConsensusPower(ctx, 10)
initial := stakingKeeper.TokensFromConsensusPower(ctx, 10)
tokens := sdk.DecCoins{sdk.NewDecCoin(sdk.DefaultBondDenom, initial)}
app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens)
distrKeeper.AllocateTokensToValidator(ctx, val, tokens)
// historical count should be 2 (initial + latest for delegation)
require.Equal(t, uint64(2), app.DistrKeeper.GetValidatorHistoricalReferenceCount(ctx))
require.Equal(t, uint64(2), distrKeeper.GetValidatorHistoricalReferenceCount(ctx))
// withdraw rewards
_, err := app.DistrKeeper.WithdrawDelegationRewards(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0])
_, err = distrKeeper.WithdrawDelegationRewards(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0])
require.Nil(t, err)
// historical count should still be 2 (added one record, cleared one)
require.Equal(t, uint64(2), app.DistrKeeper.GetValidatorHistoricalReferenceCount(ctx))
require.Equal(t, uint64(2), distrKeeper.GetValidatorHistoricalReferenceCount(ctx))
// assert correct balance
exp := balanceTokens.Sub(valTokens).Add(initial.QuoRaw(2))
require.Equal(t,
sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, exp)},
app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(valAddrs[0])),
bankKeeper.GetAllBalances(ctx, sdk.AccAddress(valAddrs[0])),
)
// withdraw commission
_, err = app.DistrKeeper.WithdrawValidatorCommission(ctx, valAddrs[0])
_, err = distrKeeper.WithdrawValidatorCommission(ctx, valAddrs[0])
require.Nil(t, err)
// assert correct balance
exp = balanceTokens.Sub(valTokens).Add(initial)
require.Equal(t,
sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, exp)},
app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(valAddrs[0])),
bankKeeper.GetAllBalances(ctx, sdk.AccAddress(valAddrs[0])),
)
}
func TestCalculateRewardsAfterManySlashesInSameBlock(t *testing.T) {
app := simapp.Setup(t, false)
var (
bankKeeper bankkeeper.Keeper
distrKeeper keeper.Keeper
stakingKeeper *stakingkeeper.Keeper
)
app, err := simtestutil.Setup(testutil.AppConfig,
&bankKeeper,
&distrKeeper,
&stakingKeeper,
)
require.NoError(t, err)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
addr := simapp.AddTestAddrs(app, ctx, 1, sdk.NewInt(1000000000))
valAddrs := simapp.ConvertAddrsToValAddrs(addr)
tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper)
addr := simtestutil.AddTestAddrs(bankKeeper, stakingKeeper, ctx, 1, sdk.NewInt(1000000000))
valAddrs := simtestutil.ConvertAddrsToValAddrs(addr)
tstaking := teststaking.NewHelper(t, ctx, stakingKeeper)
// create validator with 50% commission
valPower := int64(100)
@@ -359,20 +438,20 @@ func TestCalculateRewardsAfterManySlashesInSameBlock(t *testing.T) {
tstaking.CreateValidatorWithValPower(valAddrs[0], valConsPk1, valPower, true)
// end block to bond validator
staking.EndBlocker(ctx, app.StakingKeeper)
staking.EndBlocker(ctx, stakingKeeper)
// next block
ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1)
// fetch validator and delegation
val := app.StakingKeeper.Validator(ctx, valAddrs[0])
del := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0])
val := stakingKeeper.Validator(ctx, valAddrs[0])
del := stakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0])
// end period
endingPeriod := app.DistrKeeper.IncrementValidatorPeriod(ctx, val)
endingPeriod := distrKeeper.IncrementValidatorPeriod(ctx, val)
// calculate delegation rewards
rewards := app.DistrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod)
rewards := distrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod)
// rewards should be zero
require.True(t, rewards.IsZero())
@@ -381,45 +460,57 @@ func TestCalculateRewardsAfterManySlashesInSameBlock(t *testing.T) {
ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3)
// allocate some rewards
initial := sdk.NewDecFromInt(app.StakingKeeper.TokensFromConsensusPower(ctx, 10))
initial := sdk.NewDecFromInt(stakingKeeper.TokensFromConsensusPower(ctx, 10))
tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}}
app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens)
distrKeeper.AllocateTokensToValidator(ctx, val, tokens)
// slash the validator by 50%
app.StakingKeeper.Slash(ctx, valConsAddr1, ctx.BlockHeight(), valPower, sdk.NewDecWithPrec(5, 1))
stakingKeeper.Slash(ctx, valConsAddr1, ctx.BlockHeight(), valPower, sdk.NewDecWithPrec(5, 1))
// slash the validator by 50% again
app.StakingKeeper.Slash(ctx, valConsAddr1, ctx.BlockHeight(), valPower/2, sdk.NewDecWithPrec(5, 1))
stakingKeeper.Slash(ctx, valConsAddr1, ctx.BlockHeight(), valPower/2, sdk.NewDecWithPrec(5, 1))
// fetch the validator again
val = app.StakingKeeper.Validator(ctx, valAddrs[0])
val = stakingKeeper.Validator(ctx, valAddrs[0])
// increase block height
ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3)
// allocate some more rewards
app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens)
distrKeeper.AllocateTokensToValidator(ctx, val, tokens)
// end period
endingPeriod = app.DistrKeeper.IncrementValidatorPeriod(ctx, val)
endingPeriod = distrKeeper.IncrementValidatorPeriod(ctx, val)
// calculate delegation rewards
rewards = app.DistrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod)
rewards = distrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod)
// rewards should be half the tokens
require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}}, rewards)
// commission should be the other half
require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}}, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission)
require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}}, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission)
}
func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) {
app := simapp.Setup(t, false)
var (
bankKeeper bankkeeper.Keeper
distrKeeper keeper.Keeper
stakingKeeper *stakingkeeper.Keeper
)
app, err := simtestutil.Setup(testutil.AppConfig,
&bankKeeper,
&distrKeeper,
&stakingKeeper,
)
require.NoError(t, err)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper)
addr := simapp.AddTestAddrs(app, ctx, 2, sdk.NewInt(1000000000))
valAddrs := simapp.ConvertAddrsToValAddrs(addr)
tstaking := teststaking.NewHelper(t, ctx, stakingKeeper)
addr := simtestutil.AddTestAddrs(bankKeeper, stakingKeeper, ctx, 2, sdk.NewInt(1000000000))
valAddrs := simtestutil.ConvertAddrsToValAddrs(addr)
// create validator with 50% commission
tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0))
@@ -427,81 +518,95 @@ func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) {
tstaking.CreateValidatorWithValPower(valAddrs[0], valConsPk1, valPower, true)
// end block to bond validator
staking.EndBlocker(ctx, app.StakingKeeper)
staking.EndBlocker(ctx, stakingKeeper)
// next block
ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1)
// fetch validator and delegation
val := app.StakingKeeper.Validator(ctx, valAddrs[0])
del1 := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0])
val := stakingKeeper.Validator(ctx, valAddrs[0])
del1 := stakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0])
// allocate some rewards
initial := sdk.NewDecFromInt(app.StakingKeeper.TokensFromConsensusPower(ctx, 30))
initial := sdk.NewDecFromInt(stakingKeeper.TokensFromConsensusPower(ctx, 30))
tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}}
app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens)
distrKeeper.AllocateTokensToValidator(ctx, val, tokens)
// slash the validator
ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3)
app.StakingKeeper.Slash(ctx, valConsAddr1, ctx.BlockHeight(), valPower, sdk.NewDecWithPrec(5, 1))
stakingKeeper.Slash(ctx, valConsAddr1, ctx.BlockHeight(), valPower, sdk.NewDecWithPrec(5, 1))
ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3)
// second delegation
tstaking.DelegateWithPower(sdk.AccAddress(valAddrs[1]), valAddrs[0], 100)
del2 := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[1]), valAddrs[0])
del2 := stakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[1]), valAddrs[0])
// end block
staking.EndBlocker(ctx, app.StakingKeeper)
staking.EndBlocker(ctx, stakingKeeper)
// next block
ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1)
// allocate some more rewards
app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens)
distrKeeper.AllocateTokensToValidator(ctx, val, tokens)
// slash the validator again
ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3)
app.StakingKeeper.Slash(ctx, valConsAddr1, ctx.BlockHeight(), valPower, sdk.NewDecWithPrec(5, 1))
stakingKeeper.Slash(ctx, valConsAddr1, ctx.BlockHeight(), valPower, sdk.NewDecWithPrec(5, 1))
ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3)
// fetch updated validator
val = app.StakingKeeper.Validator(ctx, valAddrs[0])
val = stakingKeeper.Validator(ctx, valAddrs[0])
// end period
endingPeriod := app.DistrKeeper.IncrementValidatorPeriod(ctx, val)
endingPeriod := distrKeeper.IncrementValidatorPeriod(ctx, val)
// calculate delegation rewards for del1
rewards := app.DistrKeeper.CalculateDelegationRewards(ctx, val, del1, endingPeriod)
rewards := distrKeeper.CalculateDelegationRewards(ctx, val, del1, endingPeriod)
// rewards for del1 should be 2/3 initial (half initial first period, 1/6 initial second period)
require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.QuoInt64(2).Add(initial.QuoInt64(6))}}, rewards)
// calculate delegation rewards for del2
rewards = app.DistrKeeper.CalculateDelegationRewards(ctx, val, del2, endingPeriod)
rewards = distrKeeper.CalculateDelegationRewards(ctx, val, del2, endingPeriod)
// rewards for del2 should be initial / 3
require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.QuoInt64(3)}}, rewards)
// commission should be equal to initial (twice 50% commission, unaffected by slashing)
require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}}, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission)
require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}}, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission)
}
func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) {
app := simapp.Setup(t, false)
var (
accountKeeper authkeeper.AccountKeeper
bankKeeper bankkeeper.Keeper
distrKeeper keeper.Keeper
stakingKeeper *stakingkeeper.Keeper
)
app, err := simtestutil.Setup(testutil.AppConfig,
&accountKeeper,
&bankKeeper,
&distrKeeper,
&stakingKeeper,
)
require.NoError(t, err)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
app.DistrKeeper.DeleteAllValidatorHistoricalRewards(ctx)
distrKeeper.DeleteAllValidatorHistoricalRewards(ctx)
tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper)
addr := simapp.AddTestAddrs(app, ctx, 2, sdk.NewInt(1000000000))
valAddrs := simapp.ConvertAddrsToValAddrs(addr)
tstaking := teststaking.NewHelper(t, ctx, stakingKeeper)
addr := simtestutil.AddTestAddrs(bankKeeper, stakingKeeper, ctx, 2, sdk.NewInt(1000000000))
valAddrs := simtestutil.ConvertAddrsToValAddrs(addr)
initial := int64(20)
// set module account coins
distrAcc := app.DistrKeeper.GetDistributionAccount(ctx)
require.NoError(t, testutil.FundModuleAccount(app.BankKeeper, ctx, distrAcc.GetName(), sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1000)))))
app.AccountKeeper.SetModuleAccount(ctx, distrAcc)
distrAcc := distrKeeper.GetDistributionAccount(ctx)
require.NoError(t, banktestutil.FundModuleAccount(bankKeeper, ctx, distrAcc.GetName(), sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1000)))))
accountKeeper.SetModuleAccount(ctx, distrAcc)
tokens := sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, sdk.NewDec(initial))}
@@ -510,178 +615,192 @@ func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) {
tstaking.CreateValidator(valAddrs[0], valConsPk1, sdk.NewInt(100), true)
// end block to bond validator
staking.EndBlocker(ctx, app.StakingKeeper)
staking.EndBlocker(ctx, stakingKeeper)
// next block
ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1)
// fetch validator and delegation
val := app.StakingKeeper.Validator(ctx, valAddrs[0])
del1 := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0])
val := stakingKeeper.Validator(ctx, valAddrs[0])
del1 := stakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0])
// allocate some rewards
app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens)
distrKeeper.AllocateTokensToValidator(ctx, val, tokens)
// historical count should be 2 (validator init, delegation init)
require.Equal(t, uint64(2), app.DistrKeeper.GetValidatorHistoricalReferenceCount(ctx))
require.Equal(t, uint64(2), distrKeeper.GetValidatorHistoricalReferenceCount(ctx))
// second delegation
tstaking.Delegate(sdk.AccAddress(valAddrs[1]), valAddrs[0], sdk.NewInt(100))
// historical count should be 3 (second delegation init)
require.Equal(t, uint64(3), app.DistrKeeper.GetValidatorHistoricalReferenceCount(ctx))
require.Equal(t, uint64(3), distrKeeper.GetValidatorHistoricalReferenceCount(ctx))
// fetch updated validator
val = app.StakingKeeper.Validator(ctx, valAddrs[0])
del2 := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[1]), valAddrs[0])
val = stakingKeeper.Validator(ctx, valAddrs[0])
del2 := stakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[1]), valAddrs[0])
// end block
staking.EndBlocker(ctx, app.StakingKeeper)
staking.EndBlocker(ctx, stakingKeeper)
// next block
ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1)
// allocate some more rewards
app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens)
distrKeeper.AllocateTokensToValidator(ctx, val, tokens)
// first delegator withdraws
_, err := app.DistrKeeper.WithdrawDelegationRewards(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0])
_, err = distrKeeper.WithdrawDelegationRewards(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0])
require.NoError(t, err)
// second delegator withdraws
_, err = app.DistrKeeper.WithdrawDelegationRewards(ctx, sdk.AccAddress(valAddrs[1]), valAddrs[0])
_, err = distrKeeper.WithdrawDelegationRewards(ctx, sdk.AccAddress(valAddrs[1]), valAddrs[0])
require.NoError(t, err)
// historical count should be 3 (validator init + two delegations)
require.Equal(t, uint64(3), app.DistrKeeper.GetValidatorHistoricalReferenceCount(ctx))
require.Equal(t, uint64(3), distrKeeper.GetValidatorHistoricalReferenceCount(ctx))
// validator withdraws commission
_, err = app.DistrKeeper.WithdrawValidatorCommission(ctx, valAddrs[0])
_, err = distrKeeper.WithdrawValidatorCommission(ctx, valAddrs[0])
require.NoError(t, err)
// end period
endingPeriod := app.DistrKeeper.IncrementValidatorPeriod(ctx, val)
endingPeriod := distrKeeper.IncrementValidatorPeriod(ctx, val)
// calculate delegation rewards for del1
rewards := app.DistrKeeper.CalculateDelegationRewards(ctx, val, del1, endingPeriod)
rewards := distrKeeper.CalculateDelegationRewards(ctx, val, del1, endingPeriod)
// rewards for del1 should be zero
require.True(t, rewards.IsZero())
// calculate delegation rewards for del2
rewards = app.DistrKeeper.CalculateDelegationRewards(ctx, val, del2, endingPeriod)
rewards = distrKeeper.CalculateDelegationRewards(ctx, val, del2, endingPeriod)
// rewards for del2 should be zero
require.True(t, rewards.IsZero())
// commission should be zero
require.True(t, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission.IsZero())
require.True(t, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission.IsZero())
// next block
ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1)
// allocate some more rewards
app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens)
distrKeeper.AllocateTokensToValidator(ctx, val, tokens)
// first delegator withdraws again
_, err = app.DistrKeeper.WithdrawDelegationRewards(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0])
_, err = distrKeeper.WithdrawDelegationRewards(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0])
require.NoError(t, err)
// end period
endingPeriod = app.DistrKeeper.IncrementValidatorPeriod(ctx, val)
endingPeriod = distrKeeper.IncrementValidatorPeriod(ctx, val)
// calculate delegation rewards for del1
rewards = app.DistrKeeper.CalculateDelegationRewards(ctx, val, del1, endingPeriod)
rewards = distrKeeper.CalculateDelegationRewards(ctx, val, del1, endingPeriod)
// rewards for del1 should be zero
require.True(t, rewards.IsZero())
// calculate delegation rewards for del2
rewards = app.DistrKeeper.CalculateDelegationRewards(ctx, val, del2, endingPeriod)
rewards = distrKeeper.CalculateDelegationRewards(ctx, val, del2, endingPeriod)
// rewards for del2 should be 1/4 initial
require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial / 4)}}, rewards)
// commission should be half initial
require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial / 2)}}, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission)
require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial / 2)}}, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission)
// next block
ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1)
// allocate some more rewards
app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens)
distrKeeper.AllocateTokensToValidator(ctx, val, tokens)
// withdraw commission
_, err = app.DistrKeeper.WithdrawValidatorCommission(ctx, valAddrs[0])
_, err = distrKeeper.WithdrawValidatorCommission(ctx, valAddrs[0])
require.NoError(t, err)
// end period
endingPeriod = app.DistrKeeper.IncrementValidatorPeriod(ctx, val)
endingPeriod = distrKeeper.IncrementValidatorPeriod(ctx, val)
// calculate delegation rewards for del1
rewards = app.DistrKeeper.CalculateDelegationRewards(ctx, val, del1, endingPeriod)
rewards = distrKeeper.CalculateDelegationRewards(ctx, val, del1, endingPeriod)
// rewards for del1 should be 1/4 initial
require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial / 4)}}, rewards)
// calculate delegation rewards for del2
rewards = app.DistrKeeper.CalculateDelegationRewards(ctx, val, del2, endingPeriod)
rewards = distrKeeper.CalculateDelegationRewards(ctx, val, del2, endingPeriod)
// rewards for del2 should be 1/2 initial
require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial / 2)}}, rewards)
// commission should be zero
require.True(t, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission.IsZero())
require.True(t, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission.IsZero())
}
func Test100PercentCommissionReward(t *testing.T) {
app := simapp.Setup(t, false)
var (
accountKeeper authkeeper.AccountKeeper
bankKeeper bankkeeper.Keeper
distrKeeper keeper.Keeper
stakingKeeper *stakingkeeper.Keeper
)
app, err := simtestutil.Setup(testutil.AppConfig,
&accountKeeper,
&bankKeeper,
&distrKeeper,
&stakingKeeper,
)
require.NoError(t, err)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper)
addr := simapp.AddTestAddrs(app, ctx, 2, sdk.NewInt(1000000000))
valAddrs := simapp.ConvertAddrsToValAddrs(addr)
tstaking := teststaking.NewHelper(t, ctx, stakingKeeper)
addr := simtestutil.AddTestAddrs(bankKeeper, stakingKeeper, ctx, 2, sdk.NewInt(1000000000))
valAddrs := simtestutil.ConvertAddrsToValAddrs(addr)
initial := int64(20)
// set module account coins
distrAcc := app.DistrKeeper.GetDistributionAccount(ctx)
require.NoError(t, testutil.FundModuleAccount(app.BankKeeper, ctx, distrAcc.GetName(), sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1000)))))
app.AccountKeeper.SetModuleAccount(ctx, distrAcc)
distrAcc := distrKeeper.GetDistributionAccount(ctx)
require.NoError(t, banktestutil.FundModuleAccount(bankKeeper, ctx, distrAcc.GetName(), sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1000)))))
accountKeeper.SetModuleAccount(ctx, distrAcc)
tokens := sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, sdk.NewDec(initial))}
// create validator with 100% commission
tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(10, 1), sdk.NewDecWithPrec(10, 1), sdk.NewDec(0))
tstaking.CreateValidator(valAddrs[0], valConsPk1, sdk.NewInt(100), true)
app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0])
stakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0])
// end block to bond validator
staking.EndBlocker(ctx, app.StakingKeeper)
staking.EndBlocker(ctx, stakingKeeper)
// next block
ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1)
// fetch validator
val := app.StakingKeeper.Validator(ctx, valAddrs[0])
val := stakingKeeper.Validator(ctx, valAddrs[0])
// allocate some rewards
app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens)
distrKeeper.AllocateTokensToValidator(ctx, val, tokens)
// end block
staking.EndBlocker(ctx, app.StakingKeeper)
staking.EndBlocker(ctx, stakingKeeper)
// next block
ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1)
// allocate some more rewards
app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens)
distrKeeper.AllocateTokensToValidator(ctx, val, tokens)
// next block
ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1)
// allocate some more rewards
app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens)
distrKeeper.AllocateTokensToValidator(ctx, val, tokens)
rewards, err := app.DistrKeeper.WithdrawDelegationRewards(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0])
rewards, err := distrKeeper.WithdrawDelegationRewards(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0])
require.NoError(t, err)
denom, _ := sdk.GetBaseDenom()
+46 -31
View File
@@ -9,12 +9,17 @@ import (
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/simapp"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/query"
"github.com/cosmos/cosmos-sdk/x/bank/testutil"
bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper"
banktestutil "github.com/cosmos/cosmos-sdk/x/bank/testutil"
"github.com/cosmos/cosmos-sdk/x/distribution/keeper"
"github.com/cosmos/cosmos-sdk/x/distribution/testutil"
"github.com/cosmos/cosmos-sdk/x/distribution/types"
"github.com/cosmos/cosmos-sdk/x/staking"
stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
"github.com/cosmos/cosmos-sdk/x/staking/teststaking"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)
@@ -22,31 +27,41 @@ import (
type KeeperTestSuite struct {
suite.Suite
app *simapp.SimApp
ctx sdk.Context
queryClient types.QueryClient
addrs []sdk.AccAddress
valAddrs []sdk.ValAddress
interfaceRegistry codectypes.InterfaceRegistry
bankKeeper bankkeeper.Keeper
distrKeeper keeper.Keeper
stakingKeeper *stakingkeeper.Keeper
}
func (suite *KeeperTestSuite) SetupTest() {
app := simapp.Setup(suite.T(), false)
app, err := simtestutil.Setup(testutil.AppConfig,
&suite.interfaceRegistry,
&suite.bankKeeper,
&suite.distrKeeper,
&suite.stakingKeeper,
)
suite.NoError(err)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
queryHelper := baseapp.NewQueryServerTestHelper(ctx, app.InterfaceRegistry())
types.RegisterQueryServer(queryHelper, app.DistrKeeper)
queryHelper := baseapp.NewQueryServerTestHelper(ctx, suite.interfaceRegistry)
types.RegisterQueryServer(queryHelper, suite.distrKeeper)
queryClient := types.NewQueryClient(queryHelper)
suite.app = app
suite.ctx = ctx
suite.queryClient = queryClient
suite.addrs = simapp.AddTestAddrs(app, ctx, 2, sdk.NewInt(1000000000))
suite.valAddrs = simapp.ConvertAddrsToValAddrs(suite.addrs)
suite.addrs = simtestutil.AddTestAddrs(suite.bankKeeper, suite.stakingKeeper, ctx, 2, sdk.NewInt(1000000000))
suite.valAddrs = simtestutil.ConvertAddrsToValAddrs(suite.addrs)
}
func (suite *KeeperTestSuite) TestGRPCParams() {
app, ctx, queryClient := suite.app, suite.ctx, suite.queryClient
ctx, queryClient := suite.ctx, suite.queryClient
var (
params types.Params
@@ -77,7 +92,7 @@ func (suite *KeeperTestSuite) TestGRPCParams() {
WithdrawAddrEnabled: true,
}
app.DistrKeeper.SetParams(ctx, params)
suite.distrKeeper.SetParams(ctx, params)
req = &types.QueryParamsRequest{}
expParams = params
},
@@ -103,7 +118,7 @@ func (suite *KeeperTestSuite) TestGRPCParams() {
}
func (suite *KeeperTestSuite) TestGRPCValidatorOutstandingRewards() {
app, ctx, queryClient, valAddrs := suite.app, suite.ctx, suite.queryClient, suite.valAddrs
ctx, queryClient, valAddrs := suite.ctx, suite.queryClient, suite.valAddrs
valCommission := sdk.DecCoins{
sdk.NewDecCoinFromDec("mytoken", sdk.NewDec(5000)),
@@ -111,8 +126,8 @@ func (suite *KeeperTestSuite) TestGRPCValidatorOutstandingRewards() {
}
// set outstanding rewards
app.DistrKeeper.SetValidatorOutstandingRewards(ctx, valAddrs[0], types.ValidatorOutstandingRewards{Rewards: valCommission})
rewards := app.DistrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[0])
suite.distrKeeper.SetValidatorOutstandingRewards(ctx, valAddrs[0], types.ValidatorOutstandingRewards{Rewards: valCommission})
rewards := suite.distrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[0])
var req *types.QueryValidatorOutstandingRewardsRequest
@@ -155,10 +170,10 @@ func (suite *KeeperTestSuite) TestGRPCValidatorOutstandingRewards() {
}
func (suite *KeeperTestSuite) TestGRPCValidatorCommission() {
app, ctx, queryClient, valAddrs := suite.app, suite.ctx, suite.queryClient, suite.valAddrs
ctx, queryClient, valAddrs := suite.ctx, suite.queryClient, suite.valAddrs
commission := sdk.DecCoins{{Denom: "token1", Amount: sdk.NewDec(4)}, {Denom: "token2", Amount: sdk.NewDec(2)}}
app.DistrKeeper.SetValidatorAccumulatedCommission(ctx, valAddrs[0], types.ValidatorAccumulatedCommission{Commission: commission})
suite.distrKeeper.SetValidatorAccumulatedCommission(ctx, valAddrs[0], types.ValidatorAccumulatedCommission{Commission: commission})
var req *types.QueryValidatorCommissionRequest
@@ -202,7 +217,7 @@ func (suite *KeeperTestSuite) TestGRPCValidatorCommission() {
}
func (suite *KeeperTestSuite) TestGRPCValidatorSlashes() {
app, ctx, queryClient, valAddrs := suite.app, suite.ctx, suite.queryClient, suite.valAddrs
ctx, queryClient, valAddrs := suite.ctx, suite.queryClient, suite.valAddrs
slashes := []types.ValidatorSlashEvent{
types.NewValidatorSlashEvent(3, sdk.NewDecWithPrec(5, 1)),
@@ -212,7 +227,7 @@ func (suite *KeeperTestSuite) TestGRPCValidatorSlashes() {
}
for i, slash := range slashes {
app.DistrKeeper.SetValidatorSlashEvent(ctx, valAddrs[0], uint64(i+2), 0, slash)
suite.distrKeeper.SetValidatorSlashEvent(ctx, valAddrs[0], uint64(i+2), 0, slash)
}
var (
@@ -340,24 +355,24 @@ func (suite *KeeperTestSuite) TestGRPCValidatorSlashes() {
}
func (suite *KeeperTestSuite) TestGRPCDelegationRewards() {
app, ctx, addrs, valAddrs := suite.app, suite.ctx, suite.addrs, suite.valAddrs
ctx, addrs, valAddrs := suite.ctx, suite.addrs, suite.valAddrs
tstaking := teststaking.NewHelper(suite.T(), ctx, app.StakingKeeper)
tstaking := teststaking.NewHelper(suite.T(), ctx, suite.stakingKeeper)
tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0))
tstaking.CreateValidator(valAddrs[0], valConsPk1, sdk.NewInt(100), true)
staking.EndBlocker(ctx, app.StakingKeeper)
staking.EndBlocker(ctx, suite.stakingKeeper)
ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1)
queryHelper := baseapp.NewQueryServerTestHelper(ctx, app.InterfaceRegistry())
types.RegisterQueryServer(queryHelper, app.DistrKeeper)
queryHelper := baseapp.NewQueryServerTestHelper(ctx, suite.interfaceRegistry)
types.RegisterQueryServer(queryHelper, suite.distrKeeper)
queryClient := types.NewQueryClient(queryHelper)
val := app.StakingKeeper.Validator(ctx, valAddrs[0])
val := suite.stakingKeeper.Validator(ctx, valAddrs[0])
initial := int64(10)
tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial)}}
app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens)
suite.distrKeeper.AllocateTokensToValidator(ctx, val, tokens)
// test command delegation rewards grpc
var (
@@ -554,9 +569,9 @@ func (suite *KeeperTestSuite) TestGRPCDelegationRewards() {
}
func (suite *KeeperTestSuite) TestGRPCDelegatorWithdrawAddress() {
app, ctx, queryClient, addrs := suite.app, suite.ctx, suite.queryClient, suite.addrs
ctx, queryClient, addrs := suite.ctx, suite.queryClient, suite.addrs
err := app.DistrKeeper.SetWithdrawAddr(ctx, addrs[0], addrs[1])
err := suite.distrKeeper.SetWithdrawAddr(ctx, addrs[0], addrs[1])
suite.Require().Nil(err)
var req *types.QueryDelegatorWithdrawAddressRequest
@@ -600,9 +615,9 @@ func (suite *KeeperTestSuite) TestGRPCDelegatorWithdrawAddress() {
}
func (suite *KeeperTestSuite) TestGRPCCommunityPool() {
app, ctx, queryClient, addrs := suite.app, suite.ctx, suite.queryClient, suite.addrs
ctx, queryClient, addrs := suite.ctx, suite.queryClient, suite.addrs
// reset fee pool
app.DistrKeeper.SetFeePool(ctx, types.InitialFeePool())
suite.distrKeeper.SetFeePool(ctx, types.InitialFeePool())
var (
req *types.QueryCommunityPoolRequest
@@ -626,9 +641,9 @@ func (suite *KeeperTestSuite) TestGRPCCommunityPool() {
"valid request",
func() {
amount := sdk.NewCoins(sdk.NewInt64Coin("stake", 100))
suite.Require().NoError(testutil.FundAccount(app.BankKeeper, ctx, addrs[0], amount))
suite.Require().NoError(banktestutil.FundAccount(suite.bankKeeper, ctx, addrs[0], amount))
err := app.DistrKeeper.FundCommunityPool(ctx, amount, addrs[0])
err := suite.distrKeeper.FundCommunityPool(ctx, amount, addrs[0])
suite.Require().Nil(err)
req = &types.QueryCommunityPoolRequest{}
+94 -40
View File
@@ -3,40 +3,70 @@ package keeper_test
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/cosmos/cosmos-sdk/simapp"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/bank/testutil"
authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper"
bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper"
banktestutil "github.com/cosmos/cosmos-sdk/x/bank/testutil"
"github.com/cosmos/cosmos-sdk/x/distribution/keeper"
"github.com/cosmos/cosmos-sdk/x/distribution/testutil"
"github.com/cosmos/cosmos-sdk/x/distribution/types"
stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
)
func TestSetWithdrawAddr(t *testing.T) {
app := simapp.Setup(t, false)
var (
bankKeeper bankkeeper.Keeper
distrKeeper keeper.Keeper
stakingKeeper *stakingkeeper.Keeper
)
app, err := simtestutil.Setup(testutil.AppConfig,
&bankKeeper,
&distrKeeper,
&stakingKeeper,
)
require.NoError(t, err)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
addr := simapp.AddTestAddrs(app, ctx, 2, sdk.NewInt(1000000000))
addr := simtestutil.AddTestAddrs(bankKeeper, stakingKeeper, ctx, 2, sdk.NewInt(1000000000))
params := app.DistrKeeper.GetParams(ctx)
params := distrKeeper.GetParams(ctx)
params.WithdrawAddrEnabled = false
app.DistrKeeper.SetParams(ctx, params)
distrKeeper.SetParams(ctx, params)
err := app.DistrKeeper.SetWithdrawAddr(ctx, addr[0], addr[1])
err = distrKeeper.SetWithdrawAddr(ctx, addr[0], addr[1])
require.NotNil(t, err)
params.WithdrawAddrEnabled = true
app.DistrKeeper.SetParams(ctx, params)
distrKeeper.SetParams(ctx, params)
err = app.DistrKeeper.SetWithdrawAddr(ctx, addr[0], addr[1])
err = distrKeeper.SetWithdrawAddr(ctx, addr[0], addr[1])
require.Nil(t, err)
require.Error(t, app.DistrKeeper.SetWithdrawAddr(ctx, addr[0], distrAcc.GetAddress()))
require.Error(t, distrKeeper.SetWithdrawAddr(ctx, addr[0], distrAcc.GetAddress()))
}
func TestWithdrawValidatorCommission(t *testing.T) {
app := simapp.Setup(t, false)
var (
accountKeeper authkeeper.AccountKeeper
bankKeeper bankkeeper.Keeper
distrKeeper keeper.Keeper
stakingKeeper *stakingkeeper.Keeper
)
app, err := simtestutil.Setup(testutil.AppConfig,
&accountKeeper,
&bankKeeper,
&distrKeeper,
&stakingKeeper,
)
require.NoError(t, err)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
valCommission := sdk.DecCoins{
@@ -44,41 +74,41 @@ func TestWithdrawValidatorCommission(t *testing.T) {
sdk.NewDecCoinFromDec("stake", sdk.NewDec(3).Quo(sdk.NewDec(2))),
}
addr := simapp.AddTestAddrs(app, ctx, 1, sdk.NewInt(1000000000))
valAddrs := simapp.ConvertAddrsToValAddrs(addr)
addr := simtestutil.AddTestAddrs(bankKeeper, stakingKeeper, ctx, 1, sdk.NewInt(1000000000))
valAddrs := simtestutil.ConvertAddrsToValAddrs(addr)
// set module account coins
distrAcc := app.DistrKeeper.GetDistributionAccount(ctx)
distrAcc := distrKeeper.GetDistributionAccount(ctx)
coins := sdk.NewCoins(sdk.NewCoin("mytoken", sdk.NewInt(2)), sdk.NewCoin("stake", sdk.NewInt(2)))
require.NoError(t, testutil.FundModuleAccount(app.BankKeeper, ctx, distrAcc.GetName(), coins))
require.NoError(t, banktestutil.FundModuleAccount(bankKeeper, ctx, distrAcc.GetName(), coins))
app.AccountKeeper.SetModuleAccount(ctx, distrAcc)
accountKeeper.SetModuleAccount(ctx, distrAcc)
// check initial balance
balance := app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(valAddrs[0]))
expTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 1000)
balance := bankKeeper.GetAllBalances(ctx, sdk.AccAddress(valAddrs[0]))
expTokens := stakingKeeper.TokensFromConsensusPower(ctx, 1000)
expCoins := sdk.NewCoins(sdk.NewCoin("stake", expTokens))
require.Equal(t, expCoins, balance)
// set outstanding rewards
app.DistrKeeper.SetValidatorOutstandingRewards(ctx, valAddrs[0], types.ValidatorOutstandingRewards{Rewards: valCommission})
distrKeeper.SetValidatorOutstandingRewards(ctx, valAddrs[0], types.ValidatorOutstandingRewards{Rewards: valCommission})
// set commission
app.DistrKeeper.SetValidatorAccumulatedCommission(ctx, valAddrs[0], types.ValidatorAccumulatedCommission{Commission: valCommission})
distrKeeper.SetValidatorAccumulatedCommission(ctx, valAddrs[0], types.ValidatorAccumulatedCommission{Commission: valCommission})
// withdraw commission
_, err := app.DistrKeeper.WithdrawValidatorCommission(ctx, valAddrs[0])
_, err = distrKeeper.WithdrawValidatorCommission(ctx, valAddrs[0])
require.NoError(t, err)
// check balance increase
balance = app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(valAddrs[0]))
balance = bankKeeper.GetAllBalances(ctx, sdk.AccAddress(valAddrs[0]))
require.Equal(t, sdk.NewCoins(
sdk.NewCoin("mytoken", sdk.NewInt(1)),
sdk.NewCoin("stake", expTokens.AddRaw(1)),
), balance)
// check remainder
remainder := app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission
remainder := distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission
require.Equal(t, sdk.DecCoins{
sdk.NewDecCoinFromDec("mytoken", sdk.NewDec(1).Quo(sdk.NewDec(4))),
sdk.NewDecCoinFromDec("stake", sdk.NewDec(1).Quo(sdk.NewDec(2))),
@@ -88,7 +118,19 @@ func TestWithdrawValidatorCommission(t *testing.T) {
}
func TestGetTotalRewards(t *testing.T) {
app := simapp.Setup(t, false)
var (
bankKeeper bankkeeper.Keeper
distrKeeper keeper.Keeper
stakingKeeper *stakingkeeper.Keeper
)
app, err := simtestutil.Setup(testutil.AppConfig,
&bankKeeper,
&distrKeeper,
&stakingKeeper,
)
require.NoError(t, err)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
valCommission := sdk.DecCoins{
@@ -96,36 +138,48 @@ func TestGetTotalRewards(t *testing.T) {
sdk.NewDecCoinFromDec("stake", sdk.NewDec(3).Quo(sdk.NewDec(2))),
}
addr := simapp.AddTestAddrs(app, ctx, 2, sdk.NewInt(1000000000))
valAddrs := simapp.ConvertAddrsToValAddrs(addr)
addr := simtestutil.AddTestAddrs(bankKeeper, stakingKeeper, ctx, 2, sdk.NewInt(1000000000))
valAddrs := simtestutil.ConvertAddrsToValAddrs(addr)
app.DistrKeeper.SetValidatorOutstandingRewards(ctx, valAddrs[0], types.ValidatorOutstandingRewards{Rewards: valCommission})
app.DistrKeeper.SetValidatorOutstandingRewards(ctx, valAddrs[1], types.ValidatorOutstandingRewards{Rewards: valCommission})
distrKeeper.SetValidatorOutstandingRewards(ctx, valAddrs[0], types.ValidatorOutstandingRewards{Rewards: valCommission})
distrKeeper.SetValidatorOutstandingRewards(ctx, valAddrs[1], types.ValidatorOutstandingRewards{Rewards: valCommission})
expectedRewards := valCommission.MulDec(sdk.NewDec(2))
totalRewards := app.DistrKeeper.GetTotalRewards(ctx)
totalRewards := distrKeeper.GetTotalRewards(ctx)
require.Equal(t, expectedRewards, totalRewards)
}
func TestFundCommunityPool(t *testing.T) {
app := simapp.Setup(t, false)
var (
bankKeeper bankkeeper.Keeper
distrKeeper keeper.Keeper
stakingKeeper *stakingkeeper.Keeper
)
app, err := simtestutil.Setup(testutil.AppConfig,
&bankKeeper,
&distrKeeper,
&stakingKeeper,
)
require.NoError(t, err)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
// reset fee pool
app.DistrKeeper.SetFeePool(ctx, types.InitialFeePool())
distrKeeper.SetFeePool(ctx, types.InitialFeePool())
addr := simapp.AddTestAddrs(app, ctx, 2, sdk.ZeroInt())
addr := simtestutil.AddTestAddrs(bankKeeper, stakingKeeper, ctx, 2, sdk.ZeroInt())
amount := sdk.NewCoins(sdk.NewInt64Coin("stake", 100))
require.NoError(t, testutil.FundAccount(app.BankKeeper, ctx, addr[0], amount))
require.NoError(t, banktestutil.FundAccount(bankKeeper, ctx, addr[0], amount))
initPool := app.DistrKeeper.GetFeePool(ctx)
assert.Empty(t, initPool.CommunityPool)
initPool := distrKeeper.GetFeePool(ctx)
require.Empty(t, initPool.CommunityPool)
err := app.DistrKeeper.FundCommunityPool(ctx, amount, addr[0])
assert.Nil(t, err)
err = distrKeeper.FundCommunityPool(ctx, amount, addr[0])
require.Nil(t, err)
assert.Equal(t, initPool.CommunityPool.Add(sdk.NewDecCoinsFromCoins(amount...)...), app.DistrKeeper.GetFeePool(ctx).CommunityPool)
assert.Empty(t, app.BankKeeper.GetAllBalances(ctx, addr[0]))
require.Equal(t, initPool.CommunityPool.Add(sdk.NewDecCoinsFromCoins(amount...)...), distrKeeper.GetFeePool(ctx).CommunityPool)
require.Empty(t, bankKeeper.GetAllBalances(ctx, addr[0]))
}
+30 -15
View File
@@ -9,12 +9,15 @@ import (
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/simapp"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/cosmos/cosmos-sdk/x/distribution/keeper"
"github.com/cosmos/cosmos-sdk/x/distribution/testutil"
"github.com/cosmos/cosmos-sdk/x/distribution/types"
"github.com/cosmos/cosmos-sdk/x/staking"
stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
"github.com/cosmos/cosmos-sdk/x/staking/teststaking"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)
@@ -112,21 +115,33 @@ func getQueriedCommunityPool(t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmi
}
func TestQueries(t *testing.T) {
var (
bankKeeper bankkeeper.Keeper
distrKeeper keeper.Keeper
stakingKeeper *stakingkeeper.Keeper
)
app, err := simtestutil.Setup(testutil.AppConfig,
&bankKeeper,
&distrKeeper,
&stakingKeeper,
)
require.NoError(t, err)
cdc := codec.NewLegacyAmino()
types.RegisterLegacyAminoCodec(cdc)
banktypes.RegisterLegacyAminoCodec(cdc)
app := simapp.Setup(t, false)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
// reset fee pool
app.DistrKeeper.SetFeePool(ctx, types.InitialFeePool())
distrKeeper.SetFeePool(ctx, types.InitialFeePool())
addr := simapp.AddTestAddrs(app, ctx, 1, sdk.NewInt(1000000000))
valAddrs := simapp.ConvertAddrsToValAddrs(addr)
addr := simtestutil.AddTestAddrs(bankKeeper, stakingKeeper, ctx, 1, sdk.NewInt(1000000000))
valAddrs := simtestutil.ConvertAddrsToValAddrs(addr)
valOpAddr1 := valAddrs[0]
querier := keeper.NewQuerier(app.DistrKeeper, cdc)
querier := keeper.NewQuerier(distrKeeper, cdc)
// test param queries
params := types.Params{
@@ -136,7 +151,7 @@ func TestQueries(t *testing.T) {
WithdrawAddrEnabled: true,
}
app.DistrKeeper.SetParams(ctx, params)
distrKeeper.SetParams(ctx, params)
paramsRes := getQueriedParams(t, ctx, cdc, querier)
require.Equal(t, params.CommunityTax, paramsRes.CommunityTax)
@@ -146,13 +161,13 @@ func TestQueries(t *testing.T) {
// test outstanding rewards query
outstandingRewards := sdk.DecCoins{{Denom: "mytoken", Amount: sdk.NewDec(3)}, {Denom: "myothertoken", Amount: sdk.NewDecWithPrec(3, 7)}}
app.DistrKeeper.SetValidatorOutstandingRewards(ctx, valOpAddr1, types.ValidatorOutstandingRewards{Rewards: outstandingRewards})
distrKeeper.SetValidatorOutstandingRewards(ctx, valOpAddr1, types.ValidatorOutstandingRewards{Rewards: outstandingRewards})
retOutstandingRewards := getQueriedValidatorOutstandingRewards(t, ctx, cdc, querier, valOpAddr1)
require.Equal(t, outstandingRewards, retOutstandingRewards)
// test validator commission query
commission := sdk.DecCoins{{Denom: "token1", Amount: sdk.NewDec(4)}, {Denom: "token2", Amount: sdk.NewDec(2)}}
app.DistrKeeper.SetValidatorAccumulatedCommission(ctx, valOpAddr1, types.ValidatorAccumulatedCommission{Commission: commission})
distrKeeper.SetValidatorAccumulatedCommission(ctx, valOpAddr1, types.ValidatorAccumulatedCommission{Commission: commission})
retCommission := getQueriedValidatorCommission(t, ctx, cdc, querier, valOpAddr1)
require.Equal(t, commission, retCommission)
@@ -163,8 +178,8 @@ func TestQueries(t *testing.T) {
// test validator slashes query with height range
slashOne := types.NewValidatorSlashEvent(3, sdk.NewDecWithPrec(5, 1))
slashTwo := types.NewValidatorSlashEvent(7, sdk.NewDecWithPrec(6, 1))
app.DistrKeeper.SetValidatorSlashEvent(ctx, valOpAddr1, 3, 0, slashOne)
app.DistrKeeper.SetValidatorSlashEvent(ctx, valOpAddr1, 7, 0, slashTwo)
distrKeeper.SetValidatorSlashEvent(ctx, valOpAddr1, 3, 0, slashOne)
distrKeeper.SetValidatorSlashEvent(ctx, valOpAddr1, 7, 0, slashTwo)
slashes := getQueriedValidatorSlashes(t, ctx, cdc, querier, valOpAddr1, 0, 2)
require.Equal(t, 0, len(slashes))
slashes = getQueriedValidatorSlashes(t, ctx, cdc, querier, valOpAddr1, 0, 5)
@@ -173,19 +188,19 @@ func TestQueries(t *testing.T) {
require.Equal(t, []types.ValidatorSlashEvent{slashOne, slashTwo}, slashes)
// test delegation rewards query
tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper)
tstaking := teststaking.NewHelper(t, ctx, stakingKeeper)
tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0))
tstaking.CreateValidator(valOpAddr1, valConsPk1, sdk.NewInt(100), true)
staking.EndBlocker(ctx, app.StakingKeeper)
staking.EndBlocker(ctx, stakingKeeper)
val := app.StakingKeeper.Validator(ctx, valOpAddr1)
val := stakingKeeper.Validator(ctx, valOpAddr1)
rewards := getQueriedDelegationRewards(t, ctx, cdc, querier, sdk.AccAddress(valOpAddr1), valOpAddr1)
require.True(t, rewards.IsZero())
initial := int64(10)
ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1)
tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial)}}
app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens)
distrKeeper.AllocateTokensToValidator(ctx, val, tokens)
rewards = getQueriedDelegationRewards(t, ctx, cdc, querier, sdk.AccAddress(valOpAddr1), valOpAddr1)
require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial / 2)}}, rewards)
+5 -18
View File
@@ -4,35 +4,22 @@ import (
"testing"
"github.com/stretchr/testify/require"
abcitypes "github.com/tendermint/tendermint/abci/types"
tmjson "github.com/tendermint/tendermint/libs/json"
"github.com/tendermint/tendermint/libs/log"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
dbm "github.com/tendermint/tm-db"
"github.com/cosmos/cosmos-sdk/simapp"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/cosmos/cosmos-sdk/x/distribution/testutil"
"github.com/cosmos/cosmos-sdk/x/distribution/types"
)
func TestItCreatesModuleAccountOnInitBlock(t *testing.T) {
db := dbm.NewMemDB()
encCdc := simapp.MakeTestEncodingConfig()
app := simapp.NewSimApp(log.NewNopLogger(), db, nil, true, 5, encCdc, simtestutil.NewAppOptionsWithFlagHome(simapp.DefaultNodeHome))
var accountKeeper authkeeper.AccountKeeper
genesisState := simapp.GenesisStateWithSingleValidator(t, app)
stateBytes, err := tmjson.Marshal(genesisState)
app, err := simtestutil.SetupAtGenesis(testutil.AppConfig, &accountKeeper)
require.NoError(t, err)
app.InitChain(
abcitypes.RequestInitChain{
AppStateBytes: stateBytes,
ChainId: "test-chain-id",
},
)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
acc := app.AccountKeeper.GetAccount(ctx, authtypes.NewModuleAddress(types.ModuleName))
acc := accountKeeper.GetAccount(ctx, authtypes.NewModuleAddress(types.ModuleName))
require.NotNil(t, acc)
}
+49 -21
View File
@@ -7,10 +7,14 @@ import (
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/cosmos/cosmos-sdk/crypto/keys/ed25519"
"github.com/cosmos/cosmos-sdk/simapp"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/bank/testutil"
authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper"
bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper"
banktestutil "github.com/cosmos/cosmos-sdk/x/bank/testutil"
"github.com/cosmos/cosmos-sdk/x/distribution"
"github.com/cosmos/cosmos-sdk/x/distribution/keeper"
"github.com/cosmos/cosmos-sdk/x/distribution/testutil"
"github.com/cosmos/cosmos-sdk/x/distribution/types"
)
@@ -26,51 +30,75 @@ func testProposal(recipient sdk.AccAddress, amount sdk.Coins) *types.CommunityPo
}
func TestProposalHandlerPassed(t *testing.T) {
app := simapp.Setup(t, false)
var (
accountKeeper authkeeper.AccountKeeper
bankKeeper bankkeeper.Keeper
distrKeeper keeper.Keeper
)
app, err := simtestutil.Setup(testutil.AppConfig,
&accountKeeper,
&bankKeeper,
&distrKeeper,
)
require.NoError(t, err)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
recipient := delAddr1
// add coins to the module account
macc := app.DistrKeeper.GetDistributionAccount(ctx)
balances := app.BankKeeper.GetAllBalances(ctx, macc.GetAddress())
require.NoError(t, testutil.FundModuleAccount(app.BankKeeper, ctx, macc.GetName(), amount))
macc := distrKeeper.GetDistributionAccount(ctx)
balances := bankKeeper.GetAllBalances(ctx, macc.GetAddress())
require.NoError(t, banktestutil.FundModuleAccount(bankKeeper, ctx, macc.GetName(), amount))
app.AccountKeeper.SetModuleAccount(ctx, macc)
accountKeeper.SetModuleAccount(ctx, macc)
account := app.AccountKeeper.NewAccountWithAddress(ctx, recipient)
app.AccountKeeper.SetAccount(ctx, account)
require.True(t, app.BankKeeper.GetAllBalances(ctx, account.GetAddress()).IsZero())
account := accountKeeper.NewAccountWithAddress(ctx, recipient)
accountKeeper.SetAccount(ctx, account)
require.True(t, bankKeeper.GetAllBalances(ctx, account.GetAddress()).IsZero())
feePool := app.DistrKeeper.GetFeePool(ctx)
feePool := distrKeeper.GetFeePool(ctx)
feePool.CommunityPool = sdk.NewDecCoinsFromCoins(amount...)
app.DistrKeeper.SetFeePool(ctx, feePool)
distrKeeper.SetFeePool(ctx, feePool)
tp := testProposal(recipient, amount)
hdlr := distribution.NewCommunityPoolSpendProposalHandler(app.DistrKeeper)
hdlr := distribution.NewCommunityPoolSpendProposalHandler(distrKeeper)
require.NoError(t, hdlr(ctx, tp))
balances = app.BankKeeper.GetAllBalances(ctx, recipient)
balances = bankKeeper.GetAllBalances(ctx, recipient)
require.Equal(t, balances, amount)
}
func TestProposalHandlerFailed(t *testing.T) {
app := simapp.Setup(t, false)
var (
accountKeeper authkeeper.AccountKeeper
bankKeeper bankkeeper.Keeper
distrKeeper keeper.Keeper
)
app, err := simtestutil.Setup(testutil.AppConfig,
&accountKeeper,
&bankKeeper,
&distrKeeper,
)
require.NoError(t, err)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
// reset fee pool
app.DistrKeeper.SetFeePool(ctx, types.InitialFeePool())
distrKeeper.SetFeePool(ctx, types.InitialFeePool())
recipient := delAddr1
account := app.AccountKeeper.NewAccountWithAddress(ctx, recipient)
app.AccountKeeper.SetAccount(ctx, account)
require.True(t, app.BankKeeper.GetAllBalances(ctx, account.GetAddress()).IsZero())
account := accountKeeper.NewAccountWithAddress(ctx, recipient)
accountKeeper.SetAccount(ctx, account)
require.True(t, bankKeeper.GetAllBalances(ctx, account.GetAddress()).IsZero())
tp := testProposal(recipient, amount)
hdlr := distribution.NewCommunityPoolSpendProposalHandler(app.DistrKeeper)
hdlr := distribution.NewCommunityPoolSpendProposalHandler(distrKeeper)
require.Error(t, hdlr(ctx, tp))
balances := app.BankKeeper.GetAllBalances(ctx, recipient)
balances := bankKeeper.GetAllBalances(ctx, recipient)
require.True(t, balances.IsZero())
}
+7 -2
View File
@@ -6,11 +6,13 @@ import (
"github.com/stretchr/testify/require"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/crypto/keys/ed25519"
"github.com/cosmos/cosmos-sdk/simapp"
"github.com/cosmos/cosmos-sdk/depinject"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/kv"
"github.com/cosmos/cosmos-sdk/x/distribution/simulation"
"github.com/cosmos/cosmos-sdk/x/distribution/testutil"
"github.com/cosmos/cosmos-sdk/x/distribution/types"
)
@@ -22,7 +24,10 @@ var (
)
func TestDecodeDistributionStore(t *testing.T) {
cdc := simapp.MakeTestEncodingConfig().Codec
var cdc codec.Codec
err := depinject.Inject(testutil.AppConfig, &cdc)
require.NoError(t, err)
dec := simulation.NewDecodeStore(cdc)
decCoins := sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, sdk.OneDec())}
+23 -17
View File
@@ -5,10 +5,13 @@ import (
"math/rand"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec"
simappparams "github.com/cosmos/cosmos-sdk/simapp/params"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
"github.com/cosmos/cosmos-sdk/x/auth/tx"
"github.com/cosmos/cosmos-sdk/x/distribution/keeper"
"github.com/cosmos/cosmos-sdk/x/distribution/types"
"github.com/cosmos/cosmos-sdk/x/simulation"
@@ -29,55 +32,58 @@ func WeightedOperations(appParams simtypes.AppParams, cdc codec.JSONCodec, ak ty
var weightMsgSetWithdrawAddress int
appParams.GetOrGenerate(cdc, OpWeightMsgSetWithdrawAddress, &weightMsgSetWithdrawAddress, nil,
func(_ *rand.Rand) {
weightMsgSetWithdrawAddress = simappparams.DefaultWeightMsgSetWithdrawAddress
weightMsgSetWithdrawAddress = simtestutil.DefaultWeightMsgSetWithdrawAddress
},
)
var weightMsgWithdrawDelegationReward int
appParams.GetOrGenerate(cdc, OpWeightMsgWithdrawDelegationReward, &weightMsgWithdrawDelegationReward, nil,
func(_ *rand.Rand) {
weightMsgWithdrawDelegationReward = simappparams.DefaultWeightMsgWithdrawDelegationReward
weightMsgWithdrawDelegationReward = simtestutil.DefaultWeightMsgWithdrawDelegationReward
},
)
var weightMsgWithdrawValidatorCommission int
appParams.GetOrGenerate(cdc, OpWeightMsgWithdrawValidatorCommission, &weightMsgWithdrawValidatorCommission, nil,
func(_ *rand.Rand) {
weightMsgWithdrawValidatorCommission = simappparams.DefaultWeightMsgWithdrawValidatorCommission
weightMsgWithdrawValidatorCommission = simtestutil.DefaultWeightMsgWithdrawValidatorCommission
},
)
var weightMsgFundCommunityPool int
appParams.GetOrGenerate(cdc, OpWeightMsgFundCommunityPool, &weightMsgFundCommunityPool, nil,
func(_ *rand.Rand) {
weightMsgFundCommunityPool = simappparams.DefaultWeightMsgFundCommunityPool
weightMsgFundCommunityPool = simtestutil.DefaultWeightMsgFundCommunityPool
},
)
stakeKeeper := sk.(*stakingkeeper.Keeper)
interfaceRegistry := codectypes.NewInterfaceRegistry()
txConfig := tx.NewTxConfig(codec.NewProtoCodec(interfaceRegistry), tx.DefaultSignModes)
return simulation.WeightedOperations{
simulation.NewWeightedOperation(
weightMsgSetWithdrawAddress,
SimulateMsgSetWithdrawAddress(ak, bk, k),
SimulateMsgSetWithdrawAddress(txConfig, ak, bk, k),
),
simulation.NewWeightedOperation(
weightMsgWithdrawDelegationReward,
SimulateMsgWithdrawDelegatorReward(ak, bk, k, stakeKeeper),
SimulateMsgWithdrawDelegatorReward(txConfig, ak, bk, k, stakeKeeper),
),
simulation.NewWeightedOperation(
weightMsgWithdrawValidatorCommission,
SimulateMsgWithdrawValidatorCommission(ak, bk, k, stakeKeeper),
SimulateMsgWithdrawValidatorCommission(txConfig, ak, bk, k, stakeKeeper),
),
simulation.NewWeightedOperation(
weightMsgFundCommunityPool,
SimulateMsgFundCommunityPool(ak, bk, k, stakeKeeper),
SimulateMsgFundCommunityPool(txConfig, ak, bk, k, stakeKeeper),
),
}
}
// SimulateMsgSetWithdrawAddress generates a MsgSetWithdrawAddress with random values.
func SimulateMsgSetWithdrawAddress(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) simtypes.Operation {
func SimulateMsgSetWithdrawAddress(txConfig client.TxConfig, ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) simtypes.Operation {
return func(
r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string,
) (simtypes.OperationMsg, []simtypes.FutureOperation, error) {
@@ -96,7 +102,7 @@ func SimulateMsgSetWithdrawAddress(ak types.AccountKeeper, bk types.BankKeeper,
txCtx := simulation.OperationInput{
R: r,
App: app,
TxGen: simappparams.MakeTestEncodingConfig().TxConfig,
TxGen: txConfig,
Cdc: nil,
Msg: msg,
MsgType: msg.Type(),
@@ -113,7 +119,7 @@ func SimulateMsgSetWithdrawAddress(ak types.AccountKeeper, bk types.BankKeeper,
}
// SimulateMsgWithdrawDelegatorReward generates a MsgWithdrawDelegatorReward with random values.
func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, sk *stakingkeeper.Keeper) simtypes.Operation {
func SimulateMsgWithdrawDelegatorReward(txConfig client.TxConfig, ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, sk *stakingkeeper.Keeper) simtypes.Operation {
return func(
r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string,
) (simtypes.OperationMsg, []simtypes.FutureOperation, error) {
@@ -138,7 +144,7 @@ func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, bk types.BankKee
txCtx := simulation.OperationInput{
R: r,
App: app,
TxGen: simappparams.MakeTestEncodingConfig().TxConfig,
TxGen: txConfig,
Cdc: nil,
Msg: msg,
MsgType: msg.Type(),
@@ -155,7 +161,7 @@ func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, bk types.BankKee
}
// SimulateMsgWithdrawValidatorCommission generates a MsgWithdrawValidatorCommission with random values.
func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, sk *stakingkeeper.Keeper) simtypes.Operation {
func SimulateMsgWithdrawValidatorCommission(txConfig client.TxConfig, ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, sk *stakingkeeper.Keeper) simtypes.Operation {
return func(
r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string,
) (simtypes.OperationMsg, []simtypes.FutureOperation, error) {
@@ -182,7 +188,7 @@ func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, bk types.Ban
txCtx := simulation.OperationInput{
R: r,
App: app,
TxGen: simappparams.MakeTestEncodingConfig().TxConfig,
TxGen: txConfig,
Cdc: nil,
Msg: msg,
MsgType: msg.Type(),
@@ -200,7 +206,7 @@ func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, bk types.Ban
// SimulateMsgFundCommunityPool simulates MsgFundCommunityPool execution where
// a random account sends a random amount of its funds to the community pool.
func SimulateMsgFundCommunityPool(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, sk *stakingkeeper.Keeper) simtypes.Operation {
func SimulateMsgFundCommunityPool(txConfig client.TxConfig, ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, sk *stakingkeeper.Keeper) simtypes.Operation {
return func(
r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string,
) (simtypes.OperationMsg, []simtypes.FutureOperation, error) {
@@ -231,7 +237,7 @@ func SimulateMsgFundCommunityPool(ak types.AccountKeeper, bk types.BankKeeper, k
txCtx := simulation.OperationInput{
App: app,
TxGen: simappparams.MakeTestEncodingConfig().TxConfig,
TxGen: txConfig,
Cdc: nil,
Msg: msg,
MsgType: msg.Type(),
+58 -37
View File
@@ -8,25 +8,30 @@ import (
abci "github.com/tendermint/tendermint/abci/types"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/cosmos/cosmos-sdk/simapp"
simappparams "github.com/cosmos/cosmos-sdk/simapp/params"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/runtime"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
"github.com/cosmos/cosmos-sdk/x/bank/testutil"
authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper"
bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper"
banktestutil "github.com/cosmos/cosmos-sdk/x/bank/testutil"
"github.com/cosmos/cosmos-sdk/x/distribution/keeper"
"github.com/cosmos/cosmos-sdk/x/distribution/simulation"
"github.com/cosmos/cosmos-sdk/x/distribution/testutil"
"github.com/cosmos/cosmos-sdk/x/distribution/types"
distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types"
stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)
// TestWeightedOperations tests the weights of the operations.
func (suite *SimTestSuite) TestWeightedOperations() {
cdc := suite.app.AppCodec()
appParams := make(simtypes.AppParams)
weightesOps := simulation.WeightedOperations(appParams, cdc, suite.app.AccountKeeper,
suite.app.BankKeeper, suite.app.DistrKeeper, suite.app.StakingKeeper,
)
weightesOps := simulation.WeightedOperations(appParams, suite.cdc, suite.accountKeeper,
suite.bankKeeper, suite.distrKeeper, suite.stakingKeeper)
// setup 3 accounts
s := rand.NewSource(1)
@@ -38,10 +43,10 @@ func (suite *SimTestSuite) TestWeightedOperations() {
opMsgRoute string
opMsgName string
}{
{simappparams.DefaultWeightMsgSetWithdrawAddress, types.ModuleName, types.TypeMsgSetWithdrawAddress},
{simappparams.DefaultWeightMsgWithdrawDelegationReward, types.ModuleName, types.TypeMsgWithdrawDelegatorReward},
{simappparams.DefaultWeightMsgWithdrawValidatorCommission, types.ModuleName, types.TypeMsgWithdrawValidatorCommission},
{simappparams.DefaultWeightMsgFundCommunityPool, types.ModuleName, types.TypeMsgFundCommunityPool},
{simtestutil.DefaultWeightMsgSetWithdrawAddress, types.ModuleName, types.TypeMsgSetWithdrawAddress},
{simtestutil.DefaultWeightMsgWithdrawDelegationReward, types.ModuleName, types.TypeMsgWithdrawDelegatorReward},
{simtestutil.DefaultWeightMsgWithdrawValidatorCommission, types.ModuleName, types.TypeMsgWithdrawValidatorCommission},
{simtestutil.DefaultWeightMsgFundCommunityPool, types.ModuleName, types.TypeMsgFundCommunityPool},
}
for i, w := range weightesOps {
@@ -69,7 +74,7 @@ func (suite *SimTestSuite) TestSimulateMsgSetWithdrawAddress() {
suite.app.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{Height: suite.app.LastBlockHeight() + 1, AppHash: suite.app.LastCommitID().Hash}})
// execute operation
op := simulation.SimulateMsgSetWithdrawAddress(suite.app.AccountKeeper, suite.app.BankKeeper, suite.app.DistrKeeper)
op := simulation.SimulateMsgSetWithdrawAddress(suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.distrKeeper)
operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "")
suite.Require().NoError(err)
@@ -97,12 +102,12 @@ func (suite *SimTestSuite) TestSimulateMsgWithdrawDelegatorReward() {
validator0 := suite.getTestingValidator0(accounts)
// setup delegation
delTokens := suite.app.StakingKeeper.TokensFromConsensusPower(suite.ctx, 2)
delTokens := suite.stakingKeeper.TokensFromConsensusPower(suite.ctx, 2)
validator0, issuedShares := validator0.AddTokensFromDel(delTokens)
delegator := accounts[1]
delegation := stakingtypes.NewDelegation(delegator.Address, validator0.GetOperator(), issuedShares)
suite.app.StakingKeeper.SetDelegation(suite.ctx, delegation)
suite.app.DistrKeeper.SetDelegatorStartingInfo(suite.ctx, validator0.GetOperator(), delegator.Address, distrtypes.NewDelegatorStartingInfo(2, sdk.OneDec(), 200))
suite.stakingKeeper.SetDelegation(suite.ctx, delegation)
suite.distrKeeper.SetDelegatorStartingInfo(suite.ctx, validator0.GetOperator(), delegator.Address, distrtypes.NewDelegatorStartingInfo(2, sdk.OneDec(), 200))
suite.setupValidatorRewards(validator0.GetOperator())
@@ -110,7 +115,7 @@ func (suite *SimTestSuite) TestSimulateMsgWithdrawDelegatorReward() {
suite.app.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{Height: suite.app.LastBlockHeight() + 1, AppHash: suite.app.LastCommitID().Hash}})
// execute operation
op := simulation.SimulateMsgWithdrawDelegatorReward(suite.app.AccountKeeper, suite.app.BankKeeper, suite.app.DistrKeeper, suite.app.StakingKeeper)
op := simulation.SimulateMsgWithdrawDelegatorReward(suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.distrKeeper, suite.stakingKeeper)
operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "")
suite.Require().NoError(err)
@@ -144,12 +149,12 @@ func (suite *SimTestSuite) testSimulateMsgWithdrawValidatorCommission(tokenName
validator0 := suite.getTestingValidator0(accounts)
// set module account coins
distrAcc := suite.app.DistrKeeper.GetDistributionAccount(suite.ctx)
suite.Require().NoError(testutil.FundModuleAccount(suite.app.BankKeeper, suite.ctx, distrAcc.GetName(), sdk.NewCoins(
distrAcc := suite.distrKeeper.GetDistributionAccount(suite.ctx)
suite.Require().NoError(banktestutil.FundModuleAccount(suite.bankKeeper, suite.ctx, distrAcc.GetName(), sdk.NewCoins(
sdk.NewCoin(tokenName, sdk.NewInt(10)),
sdk.NewCoin("stake", sdk.NewInt(5)),
)))
suite.app.AccountKeeper.SetModuleAccount(suite.ctx, distrAcc)
suite.accountKeeper.SetModuleAccount(suite.ctx, distrAcc)
// set outstanding rewards
valCommission := sdk.NewDecCoins(
@@ -157,18 +162,18 @@ func (suite *SimTestSuite) testSimulateMsgWithdrawValidatorCommission(tokenName
sdk.NewDecCoinFromDec("stake", sdk.NewDec(1).Quo(sdk.NewDec(1))),
)
suite.app.DistrKeeper.SetValidatorOutstandingRewards(suite.ctx, validator0.GetOperator(), types.ValidatorOutstandingRewards{Rewards: valCommission})
suite.app.DistrKeeper.SetValidatorOutstandingRewards(suite.ctx, suite.genesisVals[0].GetOperator(), types.ValidatorOutstandingRewards{Rewards: valCommission})
suite.distrKeeper.SetValidatorOutstandingRewards(suite.ctx, validator0.GetOperator(), types.ValidatorOutstandingRewards{Rewards: valCommission})
suite.distrKeeper.SetValidatorOutstandingRewards(suite.ctx, suite.genesisVals[0].GetOperator(), types.ValidatorOutstandingRewards{Rewards: valCommission})
// setup validator accumulated commission
suite.app.DistrKeeper.SetValidatorAccumulatedCommission(suite.ctx, validator0.GetOperator(), types.ValidatorAccumulatedCommission{Commission: valCommission})
suite.app.DistrKeeper.SetValidatorAccumulatedCommission(suite.ctx, suite.genesisVals[0].GetOperator(), types.ValidatorAccumulatedCommission{Commission: valCommission})
suite.distrKeeper.SetValidatorAccumulatedCommission(suite.ctx, validator0.GetOperator(), types.ValidatorAccumulatedCommission{Commission: valCommission})
suite.distrKeeper.SetValidatorAccumulatedCommission(suite.ctx, suite.genesisVals[0].GetOperator(), types.ValidatorAccumulatedCommission{Commission: valCommission})
// begin a new block
suite.app.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{Height: suite.app.LastBlockHeight() + 1, AppHash: suite.app.LastCommitID().Hash}})
// execute operation
op := simulation.SimulateMsgWithdrawValidatorCommission(suite.app.AccountKeeper, suite.app.BankKeeper, suite.app.DistrKeeper, suite.app.StakingKeeper)
op := simulation.SimulateMsgWithdrawValidatorCommission(suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.distrKeeper, suite.stakingKeeper)
operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "")
if !operationMsg.OK {
suite.Require().Equal("could not find account", operationMsg.Comment)
@@ -198,7 +203,7 @@ func (suite *SimTestSuite) TestSimulateMsgFundCommunityPool() {
suite.app.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{Height: suite.app.LastBlockHeight() + 1, AppHash: suite.app.LastCommitID().Hash}})
// execute operation
op := simulation.SimulateMsgFundCommunityPool(suite.app.AccountKeeper, suite.app.BankKeeper, suite.app.DistrKeeper, suite.app.StakingKeeper)
op := simulation.SimulateMsgFundCommunityPool(suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.distrKeeper, suite.stakingKeeper)
operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "")
suite.Require().NoError(err)
@@ -217,16 +222,32 @@ type SimTestSuite struct {
suite.Suite
ctx sdk.Context
app *simapp.SimApp
app *runtime.App
genesisVals []stakingtypes.Validator
txConfig client.TxConfig
cdc codec.Codec
stakingKeeper *stakingkeeper.Keeper
accountKeeper authkeeper.AccountKeeper
bankKeeper bankkeeper.Keeper
distrKeeper keeper.Keeper
}
func (suite *SimTestSuite) SetupTest() {
checkTx := false
app := simapp.Setup(suite.T(), checkTx)
app, err := simtestutil.Setup(testutil.AppConfig,
&suite.cdc,
&suite.txConfig,
&suite.stakingKeeper,
&suite.accountKeeper,
&suite.bankKeeper,
&suite.distrKeeper,
)
suite.NoError(err)
suite.app = app
suite.ctx = app.BaseApp.NewContext(checkTx, tmproto.Header{})
genesisVals := app.StakingKeeper.GetAllValidators(suite.ctx)
suite.ctx = app.BaseApp.NewContext(false, tmproto.Header{})
genesisVals := suite.stakingKeeper.GetAllValidators(suite.ctx)
suite.Require().Len(genesisVals, 1)
suite.genesisVals = genesisVals
}
@@ -234,14 +255,14 @@ func (suite *SimTestSuite) SetupTest() {
func (suite *SimTestSuite) getTestingAccounts(r *rand.Rand, n int) []simtypes.Account {
accounts := simtypes.RandomAccounts(r, n)
initAmt := suite.app.StakingKeeper.TokensFromConsensusPower(suite.ctx, 200)
initAmt := suite.stakingKeeper.TokensFromConsensusPower(suite.ctx, 200)
initCoins := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initAmt))
// add coins to the accounts
for _, account := range accounts {
acc := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, account.Address)
suite.app.AccountKeeper.SetAccount(suite.ctx, acc)
suite.Require().NoError(testutil.FundAccount(suite.app.BankKeeper, suite.ctx, account.Address, initCoins))
acc := suite.accountKeeper.NewAccountWithAddress(suite.ctx, account.Address)
suite.accountKeeper.SetAccount(suite.ctx, acc)
suite.Require().NoError(banktestutil.FundAccount(suite.bankKeeper, suite.ctx, account.Address, initCoins))
}
return accounts
@@ -265,7 +286,7 @@ func (suite *SimTestSuite) getTestingValidator(accounts []simtypes.Account, comm
validator.DelegatorShares = sdk.NewDec(100)
validator.Tokens = sdk.NewInt(1000000)
suite.app.StakingKeeper.SetValidator(suite.ctx, validator)
suite.stakingKeeper.SetValidator(suite.ctx, validator)
return validator
}
@@ -273,10 +294,10 @@ func (suite *SimTestSuite) getTestingValidator(accounts []simtypes.Account, comm
func (suite *SimTestSuite) setupValidatorRewards(valAddress sdk.ValAddress) {
decCoins := sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, sdk.OneDec())}
historicalRewards := distrtypes.NewValidatorHistoricalRewards(decCoins, 2)
suite.app.DistrKeeper.SetValidatorHistoricalRewards(suite.ctx, valAddress, 2, historicalRewards)
suite.distrKeeper.SetValidatorHistoricalRewards(suite.ctx, valAddress, 2, historicalRewards)
// setup current revards
currentRewards := distrtypes.NewValidatorCurrentRewards(decCoins, 3)
suite.app.DistrKeeper.SetValidatorCurrentRewards(suite.ctx, valAddress, currentRewards)
suite.distrKeeper.SetValidatorCurrentRewards(suite.ctx, valAddress, currentRewards)
}
func TestSimTestSuite(t *testing.T) {
+2 -2
View File
@@ -3,7 +3,7 @@ package simulation
import (
"math/rand"
simappparams "github.com/cosmos/cosmos-sdk/simapp/params"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
"github.com/cosmos/cosmos-sdk/x/distribution/keeper"
@@ -19,7 +19,7 @@ func ProposalContents(k keeper.Keeper) []simtypes.WeightedProposalContent {
return []simtypes.WeightedProposalContent{
simulation.NewWeightedProposalContent(
OpWeightSubmitCommunitySpendProposal,
simappparams.DefaultWeightCommunitySpendProposal,
simtestutil.DefaultWeightCommunitySpendProposal,
SimulateCommunityPoolSpendProposalContent(k),
),
}
+11 -7
View File
@@ -7,15 +7,19 @@ import (
"github.com/stretchr/testify/require"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/cosmos/cosmos-sdk/simapp"
simappparams "github.com/cosmos/cosmos-sdk/simapp/params"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
"github.com/cosmos/cosmos-sdk/x/distribution/keeper"
"github.com/cosmos/cosmos-sdk/x/distribution/simulation"
"github.com/cosmos/cosmos-sdk/x/distribution/testutil"
)
func TestProposalContents(t *testing.T) {
app := simapp.Setup(t, false)
var distrKeeper keeper.Keeper
app, err := simtestutil.Setup(testutil.AppConfig, &distrKeeper)
require.NoError(t, err)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
// initialize parameters
@@ -25,20 +29,20 @@ func TestProposalContents(t *testing.T) {
accounts := simtypes.RandomAccounts(r, 3)
// execute ProposalContents function
weightedProposalContent := simulation.ProposalContents(app.DistrKeeper)
weightedProposalContent := simulation.ProposalContents(distrKeeper)
require.Len(t, weightedProposalContent, 1)
w0 := weightedProposalContent[0]
// tests w0 interface:
require.Equal(t, simulation.OpWeightSubmitCommunitySpendProposal, w0.AppParamsKey())
require.Equal(t, simappparams.DefaultWeightTextProposal, w0.DefaultWeight())
require.Equal(t, simtestutil.DefaultWeightTextProposal, w0.DefaultWeight())
amount := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1)), sdk.NewCoin("atoken", sdk.NewInt(2)))
feePool := app.DistrKeeper.GetFeePool(ctx)
feePool := distrKeeper.GetFeePool(ctx)
feePool.CommunityPool = sdk.NewDecCoinsFromCoins(amount...)
app.DistrKeeper.SetFeePool(ctx, feePool)
distrKeeper.SetFeePool(ctx, feePool)
content := w0.ContentSimulatorFn()(r, ctx, accounts)
+9 -2
View File
@@ -5,8 +5,8 @@ modules:
app_name: DistrApp
begin_blockers: [distribution, staking, auth, bank, genutil, params]
end_blockers: [staking, auth, bank, distribution, genutil, params]
begin_blockers: [mint, distribution, staking, auth, bank, genutil, params]
end_blockers: [staking, auth, bank, distribution, mint, genutil, params]
init_genesis: [auth, bank, distribution, staking, mint, genutil, params]
- name: auth
@@ -15,6 +15,9 @@ modules:
bech32_prefix: cosmos
module_account_permissions:
- account: fee_collector
- account: distribution
- account: mint
permissions: [minter]
- account: bonded_tokens_pool
permissions: [burner, staking]
- account: not_bonded_tokens_pool
@@ -40,6 +43,10 @@ modules:
config:
"@type": cosmos.genutil.module.v1.Module
- name: mint
config:
"@type": cosmos.mint.module.v1.Module
- name: distribution
config:
"@type": cosmos.distribution.module.v1.Module
+1
View File
@@ -9,6 +9,7 @@ import (
_ "github.com/cosmos/cosmos-sdk/x/bank"
_ "github.com/cosmos/cosmos-sdk/x/distribution"
_ "github.com/cosmos/cosmos-sdk/x/genutil"
_ "github.com/cosmos/cosmos-sdk/x/mint"
_ "github.com/cosmos/cosmos-sdk/x/params"
_ "github.com/cosmos/cosmos-sdk/x/staking"
)
+3 -2
View File
@@ -6,6 +6,7 @@ import (
"github.com/stretchr/testify/require"
"github.com/cosmos/cosmos-sdk/simapp"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
"github.com/cosmos/cosmos-sdk/testutil/testdata"
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
@@ -38,8 +39,8 @@ func getTestProposal() []sdk.Msg {
func createValidators(t *testing.T, ctx sdk.Context, app *simapp.SimApp, powers []int64) ([]sdk.AccAddress, []sdk.ValAddress) {
addrs := simapp.AddTestAddrsIncremental(app, ctx, 5, sdk.NewInt(30000000))
valAddrs := simapp.ConvertAddrsToValAddrs(addrs)
pks := simapp.CreateTestPubKeys(5)
valAddrs := simtestutil.ConvertAddrsToValAddrs(addrs)
pks := simtestutil.CreateTestPubKeys(5)
cdc := simapp.MakeTestEncodingConfig().Codec
app.StakingKeeper = stakingkeeper.NewKeeper(
+2 -2
View File
@@ -3,7 +3,7 @@ package simulation
import (
"math/rand"
simappparams "github.com/cosmos/cosmos-sdk/simapp/params"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
"github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1"
@@ -18,7 +18,7 @@ func ProposalContents() []simtypes.WeightedProposalContent {
return []simtypes.WeightedProposalContent{
simulation.NewWeightedProposalContent(
OpWeightMsgDeposit,
simappparams.DefaultWeightTextProposal,
simtestutil.DefaultWeightTextProposal,
SimulateTextProposalContent,
),
}
+2 -2
View File
@@ -7,7 +7,7 @@ import (
"github.com/stretchr/testify/require"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
simappparams "github.com/cosmos/cosmos-sdk/simapp/params"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
"github.com/cosmos/cosmos-sdk/x/gov/simulation"
@@ -29,7 +29,7 @@ func TestProposalContents(t *testing.T) {
// tests w0 interface:
require.Equal(t, simulation.OpWeightMsgDeposit, w0.AppParamsKey())
require.Equal(t, simappparams.DefaultWeightTextProposal, w0.DefaultWeight())
require.Equal(t, simtestutil.DefaultWeightTextProposal, w0.DefaultWeight())
content := w0.ContentSimulatorFn()(r, ctx, accounts)
+1 -1
View File
@@ -16,7 +16,7 @@ import (
func TestItCreatesModuleAccountOnInitBlock(t *testing.T) {
var accountKeeper authkeeper.AccountKeeper
app, err := simtestutil.Setup(testutil.AppConfig, &accountKeeper)
app, err := simtestutil.SetupAtGenesis(testutil.AppConfig, &accountKeeper)
require.NoError(t, err)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
+2 -1
View File
@@ -9,6 +9,7 @@ import (
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/cosmos/cosmos-sdk/simapp"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/slashing"
"github.com/cosmos/cosmos-sdk/x/staking"
@@ -20,7 +21,7 @@ func TestBeginBlocker(t *testing.T) {
app := simapp.Setup(t, false)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
pks := simapp.CreateTestPubKeys(1)
pks := simtestutil.CreateTestPubKeys(1)
simapp.AddTestAddrsFromPubKeys(app, ctx, pks, app.StakingKeeper.TokensFromConsensusPower(ctx, 200))
addr, pk := sdk.ValAddress(pks[0].Address()), pks[0]
tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper)
+8 -7
View File
@@ -8,6 +8,7 @@ import (
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/cosmos/cosmos-sdk/simapp"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/slashing/testslashing"
"github.com/cosmos/cosmos-sdk/x/staking"
@@ -24,8 +25,8 @@ func TestUnJailNotBonded(t *testing.T) {
app.StakingKeeper.SetParams(ctx, p)
addrDels := simapp.AddTestAddrsIncremental(app, ctx, 6, app.StakingKeeper.TokensFromConsensusPower(ctx, 200))
valAddrs := simapp.ConvertAddrsToValAddrs(addrDels)
pks := simapp.CreateTestPubKeys(6)
valAddrs := simtestutil.ConvertAddrsToValAddrs(addrDels)
pks := simtestutil.CreateTestPubKeys(6)
tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper)
// create max (5) validators all with the same power
@@ -86,8 +87,8 @@ func TestHandleNewValidator(t *testing.T) {
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
addrDels := simapp.AddTestAddrsIncremental(app, ctx, 1, app.StakingKeeper.TokensFromConsensusPower(ctx, 200))
valAddrs := simapp.ConvertAddrsToValAddrs(addrDels)
pks := simapp.CreateTestPubKeys(1)
valAddrs := simtestutil.ConvertAddrsToValAddrs(addrDels)
pks := simtestutil.CreateTestPubKeys(1)
addr, val := valAddrs[0], pks[0]
tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper)
ctx = ctx.WithBlockHeight(app.SlashingKeeper.SignedBlocksWindow(ctx) + 1)
@@ -132,8 +133,8 @@ func TestHandleAlreadyJailed(t *testing.T) {
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
addrDels := simapp.AddTestAddrsIncremental(app, ctx, 1, app.StakingKeeper.TokensFromConsensusPower(ctx, 200))
valAddrs := simapp.ConvertAddrsToValAddrs(addrDels)
pks := simapp.CreateTestPubKeys(1)
valAddrs := simtestutil.ConvertAddrsToValAddrs(addrDels)
pks := simtestutil.CreateTestPubKeys(1)
addr, val := valAddrs[0], pks[0]
power := int64(100)
tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper)
@@ -190,7 +191,7 @@ func TestValidatorDippingInAndOut(t *testing.T) {
app.StakingKeeper.SetParams(ctx, params)
power := int64(100)
pks := simapp.CreateTestPubKeys(3)
pks := simtestutil.CreateTestPubKeys(3)
simapp.AddTestAddrsFromPubKeys(app, ctx, pks, app.StakingKeeper.TokensFromConsensusPower(ctx, 200))
addr, val := pks[0].Address(), pks[0]
+3 -2
View File
@@ -10,6 +10,7 @@ import (
"github.com/cosmos/cosmos-sdk/crypto/keys/ed25519"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
"github.com/cosmos/cosmos-sdk/simapp"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/staking/keeper"
"github.com/cosmos/cosmos-sdk/x/staking/types"
@@ -31,7 +32,7 @@ var (
commissionRates = types.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec())
PKs = simapp.CreateTestPubKeys(500)
PKs = simtestutil.CreateTestPubKeys(500)
)
// getBaseSimappWithCustomKeeper Returns a simapp with custom StakingKeeper
@@ -57,7 +58,7 @@ func getBaseSimappWithCustomKeeper(t *testing.T) (*codec.LegacyAmino, *simapp.Si
// generateAddresses generates numAddrs of normal AccAddrs and ValAddrs
func generateAddresses(app *simapp.SimApp, ctx sdk.Context, numAddrs int, accAmount sdk.Int) ([]sdk.AccAddress, []sdk.ValAddress) {
addrDels := simapp.AddTestAddrsIncremental(app, ctx, numAddrs, accAmount)
addrVals := simapp.ConvertAddrsToValAddrs(addrDels)
addrVals := simtestutil.ConvertAddrsToValAddrs(addrDels)
return addrDels, addrVals
}
+3 -2
View File
@@ -8,12 +8,13 @@ import (
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/simapp"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/staking/keeper"
"github.com/cosmos/cosmos-sdk/x/staking/types"
)
var PKs = simapp.CreateTestPubKeys(500)
var PKs = simtestutil.CreateTestPubKeys(500)
func init() {
sdk.DefaultPowerReduction = sdk.NewIntFromBigInt(new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil))
@@ -43,7 +44,7 @@ func ValEq(t *testing.T, exp, got types.Validator) (*testing.T, bool, string, ty
// generateAddresses generates numAddrs of normal AccAddrs and ValAddrs
func generateAddresses(app *simapp.SimApp, ctx sdk.Context, numAddrs int) ([]sdk.AccAddress, []sdk.ValAddress) {
addrDels := simapp.AddTestAddrsIncremental(app, ctx, numAddrs, sdk.NewInt(10000))
addrVals := simapp.ConvertAddrsToValAddrs(addrDels)
addrVals := simtestutil.ConvertAddrsToValAddrs(addrDels)
return addrDels, addrVals
}
+16 -15
View File
@@ -8,6 +8,7 @@ import (
"github.com/stretchr/testify/require"
"github.com/cosmos/cosmos-sdk/simapp"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/bank/testutil"
"github.com/cosmos/cosmos-sdk/x/staking/keeper"
@@ -29,7 +30,7 @@ func TestDelegation(t *testing.T) {
})
addrDels := simapp.AddTestAddrsIncremental(app, ctx, 3, sdk.NewInt(10000))
valAddrs := simapp.ConvertAddrsToValAddrs(addrDels)
valAddrs := simtestutil.ConvertAddrsToValAddrs(addrDels)
// construct the validators
amts := []sdk.Int{sdk.NewInt(9), sdk.NewInt(8), sdk.NewInt(7)}
@@ -150,7 +151,7 @@ func TestUnbondingDelegation(t *testing.T) {
_, app, ctx := createTestInput(t)
delAddrs := simapp.AddTestAddrsIncremental(app, ctx, 2, sdk.NewInt(10000))
valAddrs := simapp.ConvertAddrsToValAddrs(delAddrs)
valAddrs := simtestutil.ConvertAddrsToValAddrs(delAddrs)
ubd := types.NewUnbondingDelegation(
delAddrs[0],
@@ -200,7 +201,7 @@ func TestUnbondDelegation(t *testing.T) {
_, app, ctx := createTestInput(t)
delAddrs := simapp.AddTestAddrsIncremental(app, ctx, 1, sdk.NewInt(10000))
valAddrs := simapp.ConvertAddrsToValAddrs(delAddrs)
valAddrs := simtestutil.ConvertAddrsToValAddrs(delAddrs)
startTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 10)
notBondedPool := app.StakingKeeper.GetNotBondedPool(ctx)
@@ -239,7 +240,7 @@ func TestUnbondingDelegationsMaxEntries(t *testing.T) {
_, app, ctx := createTestInput(t)
addrDels := simapp.AddTestAddrsIncremental(app, ctx, 1, sdk.NewInt(10000))
addrVals := simapp.ConvertAddrsToValAddrs(addrDels)
addrVals := simtestutil.ConvertAddrsToValAddrs(addrDels)
startTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 10)
@@ -321,7 +322,7 @@ func TestUndelegateSelfDelegationBelowMinSelfDelegation(t *testing.T) {
_, app, ctx := createTestInput(t)
addrDels := simapp.AddTestAddrsIncremental(app, ctx, 1, sdk.NewInt(10000))
addrVals := simapp.ConvertAddrsToValAddrs(addrDels)
addrVals := simtestutil.ConvertAddrsToValAddrs(addrDels)
delTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 10)
delCoins := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), delTokens))
@@ -383,7 +384,7 @@ func TestUndelegateFromUnbondingValidator(t *testing.T) {
delCoins := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), delTokens))
addrDels := simapp.AddTestAddrsIncremental(app, ctx, 2, sdk.NewInt(0))
addrVals := simapp.ConvertAddrsToValAddrs(addrDels)
addrVals := simtestutil.ConvertAddrsToValAddrs(addrDels)
// create a validator with a self-delegation
validator := teststaking.NewValidator(t, addrVals[0], PKs[0])
@@ -469,7 +470,7 @@ func TestUndelegateFromUnbondedValidator(t *testing.T) {
delCoins := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), delTokens))
addrDels := simapp.AddTestAddrsIncremental(app, ctx, 2, sdk.NewInt(0))
addrVals := simapp.ConvertAddrsToValAddrs(addrDels)
addrVals := simtestutil.ConvertAddrsToValAddrs(addrDels)
// add bonded tokens to pool for delegations
notBondedPool := app.StakingKeeper.GetNotBondedPool(ctx)
@@ -550,7 +551,7 @@ func TestUnbondingAllDelegationFromValidator(t *testing.T) {
delCoins := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), delTokens))
addrDels := simapp.AddTestAddrsIncremental(app, ctx, 2, sdk.NewInt(0))
addrVals := simapp.ConvertAddrsToValAddrs(addrDels)
addrVals := simtestutil.ConvertAddrsToValAddrs(addrDels)
// add bonded tokens to pool for delegations
notBondedPool := app.StakingKeeper.GetNotBondedPool(ctx)
@@ -621,7 +622,7 @@ func TestGetRedelegationsFromSrcValidator(t *testing.T) {
_, app, ctx := createTestInput(t)
addrDels := simapp.AddTestAddrsIncremental(app, ctx, 2, sdk.NewInt(0))
addrVals := simapp.ConvertAddrsToValAddrs(addrDels)
addrVals := simtestutil.ConvertAddrsToValAddrs(addrDels)
rd := types.NewRedelegation(addrDels[0], addrVals[0], addrVals[1], 0,
time.Unix(0, 0), sdk.NewInt(5),
@@ -648,7 +649,7 @@ func TestRedelegation(t *testing.T) {
_, app, ctx := createTestInput(t)
addrDels := simapp.AddTestAddrsIncremental(app, ctx, 2, sdk.NewInt(0))
addrVals := simapp.ConvertAddrsToValAddrs(addrDels)
addrVals := simtestutil.ConvertAddrsToValAddrs(addrDels)
rd := types.NewRedelegation(addrDels[0], addrVals[0], addrVals[1], 0,
time.Unix(0, 0).UTC(), sdk.NewInt(5),
@@ -711,7 +712,7 @@ func TestRedelegateToSameValidator(t *testing.T) {
_, app, ctx := createTestInput(t)
addrDels := simapp.AddTestAddrsIncremental(app, ctx, 1, sdk.NewInt(0))
addrVals := simapp.ConvertAddrsToValAddrs(addrDels)
addrVals := simtestutil.ConvertAddrsToValAddrs(addrDels)
valTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 10)
startCoins := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), valTokens))
@@ -740,7 +741,7 @@ func TestRedelegationMaxEntries(t *testing.T) {
_, app, ctx := createTestInput(t)
addrDels := simapp.AddTestAddrsIncremental(app, ctx, 2, sdk.NewInt(0))
addrVals := simapp.ConvertAddrsToValAddrs(addrDels)
addrVals := simtestutil.ConvertAddrsToValAddrs(addrDels)
startTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 20)
startCoins := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), startTokens))
@@ -796,7 +797,7 @@ func TestRedelegateSelfDelegation(t *testing.T) {
_, app, ctx := createTestInput(t)
addrDels := simapp.AddTestAddrsIncremental(app, ctx, 2, sdk.NewInt(0))
addrVals := simapp.ConvertAddrsToValAddrs(addrDels)
addrVals := simtestutil.ConvertAddrsToValAddrs(addrDels)
startTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 30)
startCoins := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), startTokens))
@@ -852,7 +853,7 @@ func TestRedelegateFromUnbondingValidator(t *testing.T) {
_, app, ctx := createTestInput(t)
addrDels := simapp.AddTestAddrsIncremental(app, ctx, 2, sdk.NewInt(0))
addrVals := simapp.ConvertAddrsToValAddrs(addrDels)
addrVals := simtestutil.ConvertAddrsToValAddrs(addrDels)
startTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 30)
startCoins := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), startTokens))
@@ -934,7 +935,7 @@ func TestRedelegateFromUnbondedValidator(t *testing.T) {
_, app, ctx := createTestInput(t)
addrDels := simapp.AddTestAddrsIncremental(app, ctx, 2, sdk.NewInt(0))
addrVals := simapp.ConvertAddrsToValAddrs(addrDels)
addrVals := simtestutil.ConvertAddrsToValAddrs(addrDels)
startTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 30)
startCoins := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), startTokens))
+5 -4
View File
@@ -8,6 +8,7 @@ import (
"github.com/stretchr/testify/require"
"github.com/cosmos/cosmos-sdk/simapp"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/query"
"github.com/cosmos/cosmos-sdk/x/staking/keeper"
@@ -356,7 +357,7 @@ func (suite *KeeperTestSuite) TestGRPCQueryValidatorDelegations() {
app, ctx, queryClient, addrs, vals := suite.app, suite.ctx, suite.queryClient, suite.addrs, suite.vals
addrAcc := addrs[0]
addrVal1 := vals[1].OperatorAddress
valAddrs := simapp.ConvertAddrsToValAddrs(addrs)
valAddrs := simtestutil.ConvertAddrsToValAddrs(addrs)
addrVal2 := valAddrs[4]
valAddr, err := sdk.ValAddressFromBech32(addrVal1)
suite.NoError(err)
@@ -634,7 +635,7 @@ func (suite *KeeperTestSuite) TestGRPCQueryRedelegations() {
app, ctx, queryClient, addrs, vals := suite.app, suite.ctx, suite.queryClient, suite.addrs, suite.vals
addrAcc, addrAcc1 := addrs[0], addrs[1]
valAddrs := simapp.ConvertAddrsToValAddrs(addrs)
valAddrs := simtestutil.ConvertAddrsToValAddrs(addrs)
val1, val2, val3, val4 := vals[0], vals[1], valAddrs[3], valAddrs[4]
delAmount := app.StakingKeeper.TokensFromConsensusPower(ctx, 1)
_, err := app.StakingKeeper.Delegate(ctx, addrAcc1, delAmount, types.Unbonded, val1, true)
@@ -787,8 +788,8 @@ func (suite *KeeperTestSuite) TestGRPCQueryValidatorUnbondingDelegations() {
func createValidators(t *testing.T, ctx sdk.Context, app *simapp.SimApp, powers []int64) ([]sdk.AccAddress, []sdk.ValAddress, []types.Validator) {
addrs := simapp.AddTestAddrsIncremental(app, ctx, 5, app.StakingKeeper.TokensFromConsensusPower(ctx, 300))
valAddrs := simapp.ConvertAddrsToValAddrs(addrs)
pks := simapp.CreateTestPubKeys(5)
valAddrs := simtestutil.ConvertAddrsToValAddrs(addrs)
pks := simtestutil.CreateTestPubKeys(5)
cdc := simapp.MakeTestEncodingConfig().Codec
app.StakingKeeper = keeper.NewKeeper(
cdc,
+4 -3
View File
@@ -7,6 +7,7 @@ import (
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/cosmos/cosmos-sdk/simapp"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/staking/teststaking"
"github.com/cosmos/cosmos-sdk/x/staking/types"
@@ -27,7 +28,7 @@ func TestHistoricalInfo(t *testing.T) {
_, app, ctx := createTestInput(t)
addrDels := simapp.AddTestAddrsIncremental(app, ctx, 50, sdk.NewInt(0))
addrVals := simapp.ConvertAddrsToValAddrs(addrDels)
addrVals := simtestutil.ConvertAddrsToValAddrs(addrDels)
validators := make([]types.Validator, len(addrVals))
@@ -54,7 +55,7 @@ func TestTrackHistoricalInfo(t *testing.T) {
_, app, ctx := createTestInput(t)
addrDels := simapp.AddTestAddrsIncremental(app, ctx, 50, sdk.NewInt(0))
addrVals := simapp.ConvertAddrsToValAddrs(addrDels)
addrVals := simtestutil.ConvertAddrsToValAddrs(addrDels)
// set historical entries in params to 5
params := types.DefaultParams()
@@ -140,7 +141,7 @@ func TestGetAllHistoricalInfo(t *testing.T) {
app.StakingKeeper.DeleteHistoricalInfo(ctx, infos[0].Header.Height)
addrDels := simapp.AddTestAddrsIncremental(app, ctx, 50, sdk.NewInt(0))
addrVals := simapp.ConvertAddrsToValAddrs(addrDels)
addrVals := simtestutil.ConvertAddrsToValAddrs(addrDels)
valSet := []types.Validator{
teststaking.NewValidator(t, addrVals[0], PKs[0]),
+3 -2
View File
@@ -10,6 +10,7 @@ import (
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/simapp"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/staking/keeper"
"github.com/cosmos/cosmos-sdk/x/staking/teststaking"
@@ -211,7 +212,7 @@ func TestQueryDelegation(t *testing.T) {
addrAcc1, addrAcc2 := addrs[0], addrs[1]
addrVal1, addrVal2 := sdk.ValAddress(addrAcc1), sdk.ValAddress(addrAcc2)
pubKeys := simapp.CreateTestPubKeys(2)
pubKeys := simtestutil.CreateTestPubKeys(2)
pk1, pk2 := pubKeys[0], pubKeys[1]
// Create Validators and Delegation
@@ -458,7 +459,7 @@ func TestQueryValidatorDelegations_Pagination(t *testing.T) {
querier := keeper.NewQuerier(app.StakingKeeper, legacyQuerierCdc.LegacyAmino)
addrs := simapp.AddTestAddrs(app, ctx, 100, app.StakingKeeper.TokensFromConsensusPower(ctx, 10000))
pubKeys := simapp.CreateTestPubKeys(1)
pubKeys := simtestutil.CreateTestPubKeys(1)
valAddress := sdk.ValAddress(addrs[0])
+1 -1
View File
@@ -3,7 +3,7 @@ package keeper_test
import "testing"
func BenchmarkGetValidator(b *testing.B) {
// 900 is the max number we are allowed to use in order to avoid simapp.CreateTestPubKeys
// 900 is the max number we are allowed to use in order to avoid simtestutil.CreateTestPubKeys
// panic: encoding/hex: odd length hex string
powersNumber := 900
+2 -1
View File
@@ -12,6 +12,7 @@ import (
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
"github.com/cosmos/cosmos-sdk/simapp"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/bank/testutil"
"github.com/cosmos/cosmos-sdk/x/staking"
@@ -56,7 +57,7 @@ func bootstrapValidatorTest(t testing.TB, power int64, numAddrs int) (*simapp.Si
func initValidators(t testing.TB, power int64, numAddrs int, powers []int64) (*simapp.SimApp, sdk.Context, []sdk.AccAddress, []sdk.ValAddress, []types.Validator) {
app, ctx, addrs, valAddrs := bootstrapValidatorTest(t, power, numAddrs)
pks := simapp.CreateTestPubKeys(numAddrs)
pks := simtestutil.CreateTestPubKeys(numAddrs)
vs := make([]types.Validator, len(powers))
for i, power := range powers {