diff --git a/CHANGELOG.md b/CHANGELOG.md index 7fd480a79..7b702ac57 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -527,7 +527,7 @@ BREAKING CHANGES * [gaiad init] [\#2602](https://github.com/cosmos/cosmos-sdk/issues/2602) New genesis workflow * SDK - * [simulation] [\#2665](https://github.com/cosmos/cosmos-sdk/issues/2665) only argument to simulation.Invariant is now app + * [simulation] [\#2665](https://github.com/cosmos/cosmos-sdk/issues/2665) only argument to sdk.Invariant is now app * Tendermint * Upgrade to version 0.26.0 diff --git a/PENDING.md b/PENDING.md index 0012b26f5..3c563a90b 100644 --- a/PENDING.md +++ b/PENDING.md @@ -9,6 +9,7 @@ BREAKING CHANGES * Gaia * SDK + * \#3621 staking.GenesisState.Bonds -> Delegations * Tendermint @@ -34,6 +35,7 @@ IMPROVEMENTS * Gaia * SDK + * \#3621 remove many inter-module dependancies * [\#3601] JSON-stringify the ABCI log response which includes the log and message index. * [\#3604] Improve SDK funds related error messages and allow for unicode in diff --git a/client/lcd/lcd_test.go b/client/lcd/lcd_test.go index 56dd65d3e..6cdaf0331 100644 --- a/client/lcd/lcd_test.go +++ b/client/lcd/lcd_test.go @@ -40,7 +40,7 @@ const ( altPw = "12345678901" ) -var fees = sdk.Coins{sdk.NewInt64Coin(staking.DefaultBondDenom, 5)} +var fees = sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 5)} func init() { mintkey.BcryptSecurityParameter = 1 @@ -243,14 +243,14 @@ func TestCoinSend(t *testing.T) { coins := acc.GetCoins() expectedBalance := initialBalance[0].Minus(fees[0]) - require.Equal(t, staking.DefaultBondDenom, coins[0].Denom) + require.Equal(t, sdk.DefaultBondDenom, coins[0].Denom) require.Equal(t, expectedBalance.Amount.SubRaw(1), coins[0].Amount) expectedBalance = coins[0] // query receiver acc2 := getAccount(t, port, receiveAddr) coins2 := acc2.GetCoins() - require.Equal(t, staking.DefaultBondDenom, coins2[0].Denom) + require.Equal(t, sdk.DefaultBondDenom, coins2[0].Denom) require.Equal(t, int64(1), coins2[0].Amount.Int64()) // test failure with too little gas @@ -286,7 +286,7 @@ func TestCoinSend(t *testing.T) { require.NotZero(t, gasEstResp.GasEstimate) acc = getAccount(t, port, addr) - require.Equal(t, expectedBalance.Amount, acc.GetCoins().AmountOf(staking.DefaultBondDenom)) + require.Equal(t, expectedBalance.Amount, acc.GetCoins().AmountOf(sdk.DefaultBondDenom)) // run successful tx gas := fmt.Sprintf("%d", gasEstResp.GasEstimate) @@ -301,7 +301,7 @@ func TestCoinSend(t *testing.T) { acc = getAccount(t, port, addr) expectedBalance = expectedBalance.Minus(fees[0]) - require.Equal(t, expectedBalance.Amount.SubRaw(1), acc.GetCoins().AmountOf(staking.DefaultBondDenom)) + require.Equal(t, expectedBalance.Amount.SubRaw(1), acc.GetCoins().AmountOf(sdk.DefaultBondDenom)) } func TestCoinSendAccAuto(t *testing.T) { @@ -323,7 +323,7 @@ func TestCoinSendAccAuto(t *testing.T) { coins := acc.GetCoins() expectedBalance := initialBalance[0].Minus(fees[0]) - require.Equal(t, staking.DefaultBondDenom, coins[0].Denom) + require.Equal(t, sdk.DefaultBondDenom, coins[0].Denom) require.Equal(t, expectedBalance.Amount.SubRaw(1), coins[0].Amount) } @@ -520,11 +520,11 @@ func TestPoolParamsQuery(t *testing.T) { pool := getStakingPool(t, port) initialPool := staking.InitialPool() - tokens := staking.TokensFromTendermintPower(100) - freeFermions := staking.TokensFromTendermintPower(50) + tokens := sdk.TokensFromTendermintPower(100) + freeTokens := sdk.TokensFromTendermintPower(50) initialPool.NotBondedTokens = initialPool.NotBondedTokens.Add(tokens) - initialPool.BondedTokens = initialPool.BondedTokens.Add(tokens) // Delegate tx on GaiaAppGenState - initialPool.NotBondedTokens = initialPool.NotBondedTokens.Add(freeFermions) // freeFermionsAcc = 50 on GaiaAppGenState + initialPool.BondedTokens = initialPool.BondedTokens.Add(tokens) // Delegate tx on GaiaAppGenState + initialPool.NotBondedTokens = initialPool.NotBondedTokens.Add(freeTokens) // freeTokensPerAcc = 50 on GaiaAppGenState require.Equal(t, initialPool.BondedTokens, pool.BondedTokens) @@ -575,7 +575,7 @@ func TestBonding(t *testing.T) { require.Equal(t, 2, len(valPubKeys)) require.Equal(t, 2, len(operAddrs)) - amt := staking.TokensFromTendermintPower(60) + amt := sdk.TokensFromTendermintPower(60) amtDec := sdk.NewDecFromInt(amt) validator := getValidator(t, port, operAddrs[0]) @@ -583,7 +583,7 @@ func TestBonding(t *testing.T) { initialBalance := acc.GetCoins() // create bond TX - delTokens := staking.TokensFromTendermintPower(60) + delTokens := sdk.TokensFromTendermintPower(60) resultTx := doDelegate(t, port, name1, pw, addr, operAddrs[0], delTokens, fees) tests.WaitForHeight(resultTx.Height+1, port) @@ -601,7 +601,7 @@ func TestBonding(t *testing.T) { acc = getAccount(t, port, addr) coins := acc.GetCoins() expectedBalance := initialBalance[0].Minus(fees[0]) - require.Equal(t, expectedBalance.Amount.Sub(delTokens), coins.AmountOf(staking.DefaultBondDenom)) + require.Equal(t, expectedBalance.Amount.Sub(delTokens), coins.AmountOf(sdk.DefaultBondDenom)) expectedBalance = coins[0] // query delegation @@ -625,7 +625,7 @@ func TestBonding(t *testing.T) { require.Equal(t, operAddrs[0], bondedValidator.OperatorAddr) // testing unbonding - unbondingTokens := staking.TokensFromTendermintPower(30) + unbondingTokens := sdk.TokensFromTendermintPower(30) resultTx = doUndelegate(t, port, name1, pw, addr, operAddrs[0], unbondingTokens, fees) tests.WaitForHeight(resultTx.Height+1, port) @@ -636,8 +636,8 @@ func TestBonding(t *testing.T) { coins = acc.GetCoins() expectedBalance = expectedBalance.Minus(fees[0]) require.True(t, - expectedBalance.Amount.LT(coins.AmountOf(staking.DefaultBondDenom)) || - expectedBalance.Amount.Equal(coins.AmountOf(staking.DefaultBondDenom)), + expectedBalance.Amount.LT(coins.AmountOf(sdk.DefaultBondDenom)) || + expectedBalance.Amount.Equal(coins.AmountOf(sdk.DefaultBondDenom)), "should get tokens back from automatic withdrawal after an unbonding delegation", ) expectedBalance = coins[0] @@ -655,7 +655,7 @@ func TestBonding(t *testing.T) { require.Equal(t, delTokens.DivRaw(2), ubd.Entries[0].Balance) // test redelegation - rdTokens := staking.TokensFromTendermintPower(30) + rdTokens := sdk.TokensFromTendermintPower(30) resultTx = doBeginRedelegation(t, port, name1, pw, addr, operAddrs[0], operAddrs[1], rdTokens, fees) tests.WaitForHeight(resultTx.Height+1, port) @@ -665,8 +665,8 @@ func TestBonding(t *testing.T) { acc = getAccount(t, port, addr) expectedBalance = expectedBalance.Minus(fees[0]) require.True(t, - expectedBalance.Amount.LT(coins.AmountOf(staking.DefaultBondDenom)) || - expectedBalance.Amount.Equal(coins.AmountOf(staking.DefaultBondDenom)), + expectedBalance.Amount.LT(coins.AmountOf(sdk.DefaultBondDenom)) || + expectedBalance.Amount.Equal(coins.AmountOf(sdk.DefaultBondDenom)), "should get tokens back from automatic withdrawal after an unbonding delegation", ) @@ -735,7 +735,7 @@ func TestSubmitProposal(t *testing.T) { initialBalance := acc.GetCoins() // create SubmitProposal TX - proposalTokens := staking.TokensFromTendermintPower(5) + proposalTokens := sdk.TokensFromTendermintPower(5) resultTx := doSubmitProposal(t, port, seed, name1, pw, addr, proposalTokens, fees) tests.WaitForHeight(resultTx.Height+1, port) @@ -748,7 +748,7 @@ func TestSubmitProposal(t *testing.T) { // verify balance acc = getAccount(t, port, addr) expectedBalance := initialBalance[0].Minus(fees[0]) - require.Equal(t, expectedBalance.Amount.Sub(proposalTokens), acc.GetCoins().AmountOf(staking.DefaultBondDenom)) + require.Equal(t, expectedBalance.Amount.Sub(proposalTokens), acc.GetCoins().AmountOf(sdk.DefaultBondDenom)) // query proposal proposal := getProposal(t, port, proposalID) @@ -770,7 +770,7 @@ func TestDeposit(t *testing.T) { initialBalance := acc.GetCoins() // create SubmitProposal TX - proposalTokens := staking.TokensFromTendermintPower(5) + proposalTokens := sdk.TokensFromTendermintPower(5) resultTx := doSubmitProposal(t, port, seed, name1, pw, addr, proposalTokens, fees) tests.WaitForHeight(resultTx.Height+1, port) @@ -784,7 +784,7 @@ func TestDeposit(t *testing.T) { acc = getAccount(t, port, addr) coins := acc.GetCoins() expectedBalance := initialBalance[0].Minus(fees[0]) - require.Equal(t, expectedBalance.Amount.Sub(proposalTokens), coins.AmountOf(staking.DefaultBondDenom)) + require.Equal(t, expectedBalance.Amount.Sub(proposalTokens), coins.AmountOf(sdk.DefaultBondDenom)) expectedBalance = coins[0] // query proposal @@ -792,14 +792,14 @@ func TestDeposit(t *testing.T) { require.Equal(t, "Test", proposal.GetTitle()) // create SubmitProposal TX - depositTokens := staking.TokensFromTendermintPower(5) + depositTokens := sdk.TokensFromTendermintPower(5) resultTx = doDeposit(t, port, seed, name1, pw, addr, proposalID, depositTokens, fees) tests.WaitForHeight(resultTx.Height+1, port) // verify balance after deposit and fee acc = getAccount(t, port, addr) expectedBalance = expectedBalance.Minus(fees[0]) - require.Equal(t, expectedBalance.Amount.Sub(depositTokens), acc.GetCoins().AmountOf(staking.DefaultBondDenom)) + require.Equal(t, expectedBalance.Amount.Sub(depositTokens), acc.GetCoins().AmountOf(sdk.DefaultBondDenom)) // query tx txs := getTransactions(t, port, fmt.Sprintf("action=deposit&depositor=%s", addr)) @@ -807,7 +807,7 @@ func TestDeposit(t *testing.T) { require.Equal(t, resultTx.Height, txs[0].Height) // query proposal - totalCoins := sdk.Coins{sdk.NewCoin(staking.DefaultBondDenom, staking.TokensFromTendermintPower(10))} + totalCoins := sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.TokensFromTendermintPower(10))} proposal = getProposal(t, port, proposalID) require.True(t, proposal.GetTotalDeposit().IsEqual(totalCoins)) @@ -827,7 +827,7 @@ func TestVote(t *testing.T) { initialBalance := acc.GetCoins() // create SubmitProposal TX - proposalTokens := staking.TokensFromTendermintPower(10) + proposalTokens := sdk.TokensFromTendermintPower(10) resultTx := doSubmitProposal(t, port, seed, name1, pw, addr, proposalTokens, fees) tests.WaitForHeight(resultTx.Height+1, port) @@ -841,7 +841,7 @@ func TestVote(t *testing.T) { acc = getAccount(t, port, addr) coins := acc.GetCoins() expectedBalance := initialBalance[0].Minus(fees[0]) - require.Equal(t, expectedBalance.Amount.Sub(proposalTokens), coins.AmountOf(staking.DefaultBondDenom)) + require.Equal(t, expectedBalance.Amount.Sub(proposalTokens), coins.AmountOf(sdk.DefaultBondDenom)) expectedBalance = coins[0] // query proposal @@ -857,7 +857,7 @@ func TestVote(t *testing.T) { acc = getAccount(t, port, addr) coins = acc.GetCoins() expectedBalance = expectedBalance.Minus(fees[0]) - require.Equal(t, expectedBalance.Amount, coins.AmountOf(staking.DefaultBondDenom)) + require.Equal(t, expectedBalance.Amount, coins.AmountOf(sdk.DefaultBondDenom)) expectedBalance = coins[0] // query tx @@ -873,7 +873,7 @@ func TestVote(t *testing.T) { require.Equal(t, sdk.ZeroInt(), tally.Yes, "tally should be 0 as the address is not bonded") // create bond TX - delTokens := staking.TokensFromTendermintPower(60) + delTokens := sdk.TokensFromTendermintPower(60) resultTx = doDelegate(t, port, name1, pw, addr, operAddrs[0], delTokens, fees) tests.WaitForHeight(resultTx.Height+1, port) @@ -881,7 +881,7 @@ func TestVote(t *testing.T) { acc = getAccount(t, port, addr) coins = acc.GetCoins() expectedBalance = expectedBalance.Minus(fees[0]) - require.Equal(t, expectedBalance.Amount.Sub(delTokens), coins.AmountOf(staking.DefaultBondDenom)) + require.Equal(t, expectedBalance.Amount.Sub(delTokens), coins.AmountOf(sdk.DefaultBondDenom)) expectedBalance = coins[0] tally = getTally(t, port, proposalID) @@ -894,7 +894,7 @@ func TestVote(t *testing.T) { // verify balance acc = getAccount(t, port, addr) expectedBalance = expectedBalance.Minus(fees[0]) - require.Equal(t, expectedBalance.Amount, acc.GetCoins().AmountOf(staking.DefaultBondDenom)) + require.Equal(t, expectedBalance.Amount, acc.GetCoins().AmountOf(sdk.DefaultBondDenom)) tally = getTally(t, port, proposalID) require.Equal(t, sdk.ZeroInt(), tally.Yes, "tally should be 0 the user changed the option") @@ -927,7 +927,7 @@ func TestProposalsQuery(t *testing.T) { defer cleanup() depositParam := getDepositParam(t, port) - halfMinDeposit := depositParam.MinDeposit.AmountOf(staking.DefaultBondDenom).DivRaw(2) + halfMinDeposit := depositParam.MinDeposit.AmountOf(sdk.DefaultBondDenom).DivRaw(2) getVotingParam(t, port) getTallyingParam(t, port) @@ -974,7 +974,7 @@ func TestProposalsQuery(t *testing.T) { require.Equal(t, deposit, deposits[0]) // increasing the amount of the deposit should update the existing one - depositTokens := staking.TokensFromTendermintPower(1) + depositTokens := sdk.TokensFromTendermintPower(1) resultTx = doDeposit(t, port, seeds[0], names[0], passwords[0], addrs[0], proposalID1, depositTokens, fees) tests.WaitForHeight(resultTx.Height+1, port) @@ -1085,7 +1085,7 @@ func TestDistributionFlow(t *testing.T) { require.Equal(t, valDistInfo.OperatorAddress.String(), sdk.AccAddress(valAddr).String()) // Delegate some coins - delTokens := staking.TokensFromTendermintPower(60) + delTokens := sdk.TokensFromTendermintPower(60) resultTx := doDelegate(t, port, name1, pw, addr, valAddr, delTokens, fees) tests.WaitForHeight(resultTx.Height+1, port) require.Equal(t, uint32(0), resultTx.Code) diff --git a/client/lcd/test_helpers.go b/client/lcd/test_helpers.go index ae126ef1d..ede3b4cfd 100644 --- a/client/lcd/test_helpers.go +++ b/client/lcd/test_helpers.go @@ -230,12 +230,12 @@ func InitializeTestLCD(t *testing.T, nValidators int, initAddrs []sdk.AccAddress pubKey = ed25519.GenPrivKey().PubKey() power = 1 } - startTokens := staking.TokensFromTendermintPower(power) + startTokens := sdk.TokensFromTendermintPower(power) msg := staking.NewMsgCreateValidator( sdk.ValAddress(operAddr), pubKey, - sdk.NewCoin(staking.DefaultBondDenom, startTokens), + sdk.NewCoin(sdk.DefaultBondDenom, startTokens), staking.NewDescription(fmt.Sprintf("validator-%d", i+1), "", "", ""), staking.NewCommissionMsg(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), sdk.OneInt(), @@ -255,8 +255,8 @@ func InitializeTestLCD(t *testing.T, nValidators int, initAddrs []sdk.AccAddress valOperAddrs = append(valOperAddrs, sdk.ValAddress(operAddr)) accAuth := auth.NewBaseAccountWithAddress(sdk.AccAddress(operAddr)) - accTokens := staking.TokensFromTendermintPower(150) - accAuth.Coins = sdk.Coins{sdk.NewCoin(staking.DefaultBondDenom, accTokens)} + accTokens := sdk.TokensFromTendermintPower(150) + accAuth.Coins = sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, accTokens)} accs = append(accs, gapp.NewGenesisAccount(&accAuth)) } @@ -270,8 +270,8 @@ func InitializeTestLCD(t *testing.T, nValidators int, initAddrs []sdk.AccAddress // add some tokens to init accounts for _, addr := range initAddrs { accAuth := auth.NewBaseAccountWithAddress(addr) - accTokens := staking.TokensFromTendermintPower(100) - accAuth.Coins = sdk.Coins{sdk.NewCoin(staking.DefaultBondDenom, accTokens)} + accTokens := sdk.TokensFromTendermintPower(100) + accAuth.Coins = sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, accTokens)} acc := gapp.NewGenesisAccount(&accAuth) genesisState.Accounts = append(genesisState.Accounts, acc) genesisState.StakingData.Pool.NotBondedTokens = genesisState.StakingData.Pool.NotBondedTokens.Add(accTokens) @@ -707,7 +707,7 @@ func doTransferWithGas( ) sr := rest.SendReq{ - Amount: sdk.Coins{sdk.NewInt64Coin(staking.DefaultBondDenom, 1)}, + Amount: sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 1)}, BaseReq: baseReq, } @@ -740,7 +740,7 @@ func doTransferWithGasAccAuto( ) sr := rest.SendReq{ - Amount: sdk.Coins{sdk.NewInt64Coin(staking.DefaultBondDenom, 1)}, + Amount: sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 1)}, BaseReq: baseReq, } @@ -773,7 +773,7 @@ func doDelegate(t *testing.T, port, name, password string, BaseReq: baseReq, DelegatorAddr: delAddr, ValidatorAddr: valAddr, - Delegation: sdk.NewCoin(staking.DefaultBondDenom, amount), + Delegation: sdk.NewCoin(sdk.DefaultBondDenom, amount), } req, err := cdc.MarshalJSON(msg) require.NoError(t, err) @@ -1079,7 +1079,7 @@ func doSubmitProposal(t *testing.T, port, seed, name, password string, proposerA Description: "test", ProposalType: "Text", Proposer: proposerAddr, - InitialDeposit: sdk.Coins{sdk.NewCoin(staking.DefaultBondDenom, amount)}, + InitialDeposit: sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, amount)}, BaseReq: baseReq, } @@ -1173,7 +1173,7 @@ func doDeposit(t *testing.T, port, seed, name, password string, proposerAddr sdk dr := rest.DepositReq{ Depositor: proposerAddr, - Amount: sdk.Coins{sdk.NewCoin(staking.DefaultBondDenom, amount)}, + Amount: sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, amount)}, BaseReq: baseReq, } diff --git a/cmd/gaia/app/app.go b/cmd/gaia/app/app.go index a84f179a4..096d68ba5 100644 --- a/cmd/gaia/app/app.go +++ b/cmd/gaia/app/app.go @@ -254,7 +254,7 @@ func (app *GaiaApp) initFromGenesisState(ctx sdk.Context, genesisState GenesisSt // initialize module-specific stores auth.InitGenesis(ctx, app.accountKeeper, app.feeCollectionKeeper, genesisState.AuthData) bank.InitGenesis(ctx, app.bankKeeper, genesisState.BankData) - slashing.InitGenesis(ctx, app.slashingKeeper, genesisState.SlashingData, genesisState.StakingData) + slashing.InitGenesis(ctx, app.slashingKeeper, genesisState.SlashingData, genesisState.StakingData.Validators.ToSDKValidators()) gov.InitGenesis(ctx, app.govKeeper, genesisState.GovData) mint.InitGenesis(ctx, app.mintKeeper, genesisState.MintData) diff --git a/cmd/gaia/app/genesis.go b/cmd/gaia/app/genesis.go index 2cf3e3cba..3938c9dce 100644 --- a/cmd/gaia/app/genesis.go +++ b/cmd/gaia/app/genesis.go @@ -27,8 +27,8 @@ import ( var ( // bonded tokens given to genesis validators/accounts - freeFermionsAcc = staking.TokensFromTendermintPower(150) - defaultBondDenom = staking.DefaultBondDenom + freeTokensPerAcc = sdk.TokensFromTendermintPower(150) + defaultBondDenom = sdk.DefaultBondDenom ) // State to Unmarshal @@ -401,7 +401,7 @@ func NewDefaultGenesisAccount(addr sdk.AccAddress) GenesisAccount { accAuth := auth.NewBaseAccountWithAddress(addr) coins := sdk.Coins{ sdk.NewCoin("footoken", sdk.NewInt(1000)), - sdk.NewCoin(defaultBondDenom, freeFermionsAcc), + sdk.NewCoin(defaultBondDenom, freeTokensPerAcc), } coins.Sort() diff --git a/cmd/gaia/app/genesis_test.go b/cmd/gaia/app/genesis_test.go index cbbad1ee7..058347069 100644 --- a/cmd/gaia/app/genesis_test.go +++ b/cmd/gaia/app/genesis_test.go @@ -151,7 +151,7 @@ func TestNewDefaultGenesisAccount(t *testing.T) { addr := secp256k1.GenPrivKeySecp256k1([]byte("")).PubKey().Address() acc := NewDefaultGenesisAccount(sdk.AccAddress(addr)) require.Equal(t, sdk.NewInt(1000), acc.Coins.AmountOf("footoken")) - require.Equal(t, staking.TokensFromTendermintPower(150), acc.Coins.AmountOf(defaultBondDenom)) + require.Equal(t, sdk.TokensFromTendermintPower(150), acc.Coins.AmountOf(defaultBondDenom)) } func TestGenesisStateSanitize(t *testing.T) { diff --git a/cmd/gaia/app/invariants.go b/cmd/gaia/app/invariants.go index 6b98edb6a..535cbff37 100644 --- a/cmd/gaia/app/invariants.go +++ b/cmd/gaia/app/invariants.go @@ -9,16 +9,14 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" banksim "github.com/cosmos/cosmos-sdk/x/bank/simulation" distrsim "github.com/cosmos/cosmos-sdk/x/distribution/simulation" - "github.com/cosmos/cosmos-sdk/x/mock/simulation" stakingsim "github.com/cosmos/cosmos-sdk/x/staking/simulation" ) -func (app *GaiaApp) runtimeInvariants() []simulation.Invariant { - return []simulation.Invariant{ +func (app *GaiaApp) runtimeInvariants() []sdk.Invariant { + return []sdk.Invariant{ banksim.NonnegativeBalanceInvariant(app.accountKeeper), distrsim.NonNegativeOutstandingInvariant(app.distrKeeper), - stakingsim.SupplyInvariants(app.bankKeeper, app.stakingKeeper, - app.feeCollectionKeeper, app.distrKeeper, app.accountKeeper), + stakingsim.SupplyInvariants(app.stakingKeeper, app.feeCollectionKeeper, app.distrKeeper, app.accountKeeper), stakingsim.NonNegativePowerInvariant(app.stakingKeeper), } } diff --git a/cmd/gaia/app/sim_test.go b/cmd/gaia/app/sim_test.go index 90b1785b1..7e4d465fe 100644 --- a/cmd/gaia/app/sim_test.go +++ b/cmd/gaia/app/sim_test.go @@ -97,7 +97,7 @@ func appStateRandomizedFn(r *rand.Rand, accs []simulation.Account, genesisTimest // randomly generate some genesis accounts for i, acc := range accs { - coins := sdk.Coins{sdk.NewCoin(staking.DefaultBondDenom, sdk.NewInt(amount))} + coins := sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(amount))} bacc := auth.NewBaseAccountWithAddress(acc.Address) bacc.SetCoins(coins) @@ -154,7 +154,7 @@ func appStateRandomizedFn(r *rand.Rand, accs []simulation.Account, genesisTimest govGenesis := gov.GenesisState{ StartingProposalID: uint64(r.Intn(100)), DepositParams: gov.DepositParams{ - MinDeposit: sdk.Coins{sdk.NewInt64Coin(staking.DefaultBondDenom, int64(r.Intn(1e3)))}, + MinDeposit: sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, int64(r.Intn(1e3)))}, MaxDepositPeriod: vp, }, VotingParams: gov.VotingParams{ @@ -173,7 +173,7 @@ func appStateRandomizedFn(r *rand.Rand, accs []simulation.Account, genesisTimest Params: staking.Params{ UnbondingTime: time.Duration(randIntBetween(r, 60, 60*60*24*3*2)) * time.Second, MaxValidators: uint16(r.Intn(250)), - BondDenom: staking.DefaultBondDenom, + BondDenom: sdk.DefaultBondDenom, }, } fmt.Printf("Selected randomly generated staking parameters:\n\t%+v\n", stakingGenesis) @@ -194,7 +194,7 @@ func appStateRandomizedFn(r *rand.Rand, accs []simulation.Account, genesisTimest Minter: mint.InitialMinter( sdk.NewDecWithPrec(int64(r.Intn(99)), 2)), Params: mint.NewParams( - staking.DefaultBondDenom, + sdk.DefaultBondDenom, sdk.NewDecWithPrec(int64(r.Intn(99)), 2), sdk.NewDecWithPrec(20, 2), sdk.NewDecWithPrec(7, 2), @@ -221,7 +221,7 @@ func appStateRandomizedFn(r *rand.Rand, accs []simulation.Account, genesisTimest stakingGenesis.Pool.NotBondedTokens = sdk.NewInt((amount * numAccs) + (numInitiallyBonded * amount)) stakingGenesis.Validators = validators - stakingGenesis.Bonds = delegations + stakingGenesis.Delegations = delegations distrGenesis := distr.GenesisState{ FeePool: distr.InitialFeePool(), @@ -270,7 +270,7 @@ func testAndRunTxs(app *GaiaApp) []simulation.WeightedOperation { {50, distrsim.SimulateMsgSetWithdrawAddress(app.accountKeeper, app.distrKeeper)}, {50, distrsim.SimulateMsgWithdrawDelegatorReward(app.accountKeeper, app.distrKeeper)}, {50, distrsim.SimulateMsgWithdrawValidatorCommission(app.accountKeeper, app.distrKeeper)}, - {5, govsim.SimulateSubmittingVotingAndSlashingForProposal(app.govKeeper, app.stakingKeeper)}, + {5, govsim.SimulateSubmittingVotingAndSlashingForProposal(app.govKeeper)}, {100, govsim.SimulateMsgDeposit(app.govKeeper)}, {100, stakingsim.SimulateMsgCreateValidator(app.accountKeeper, app.stakingKeeper)}, {5, stakingsim.SimulateMsgEditValidator(app.stakingKeeper)}, @@ -281,13 +281,13 @@ func testAndRunTxs(app *GaiaApp) []simulation.WeightedOperation { } } -func invariants(app *GaiaApp) []simulation.Invariant { - return []simulation.Invariant{ +func invariants(app *GaiaApp) []sdk.Invariant { + return []sdk.Invariant{ simulation.PeriodicInvariant(banksim.NonnegativeBalanceInvariant(app.accountKeeper), period, 0), simulation.PeriodicInvariant(govsim.AllInvariants(), period, 0), simulation.PeriodicInvariant(distrsim.AllInvariants(app.distrKeeper, app.stakingKeeper), period, 0), - simulation.PeriodicInvariant(stakingsim.AllInvariants(app.bankKeeper, app.stakingKeeper, - app.feeCollectionKeeper, app.distrKeeper, app.accountKeeper), period, 0), + simulation.PeriodicInvariant(stakingsim.AllInvariants(app.stakingKeeper, app.feeCollectionKeeper, + app.distrKeeper, app.accountKeeper), period, 0), simulation.PeriodicInvariant(slashingsim.AllInvariants(), period, 0), } } @@ -571,7 +571,7 @@ func TestAppStateDeterminism(t *testing.T) { simulation.SimulateFromSeed( t, app.BaseApp, appStateFn, seed, testAndRunTxs(app), - []simulation.Invariant{}, + []sdk.Invariant{}, 50, 100, true, diff --git a/cmd/gaia/cli_test/cli_test.go b/cmd/gaia/cli_test/cli_test.go index bff6f34e1..0fec6eb6e 100644 --- a/cmd/gaia/cli_test/cli_test.go +++ b/cmd/gaia/cli_test/cli_test.go @@ -22,7 +22,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/gov" - "github.com/cosmos/cosmos-sdk/x/staking" ) func TestGaiaCLIKeysAddMultisig(t *testing.T) { @@ -169,7 +168,7 @@ func TestGaiaCLIFeesDeduction(t *testing.T) { require.Equal(t, fooAmt.Int64(), fooAcc.GetCoins().AmountOf(fooDenom).Int64()) // insufficient funds (coins + fees) tx fails - largeCoins := staking.TokensFromTendermintPower(10000000) + largeCoins := sdk.TokensFromTendermintPower(10000000) success, _, _ = f.TxSend( keyFoo, barAddr, sdk.NewCoin(fooDenom, largeCoins), fmt.Sprintf("--fees=%s", sdk.NewInt64Coin(feeDenom, 2))) @@ -204,11 +203,11 @@ func TestGaiaCLISend(t *testing.T) { barAddr := f.KeyAddress(keyBar) fooAcc := f.QueryAccount(fooAddr) - startTokens := staking.TokensFromTendermintPower(50) + startTokens := sdk.TokensFromTendermintPower(50) require.Equal(t, startTokens, fooAcc.GetCoins().AmountOf(denom)) // Send some tokens from one account to the other - sendTokens := staking.TokensFromTendermintPower(10) + sendTokens := sdk.TokensFromTendermintPower(10) f.TxSend(keyFoo, barAddr, sdk.NewCoin(denom, sendTokens)) tests.WaitForNextNBlocksTM(1, f.Port) @@ -261,11 +260,11 @@ func TestGaiaCLIGasAuto(t *testing.T) { barAddr := f.KeyAddress(keyBar) fooAcc := f.QueryAccount(fooAddr) - startTokens := staking.TokensFromTendermintPower(50) + startTokens := sdk.TokensFromTendermintPower(50) require.Equal(t, startTokens, fooAcc.GetCoins().AmountOf(denom)) // Test failure with auto gas disabled and very little gas set by hand - sendTokens := staking.TokensFromTendermintPower(10) + sendTokens := sdk.TokensFromTendermintPower(10) success, _, _ := f.TxSend(keyFoo, barAddr, sdk.NewCoin(denom, sendTokens), "--gas=10") require.False(t, success) @@ -320,7 +319,7 @@ func TestGaiaCLICreateValidator(t *testing.T) { consPubKey := sdk.MustBech32ifyConsPub(ed25519.GenPrivKey().PubKey()) - sendTokens := staking.TokensFromTendermintPower(10) + sendTokens := sdk.TokensFromTendermintPower(10) f.TxSend(keyFoo, barAddr, sdk.NewCoin(denom, sendTokens)) tests.WaitForNextNBlocksTM(1, f.Port) @@ -338,7 +337,7 @@ func TestGaiaCLICreateValidator(t *testing.T) { require.Equal(t, 0, len(msg.GetSignatures())) // Test --dry-run - newValTokens := staking.TokensFromTendermintPower(2) + newValTokens := sdk.TokensFromTendermintPower(2) success, _, _ = f.TxStakingCreateValidator(keyBar, consPubKey, sdk.NewCoin(denom, newValTokens), "--dry-run") require.True(t, success) @@ -361,7 +360,7 @@ func TestGaiaCLICreateValidator(t *testing.T) { require.NotZero(t, validatorDelegations[0].Shares) // unbond a single share - unbondTokens := staking.TokensFromTendermintPower(1) + unbondTokens := sdk.TokensFromTendermintPower(1) success = f.TxStakingUnbond(keyBar, unbondTokens.String(), barVal) require.True(t, success) tests.WaitForNextNBlocksTM(1, f.Port) @@ -395,14 +394,14 @@ func TestGaiaCLISubmitProposal(t *testing.T) { fooAddr := f.KeyAddress(keyFoo) fooAcc := f.QueryAccount(fooAddr) - startTokens := staking.TokensFromTendermintPower(50) - require.Equal(t, startTokens, fooAcc.GetCoins().AmountOf(staking.DefaultBondDenom)) + startTokens := sdk.TokensFromTendermintPower(50) + require.Equal(t, startTokens, fooAcc.GetCoins().AmountOf(sdk.DefaultBondDenom)) proposalsQuery := f.QueryGovProposals() require.Empty(t, proposalsQuery) // Test submit generate only for submit proposal - proposalTokens := staking.TokensFromTendermintPower(5) + proposalTokens := sdk.TokensFromTendermintPower(5) success, stdout, stderr := f.TxGovSubmitProposal( keyFoo, "Text", "Test", "test", sdk.NewCoin(denom, proposalTokens), "--generate-only") require.True(t, success) @@ -442,7 +441,7 @@ func TestGaiaCLISubmitProposal(t *testing.T) { require.Equal(t, proposalTokens, deposit.Amount.AmountOf(denom)) // Test deposit generate only - depositTokens := staking.TokensFromTendermintPower(10) + depositTokens := sdk.TokensFromTendermintPower(10) success, stdout, stderr = f.TxGovDeposit(1, keyFoo, sdk.NewCoin(denom, depositTokens), "--generate-only") require.True(t, success) require.Empty(t, stderr) @@ -635,7 +634,7 @@ func TestGaiaCLISendGenerateSignAndBroadcast(t *testing.T) { barAddr := f.KeyAddress(keyBar) // Test generate sendTx with default gas - sendTokens := staking.TokensFromTendermintPower(10) + sendTokens := sdk.TokensFromTendermintPower(10) success, stdout, stderr := f.TxSend(keyFoo, barAddr, sdk.NewCoin(denom, sendTokens), "--generate-only") require.True(t, success) require.Empty(t, stderr) @@ -690,7 +689,7 @@ func TestGaiaCLISendGenerateSignAndBroadcast(t *testing.T) { // Ensure foo has right amount of funds fooAcc := f.QueryAccount(fooAddr) - startTokens := staking.TokensFromTendermintPower(50) + startTokens := sdk.TokensFromTendermintPower(50) require.Equal(t, startTokens, fooAcc.GetCoins().AmountOf(denom)) // Test broadcast @@ -775,7 +774,7 @@ func TestGaiaCLIEncode(t *testing.T) { // Build a testing transaction and write it to disk barAddr := f.KeyAddress(keyBar) - sendTokens := staking.TokensFromTendermintPower(10) + sendTokens := sdk.TokensFromTendermintPower(10) success, stdout, stderr := f.TxSend(keyFoo, barAddr, sdk.NewCoin(denom, sendTokens), "--generate-only", "--memo", "deadbeef") require.True(t, success) require.Empty(t, stderr) diff --git a/cmd/gaia/cli_test/test_helpers.go b/cmd/gaia/cli_test/test_helpers.go index 899a1db0e..22fe83ef4 100644 --- a/cmd/gaia/cli_test/test_helpers.go +++ b/cmd/gaia/cli_test/test_helpers.go @@ -41,14 +41,14 @@ const ( var ( startCoins = sdk.Coins{ - sdk.NewCoin(feeDenom, staking.TokensFromTendermintPower(1000000)), - sdk.NewCoin(fee2Denom, staking.TokensFromTendermintPower(1000000)), - sdk.NewCoin(fooDenom, staking.TokensFromTendermintPower(1000)), - sdk.NewCoin(denom, staking.TokensFromTendermintPower(150)), + sdk.NewCoin(feeDenom, sdk.TokensFromTendermintPower(1000000)), + sdk.NewCoin(fee2Denom, sdk.TokensFromTendermintPower(1000000)), + sdk.NewCoin(fooDenom, sdk.TokensFromTendermintPower(1000)), + sdk.NewCoin(denom, sdk.TokensFromTendermintPower(150)), } vestingCoins = sdk.Coins{ - sdk.NewCoin(feeDenom, staking.TokensFromTendermintPower(500000)), + sdk.NewCoin(feeDenom, sdk.TokensFromTendermintPower(500000)), } ) diff --git a/cmd/gaia/cmd/gaiadebug/hack.go b/cmd/gaia/cmd/gaiadebug/hack.go index eb4c8749b..e7a89cea7 100644 --- a/cmd/gaia/cmd/gaiadebug/hack.go +++ b/cmd/gaia/cmd/gaiadebug/hack.go @@ -260,7 +260,7 @@ func (app *GaiaApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci panic(err) // TODO https://github.com/cosmos/cosmos-sdk/issues/468 // return sdk.ErrGenesisParse("").TraceCause(err, "") } - slashing.InitGenesis(ctx, app.slashingKeeper, genesisState.SlashingData, genesisState.StakingData) + slashing.InitGenesis(ctx, app.slashingKeeper, genesisState.SlashingData, genesisState.StakingData.Validators.ToSDKValidators()) return abci.ResponseInitChain{ Validators: validators, diff --git a/cmd/gaia/init/gentx.go b/cmd/gaia/init/gentx.go index ef3ee7106..e7779a343 100644 --- a/cmd/gaia/init/gentx.go +++ b/cmd/gaia/init/gentx.go @@ -28,13 +28,12 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" - "github.com/cosmos/cosmos-sdk/x/staking" "github.com/cosmos/cosmos-sdk/x/staking/client/cli" ) var ( - defaultTokens = staking.TokensFromTendermintPower(100) - defaultAmount = defaultTokens.String() + staking.DefaultBondDenom + defaultTokens = sdk.TokensFromTendermintPower(100) + defaultAmount = defaultTokens.String() + sdk.DefaultBondDenom defaultCommissionRate = "0.1" defaultCommissionMaxRate = "0.2" defaultCommissionMaxChangeRate = "0.01" diff --git a/cmd/gaia/init/testnet.go b/cmd/gaia/init/testnet.go index 346e6a4b3..fc59827a6 100644 --- a/cmd/gaia/init/testnet.go +++ b/cmd/gaia/init/testnet.go @@ -19,7 +19,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth" authtx "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" "github.com/cosmos/cosmos-sdk/x/staking" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/spf13/cobra" "github.com/spf13/viper" @@ -85,7 +84,7 @@ Example: client.FlagChainID, "", "genesis file chain-id, if left blank will be randomly created", ) cmd.Flags().String( - server.FlagMinGasPrices, fmt.Sprintf("0.000006%s", stakingtypes.DefaultBondDenom), + server.FlagMinGasPrices, fmt.Sprintf("0.000006%s", sdk.DefaultBondDenom), "Minimum gas prices to accept for transactions; All fees in a tx must meet this minimum (e.g. 0.01photino,0.001stake)", ) @@ -192,21 +191,21 @@ func initTestnet(config *tmconfig.Config, cdc *codec.Codec) error { return err } - accTokens := staking.TokensFromTendermintPower(1000) - accStakingTokens := staking.TokensFromTendermintPower(500) + accTokens := sdk.TokensFromTendermintPower(1000) + accStakingTokens := sdk.TokensFromTendermintPower(500) accs = append(accs, app.GenesisAccount{ Address: addr, Coins: sdk.Coins{ sdk.NewCoin(fmt.Sprintf("%stoken", nodeDirName), accTokens), - sdk.NewCoin(stakingtypes.DefaultBondDenom, accStakingTokens), + sdk.NewCoin(sdk.DefaultBondDenom, accStakingTokens), }, }) - valTokens := staking.TokensFromTendermintPower(100) + valTokens := sdk.TokensFromTendermintPower(100) msg := staking.NewMsgCreateValidator( sdk.ValAddress(addr), valPubKeys[i], - sdk.NewCoin(stakingtypes.DefaultBondDenom, valTokens), + sdk.NewCoin(sdk.DefaultBondDenom, valTokens), staking.NewDescription(nodeDirName, "", "", ""), staking.NewCommissionMsg(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), sdk.OneInt(), diff --git a/types/invariant.go b/types/invariant.go new file mode 100644 index 000000000..86c9024fa --- /dev/null +++ b/types/invariant.go @@ -0,0 +1,10 @@ +package types + +// An Invariant is a function which tests a particular invariant. +// If the invariant has been broken, it should return an error +// containing a descriptive message about what happened. +// The simulator will then halt and print the logs. +type Invariant func(ctx Context) error + +// group of Invarient +type Invariants []Invariant diff --git a/types/stake.go b/types/stake.go index 6cf13385b..8169307c9 100644 --- a/types/stake.go +++ b/types/stake.go @@ -1,6 +1,8 @@ package types import ( + "math/big" + abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/crypto" ) @@ -8,11 +10,21 @@ import ( // status of a validator type BondStatus byte -// nolint +// staking constants const ( Unbonded BondStatus = 0x00 Unbonding BondStatus = 0x01 Bonded BondStatus = 0x02 + + // default bond denomination + DefaultBondDenom = "stake" + + // Delay, in blocks, between when validator updates are returned to Tendermint and when they are applied. + // For example, if this is 0, the validator set at the end of a block will sign the next block, or + // if this is 1, the validator set at the end of a block will sign the block after the next. + // Constant as this should not change without a hard fork. + // TODO: Link to some Tendermint docs, this is very unobvious. + ValidatorUpdateDelay int64 = 1 ) //BondStatusToString for pretty prints of Bond Status @@ -29,6 +41,19 @@ func BondStatusToString(b BondStatus) string { } } +// PowerReduction is the amount of staking tokens required for 1 unit of Tendermint power +var PowerReduction = NewIntFromBigInt(new(big.Int).Exp(big.NewInt(10), big.NewInt(6), nil)) + +// TokensToTendermintPower - convert input tokens to potential tendermint power +func TokensToTendermintPower(tokens Int) int64 { + return (tokens.Div(PowerReduction)).Int64() +} + +// TokensFromTendermintPower - convert input power to tokens +func TokensFromTendermintPower(power int64) Int { + return NewInt(power).Mul(PowerReduction) +} + // nolint func (b BondStatus) Equal(b2 BondStatus) bool { return byte(b) == byte(b2) diff --git a/x/auth/client/txbuilder/txbuilder_test.go b/x/auth/client/txbuilder/txbuilder_test.go index cddd13141..3ae2f7124 100644 --- a/x/auth/client/txbuilder/txbuilder_test.go +++ b/x/auth/client/txbuilder/txbuilder_test.go @@ -11,7 +11,6 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) var ( @@ -49,7 +48,7 @@ func TestTxBuilderBuild(t *testing.T) { SimulateGas: false, ChainID: "test-chain", Memo: "hello from Voyager 1!", - Fees: sdk.Coins{sdk.NewCoin(stakingtypes.DefaultBondDenom, sdk.NewInt(1))}, + Fees: sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1))}, }, defaultMsg, StdSignMsg{ @@ -58,7 +57,7 @@ func TestTxBuilderBuild(t *testing.T) { Sequence: 1, Memo: "hello from Voyager 1!", Msgs: defaultMsg, - Fee: auth.NewStdFee(200000, sdk.Coins{sdk.NewCoin(stakingtypes.DefaultBondDenom, sdk.NewInt(1))}), + Fee: auth.NewStdFee(200000, sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1))}), }, false, }, @@ -72,7 +71,7 @@ func TestTxBuilderBuild(t *testing.T) { SimulateGas: false, ChainID: "test-chain", Memo: "hello from Voyager 2!", - GasPrices: sdk.DecCoins{sdk.NewDecCoinFromDec(stakingtypes.DefaultBondDenom, sdk.NewDecWithPrec(10000, sdk.Precision))}, + GasPrices: sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, sdk.NewDecWithPrec(10000, sdk.Precision))}, }, defaultMsg, StdSignMsg{ @@ -81,7 +80,7 @@ func TestTxBuilderBuild(t *testing.T) { Sequence: 1, Memo: "hello from Voyager 2!", Msgs: defaultMsg, - Fee: auth.NewStdFee(200000, sdk.Coins{sdk.NewCoin(stakingtypes.DefaultBondDenom, sdk.NewInt(1))}), + Fee: auth.NewStdFee(200000, sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1))}), }, false, }, diff --git a/x/auth/keeper.go b/x/auth/keeper.go index e01c5c9a8..84899fa1c 100644 --- a/x/auth/keeper.go +++ b/x/auth/keeper.go @@ -91,6 +91,17 @@ func (ak AccountKeeper) GetAccount(ctx sdk.Context, addr sdk.AccAddress) Account return acc } +// GetAllAccounts returns all accounts in the accountKeeper. +func (ak AccountKeeper) GetAllAccounts(ctx sdk.Context) []Account { + accounts := []Account{} + appendAccount := func(acc Account) (stop bool) { + accounts = append(accounts, acc) + return false + } + ak.IterateAccounts(ctx, appendAccount) + return accounts +} + // SetAccount implements sdk.AccountKeeper. func (ak AccountKeeper) SetAccount(ctx sdk.Context, acc Account) { addr := acc.GetAddress() diff --git a/x/bank/simulation/invariants.go b/x/bank/simulation/invariants.go index 34778b275..70ca9b9db 100644 --- a/x/bank/simulation/invariants.go +++ b/x/bank/simulation/invariants.go @@ -6,14 +6,12 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/mock" - "github.com/cosmos/cosmos-sdk/x/mock/simulation" ) // NonnegativeBalanceInvariant checks that all accounts in the application have non-negative balances -func NonnegativeBalanceInvariant(mapper auth.AccountKeeper) simulation.Invariant { +func NonnegativeBalanceInvariant(ak auth.AccountKeeper) sdk.Invariant { return func(ctx sdk.Context) error { - accts := mock.GetAllAccounts(mapper, ctx) + accts := ak.GetAllAccounts(ctx) for _, acc := range accts { coins := acc.GetCoins() if coins.IsAnyNegative() { @@ -28,7 +26,7 @@ func NonnegativeBalanceInvariant(mapper auth.AccountKeeper) simulation.Invariant // TotalCoinsInvariant checks that the sum of the coins across all accounts // is what is expected -func TotalCoinsInvariant(mapper auth.AccountKeeper, totalSupplyFn func() sdk.Coins) simulation.Invariant { +func TotalCoinsInvariant(ak auth.AccountKeeper, totalSupplyFn func() sdk.Coins) sdk.Invariant { return func(ctx sdk.Context) error { totalCoins := sdk.Coins{} @@ -38,7 +36,7 @@ func TotalCoinsInvariant(mapper auth.AccountKeeper, totalSupplyFn func() sdk.Coi return false } - mapper.IterateAccounts(ctx, chkAccount) + ak.IterateAccounts(ctx, chkAccount) if !totalSupplyFn().IsEqual(totalCoins) { return errors.New("total calculated coins doesn't equal expected coins") } diff --git a/x/distribution/keeper/alias_functions.go b/x/distribution/keeper/alias_functions.go new file mode 100644 index 000000000..575eafe53 --- /dev/null +++ b/x/distribution/keeper/alias_functions.go @@ -0,0 +1,15 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// get outstanding rewards +func (k Keeper) GetOutstandingRewardsCoins(ctx sdk.Context) sdk.DecCoins { + return k.GetOutstandingRewards(ctx) +} + +// get the community coins +func (k Keeper) GetFeePoolCommunityCoins(ctx sdk.Context) sdk.DecCoins { + return k.GetFeePool(ctx).CommunityPool +} diff --git a/x/distribution/keeper/allocation_test.go b/x/distribution/keeper/allocation_test.go index 84736f8b2..d2c354a10 100644 --- a/x/distribution/keeper/allocation_test.go +++ b/x/distribution/keeper/allocation_test.go @@ -20,19 +20,19 @@ func TestAllocateTokensToValidatorWithCommission(t *testing.T) { // create validator with 50% commission commission := staking.NewCommissionMsg(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) msg := staking.NewMsgCreateValidator(valOpAddr1, valConsPk1, - sdk.NewCoin(staking.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt()) + sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt()) require.True(t, sh(ctx, msg).IsOK()) val := sk.Validator(ctx, valOpAddr1) // allocate tokens tokens := sdk.DecCoins{ - {staking.DefaultBondDenom, sdk.NewDec(10)}, + {sdk.DefaultBondDenom, sdk.NewDec(10)}, } k.AllocateTokensToValidator(ctx, val, tokens) // check commission expected := sdk.DecCoins{ - {staking.DefaultBondDenom, sdk.NewDec(5)}, + {sdk.DefaultBondDenom, sdk.NewDec(5)}, } require.Equal(t, expected, k.GetValidatorAccumulatedCommission(ctx, val.GetOperator())) @@ -50,13 +50,13 @@ func TestAllocateTokensToManyValidators(t *testing.T) { // create validator with 50% commission commission := staking.NewCommissionMsg(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) msg := staking.NewMsgCreateValidator(valOpAddr1, valConsPk1, - sdk.NewCoin(staking.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt()) + sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt()) require.True(t, sh(ctx, msg).IsOK()) // create second validator with 0% commission commission = staking.NewCommissionMsg(sdk.NewDec(0), sdk.NewDec(0), sdk.NewDec(0)) msg = staking.NewMsgCreateValidator(valOpAddr2, valConsPk2, - sdk.NewCoin(staking.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt()) + sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt()) require.True(t, sh(ctx, msg).IsOK()) abciValA := abci.Validator{ @@ -78,7 +78,7 @@ func TestAllocateTokensToManyValidators(t *testing.T) { // allocate tokens as if both had voted and second was proposer fees := sdk.Coins{ - {staking.DefaultBondDenom, sdk.NewInt(100)}, + {sdk.DefaultBondDenom, sdk.NewInt(100)}, } fck.SetCollectedFees(fees) votes := []abci.VoteInfo{ @@ -94,15 +94,15 @@ func TestAllocateTokensToManyValidators(t *testing.T) { k.AllocateTokens(ctx, 200, 200, valConsAddr2, votes) // 98 outstanding rewards (100 less 2 to community pool) - require.Equal(t, sdk.DecCoins{{staking.DefaultBondDenom, sdk.NewDec(98)}}, k.GetOutstandingRewards(ctx)) + require.Equal(t, sdk.DecCoins{{sdk.DefaultBondDenom, sdk.NewDec(98)}}, k.GetOutstandingRewards(ctx)) // 2 community pool coins - require.Equal(t, sdk.DecCoins{{staking.DefaultBondDenom, sdk.NewDec(2)}}, k.GetFeePool(ctx).CommunityPool) + require.Equal(t, sdk.DecCoins{{sdk.DefaultBondDenom, sdk.NewDec(2)}}, k.GetFeePool(ctx).CommunityPool) // 50% commission for first proposer, (0.5 * 93%) * 100 / 2 = 23.25 - require.Equal(t, sdk.DecCoins{{staking.DefaultBondDenom, sdk.NewDecWithPrec(2325, 2)}}, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1)) + require.Equal(t, sdk.DecCoins{{sdk.DefaultBondDenom, sdk.NewDecWithPrec(2325, 2)}}, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1)) // zero commission for second proposer require.True(t, k.GetValidatorAccumulatedCommission(ctx, valOpAddr2).IsZero()) // just staking.proportional for first proposer less commission = (0.5 * 93%) * 100 / 2 = 23.25 - require.Equal(t, sdk.DecCoins{{staking.DefaultBondDenom, sdk.NewDecWithPrec(2325, 2)}}, k.GetValidatorCurrentRewards(ctx, valOpAddr1).Rewards) + require.Equal(t, sdk.DecCoins{{sdk.DefaultBondDenom, sdk.NewDecWithPrec(2325, 2)}}, k.GetValidatorCurrentRewards(ctx, valOpAddr1).Rewards) // proposer reward + staking.proportional for second proposer = (5 % + 0.5 * (93%)) * 100 = 51.5 - require.Equal(t, sdk.DecCoins{{staking.DefaultBondDenom, sdk.NewDecWithPrec(515, 1)}}, k.GetValidatorCurrentRewards(ctx, valOpAddr2).Rewards) + require.Equal(t, sdk.DecCoins{{sdk.DefaultBondDenom, sdk.NewDecWithPrec(515, 1)}}, k.GetValidatorCurrentRewards(ctx, valOpAddr2).Rewards) } diff --git a/x/distribution/keeper/delegation_test.go b/x/distribution/keeper/delegation_test.go index b6082b34c..a34960b1c 100644 --- a/x/distribution/keeper/delegation_test.go +++ b/x/distribution/keeper/delegation_test.go @@ -19,7 +19,7 @@ func TestCalculateRewardsBasic(t *testing.T) { // create validator with 50% commission commission := staking.NewCommissionMsg(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) msg := staking.NewMsgCreateValidator(valOpAddr1, valConsPk1, - sdk.NewCoin(staking.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt()) + sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt()) require.True(t, sh(ctx, msg).IsOK()) // end block to bond validator @@ -46,7 +46,7 @@ func TestCalculateRewardsBasic(t *testing.T) { // allocate some rewards initial := int64(10) - tokens := sdk.DecCoins{{staking.DefaultBondDenom, sdk.NewDec(initial)}} + tokens := sdk.DecCoins{{sdk.DefaultBondDenom, sdk.NewDec(initial)}} k.AllocateTokensToValidator(ctx, val, tokens) // end period @@ -56,10 +56,10 @@ func TestCalculateRewardsBasic(t *testing.T) { rewards = k.calculateDelegationRewards(ctx, val, del, endingPeriod) // rewards should be half the tokens - require.Equal(t, sdk.DecCoins{{staking.DefaultBondDenom, sdk.NewDec(initial / 2)}}, rewards) + require.Equal(t, sdk.DecCoins{{sdk.DefaultBondDenom, sdk.NewDec(initial / 2)}}, rewards) // commission should be the other half - require.Equal(t, sdk.DecCoins{{staking.DefaultBondDenom, sdk.NewDec(initial / 2)}}, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1)) + require.Equal(t, sdk.DecCoins{{sdk.DefaultBondDenom, sdk.NewDec(initial / 2)}}, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1)) } func TestCalculateRewardsAfterSlash(t *testing.T) { @@ -72,9 +72,9 @@ func TestCalculateRewardsAfterSlash(t *testing.T) { // create validator with 50% commission commission := staking.NewCommissionMsg(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) valPower := int64(100) - valTokens := staking.TokensFromTendermintPower(valPower) + valTokens := sdk.TokensFromTendermintPower(valPower) msg := staking.NewMsgCreateValidator(valOpAddr1, valConsPk1, - sdk.NewCoin(staking.DefaultBondDenom, valTokens), staking.Description{}, commission, sdk.OneInt()) + sdk.NewCoin(sdk.DefaultBondDenom, valTokens), staking.Description{}, commission, sdk.OneInt()) got := sh(ctx, msg) require.True(t, got.IsOK(), "%v", got) @@ -107,8 +107,8 @@ func TestCalculateRewardsAfterSlash(t *testing.T) { ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) // allocate some rewards - initial := staking.TokensFromTendermintPower(10) - tokens := sdk.DecCoins{{staking.DefaultBondDenom, sdk.NewDecFromInt(initial)}} + initial := sdk.TokensFromTendermintPower(10) + tokens := sdk.DecCoins{{sdk.DefaultBondDenom, sdk.NewDecFromInt(initial)}} k.AllocateTokensToValidator(ctx, val, tokens) // end period @@ -118,10 +118,10 @@ func TestCalculateRewardsAfterSlash(t *testing.T) { rewards = k.calculateDelegationRewards(ctx, val, del, endingPeriod) // rewards should be half the tokens - require.Equal(t, sdk.DecCoins{{staking.DefaultBondDenom, sdk.NewDecFromInt(initial.DivRaw(2))}}, rewards) + require.Equal(t, sdk.DecCoins{{sdk.DefaultBondDenom, sdk.NewDecFromInt(initial.DivRaw(2))}}, rewards) // commission should be the other half - require.Equal(t, sdk.DecCoins{{staking.DefaultBondDenom, sdk.NewDecFromInt(initial.DivRaw(2))}}, + require.Equal(t, sdk.DecCoins{{sdk.DefaultBondDenom, sdk.NewDecFromInt(initial.DivRaw(2))}}, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1)) } @@ -134,10 +134,10 @@ func TestCalculateRewardsAfterManySlashes(t *testing.T) { // create validator with 50% commission power := int64(100) - valTokens := staking.TokensFromTendermintPower(power) + valTokens := sdk.TokensFromTendermintPower(power) commission := staking.NewCommissionMsg(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) msg := staking.NewMsgCreateValidator(valOpAddr1, valConsPk1, - sdk.NewCoin(staking.DefaultBondDenom, valTokens), staking.Description{}, commission, sdk.OneInt()) + sdk.NewCoin(sdk.DefaultBondDenom, valTokens), staking.Description{}, commission, sdk.OneInt()) require.True(t, sh(ctx, msg).IsOK()) // end block to bond validator @@ -169,8 +169,8 @@ func TestCalculateRewardsAfterManySlashes(t *testing.T) { ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) // allocate some rewards - initial := staking.TokensFromTendermintPower(10) - tokens := sdk.DecCoins{{staking.DefaultBondDenom, sdk.NewDecFromInt(initial)}} + initial := sdk.TokensFromTendermintPower(10) + tokens := sdk.DecCoins{{sdk.DefaultBondDenom, sdk.NewDecFromInt(initial)}} k.AllocateTokensToValidator(ctx, val, tokens) // slash the validator by 50% again @@ -192,10 +192,10 @@ func TestCalculateRewardsAfterManySlashes(t *testing.T) { rewards = k.calculateDelegationRewards(ctx, val, del, endingPeriod) // rewards should be half the tokens - require.Equal(t, sdk.DecCoins{{staking.DefaultBondDenom, sdk.NewDecFromInt(initial)}}, rewards) + require.Equal(t, sdk.DecCoins{{sdk.DefaultBondDenom, sdk.NewDecFromInt(initial)}}, rewards) // commission should be the other half - require.Equal(t, sdk.DecCoins{{staking.DefaultBondDenom, sdk.NewDecFromInt(initial)}}, + require.Equal(t, sdk.DecCoins{{sdk.DefaultBondDenom, sdk.NewDecFromInt(initial)}}, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1)) } @@ -209,7 +209,7 @@ func TestCalculateRewardsMultiDelegator(t *testing.T) { // create validator with 50% commission commission := staking.NewCommissionMsg(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) msg := staking.NewMsgCreateValidator(valOpAddr1, valConsPk1, - sdk.NewCoin(staking.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt()) + sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt()) require.True(t, sh(ctx, msg).IsOK()) // end block to bond validator @@ -221,11 +221,11 @@ func TestCalculateRewardsMultiDelegator(t *testing.T) { // allocate some rewards initial := int64(20) - tokens := sdk.DecCoins{{staking.DefaultBondDenom, sdk.NewDec(initial)}} + tokens := sdk.DecCoins{{sdk.DefaultBondDenom, sdk.NewDec(initial)}} k.AllocateTokensToValidator(ctx, val, tokens) // second delegation - msg2 := staking.NewMsgDelegate(sdk.AccAddress(valOpAddr2), valOpAddr1, sdk.NewCoin(staking.DefaultBondDenom, sdk.NewInt(100))) + msg2 := staking.NewMsgDelegate(sdk.AccAddress(valOpAddr2), valOpAddr1, sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100))) require.True(t, sh(ctx, msg2).IsOK()) del2 := sk.Delegation(ctx, sdk.AccAddress(valOpAddr2), valOpAddr1) @@ -245,21 +245,21 @@ func TestCalculateRewardsMultiDelegator(t *testing.T) { rewards := k.calculateDelegationRewards(ctx, val, del1, endingPeriod) // rewards for del1 should be 3/4 initial - require.Equal(t, sdk.DecCoins{{staking.DefaultBondDenom, sdk.NewDec(initial * 3 / 4)}}, rewards) + require.Equal(t, sdk.DecCoins{{sdk.DefaultBondDenom, sdk.NewDec(initial * 3 / 4)}}, rewards) // calculate delegation rewards for del2 rewards = k.calculateDelegationRewards(ctx, val, del2, endingPeriod) // rewards for del2 should be 1/4 initial - require.Equal(t, sdk.DecCoins{{staking.DefaultBondDenom, sdk.NewDec(initial * 1 / 4)}}, rewards) + require.Equal(t, sdk.DecCoins{{sdk.DefaultBondDenom, sdk.NewDec(initial * 1 / 4)}}, rewards) // commission should be equal to initial (50% twice) - require.Equal(t, sdk.DecCoins{{staking.DefaultBondDenom, sdk.NewDec(initial)}}, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1)) + require.Equal(t, sdk.DecCoins{{sdk.DefaultBondDenom, sdk.NewDec(initial)}}, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1)) } func TestWithdrawDelegationRewardsBasic(t *testing.T) { balancePower := int64(1000) - balanceTokens := staking.TokensFromTendermintPower(balancePower) + balanceTokens := sdk.TokensFromTendermintPower(balancePower) ctx, ak, k, sk, _ := CreateTestInputDefault(t, false, balancePower) sh := staking.NewHandler(sk) @@ -268,16 +268,16 @@ func TestWithdrawDelegationRewardsBasic(t *testing.T) { // create validator with 50% commission power := int64(100) - valTokens := staking.TokensFromTendermintPower(power) + valTokens := sdk.TokensFromTendermintPower(power) commission := staking.NewCommissionMsg(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) msg := staking.NewMsgCreateValidator(valOpAddr1, valConsPk1, - sdk.NewCoin(staking.DefaultBondDenom, valTokens), staking.Description{}, commission, sdk.OneInt()) + sdk.NewCoin(sdk.DefaultBondDenom, valTokens), staking.Description{}, commission, sdk.OneInt()) require.True(t, sh(ctx, msg).IsOK()) // assert correct initial balance expTokens := balanceTokens.Sub(valTokens) require.Equal(t, - sdk.Coins{{staking.DefaultBondDenom, expTokens}}, + sdk.Coins{{sdk.DefaultBondDenom, expTokens}}, ak.GetAccount(ctx, sdk.AccAddress(valOpAddr1)).GetCoins()) // end block to bond validator @@ -290,8 +290,8 @@ func TestWithdrawDelegationRewardsBasic(t *testing.T) { val := sk.Validator(ctx, valOpAddr1) // allocate some rewards - initial := staking.TokensFromTendermintPower(10) - tokens := sdk.DecCoins{{staking.DefaultBondDenom, sdk.NewDecFromInt(initial)}} + initial := sdk.TokensFromTendermintPower(10) + tokens := sdk.DecCoins{{sdk.DefaultBondDenom, sdk.NewDecFromInt(initial)}} k.AllocateTokensToValidator(ctx, val, tokens) // historical count should be 2 (initial + latest for delegation) @@ -305,14 +305,14 @@ func TestWithdrawDelegationRewardsBasic(t *testing.T) { // assert correct balance exp := balanceTokens.Sub(valTokens).Add(initial.DivRaw(2)) - require.Equal(t, sdk.Coins{{staking.DefaultBondDenom, exp}}, ak.GetAccount(ctx, sdk.AccAddress(valOpAddr1)).GetCoins()) + require.Equal(t, sdk.Coins{{sdk.DefaultBondDenom, exp}}, ak.GetAccount(ctx, sdk.AccAddress(valOpAddr1)).GetCoins()) // withdraw commission require.Nil(t, k.WithdrawValidatorCommission(ctx, valOpAddr1)) // assert correct balance exp = balanceTokens.Sub(valTokens).Add(initial) - require.Equal(t, sdk.Coins{{staking.DefaultBondDenom, exp}}, ak.GetAccount(ctx, sdk.AccAddress(valOpAddr1)).GetCoins()) + require.Equal(t, sdk.Coins{{sdk.DefaultBondDenom, exp}}, ak.GetAccount(ctx, sdk.AccAddress(valOpAddr1)).GetCoins()) } func TestCalculateRewardsAfterManySlashesInSameBlock(t *testing.T) { @@ -324,10 +324,10 @@ func TestCalculateRewardsAfterManySlashesInSameBlock(t *testing.T) { // create validator with 50% commission power := int64(100) - valTokens := staking.TokensFromTendermintPower(power) + valTokens := sdk.TokensFromTendermintPower(power) commission := staking.NewCommissionMsg(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) msg := staking.NewMsgCreateValidator(valOpAddr1, valConsPk1, - sdk.NewCoin(staking.DefaultBondDenom, valTokens), staking.Description{}, commission, sdk.OneInt()) + sdk.NewCoin(sdk.DefaultBondDenom, valTokens), staking.Description{}, commission, sdk.OneInt()) require.True(t, sh(ctx, msg).IsOK()) // end block to bond validator @@ -350,8 +350,8 @@ func TestCalculateRewardsAfterManySlashesInSameBlock(t *testing.T) { ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) // allocate some rewards - initial := sdk.NewDecFromInt(staking.TokensFromTendermintPower(10)) - tokens := sdk.DecCoins{{staking.DefaultBondDenom, initial}} + initial := sdk.NewDecFromInt(sdk.TokensFromTendermintPower(10)) + tokens := sdk.DecCoins{{sdk.DefaultBondDenom, initial}} k.AllocateTokensToValidator(ctx, val, tokens) // slash the validator by 50% @@ -376,10 +376,10 @@ func TestCalculateRewardsAfterManySlashesInSameBlock(t *testing.T) { rewards = k.calculateDelegationRewards(ctx, val, del, endingPeriod) // rewards should be half the tokens - require.Equal(t, sdk.DecCoins{{staking.DefaultBondDenom, initial}}, rewards) + require.Equal(t, sdk.DecCoins{{sdk.DefaultBondDenom, initial}}, rewards) // commission should be the other half - require.Equal(t, sdk.DecCoins{{staking.DefaultBondDenom, initial}}, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1)) + require.Equal(t, sdk.DecCoins{{sdk.DefaultBondDenom, initial}}, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1)) } func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { @@ -392,9 +392,9 @@ func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { // create validator with 50% commission commission := staking.NewCommissionMsg(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) power := int64(100) - valTokens := staking.TokensFromTendermintPower(power) + valTokens := sdk.TokensFromTendermintPower(power) msg := staking.NewMsgCreateValidator(valOpAddr1, valConsPk1, - sdk.NewCoin(staking.DefaultBondDenom, valTokens), staking.Description{}, commission, sdk.OneInt()) + sdk.NewCoin(sdk.DefaultBondDenom, valTokens), staking.Description{}, commission, sdk.OneInt()) require.True(t, sh(ctx, msg).IsOK()) // end block to bond validator @@ -405,8 +405,8 @@ func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { del1 := sk.Delegation(ctx, sdk.AccAddress(valOpAddr1), valOpAddr1) // allocate some rewards - initial := sdk.NewDecFromInt(staking.TokensFromTendermintPower(30)) - tokens := sdk.DecCoins{{staking.DefaultBondDenom, initial}} + initial := sdk.NewDecFromInt(sdk.TokensFromTendermintPower(30)) + tokens := sdk.DecCoins{{sdk.DefaultBondDenom, initial}} k.AllocateTokensToValidator(ctx, val, tokens) // slash the validator @@ -415,9 +415,9 @@ func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) // second delegation - delTokens := staking.TokensFromTendermintPower(100) + delTokens := sdk.TokensFromTendermintPower(100) msg2 := staking.NewMsgDelegate(sdk.AccAddress(valOpAddr2), valOpAddr1, - sdk.NewCoin(staking.DefaultBondDenom, delTokens)) + sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) require.True(t, sh(ctx, msg2).IsOK()) del2 := sk.Delegation(ctx, sdk.AccAddress(valOpAddr2), valOpAddr1) @@ -442,16 +442,16 @@ func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { rewards := k.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{{staking.DefaultBondDenom, initial.QuoInt64(2).Add(initial.QuoInt64(6))}}, rewards) + require.Equal(t, sdk.DecCoins{{sdk.DefaultBondDenom, initial.QuoInt64(2).Add(initial.QuoInt64(6))}}, rewards) // calculate delegation rewards for del2 rewards = k.calculateDelegationRewards(ctx, val, del2, endingPeriod) // rewards for del2 should be initial / 3 - require.Equal(t, sdk.DecCoins{{staking.DefaultBondDenom, initial.QuoInt64(3)}}, rewards) + require.Equal(t, sdk.DecCoins{{sdk.DefaultBondDenom, initial.QuoInt64(3)}}, rewards) // commission should be equal to initial (twice 50% commission, unaffected by slashing) - require.Equal(t, sdk.DecCoins{{staking.DefaultBondDenom, initial}}, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1)) + require.Equal(t, sdk.DecCoins{{sdk.DefaultBondDenom, initial}}, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1)) } func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) { @@ -464,7 +464,7 @@ func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) { // create validator with 50% commission commission := staking.NewCommissionMsg(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) msg := staking.NewMsgCreateValidator(valOpAddr1, valConsPk1, - sdk.NewCoin(staking.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt()) + sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt()) require.True(t, sh(ctx, msg).IsOK()) // end block to bond validator @@ -476,14 +476,14 @@ func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) { // allocate some rewards initial := int64(20) - tokens := sdk.DecCoins{{staking.DefaultBondDenom, sdk.NewDec(initial)}} + tokens := sdk.DecCoins{{sdk.DefaultBondDenom, sdk.NewDec(initial)}} k.AllocateTokensToValidator(ctx, val, tokens) // historical count should be 2 (validator init, delegation init) require.Equal(t, uint64(2), k.GetValidatorHistoricalReferenceCount(ctx)) // second delegation - msg2 := staking.NewMsgDelegate(sdk.AccAddress(valOpAddr2), valOpAddr1, sdk.NewCoin(staking.DefaultBondDenom, sdk.NewInt(100))) + msg2 := staking.NewMsgDelegate(sdk.AccAddress(valOpAddr2), valOpAddr1, sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100))) require.True(t, sh(ctx, msg2).IsOK()) // historical count should be 3 (second delegation init) @@ -548,10 +548,10 @@ func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) { rewards = k.calculateDelegationRewards(ctx, val, del2, endingPeriod) // rewards for del2 should be 1/4 initial - require.Equal(t, sdk.DecCoins{{staking.DefaultBondDenom, sdk.NewDec(initial / 4)}}, rewards) + require.Equal(t, sdk.DecCoins{{sdk.DefaultBondDenom, sdk.NewDec(initial / 4)}}, rewards) // commission should be half initial - require.Equal(t, sdk.DecCoins{{staking.DefaultBondDenom, sdk.NewDec(initial / 2)}}, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1)) + require.Equal(t, sdk.DecCoins{{sdk.DefaultBondDenom, sdk.NewDec(initial / 2)}}, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1)) // allocate some more rewards k.AllocateTokensToValidator(ctx, val, tokens) @@ -566,13 +566,13 @@ func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) { rewards = k.calculateDelegationRewards(ctx, val, del1, endingPeriod) // rewards for del1 should be 1/4 initial - require.Equal(t, sdk.DecCoins{{staking.DefaultBondDenom, sdk.NewDec(initial / 4)}}, rewards) + require.Equal(t, sdk.DecCoins{{sdk.DefaultBondDenom, sdk.NewDec(initial / 4)}}, rewards) // calculate delegation rewards for del2 rewards = k.calculateDelegationRewards(ctx, val, del2, endingPeriod) // rewards for del2 should be 1/2 initial - require.Equal(t, sdk.DecCoins{{staking.DefaultBondDenom, sdk.NewDec(initial / 2)}}, rewards) + require.Equal(t, sdk.DecCoins{{sdk.DefaultBondDenom, sdk.NewDec(initial / 2)}}, rewards) // commission should be zero require.True(t, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1).IsZero()) diff --git a/x/distribution/keeper/keeper_test.go b/x/distribution/keeper/keeper_test.go index e30eb78f9..56ca70703 100644 --- a/x/distribution/keeper/keeper_test.go +++ b/x/distribution/keeper/keeper_test.go @@ -7,7 +7,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/distribution/types" - "github.com/cosmos/cosmos-sdk/x/staking" ) func TestSetWithdrawAddr(t *testing.T) { @@ -32,9 +31,9 @@ func TestWithdrawValidatorCommission(t *testing.T) { // check initial balance balance := ak.GetAccount(ctx, sdk.AccAddress(valOpAddr3)).GetCoins() - expTokens := staking.TokensFromTendermintPower(1000) + expTokens := sdk.TokensFromTendermintPower(1000) require.Equal(t, sdk.Coins{ - {"stake", staking.TokensFromTendermintPower(1000)}, + {"stake", sdk.TokensFromTendermintPower(1000)}, }, balance) // set commission diff --git a/x/distribution/keeper/querier_test.go b/x/distribution/keeper/querier_test.go index 61c3af57b..874b85034 100644 --- a/x/distribution/keeper/querier_test.go +++ b/x/distribution/keeper/querier_test.go @@ -158,15 +158,15 @@ func TestQueries(t *testing.T) { keeper.SetOutstandingRewards(ctx, sdk.DecCoins{}) comm := staking.NewCommissionMsg(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) msg := staking.NewMsgCreateValidator(valOpAddr1, valConsPk1, - sdk.NewCoin(staking.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, comm, sdk.OneInt()) + sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, comm, sdk.OneInt()) require.True(t, sh(ctx, msg).IsOK()) staking.EndBlocker(ctx, sk) val := sk.Validator(ctx, valOpAddr1) rewards := getQueriedDelegationRewards(t, ctx, cdc, querier, sdk.AccAddress(valOpAddr1), valOpAddr1) require.True(t, rewards.IsZero()) initial := int64(10) - tokens := sdk.DecCoins{{staking.DefaultBondDenom, sdk.NewDec(initial)}} + tokens := sdk.DecCoins{{sdk.DefaultBondDenom, sdk.NewDec(initial)}} keeper.AllocateTokensToValidator(ctx, val, tokens) rewards = getQueriedDelegationRewards(t, ctx, cdc, querier, sdk.AccAddress(valOpAddr1), valOpAddr1) - require.Equal(t, sdk.DecCoins{{staking.DefaultBondDenom, sdk.NewDec(initial / 2)}}, rewards) + require.Equal(t, sdk.DecCoins{{sdk.DefaultBondDenom, sdk.NewDec(initial / 2)}}, rewards) } diff --git a/x/distribution/keeper/test_common.go b/x/distribution/keeper/test_common.go index 0a36910e8..a17b4b5fe 100644 --- a/x/distribution/keeper/test_common.go +++ b/x/distribution/keeper/test_common.go @@ -83,7 +83,7 @@ func CreateTestInputAdvanced(t *testing.T, isCheckTx bool, initPower int64, communityTax sdk.Dec) ( sdk.Context, auth.AccountKeeper, Keeper, staking.Keeper, DummyFeeCollectionKeeper) { - initCoins := staking.TokensFromTendermintPower(initPower) + initCoins := sdk.TokensFromTendermintPower(initPower) keyDistr := sdk.NewKVStoreKey(types.StoreKey) keyStaking := sdk.NewKVStoreKey(staking.StoreKey) diff --git a/x/distribution/simulation/invariants.go b/x/distribution/simulation/invariants.go index 2f33d02b2..ac4fcdffe 100644 --- a/x/distribution/simulation/invariants.go +++ b/x/distribution/simulation/invariants.go @@ -6,12 +6,10 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" distr "github.com/cosmos/cosmos-sdk/x/distribution" "github.com/cosmos/cosmos-sdk/x/distribution/types" - "github.com/cosmos/cosmos-sdk/x/mock/simulation" - "github.com/cosmos/cosmos-sdk/x/staking" ) // AllInvariants runs all invariants of the distribution module -func AllInvariants(d distr.Keeper, stk staking.Keeper) simulation.Invariant { +func AllInvariants(d distr.Keeper, stk types.StakingKeeper) sdk.Invariant { return func(ctx sdk.Context) error { err := CanWithdrawInvariant(d, stk)(ctx) if err != nil { @@ -30,7 +28,7 @@ func AllInvariants(d distr.Keeper, stk staking.Keeper) simulation.Invariant { } // NonNegativeOutstandingInvariant checks that outstanding unwithdrawn fees are never negative -func NonNegativeOutstandingInvariant(k distr.Keeper) simulation.Invariant { +func NonNegativeOutstandingInvariant(k distr.Keeper) sdk.Invariant { return func(ctx sdk.Context) error { outstanding := k.GetOutstandingRewards(ctx) if outstanding.HasNegative() { @@ -41,7 +39,7 @@ func NonNegativeOutstandingInvariant(k distr.Keeper) simulation.Invariant { } // CanWithdrawInvariant checks that current rewards can be completely withdrawn -func CanWithdrawInvariant(k distr.Keeper, sk staking.Keeper) simulation.Invariant { +func CanWithdrawInvariant(k distr.Keeper, sk types.StakingKeeper) sdk.Invariant { return func(ctx sdk.Context) error { // cache, we don't want to write changes @@ -54,9 +52,9 @@ func CanWithdrawInvariant(k distr.Keeper, sk staking.Keeper) simulation.Invarian }) // iterate over all current delegations, withdraw rewards - dels := sk.GetAllDelegations(ctx) + dels := sk.GetAllSDKDelegations(ctx) for _, delegation := range dels { - _ = k.WithdrawDelegationRewards(ctx, delegation.DelegatorAddr, delegation.ValidatorAddr) + _ = k.WithdrawDelegationRewards(ctx, delegation.GetDelegatorAddr(), delegation.GetValidatorAddr()) } remaining := k.GetOutstandingRewards(ctx) @@ -70,7 +68,7 @@ func CanWithdrawInvariant(k distr.Keeper, sk staking.Keeper) simulation.Invarian } // ReferenceCountInvariant checks that the number of historical rewards records is correct -func ReferenceCountInvariant(k distr.Keeper, sk staking.Keeper) simulation.Invariant { +func ReferenceCountInvariant(k distr.Keeper, sk types.StakingKeeper) sdk.Invariant { return func(ctx sdk.Context) error { valCount := uint64(0) @@ -78,19 +76,23 @@ func ReferenceCountInvariant(k distr.Keeper, sk staking.Keeper) simulation.Invar valCount++ return false }) - dels := sk.GetAllDelegations(ctx) + dels := sk.GetAllSDKDelegations(ctx) slashCount := uint64(0) - k.IterateValidatorSlashEvents(ctx, func(_ sdk.ValAddress, _ uint64, _ types.ValidatorSlashEvent) (stop bool) { - slashCount++ - return false - }) + k.IterateValidatorSlashEvents(ctx, + func(_ sdk.ValAddress, _ uint64, _ types.ValidatorSlashEvent) (stop bool) { + slashCount++ + return false + }) - // one record per validator (last tracked period), one record per delegation (previous period), one record per slash (previous period) + // one record per validator (last tracked period), one record per + // delegation (previous period), one record per slash (previous period) expected := valCount + uint64(len(dels)) + slashCount count := k.GetValidatorHistoricalReferenceCount(ctx) if count != expected { - return fmt.Errorf("unexpected number of historical rewards records: expected %v (%v vals + %v dels + %v slashes), got %v", expected, valCount, len(dels), slashCount, count) + return fmt.Errorf("unexpected number of historical rewards records: "+ + "expected %v (%v vals + %v dels + %v slashes), got %v", + expected, valCount, len(dels), slashCount, count) } return nil diff --git a/x/distribution/types/keepers.go b/x/distribution/types/expected_keepers.go similarity index 84% rename from x/distribution/types/keepers.go rename to x/distribution/types/expected_keepers.go index 07fd2b736..51b992b3b 100644 --- a/x/distribution/types/keepers.go +++ b/x/distribution/types/expected_keepers.go @@ -12,6 +12,11 @@ type StakingKeeper interface { TotalPower(ctx sdk.Context) sdk.Int GetLastTotalPower(ctx sdk.Context) sdk.Int GetLastValidatorPower(ctx sdk.Context, valAddr sdk.ValAddress) int64 + + // used for invariants + IterateValidators(ctx sdk.Context, + fn func(index int64, validator sdk.Validator) (stop bool)) + GetAllSDKDelegations(ctx sdk.Context) []sdk.Delegation } // expected coin keeper diff --git a/x/gov/endblocker_test.go b/x/gov/endblocker_test.go index 9ce46419e..d4847b764 100644 --- a/x/gov/endblocker_test.go +++ b/x/gov/endblocker_test.go @@ -9,7 +9,6 @@ import ( abci "github.com/tendermint/tendermint/abci/types" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/staking" ) func TestTickExpiredDepositPeriod(t *testing.T) { @@ -23,7 +22,7 @@ func TestTickExpiredDepositPeriod(t *testing.T) { require.False(t, inactiveQueue.Valid()) inactiveQueue.Close() - newProposalMsg := NewMsgSubmitProposal("Test", "test", ProposalTypeText, addrs[0], sdk.Coins{sdk.NewInt64Coin(staking.DefaultBondDenom, 5)}) + newProposalMsg := NewMsgSubmitProposal("Test", "test", ProposalTypeText, addrs[0], sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 5)}) res := govHandler(ctx, newProposalMsg) require.True(t, res.IsOK()) @@ -66,7 +65,7 @@ func TestTickMultipleExpiredDepositPeriod(t *testing.T) { require.False(t, inactiveQueue.Valid()) inactiveQueue.Close() - newProposalMsg := NewMsgSubmitProposal("Test", "test", ProposalTypeText, addrs[0], sdk.Coins{sdk.NewInt64Coin(staking.DefaultBondDenom, 5)}) + newProposalMsg := NewMsgSubmitProposal("Test", "test", ProposalTypeText, addrs[0], sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 5)}) res := govHandler(ctx, newProposalMsg) require.True(t, res.IsOK()) @@ -83,7 +82,7 @@ func TestTickMultipleExpiredDepositPeriod(t *testing.T) { require.False(t, inactiveQueue.Valid()) inactiveQueue.Close() - newProposalMsg2 := NewMsgSubmitProposal("Test2", "test2", ProposalTypeText, addrs[1], sdk.Coins{sdk.NewInt64Coin(staking.DefaultBondDenom, 5)}) + newProposalMsg2 := NewMsgSubmitProposal("Test2", "test2", ProposalTypeText, addrs[1], sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 5)}) res = govHandler(ctx, newProposalMsg2) require.True(t, res.IsOK()) @@ -126,7 +125,7 @@ func TestTickPassedDepositPeriod(t *testing.T) { require.False(t, activeQueue.Valid()) activeQueue.Close() - newProposalMsg := NewMsgSubmitProposal("Test", "test", ProposalTypeText, addrs[0], sdk.Coins{sdk.NewInt64Coin(staking.DefaultBondDenom, 5)}) + newProposalMsg := NewMsgSubmitProposal("Test", "test", ProposalTypeText, addrs[0], sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 5)}) res := govHandler(ctx, newProposalMsg) require.True(t, res.IsOK()) @@ -145,7 +144,7 @@ func TestTickPassedDepositPeriod(t *testing.T) { require.False(t, inactiveQueue.Valid()) inactiveQueue.Close() - newDepositMsg := NewMsgDeposit(addrs[1], proposalID, sdk.Coins{sdk.NewInt64Coin(staking.DefaultBondDenom, 5)}) + newDepositMsg := NewMsgDeposit(addrs[1], proposalID, sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 5)}) res = govHandler(ctx, newDepositMsg) require.True(t, res.IsOK()) @@ -169,7 +168,7 @@ func TestTickPassedVotingPeriod(t *testing.T) { require.False(t, activeQueue.Valid()) activeQueue.Close() - proposalCoins := sdk.Coins{sdk.NewCoin(staking.DefaultBondDenom, staking.TokensFromTendermintPower(5))} + proposalCoins := sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.TokensFromTendermintPower(5))} newProposalMsg := NewMsgSubmitProposal("Test", "test", ProposalTypeText, addrs[0], proposalCoins) res := govHandler(ctx, newProposalMsg) diff --git a/x/gov/expected_keepers.go b/x/gov/expected_keepers.go new file mode 100644 index 000000000..513c08ca0 --- /dev/null +++ b/x/gov/expected_keepers.go @@ -0,0 +1,12 @@ +package gov + +import sdk "github.com/cosmos/cosmos-sdk/types" + +// expected bank keeper +type BankKeeper interface { + GetCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins + + // TODO remove once governance doesn't require use of accounts + SendCoins(ctx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) (sdk.Tags, sdk.Error) + SetSendEnabled(ctx sdk.Context, enabled bool) +} diff --git a/x/gov/genesis.go b/x/gov/genesis.go index 8e4c31ac5..957381d59 100644 --- a/x/gov/genesis.go +++ b/x/gov/genesis.go @@ -6,7 +6,6 @@ import ( "time" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/staking" ) const ( @@ -48,11 +47,11 @@ func NewGenesisState(startingProposalID uint64, dp DepositParams, vp VotingParam // get raw genesis raw message for testing func DefaultGenesisState() GenesisState { - minDepositTokens := staking.TokensFromTendermintPower(10) + minDepositTokens := sdk.TokensFromTendermintPower(10) return GenesisState{ StartingProposalID: 1, DepositParams: DepositParams{ - MinDeposit: sdk.Coins{sdk.NewCoin(staking.DefaultBondDenom, minDepositTokens)}, + MinDeposit: sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, minDepositTokens)}, MaxDepositPeriod: DefaultPeriod, }, VotingParams: VotingParams{ diff --git a/x/gov/genesis_test.go b/x/gov/genesis_test.go index 61f2c299a..5624c58ae 100644 --- a/x/gov/genesis_test.go +++ b/x/gov/genesis_test.go @@ -5,8 +5,6 @@ import ( "github.com/stretchr/testify/require" - "github.com/cosmos/cosmos-sdk/x/mock" - abci "github.com/tendermint/tendermint/abci/types" ) @@ -78,7 +76,7 @@ func TestImportExportQueues(t *testing.T) { require.True(t, keeper.GetProposal(ctx, proposalID1).GetStatus() == StatusDepositPeriod) require.True(t, keeper.GetProposal(ctx, proposalID2).GetStatus() == StatusVotingPeriod) - genAccs := mock.GetAllAccounts(mapp.AccountKeeper, ctx) + genAccs := mapp.AccountKeeper.GetAllAccounts(ctx) // Export the state and import it into a new Mock App genState := ExportGenesis(ctx, keeper) diff --git a/x/gov/keeper.go b/x/gov/keeper.go index 3a3cdcb81..9616791dd 100644 --- a/x/gov/keeper.go +++ b/x/gov/keeper.go @@ -5,7 +5,6 @@ import ( codec "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/bank" "github.com/cosmos/cosmos-sdk/x/params" "github.com/tendermint/tendermint/crypto" @@ -57,7 +56,7 @@ type Keeper struct { paramSpace params.Subspace // The reference to the CoinKeeper to modify balances - ck bank.Keeper + ck BankKeeper // The ValidatorSet to get information about validators vs sdk.ValidatorSet @@ -80,7 +79,9 @@ type Keeper struct { // - depositing funds into proposals, and activating upon sufficient funds being deposited // - users voting on proposals, with weight proportional to stake in the system // - and tallying the result of the vote. -func NewKeeper(cdc *codec.Codec, key sdk.StoreKey, paramsKeeper params.Keeper, paramSpace params.Subspace, ck bank.Keeper, ds sdk.DelegationSet, codespace sdk.CodespaceType) Keeper { +func NewKeeper(cdc *codec.Codec, key sdk.StoreKey, paramsKeeper params.Keeper, + paramSpace params.Subspace, ck BankKeeper, ds sdk.DelegationSet, codespace sdk.CodespaceType) Keeper { + return Keeper{ storeKey: key, paramsKeeper: paramsKeeper, diff --git a/x/gov/keeper_test.go b/x/gov/keeper_test.go index 8fc2460ca..452450553 100644 --- a/x/gov/keeper_test.go +++ b/x/gov/keeper_test.go @@ -9,7 +9,6 @@ import ( abci "github.com/tendermint/tendermint/abci/types" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/staking" ) func TestGetSetProposal(t *testing.T) { @@ -70,14 +69,14 @@ func TestDeposits(t *testing.T) { proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) proposalID := proposal.GetProposalID() - fourSteak := sdk.Coins{sdk.NewCoin(staking.DefaultBondDenom, staking.TokensFromTendermintPower(4))} - fiveSteak := sdk.Coins{sdk.NewCoin(staking.DefaultBondDenom, staking.TokensFromTendermintPower(5))} + fourSteak := sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.TokensFromTendermintPower(4))} + fiveSteak := sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.TokensFromTendermintPower(5))} addr0Initial := keeper.ck.GetCoins(ctx, addrs[0]) addr1Initial := keeper.ck.GetCoins(ctx, addrs[1]) - expTokens := staking.TokensFromTendermintPower(42) - require.Equal(t, sdk.Coins{sdk.NewCoin(staking.DefaultBondDenom, expTokens)}, addr0Initial) + expTokens := sdk.TokensFromTendermintPower(42) + require.Equal(t, sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, expTokens)}, addr0Initial) require.True(t, proposal.GetTotalDeposit().IsEqual(sdk.Coins{})) // Check no deposits at beginning diff --git a/x/gov/msgs_test.go b/x/gov/msgs_test.go index 682aecdce..41e9cc65f 100644 --- a/x/gov/msgs_test.go +++ b/x/gov/msgs_test.go @@ -8,14 +8,13 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/mock" - "github.com/cosmos/cosmos-sdk/x/staking" ) var ( - coinsPos = sdk.Coins{sdk.NewInt64Coin(staking.DefaultBondDenom, 1000)} + coinsPos = sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 1000)} coinsZero = sdk.Coins{} coinsPosNotAtoms = sdk.Coins{sdk.NewInt64Coin("foo", 10000)} - coinsMulti = sdk.Coins{sdk.NewInt64Coin(staking.DefaultBondDenom, 1000), sdk.NewInt64Coin("foo", 10000)} + coinsMulti = sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 1000), sdk.NewInt64Coin("foo", 10000)} ) func init() { diff --git a/x/gov/simulation/invariants.go b/x/gov/simulation/invariants.go index 06f8e9774..89f886ed7 100644 --- a/x/gov/simulation/invariants.go +++ b/x/gov/simulation/invariants.go @@ -2,11 +2,10 @@ package simulation import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/mock/simulation" ) // AllInvariants tests all governance invariants -func AllInvariants() simulation.Invariant { +func AllInvariants() sdk.Invariant { return func(ctx sdk.Context) error { // TODO Add some invariants! // Checking proposal queues, no passed-but-unexecuted proposals, etc. diff --git a/x/gov/simulation/msgs.go b/x/gov/simulation/msgs.go index 7c078bdcf..d3707d525 100644 --- a/x/gov/simulation/msgs.go +++ b/x/gov/simulation/msgs.go @@ -10,7 +10,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/gov" "github.com/cosmos/cosmos-sdk/x/mock/simulation" - "github.com/cosmos/cosmos-sdk/x/staking" ) // SimulateSubmittingVotingAndSlashingForProposal simulates creating a msg Submit Proposal @@ -18,7 +17,7 @@ import ( // future operations. // TODO: Vote more intelligently, so we can actually do some checks regarding votes passing or failing // TODO: Actually check that validator slashings happened -func SimulateSubmittingVotingAndSlashingForProposal(k gov.Keeper, sk staking.Keeper) simulation.Operation { +func SimulateSubmittingVotingAndSlashingForProposal(k gov.Keeper) simulation.Operation { handler := gov.NewHandler(k) // The states are: // column 1: All validators vote @@ -178,7 +177,7 @@ func operationSimulateMsgVote(k gov.Keeper, acc simulation.Account, proposalID u func randomDeposit(r *rand.Rand) sdk.Coins { // TODO Choose based on account balance and min deposit amount := int64(r.Intn(20)) + 1 - return sdk.Coins{sdk.NewInt64Coin(staking.DefaultBondDenom, amount)} + return sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, amount)} } // Pick a random proposal ID diff --git a/x/gov/tally_test.go b/x/gov/tally_test.go index 966635fc7..cf89293ee 100644 --- a/x/gov/tally_test.go +++ b/x/gov/tally_test.go @@ -25,9 +25,9 @@ func createValidators(t *testing.T, stakingHandler sdk.Handler, ctx sdk.Context, for i := 0; i < len(addrs); i++ { - valTokens := staking.TokensFromTendermintPower(powerAmt[i]) + valTokens := sdk.TokensFromTendermintPower(powerAmt[i]) valCreateMsg := staking.NewMsgCreateValidator( - addrs[i], pubkeys[i], sdk.NewCoin(staking.DefaultBondDenom, valTokens), + addrs[i], pubkeys[i], sdk.NewCoin(sdk.DefaultBondDenom, valTokens), testDescription, testCommissionMsg, sdk.OneInt(), ) @@ -318,8 +318,8 @@ func TestTallyDelgatorOverride(t *testing.T) { createValidators(t, stakingHandler, ctx, valAddrs, []int64{5, 6, 7}) staking.EndBlocker(ctx, sk) - delTokens := staking.TokensFromTendermintPower(30) - delegator1Msg := staking.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[2]), sdk.NewCoin(staking.DefaultBondDenom, delTokens)) + delTokens := sdk.TokensFromTendermintPower(30) + delegator1Msg := staking.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[2]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) stakingHandler(ctx, delegator1Msg) proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) @@ -356,8 +356,8 @@ func TestTallyDelgatorInherit(t *testing.T) { createValidators(t, stakingHandler, ctx, valAddrs, []int64{5, 6, 7}) staking.EndBlocker(ctx, sk) - delTokens := staking.TokensFromTendermintPower(30) - delegator1Msg := staking.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[2]), sdk.NewCoin(staking.DefaultBondDenom, delTokens)) + delTokens := sdk.TokensFromTendermintPower(30) + delegator1Msg := staking.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[2]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) stakingHandler(ctx, delegator1Msg) proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) @@ -392,10 +392,10 @@ func TestTallyDelgatorMultipleOverride(t *testing.T) { createValidators(t, stakingHandler, ctx, valAddrs, []int64{5, 6, 7}) staking.EndBlocker(ctx, sk) - delTokens := staking.TokensFromTendermintPower(10) - delegator1Msg := staking.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[2]), sdk.NewCoin(staking.DefaultBondDenom, delTokens)) + delTokens := sdk.TokensFromTendermintPower(10) + delegator1Msg := staking.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[2]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) stakingHandler(ctx, delegator1Msg) - delegator1Msg2 := staking.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[1]), sdk.NewCoin(staking.DefaultBondDenom, delTokens)) + delegator1Msg2 := staking.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[1]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) stakingHandler(ctx, delegator1Msg2) proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) @@ -424,29 +424,29 @@ func TestTallyDelgatorMultipleInherit(t *testing.T) { ctx := mapp.BaseApp.NewContext(false, abci.Header{}) stakingHandler := staking.NewHandler(sk) - valTokens1 := staking.TokensFromTendermintPower(25) + valTokens1 := sdk.TokensFromTendermintPower(25) val1CreateMsg := staking.NewMsgCreateValidator( - sdk.ValAddress(addrs[0]), ed25519.GenPrivKey().PubKey(), sdk.NewCoin(staking.DefaultBondDenom, valTokens1), testDescription, testCommissionMsg, sdk.OneInt(), + sdk.ValAddress(addrs[0]), ed25519.GenPrivKey().PubKey(), sdk.NewCoin(sdk.DefaultBondDenom, valTokens1), testDescription, testCommissionMsg, sdk.OneInt(), ) stakingHandler(ctx, val1CreateMsg) - valTokens2 := staking.TokensFromTendermintPower(6) + valTokens2 := sdk.TokensFromTendermintPower(6) val2CreateMsg := staking.NewMsgCreateValidator( - sdk.ValAddress(addrs[1]), ed25519.GenPrivKey().PubKey(), sdk.NewCoin(staking.DefaultBondDenom, valTokens2), testDescription, testCommissionMsg, sdk.OneInt(), + sdk.ValAddress(addrs[1]), ed25519.GenPrivKey().PubKey(), sdk.NewCoin(sdk.DefaultBondDenom, valTokens2), testDescription, testCommissionMsg, sdk.OneInt(), ) stakingHandler(ctx, val2CreateMsg) - valTokens3 := staking.TokensFromTendermintPower(7) + valTokens3 := sdk.TokensFromTendermintPower(7) val3CreateMsg := staking.NewMsgCreateValidator( - sdk.ValAddress(addrs[2]), ed25519.GenPrivKey().PubKey(), sdk.NewCoin(staking.DefaultBondDenom, valTokens3), testDescription, testCommissionMsg, sdk.OneInt(), + sdk.ValAddress(addrs[2]), ed25519.GenPrivKey().PubKey(), sdk.NewCoin(sdk.DefaultBondDenom, valTokens3), testDescription, testCommissionMsg, sdk.OneInt(), ) stakingHandler(ctx, val3CreateMsg) - delTokens := staking.TokensFromTendermintPower(10) - delegator1Msg := staking.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[2]), sdk.NewCoin(staking.DefaultBondDenom, delTokens)) + delTokens := sdk.TokensFromTendermintPower(10) + delegator1Msg := staking.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[2]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) stakingHandler(ctx, delegator1Msg) - delegator1Msg2 := staking.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[1]), sdk.NewCoin(staking.DefaultBondDenom, delTokens)) + delegator1Msg2 := staking.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[1]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) stakingHandler(ctx, delegator1Msg2) staking.EndBlocker(ctx, sk) @@ -483,11 +483,11 @@ func TestTallyJailedValidator(t *testing.T) { createValidators(t, stakingHandler, ctx, valAddrs, []int64{25, 6, 7}) staking.EndBlocker(ctx, sk) - delTokens := staking.TokensFromTendermintPower(10) - delegator1Msg := staking.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[2]), sdk.NewCoin(staking.DefaultBondDenom, delTokens)) + delTokens := sdk.TokensFromTendermintPower(10) + delegator1Msg := staking.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[2]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) stakingHandler(ctx, delegator1Msg) - delegator1Msg2 := staking.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[1]), sdk.NewCoin(staking.DefaultBondDenom, delTokens)) + delegator1Msg2 := staking.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[1]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) stakingHandler(ctx, delegator1Msg2) val2, found := sk.GetValidator(ctx, sdk.ValAddress(addrs[1])) diff --git a/x/gov/test_common.go b/x/gov/test_common.go index ee3b95850..0c0d74306 100644 --- a/x/gov/test_common.go +++ b/x/gov/test_common.go @@ -16,7 +16,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/bank" "github.com/cosmos/cosmos-sdk/x/mock" "github.com/cosmos/cosmos-sdk/x/staking" - "github.com/cosmos/cosmos-sdk/x/staking/types" ) // initialize the mock application for this module @@ -46,10 +45,10 @@ func getMockApp(t *testing.T, numGenAccs int, genState GenesisState, genAccs []a require.NoError(t, mapp.CompleteSetup(keyStaking, tkeyStaking, keyGov)) - valTokens := staking.TokensFromTendermintPower(42) + valTokens := sdk.TokensFromTendermintPower(42) if genAccs == nil || len(genAccs) == 0 { genAccs, addrs, pubKeys, privKeys = mock.CreateGenAccounts(numGenAccs, - sdk.Coins{sdk.NewCoin(staking.DefaultBondDenom, valTokens)}) + sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, valTokens)}) } mock.SetGenesis(mapp, genAccs) @@ -73,7 +72,7 @@ func getInitChainer(mapp *mock.App, keeper Keeper, stakingKeeper staking.Keeper, mapp.InitChainer(ctx, req) stakingGenesis := staking.DefaultGenesisState() - tokens := types.TokensFromTendermintPower(100000) + tokens := sdk.TokensFromTendermintPower(100000) stakingGenesis.Pool.NotBondedTokens = tokens validators, err := staking.InitGenesis(ctx, stakingKeeper, stakingGenesis) diff --git a/x/ibc/expected_keepers.go b/x/ibc/expected_keepers.go new file mode 100644 index 000000000..f2b65f162 --- /dev/null +++ b/x/ibc/expected_keepers.go @@ -0,0 +1,9 @@ +package ibc + +import sdk "github.com/cosmos/cosmos-sdk/types" + +// expected bank keeper +type BankKeeper interface { + AddCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) (sdk.Coins, sdk.Tags, sdk.Error) + SubtractCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) (sdk.Coins, sdk.Tags, sdk.Error) +} diff --git a/x/ibc/handler.go b/x/ibc/handler.go index c7bffc529..afc302768 100644 --- a/x/ibc/handler.go +++ b/x/ibc/handler.go @@ -2,10 +2,9 @@ package ibc import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/bank" ) -func NewHandler(ibcm Mapper, ck bank.Keeper) sdk.Handler { +func NewHandler(ibcm Mapper, ck BankKeeper) sdk.Handler { return func(ctx sdk.Context, msg sdk.Msg) sdk.Result { switch msg := msg.(type) { case IBCTransferMsg: @@ -20,7 +19,7 @@ func NewHandler(ibcm Mapper, ck bank.Keeper) sdk.Handler { } // IBCTransferMsg deducts coins from the account and creates an egress IBC packet. -func handleIBCTransferMsg(ctx sdk.Context, ibcm Mapper, ck bank.Keeper, msg IBCTransferMsg) sdk.Result { +func handleIBCTransferMsg(ctx sdk.Context, ibcm Mapper, ck BankKeeper, msg IBCTransferMsg) sdk.Result { packet := msg.IBCPacket _, _, err := ck.SubtractCoins(ctx, packet.SrcAddr, packet.Coins) @@ -37,7 +36,7 @@ func handleIBCTransferMsg(ctx sdk.Context, ibcm Mapper, ck bank.Keeper, msg IBCT } // IBCReceiveMsg adds coins to the destination address and creates an ingress IBC packet. -func handleIBCReceiveMsg(ctx sdk.Context, ibcm Mapper, ck bank.Keeper, msg IBCReceiveMsg) sdk.Result { +func handleIBCReceiveMsg(ctx sdk.Context, ibcm Mapper, ck BankKeeper, msg IBCReceiveMsg) sdk.Result { packet := msg.IBCPacket seq := ibcm.GetIngressSequence(ctx, packet.SrcChain) diff --git a/x/mint/params.go b/x/mint/params.go index 62018397d..38366851e 100644 --- a/x/mint/params.go +++ b/x/mint/params.go @@ -4,7 +4,6 @@ import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/staking" ) // mint parameters @@ -33,7 +32,7 @@ func NewParams(mintDenom string, inflationRateChange, inflationMax, // default minting module parameters func DefaultParams() Params { return Params{ - MintDenom: staking.DefaultBondDenom, + MintDenom: sdk.DefaultBondDenom, InflationRateChange: sdk.NewDecWithPrec(13, 2), InflationMax: sdk.NewDecWithPrec(20, 2), InflationMin: sdk.NewDecWithPrec(7, 2), diff --git a/x/mock/app.go b/x/mock/app.go index e4826fc8f..1864e3941 100644 --- a/x/mock/app.go +++ b/x/mock/app.go @@ -313,17 +313,6 @@ func RandomSetGenesis(r *rand.Rand, app *App, addrs []sdk.AccAddress, denoms []s app.GenesisAccounts = accts } -// GetAllAccounts returns all accounts in the accountKeeper. -func GetAllAccounts(mapper auth.AccountKeeper, ctx sdk.Context) []auth.Account { - accounts := []auth.Account{} - appendAccount := func(acc auth.Account) (stop bool) { - accounts = append(accounts, acc) - return false - } - mapper.IterateAccounts(ctx, appendAccount) - return accounts -} - // GenSequenceOfTxs generates a set of signed transactions of messages, such // that they differ only by having the sequence numbers incremented between // every transaction. diff --git a/x/mock/simulation/invariants.go b/x/mock/simulation/invariants.go deleted file mode 100644 index d30b67be9..000000000 --- a/x/mock/simulation/invariants.go +++ /dev/null @@ -1,35 +0,0 @@ -package simulation - -import ( - "fmt" - "testing" - - abci "github.com/tendermint/tendermint/abci/types" - - "github.com/cosmos/cosmos-sdk/baseapp" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// An Invariant is a function which tests a particular invariant. -// If the invariant has been broken, it should return an error -// containing a descriptive message about what happened. -// The simulator will then halt and print the logs. -type Invariant func(ctx sdk.Context) error - -// group of Invarient -type Invariants []Invariant - -// assertAll asserts the all invariants against application state -func (invs Invariants) assertAll(t *testing.T, app *baseapp.BaseApp, - event string, displayLogs func()) { - - ctx := app.NewContext(false, abci.Header{Height: app.LastBlockHeight() + 1}) - - for i := 0; i < len(invs); i++ { - if err := invs[i](ctx); err != nil { - fmt.Printf("Invariants broken after %s\n%s\n", event, err.Error()) - displayLogs() - t.Fatal() - } - } -} diff --git a/x/mock/simulation/simulate.go b/x/mock/simulation/simulate.go index 723955f6b..e67bddc3c 100644 --- a/x/mock/simulation/simulate.go +++ b/x/mock/simulation/simulate.go @@ -24,7 +24,7 @@ type AppStateFn func(r *rand.Rand, accs []Account, genesisTimestamp time.Time) ( // Simulate tests application by sending random messages. func Simulate(t *testing.T, app *baseapp.BaseApp, appStateFn AppStateFn, ops WeightedOperations, - invariants Invariants, numBlocks int, blockSize int, commit bool) (bool, error) { + invariants sdk.Invariants, numBlocks int, blockSize int, commit bool) (bool, error) { time := time.Now().UnixNano() return SimulateFromSeed(t, app, appStateFn, time, ops, @@ -54,7 +54,7 @@ func initChain( // TODO split this monster function up func SimulateFromSeed(tb testing.TB, app *baseapp.BaseApp, appStateFn AppStateFn, seed int64, ops WeightedOperations, - invariants Invariants, + invariants sdk.Invariants, numBlocks int, blockSize int, commit bool) (stopEarly bool, simError error) { // in case we have to end early, don't os.Exit so that we can run cleanup code. @@ -153,7 +153,7 @@ func SimulateFromSeed(tb testing.TB, app *baseapp.BaseApp, app.BeginBlock(request) if testingMode { - invariants.assertAll(t, app, "BeginBlock", displayLogs) + assertAllInvariants(t, app, invariants, "BeginBlock", displayLogs) } ctx := app.NewContext(false, header) @@ -171,14 +171,14 @@ func SimulateFromSeed(tb testing.TB, app *baseapp.BaseApp, logWriter, displayLogs, eventStats.tally) if testingMode && onOperation { - invariants.assertAll(t, app, "QueuedOperations", displayLogs) + assertAllInvariants(t, app, invariants, "QueuedOperations", displayLogs) } logWriter("Standard operations") operations := blockSimulator(r, app, ctx, accs, header, logWriter) opCount += operations + numQueuedOpsRan + numQueuedTimeOpsRan if testingMode { - invariants.assertAll(t, app, "StandardOperations", displayLogs) + assertAllInvariants(t, app, invariants, "StandardOperations", displayLogs) } res := app.EndBlock(abci.RequestEndBlock{}) @@ -191,7 +191,7 @@ func SimulateFromSeed(tb testing.TB, app *baseapp.BaseApp, logWriter("EndBlock") if testingMode { - invariants.assertAll(t, app, "EndBlock", displayLogs) + assertAllInvariants(t, app, invariants, "EndBlock", displayLogs) } if commit { app.Commit() @@ -236,7 +236,7 @@ type blockSimFn func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, // Returns a function to simulate blocks. Written like this to avoid constant // parameters being passed everytime, to minimize memory overhead. func createBlockSimulator(testingMode bool, tb testing.TB, t *testing.T, params Params, - event func(string), invariants Invariants, ops WeightedOperations, + event func(string), invariants sdk.Invariants, ops WeightedOperations, operationQueue OperationQueue, timeOperationQueue []FutureOperation, totalNumBlocks int, avgBlockSize int, displayLogs func()) blockSimFn { @@ -281,7 +281,7 @@ func createBlockSimulator(testingMode bool, tb testing.TB, t *testing.T, params if testingMode { if onOperation { eventStr := fmt.Sprintf("operation: %v", logUpdate) - invariants.assertAll(t, app, eventStr, displayLogs) + assertAllInvariants(t, app, invariants, eventStr, displayLogs) } if opCount%50 == 0 { fmt.Printf("\rSimulating... block %d/%d, operation %d/%d. ", diff --git a/x/mock/simulation/util.go b/x/mock/simulation/util.go index 7d127131b..962dbfe43 100644 --- a/x/mock/simulation/util.go +++ b/x/mock/simulation/util.go @@ -8,9 +8,26 @@ import ( "testing" "time" + "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" + abci "github.com/tendermint/tendermint/abci/types" ) +// assertAll asserts the all invariants against application state +func assertAllInvariants(t *testing.T, app *baseapp.BaseApp, invs sdk.Invariants, + event string, displayLogs func()) { + + ctx := app.NewContext(false, abci.Header{Height: app.LastBlockHeight() + 1}) + + for i := 0; i < len(invs); i++ { + if err := invs[i](ctx); err != nil { + fmt.Printf("Invariants broken after %s\n%s\n", event, err.Error()) + displayLogs() + t.Fatal() + } + } +} + func getTestingMode(tb testing.TB) (testingMode bool, t *testing.T, b *testing.B) { testingMode = false if _t, ok := tb.(*testing.T); ok { @@ -112,7 +129,7 @@ func getBlockSize(r *rand.Rand, params Params, // NOTE this function is intended to be used manually used while running // computationally heavy simulations. // TODO reference this function in the codebase probably through use of a switch -func PeriodicInvariant(invariant Invariant, period int, offset int) Invariant { +func PeriodicInvariant(invariant sdk.Invariant, period int, offset int) sdk.Invariant { return func(ctx sdk.Context) error { if int(ctx.BlockHeight())%period == offset { return invariant(ctx) diff --git a/x/slashing/app_test.go b/x/slashing/app_test.go index 56f5a0e12..2ede44922 100644 --- a/x/slashing/app_test.go +++ b/x/slashing/app_test.go @@ -61,7 +61,7 @@ func getInitChainer(mapp *mock.App, keeper staking.Keeper) sdk.InitChainer { return func(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { mapp.InitChainer(ctx, req) stakingGenesis := staking.DefaultGenesisState() - tokens := staking.TokensFromTendermintPower(100000) + tokens := sdk.TokensFromTendermintPower(100000) stakingGenesis.Pool.NotBondedTokens = tokens validators, err := staking.InitGenesis(ctx, keeper, stakingGenesis) if err != nil { @@ -93,10 +93,10 @@ func checkValidatorSigningInfo(t *testing.T, mapp *mock.App, keeper Keeper, func TestSlashingMsgs(t *testing.T) { mapp, stakingKeeper, keeper := getMockApp(t) - genTokens := staking.TokensFromTendermintPower(42) - bondTokens := staking.TokensFromTendermintPower(10) - genCoin := sdk.NewCoin(staking.DefaultBondDenom, genTokens) - bondCoin := sdk.NewCoin(staking.DefaultBondDenom, bondTokens) + genTokens := sdk.TokensFromTendermintPower(42) + bondTokens := sdk.TokensFromTendermintPower(10) + genCoin := sdk.NewCoin(sdk.DefaultBondDenom, genTokens) + bondCoin := sdk.NewCoin(sdk.DefaultBondDenom, bondTokens) acc1 := &auth.BaseAccount{ Address: addr1, diff --git a/x/slashing/genesis.go b/x/slashing/genesis.go index 8a6cfdee6..49c1a866b 100644 --- a/x/slashing/genesis.go +++ b/x/slashing/genesis.go @@ -5,7 +5,6 @@ import ( "time" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/staking/types" ) // GenesisState - all slashing state that must be provided at genesis @@ -67,8 +66,8 @@ func ValidateGenesis(data GenesisState) error { // InitGenesis initialize default parameters // and the keeper's address to pubkey map -func InitGenesis(ctx sdk.Context, keeper Keeper, data GenesisState, sdata types.GenesisState) { - for _, validator := range sdata.Validators { +func InitGenesis(ctx sdk.Context, keeper Keeper, data GenesisState, validators []sdk.Validator) { + for _, validator := range validators { keeper.addPubkey(ctx, validator.GetConsPubKey()) } diff --git a/x/slashing/handler_test.go b/x/slashing/handler_test.go index 92311bd0f..569fb54ad 100644 --- a/x/slashing/handler_test.go +++ b/x/slashing/handler_test.go @@ -8,14 +8,13 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/staking" - "github.com/cosmos/cosmos-sdk/x/staking/types" ) func TestCannotUnjailUnlessJailed(t *testing.T) { // initial setup ctx, ck, sk, _, keeper := createTestInput(t, DefaultParams()) slh := NewHandler(keeper) - amt := types.TokensFromTendermintPower(100) + amt := sdk.TokensFromTendermintPower(100) addr, val := addrs[0], pks[0] msg := NewTestMsgCreateValidator(addr, val, amt) got := staking.NewHandler(sk)(ctx, msg) @@ -40,7 +39,7 @@ func TestCannotUnjailUnlessMeetMinSelfDelegation(t *testing.T) { ctx, ck, sk, _, keeper := createTestInput(t, DefaultParams()) slh := NewHandler(keeper) amtInt := int64(100) - addr, val, amt := addrs[0], pks[0], types.TokensFromTendermintPower(amtInt) + addr, val, amt := addrs[0], pks[0], sdk.TokensFromTendermintPower(amtInt) msg := NewTestMsgCreateValidator(addr, val, amt) msg.MinSelfDelegation = amt got := staking.NewHandler(sk)(ctx, msg) @@ -72,7 +71,7 @@ func TestJailedValidatorDelegations(t *testing.T) { stakingKeeper.SetParams(ctx, stakingParams) // create a validator - bondAmount := staking.TokensFromTendermintPower(10) + bondAmount := sdk.TokensFromTendermintPower(10) valPubKey := pks[0] valAddr, consAddr := addrs[1], sdk.ConsAddress(addrs[0]) diff --git a/x/slashing/keeper.go b/x/slashing/keeper.go index 036d2c608..de3751a15 100644 --- a/x/slashing/keeper.go +++ b/x/slashing/keeper.go @@ -9,7 +9,6 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/params" - staking "github.com/cosmos/cosmos-sdk/x/staking" ) // Keeper of the slashing store @@ -86,7 +85,7 @@ func (k Keeper) handleDoubleSign(ctx sdk.Context, addr crypto.Address, infractio // Note that this *can* result in a negative "distributionHeight", up to -ValidatorUpdateDelay, // i.e. at the end of the pre-genesis block (none) = at the beginning of the genesis block. // That's fine since this is just used to filter unbonding delegations & redelegations. - distributionHeight := infractionHeight - staking.ValidatorUpdateDelay + distributionHeight := infractionHeight - sdk.ValidatorUpdateDelay // get the percentage slash penalty fraction fraction := k.SlashFractionDoubleSign(ctx) @@ -175,7 +174,7 @@ func (k Keeper) handleValidatorSignature(ctx sdk.Context, addr crypto.Address, p // Note that this *can* result in a negative "distributionHeight" up to -ValidatorUpdateDelay-1, // i.e. at the end of the pre-genesis block (none) = at the beginning of the genesis block. // That's fine since this is just used to filter unbonding delegations & redelegations. - distributionHeight := height - staking.ValidatorUpdateDelay - 1 + distributionHeight := height - sdk.ValidatorUpdateDelay - 1 k.validatorSet.Slash(ctx, consAddr, distributionHeight, power, k.SlashFractionDowntime(ctx)) k.validatorSet.Jail(ctx, consAddr) signInfo.JailedUntil = ctx.BlockHeader().Time.Add(k.DowntimeJailDuration(ctx)) diff --git a/x/slashing/keeper_test.go b/x/slashing/keeper_test.go index f43dccac8..266e443ca 100644 --- a/x/slashing/keeper_test.go +++ b/x/slashing/keeper_test.go @@ -9,7 +9,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/staking" - "github.com/cosmos/cosmos-sdk/x/staking/types" ) // Have to change these parameters for tests @@ -32,7 +31,7 @@ func TestHandleDoubleSign(t *testing.T) { // validator added pre-genesis ctx = ctx.WithBlockHeight(-1) power := int64(100) - amt := staking.TokensFromTendermintPower(power) + amt := sdk.TokensFromTendermintPower(power) operatorAddr, val := addrs[0], pks[0] got := staking.NewHandler(sk)(ctx, NewTestMsgCreateValidator(operatorAddr, val, amt)) require.True(t, got.IsOK()) @@ -90,7 +89,7 @@ func TestPastMaxEvidenceAge(t *testing.T) { // validator added pre-genesis ctx = ctx.WithBlockHeight(-1) power := int64(100) - amt := staking.TokensFromTendermintPower(power) + amt := sdk.TokensFromTendermintPower(power) operatorAddr, val := addrs[0], pks[0] got := staking.NewHandler(sk)(ctx, NewTestMsgCreateValidator(operatorAddr, val, amt)) require.True(t, got.IsOK()) @@ -125,7 +124,7 @@ func TestHandleAbsentValidator(t *testing.T) { // initial setup ctx, ck, sk, _, keeper := createTestInput(t, keeperTestParams()) power := int64(100) - amt := staking.TokensFromTendermintPower(power) + amt := sdk.TokensFromTendermintPower(power) addr, val := addrs[0], pks[0] sh := staking.NewHandler(sk) slh := NewHandler(keeper) @@ -276,7 +275,7 @@ func TestHandleNewValidator(t *testing.T) { // initial setup ctx, ck, sk, _, keeper := createTestInput(t, keeperTestParams()) addr, val := addrs[0], pks[0] - amt := staking.TokensFromTendermintPower(100) + amt := sdk.TokensFromTendermintPower(100) sh := staking.NewHandler(sk) // 1000 first blocks not a validator @@ -309,7 +308,7 @@ func TestHandleNewValidator(t *testing.T) { validator, _ := sk.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(val)) require.Equal(t, sdk.Bonded, validator.GetStatus()) pool := sk.GetPool(ctx) - expTokens := staking.TokensFromTendermintPower(100) + expTokens := sdk.TokensFromTendermintPower(100) require.Equal(t, expTokens, pool.BondedTokens) } @@ -320,7 +319,7 @@ func TestHandleAlreadyJailed(t *testing.T) { // initial setup ctx, _, sk, _, keeper := createTestInput(t, DefaultParams()) power := int64(100) - amt := staking.TokensFromTendermintPower(power) + amt := sdk.TokensFromTendermintPower(power) addr, val := addrs[0], pks[0] sh := staking.NewHandler(sk) got := sh(ctx, NewTestMsgCreateValidator(addr, val, amt)) @@ -348,7 +347,7 @@ func TestHandleAlreadyJailed(t *testing.T) { require.Equal(t, sdk.Unbonding, validator.GetStatus()) // validator should have been slashed - resultingTokens := amt.Sub(staking.TokensFromTendermintPower(1)) + resultingTokens := amt.Sub(sdk.TokensFromTendermintPower(1)) require.Equal(t, resultingTokens, validator.GetTokens()) // another block missed @@ -373,7 +372,7 @@ func TestValidatorDippingInAndOut(t *testing.T) { params.MaxValidators = 1 sk.SetParams(ctx, params) power := int64(100) - amt := staking.TokensFromTendermintPower(power) + amt := sdk.TokensFromTendermintPower(power) addr, val := addrs[0], pks[0] consAddr := sdk.ConsAddress(addr) sh := staking.NewHandler(sk) @@ -389,7 +388,7 @@ func TestValidatorDippingInAndOut(t *testing.T) { } // validator kicked out of validator set - newAmt := staking.TokensFromTendermintPower(101) + newAmt := sdk.TokensFromTendermintPower(101) got = sh(ctx, NewTestMsgCreateValidator(addrs[1], pks[1], newAmt)) require.True(t, got.IsOK()) validatorUpdates, _ := staking.EndBlocker(ctx, sk) @@ -402,7 +401,7 @@ func TestValidatorDippingInAndOut(t *testing.T) { ctx = ctx.WithBlockHeight(height) // validator added back in - delTokens := types.TokensFromTendermintPower(3) + delTokens := sdk.TokensFromTendermintPower(3) got = sh(ctx, newTestMsgDelegate(sdk.AccAddress(addrs[2]), addrs[0], delTokens)) require.True(t, got.IsOK()) validatorUpdates, _ = staking.EndBlocker(ctx, sk) diff --git a/x/slashing/keys.go b/x/slashing/keys.go index c2f491508..ce3da1c7e 100644 --- a/x/slashing/keys.go +++ b/x/slashing/keys.go @@ -4,7 +4,6 @@ import ( "encoding/binary" sdk "github.com/cosmos/cosmos-sdk/types" - staking "github.com/cosmos/cosmos-sdk/x/staking/types" ) const ( @@ -64,7 +63,7 @@ func GetValidatorSlashingPeriodPrefix(v sdk.ConsAddress) []byte { func GetValidatorSlashingPeriodKey(v sdk.ConsAddress, startHeight int64) []byte { b := make([]byte, 8) // this needs to be height + ValidatorUpdateDelay because the slashing period for genesis validators starts at height -ValidatorUpdateDelay - binary.BigEndian.PutUint64(b, uint64(startHeight+staking.ValidatorUpdateDelay)) + binary.BigEndian.PutUint64(b, uint64(startHeight+sdk.ValidatorUpdateDelay)) return append(GetValidatorSlashingPeriodPrefix(v), b...) } diff --git a/x/slashing/simulation/invariants.go b/x/slashing/simulation/invariants.go index c140a5eb9..1545db2c7 100644 --- a/x/slashing/simulation/invariants.go +++ b/x/slashing/simulation/invariants.go @@ -2,12 +2,11 @@ package simulation import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/mock/simulation" ) // TODO Any invariants to check here? // AllInvariants tests all slashing invariants -func AllInvariants() simulation.Invariant { +func AllInvariants() sdk.Invariant { return func(_ sdk.Context) error { return nil } diff --git a/x/slashing/simulation/msgs.go b/x/slashing/simulation/msgs.go index 2b09226f2..732b3c28c 100644 --- a/x/slashing/simulation/msgs.go +++ b/x/slashing/simulation/msgs.go @@ -12,7 +12,10 @@ import ( // SimulateMsgUnjail func SimulateMsgUnjail(k slashing.Keeper) simulation.Operation { - return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, event func(string)) (action string, fOp []simulation.FutureOperation, err error) { + return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, + accs []simulation.Account, event func(string)) ( + action string, fOp []simulation.FutureOperation, err error) { + acc := simulation.RandomAcc(r, accs) address := sdk.ValAddress(acc.Address) msg := slashing.NewMsgUnjail(address) diff --git a/x/slashing/test_common.go b/x/slashing/test_common.go index 9b8736fc8..13279d614 100644 --- a/x/slashing/test_common.go +++ b/x/slashing/test_common.go @@ -36,7 +36,7 @@ var ( sdk.ValAddress(pks[1].Address()), sdk.ValAddress(pks[2].Address()), } - initCoins = staking.TokensFromTendermintPower(200) + initCoins = sdk.TokensFromTendermintPower(200) ) func createTestCodec() *codec.Codec { @@ -91,7 +91,7 @@ func createTestInput(t *testing.T, defaults Params) (sdk.Context, bank.Keeper, s sk.SetHooks(keeper.Hooks()) require.NotPanics(t, func() { - InitGenesis(ctx, keeper, GenesisState{defaults, nil, nil}, genesis) + InitGenesis(ctx, keeper, GenesisState{defaults, nil, nil}, genesis.Validators.ToSDKValidators()) }) return ctx, ck, sk, paramstore, keeper @@ -115,12 +115,12 @@ func testAddr(addr string) sdk.AccAddress { func NewTestMsgCreateValidator(address sdk.ValAddress, pubKey crypto.PubKey, amt sdk.Int) staking.MsgCreateValidator { commission := staking.NewCommissionMsg(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()) return staking.NewMsgCreateValidator( - address, pubKey, sdk.NewCoin(staking.DefaultBondDenom, amt), + address, pubKey, sdk.NewCoin(sdk.DefaultBondDenom, amt), staking.Description{}, commission, sdk.OneInt(), ) } func newTestMsgDelegate(delAddr sdk.AccAddress, valAddr sdk.ValAddress, delAmount sdk.Int) staking.MsgDelegate { - amount := sdk.NewCoin(staking.DefaultBondDenom, delAmount) + amount := sdk.NewCoin(sdk.DefaultBondDenom, delAmount) return staking.NewMsgDelegate(delAddr, valAddr, amount) } diff --git a/x/slashing/tick_test.go b/x/slashing/tick_test.go index 2476ec99b..cc0e5f13b 100644 --- a/x/slashing/tick_test.go +++ b/x/slashing/tick_test.go @@ -10,13 +10,12 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/staking" - "github.com/cosmos/cosmos-sdk/x/staking/types" ) func TestBeginBlocker(t *testing.T) { ctx, ck, sk, _, keeper := createTestInput(t, DefaultParams()) power := int64(100) - amt := types.TokensFromTendermintPower(power) + amt := sdk.TokensFromTendermintPower(power) addr, pk := addrs[2], pks[2] // bond the validator diff --git a/x/staking/alias.go b/x/staking/alias.go index dd41da0c0..5e9ddaccd 100644 --- a/x/staking/alias.go +++ b/x/staking/alias.go @@ -10,6 +10,9 @@ import ( type ( Keeper = keeper.Keeper + FeeCollectionKeeper = types.FeeCollectionKeeper + BankKeeper = types.BankKeeper + DistributionKeeper = types.DistributionKeeper Validator = types.Validator Validators = types.Validators Description = types.Description @@ -72,7 +75,6 @@ var ( KeyBondDenom = types.KeyBondDenom DefaultParams = types.DefaultParams - DefaultBondDenom = types.DefaultBondDenom InitialPool = types.InitialPool NewValidator = types.NewValidator NewDescription = types.NewDescription @@ -83,10 +85,6 @@ var ( DefaultGenesisState = types.DefaultGenesisState RegisterCodec = types.RegisterCodec - ValidatorUpdateDelay = types.ValidatorUpdateDelay - TokensToTendermintPower = types.TokensToTendermintPower - TokensFromTendermintPower = types.TokensFromTendermintPower - NewMsgCreateValidator = types.NewMsgCreateValidator NewMsgCreateValidatorOnBehalfOf = types.NewMsgCreateValidatorOnBehalfOf NewMsgEditValidator = types.NewMsgEditValidator diff --git a/x/staking/app_test.go b/x/staking/app_test.go index 53216a47d..d9781201d 100644 --- a/x/staking/app_test.go +++ b/x/staking/app_test.go @@ -51,7 +51,7 @@ func getInitChainer(mapp *mock.App, keeper Keeper) sdk.InitChainer { mapp.InitChainer(ctx, req) stakingGenesis := DefaultGenesisState() - tokens := TokensFromTendermintPower(100000) + tokens := sdk.TokensFromTendermintPower(100000) stakingGenesis.Pool.NotBondedTokens = tokens validators, err := InitGenesis(ctx, keeper, stakingGenesis) @@ -97,10 +97,10 @@ func checkDelegation( func TestStakingMsgs(t *testing.T) { mApp, keeper := getMockApp(t) - genTokens := TokensFromTendermintPower(42) - bondTokens := TokensFromTendermintPower(10) - genCoin := sdk.NewCoin(DefaultBondDenom, genTokens) - bondCoin := sdk.NewCoin(DefaultBondDenom, bondTokens) + genTokens := sdk.TokensFromTendermintPower(42) + bondTokens := sdk.TokensFromTendermintPower(10) + genCoin := sdk.NewCoin(sdk.DefaultBondDenom, genTokens) + bondCoin := sdk.NewCoin(sdk.DefaultBondDenom, bondTokens) acc1 := &auth.BaseAccount{ Address: addr1, diff --git a/x/staking/genesis.go b/x/staking/genesis.go index 8940378f1..1374e75be 100644 --- a/x/staking/genesis.go +++ b/x/staking/genesis.go @@ -22,7 +22,7 @@ func InitGenesis(ctx sdk.Context, keeper Keeper, data types.GenesisState) (res [ // initialized for the validator set e.g. with a one-block offset - the // first TM block is at height 1, so state updates applied from // genesis.json are in block 0. - ctx = ctx.WithBlockHeight(1 - types.ValidatorUpdateDelay) + ctx = ctx.WithBlockHeight(1 - sdk.ValidatorUpdateDelay) keeper.SetPool(ctx, data.Pool) keeper.SetParams(ctx, data.Params) @@ -46,7 +46,7 @@ func InitGenesis(ctx sdk.Context, keeper Keeper, data types.GenesisState) (res [ } } - for _, delegation := range data.Bonds { + for _, delegation := range data.Delegations { // Call the before-creation hook if not exported if !data.Exported { keeper.BeforeDelegationCreated(ctx, delegation.DelegatorAddr, delegation.ValidatorAddr) @@ -99,7 +99,7 @@ func ExportGenesis(ctx sdk.Context, keeper Keeper) types.GenesisState { params := keeper.GetParams(ctx) lastTotalPower := keeper.GetLastTotalPower(ctx) validators := keeper.GetAllValidators(ctx) - bonds := keeper.GetAllDelegations(ctx) + delegations := keeper.GetAllDelegations(ctx) var unbondingDelegations []types.UnbondingDelegation keeper.IterateUnbondingDelegations(ctx, func(_ int64, ubd types.UnbondingDelegation) (stop bool) { unbondingDelegations = append(unbondingDelegations, ubd) @@ -122,7 +122,7 @@ func ExportGenesis(ctx sdk.Context, keeper Keeper) types.GenesisState { LastTotalPower: lastTotalPower, LastValidatorPowers: lastValidatorPowers, Validators: validators, - Bonds: bonds, + Delegations: delegations, UnbondingDelegations: unbondingDelegations, Redelegations: redelegations, Exported: true, diff --git a/x/staking/genesis_test.go b/x/staking/genesis_test.go index 9a9a716fe..82b076104 100644 --- a/x/staking/genesis_test.go +++ b/x/staking/genesis_test.go @@ -20,8 +20,8 @@ func TestInitGenesis(t *testing.T) { ctx, _, keeper := keep.CreateTestInput(t, false, 1000) pool := keeper.GetPool(ctx) - pool.BondedTokens = TokensFromTendermintPower(2) - valTokens := TokensFromTendermintPower(1) + pool.BondedTokens = sdk.TokensFromTendermintPower(2) + valTokens := sdk.TokensFromTendermintPower(1) params := keeper.GetParams(ctx) validators := make([]Validator, 2) @@ -48,7 +48,7 @@ func TestInitGenesis(t *testing.T) { actualGenesis := ExportGenesis(ctx, keeper) require.Equal(t, genesisState.Pool, actualGenesis.Pool) require.Equal(t, genesisState.Params, actualGenesis.Params) - require.Equal(t, genesisState.Bonds, actualGenesis.Bonds) + require.Equal(t, genesisState.Delegations, actualGenesis.Delegations) require.EqualValues(t, keeper.GetAllValidators(ctx), actualGenesis.Validators) // now make sure the validators are bonded and intra-tx counters are correct @@ -76,7 +76,7 @@ func TestInitGenesisLargeValidatorSet(t *testing.T) { // Assigning 2 to the first 100 vals, 1 to the rest pool := keeper.GetPool(ctx) - bondedTokens := TokensFromTendermintPower(int64(200 + (size - 100))) + bondedTokens := sdk.TokensFromTendermintPower(int64(200 + (size - 100))) pool.BondedTokens = bondedTokens params := keeper.GetParams(ctx) @@ -89,9 +89,9 @@ func TestInitGenesisLargeValidatorSet(t *testing.T) { validators[i].Status = sdk.Bonded - tokens := TokensFromTendermintPower(1) + tokens := sdk.TokensFromTendermintPower(1) if i < 100 { - tokens = TokensFromTendermintPower(2) + tokens = sdk.TokensFromTendermintPower(2) } validators[i].Tokens = tokens validators[i].DelegatorShares = sdk.NewDecFromInt(tokens) diff --git a/x/staking/handler_test.go b/x/staking/handler_test.go index ef9391ed8..2daea30e6 100644 --- a/x/staking/handler_test.go +++ b/x/staking/handler_test.go @@ -32,7 +32,7 @@ func TestValidatorByPowerIndex(t *testing.T) { validatorAddr, validatorAddr3 := sdk.ValAddress(keep.Addrs[0]), sdk.ValAddress(keep.Addrs[1]) initPower := int64(1000000) - initBond := TokensFromTendermintPower(initPower) + initBond := sdk.TokensFromTendermintPower(initPower) ctx, _, keeper := keep.CreateTestInput(t, false, initPower) _ = setInstantUnbondPeriod(keeper, ctx) @@ -113,7 +113,7 @@ func TestDuplicatesMsgCreateValidator(t *testing.T) { addr1, addr2 := sdk.ValAddress(keep.Addrs[0]), sdk.ValAddress(keep.Addrs[1]) pk1, pk2 := keep.PKs[0], keep.PKs[1] - valTokens := types.TokensFromTendermintPower(10) + valTokens := sdk.TokensFromTendermintPower(10) msgCreateValidator1 := NewTestMsgCreateValidator(addr1, pk1, valTokens) got := handleMsgCreateValidator(ctx, msgCreateValidator1, keeper) require.True(t, got.IsOK(), "%v", got) @@ -184,7 +184,7 @@ func TestDuplicatesMsgCreateValidatorOnBehalfOf(t *testing.T) { validatorAddr := sdk.ValAddress(keep.Addrs[0]) delegatorAddr := keep.Addrs[1] pk := keep.PKs[0] - valTokens := types.TokensFromTendermintPower(10) + valTokens := sdk.TokensFromTendermintPower(10) msgCreateValidatorOnBehalfOf := NewTestMsgCreateValidatorOnBehalfOf(delegatorAddr, validatorAddr, pk, valTokens) got := handleMsgCreateValidator(ctx, msgCreateValidatorOnBehalfOf, keeper) require.True(t, got.IsOK(), "%v", got) @@ -214,7 +214,7 @@ func TestLegacyValidatorDelegations(t *testing.T) { ctx, _, keeper := keep.CreateTestInput(t, false, int64(1000)) setInstantUnbondPeriod(keeper, ctx) - bondAmount := TokensFromTendermintPower(10) + bondAmount := sdk.TokensFromTendermintPower(10) valAddr := sdk.ValAddress(keep.Addrs[0]) valConsPubKey, valConsAddr := keep.PKs[0], sdk.ConsAddress(keep.PKs[0].Address()) delAddr := keep.Addrs[1] @@ -247,7 +247,7 @@ func TestLegacyValidatorDelegations(t *testing.T) { require.Equal(t, bondAmount.MulRaw(2), validator.BondedTokens()) // unbond validator total self-delegations (which should jail the validator) - unbondShares := types.TokensFromTendermintPower(10) + unbondShares := sdk.TokensFromTendermintPower(10) msgUndelegate := NewMsgUndelegate(sdk.AccAddress(valAddr), valAddr, sdk.NewDecFromInt(unbondShares)) got = handleMsgUndelegate(ctx, msgUndelegate, keeper) @@ -304,11 +304,11 @@ func TestLegacyValidatorDelegations(t *testing.T) { func TestIncrementsMsgDelegate(t *testing.T) { initPower := int64(1000) - initBond := TokensFromTendermintPower(initPower) + initBond := sdk.TokensFromTendermintPower(initPower) ctx, accMapper, keeper := keep.CreateTestInput(t, false, initPower) params := keeper.GetParams(ctx) - bondAmount := TokensFromTendermintPower(10) + bondAmount := sdk.TokensFromTendermintPower(10) validatorAddr, delegatorAddr := sdk.ValAddress(keep.Addrs[0]), keep.Addrs[1] // first create validator @@ -379,7 +379,7 @@ func TestEditValidatorDecreaseMinSelfDelegation(t *testing.T) { validatorAddr := sdk.ValAddress(keep.Addrs[0]) initPower := int64(100) - initBond := types.TokensFromTendermintPower(100) + initBond := sdk.TokensFromTendermintPower(100) ctx, _, keeper := keep.CreateTestInput(t, false, initPower) _ = setInstantUnbondPeriod(keeper, ctx) @@ -411,7 +411,7 @@ func TestEditValidatorIncreaseMinSelfDelegationBeyondCurrentBond(t *testing.T) { validatorAddr := sdk.ValAddress(keep.Addrs[0]) initPower := int64(100) - initBond := types.TokensFromTendermintPower(100) + initBond := sdk.TokensFromTendermintPower(100) ctx, _, keeper := keep.CreateTestInput(t, false, initPower) _ = setInstantUnbondPeriod(keeper, ctx) @@ -441,7 +441,7 @@ func TestEditValidatorIncreaseMinSelfDelegationBeyondCurrentBond(t *testing.T) { func TestIncrementsMsgUnbond(t *testing.T) { initPower := int64(1000) - initBond := TokensFromTendermintPower(initPower) + initBond := sdk.TokensFromTendermintPower(initPower) ctx, accMapper, keeper := keep.CreateTestInput(t, false, initPower) params := setInstantUnbondPeriod(keeper, ctx) denom := params.BondDenom @@ -515,8 +515,8 @@ func TestIncrementsMsgUnbond(t *testing.T) { errorCases := []sdk.Int{ //1<<64 - 1, // more than int64 power //1<<63 + 1, // more than int64 power - types.TokensFromTendermintPower(1<<63 - 1), - types.TokensFromTendermintPower(1 << 31), + sdk.TokensFromTendermintPower(1<<63 - 1), + sdk.TokensFromTendermintPower(1 << 31), initBond, } for i, c := range errorCases { @@ -545,7 +545,7 @@ func TestIncrementsMsgUnbond(t *testing.T) { func TestMultipleMsgCreateValidator(t *testing.T) { initPower := int64(1000) - initTokens := types.TokensFromTendermintPower(initPower) + initTokens := sdk.TokensFromTendermintPower(initPower) ctx, accMapper, keeper := keep.CreateTestInput(t, false, initPower) params := setInstantUnbondPeriod(keeper, ctx) @@ -562,7 +562,7 @@ func TestMultipleMsgCreateValidator(t *testing.T) { // bond them all for i, validatorAddr := range validatorAddrs { - valTokens := types.TokensFromTendermintPower(10) + valTokens := sdk.TokensFromTendermintPower(10) msgCreateValidatorOnBehalfOf := NewTestMsgCreateValidatorOnBehalfOf( delegatorAddrs[i], validatorAddr, keep.PKs[i], valTokens) got := handleMsgCreateValidator(ctx, msgCreateValidatorOnBehalfOf, keeper) @@ -583,7 +583,7 @@ func TestMultipleMsgCreateValidator(t *testing.T) { for i, validatorAddr := range validatorAddrs { _, found := keeper.GetValidator(ctx, validatorAddr) require.True(t, found) - unbondingTokens := types.TokensFromTendermintPower(10) + unbondingTokens := sdk.TokensFromTendermintPower(10) msgUndelegate := NewMsgUndelegate(delegatorAddrs[i], validatorAddr, sdk.NewDecFromInt(unbondingTokens)) // remove delegation got := handleMsgUndelegate(ctx, msgUndelegate, keeper) require.True(t, got.IsOK(), "expected msg %d to be ok, got %v", i, got) @@ -695,13 +695,13 @@ func TestValidatorQueue(t *testing.T) { keeper.SetParams(ctx, params) // create the validator - valTokens := types.TokensFromTendermintPower(10) + valTokens := sdk.TokensFromTendermintPower(10) msgCreateValidator := NewTestMsgCreateValidator(validatorAddr, keep.PKs[0], valTokens) got := handleMsgCreateValidator(ctx, msgCreateValidator, keeper) require.True(t, got.IsOK(), "expected no error on runMsgCreateValidator") // bond a delegator - delTokens := types.TokensFromTendermintPower(10) + delTokens := sdk.TokensFromTendermintPower(10) msgDelegate := NewTestMsgDelegate(delegatorAddr, validatorAddr, delTokens) got = handleMsgDelegate(ctx, msgDelegate, keeper) require.True(t, got.IsOK(), "expected ok, got %v", got) @@ -748,7 +748,7 @@ func TestUnbondingPeriod(t *testing.T) { keeper.SetParams(ctx, params) // create the validator - valTokens := types.TokensFromTendermintPower(10) + valTokens := sdk.TokensFromTendermintPower(10) msgCreateValidator := NewTestMsgCreateValidator(validatorAddr, keep.PKs[0], valTokens) got := handleMsgCreateValidator(ctx, msgCreateValidator, keeper) require.True(t, got.IsOK(), "expected no error on runMsgCreateValidator") @@ -756,7 +756,7 @@ func TestUnbondingPeriod(t *testing.T) { EndBlocker(ctx, keeper) // begin unbonding - unbondingTokens := types.TokensFromTendermintPower(10) + unbondingTokens := sdk.TokensFromTendermintPower(10) msgUndelegate := NewMsgUndelegate(sdk.AccAddress(validatorAddr), validatorAddr, sdk.NewDecFromInt(unbondingTokens)) got = handleMsgUndelegate(ctx, msgUndelegate, keeper) @@ -936,7 +936,7 @@ func TestMultipleRedelegationAtSameTime(t *testing.T) { keeper.SetParams(ctx, params) // create the validators - valTokens := types.TokensFromTendermintPower(10) + valTokens := sdk.TokensFromTendermintPower(10) msgCreateValidator := NewTestMsgCreateValidator(valAddr, keep.PKs[0], valTokens) got := handleMsgCreateValidator(ctx, msgCreateValidator, keeper) require.True(t, got.IsOK(), "expected no error on runMsgCreateValidator") @@ -988,7 +988,7 @@ func TestMultipleRedelegationAtUniqueTimes(t *testing.T) { keeper.SetParams(ctx, params) // create the validators - valTokens := types.TokensFromTendermintPower(10) + valTokens := sdk.TokensFromTendermintPower(10) msgCreateValidator := NewTestMsgCreateValidator(valAddr, keep.PKs[0], valTokens) got := handleMsgCreateValidator(ctx, msgCreateValidator, keeper) require.True(t, got.IsOK(), "expected no error on runMsgCreateValidator") @@ -1041,7 +1041,7 @@ func TestMultipleUnbondingDelegationAtSameTime(t *testing.T) { keeper.SetParams(ctx, params) // create the validator - valTokens := types.TokensFromTendermintPower(10) + valTokens := sdk.TokensFromTendermintPower(10) msgCreateValidator := NewTestMsgCreateValidator(valAddr, keep.PKs[0], valTokens) got := handleMsgCreateValidator(ctx, msgCreateValidator, keeper) require.True(t, got.IsOK(), "expected no error on runMsgCreateValidator") @@ -1087,7 +1087,7 @@ func TestMultipleUnbondingDelegationAtUniqueTimes(t *testing.T) { keeper.SetParams(ctx, params) // create the validator - valTokens := types.TokensFromTendermintPower(10) + valTokens := sdk.TokensFromTendermintPower(10) msgCreateValidator := NewTestMsgCreateValidator(valAddr, keep.PKs[0], valTokens) got := handleMsgCreateValidator(ctx, msgCreateValidator, keeper) require.True(t, got.IsOK(), "expected no error on runMsgCreateValidator") @@ -1143,7 +1143,7 @@ func TestUnbondingWhenExcessValidators(t *testing.T) { keeper.SetParams(ctx, params) // add three validators - valTokens1 := types.TokensFromTendermintPower(50) + valTokens1 := sdk.TokensFromTendermintPower(50) msgCreateValidator := NewTestMsgCreateValidator(validatorAddr1, keep.PKs[0], valTokens1) got := handleMsgCreateValidator(ctx, msgCreateValidator, keeper) require.True(t, got.IsOK(), "expected no error on runMsgCreateValidator") @@ -1151,7 +1151,7 @@ func TestUnbondingWhenExcessValidators(t *testing.T) { keeper.ApplyAndReturnValidatorSetUpdates(ctx) require.Equal(t, 1, len(keeper.GetLastValidators(ctx))) - valTokens2 := types.TokensFromTendermintPower(30) + valTokens2 := sdk.TokensFromTendermintPower(30) msgCreateValidator = NewTestMsgCreateValidator(validatorAddr2, keep.PKs[1], valTokens2) got = handleMsgCreateValidator(ctx, msgCreateValidator, keeper) require.True(t, got.IsOK(), "expected no error on runMsgCreateValidator") @@ -1159,7 +1159,7 @@ func TestUnbondingWhenExcessValidators(t *testing.T) { keeper.ApplyAndReturnValidatorSetUpdates(ctx) require.Equal(t, 2, len(keeper.GetLastValidators(ctx))) - valTokens3 := types.TokensFromTendermintPower(10) + valTokens3 := sdk.TokensFromTendermintPower(10) msgCreateValidator = NewTestMsgCreateValidator(validatorAddr3, keep.PKs[2], valTokens3) got = handleMsgCreateValidator(ctx, msgCreateValidator, keeper) require.True(t, got.IsOK(), "expected no error on runMsgCreateValidator") @@ -1190,7 +1190,7 @@ func TestBondUnbondRedelegateSlashTwice(t *testing.T) { valA, valB, del := sdk.ValAddress(keep.Addrs[0]), sdk.ValAddress(keep.Addrs[1]), keep.Addrs[2] consAddr0 := sdk.ConsAddress(keep.PKs[0].Address()) - valTokens := types.TokensFromTendermintPower(10) + valTokens := sdk.TokensFromTendermintPower(10) msgCreateValidator := NewTestMsgCreateValidator(valA, keep.PKs[0], valTokens) got := handleMsgCreateValidator(ctx, msgCreateValidator, keeper) require.True(t, got.IsOK(), "expected no error on runMsgCreateValidator") @@ -1212,13 +1212,13 @@ func TestBondUnbondRedelegateSlashTwice(t *testing.T) { ctx = ctx.WithBlockHeight(1) // begin unbonding 4 stake - ubdTokens := types.TokensFromTendermintPower(4) + ubdTokens := sdk.TokensFromTendermintPower(4) msgUndelegate := NewMsgUndelegate(del, valA, sdk.NewDecFromInt(ubdTokens)) got = handleMsgUndelegate(ctx, msgUndelegate, keeper) require.True(t, got.IsOK(), "expected no error on runMsgUndelegate") // begin redelegate 6 stake - rdTokens := types.TokensFromTendermintPower(6) + rdTokens := sdk.TokensFromTendermintPower(6) msgBeginRedelegate := NewMsgBeginRedelegate(del, valA, valB, sdk.NewDecFromInt(rdTokens)) got = handleMsgBeginRedelegate(ctx, msgBeginRedelegate, keeper) require.True(t, got.IsOK(), "expected no error on runMsgBeginRedelegate") diff --git a/x/staking/keeper/sdk_types.go b/x/staking/keeper/alias_functions.go similarity index 89% rename from x/staking/keeper/sdk_types.go rename to x/staking/keeper/alias_functions.go index ad52c8b25..848f66051 100644 --- a/x/staking/keeper/sdk_types.go +++ b/x/staking/keeper/alias_functions.go @@ -142,3 +142,17 @@ func (k Keeper) IterateDelegations(ctx sdk.Context, delAddr sdk.AccAddress, i++ } } + +// return all delegations used during genesis dump +// TODO: remove this func, change all usage for iterate functionality +func (k Keeper) GetAllSDKDelegations(ctx sdk.Context) (delegations []sdk.Delegation) { + store := ctx.KVStore(k.storeKey) + iterator := sdk.KVStorePrefixIterator(store, DelegationKey) + defer iterator.Close() + + for ; iterator.Valid(); iterator.Next() { + delegation := types.MustUnmarshalDelegation(k.cdc, iterator.Value()) + delegations = append(delegations, delegation) + } + return delegations +} diff --git a/x/staking/keeper/delegation_test.go b/x/staking/keeper/delegation_test.go index 6a1526fc3..45c6320c5 100644 --- a/x/staking/keeper/delegation_test.go +++ b/x/staking/keeper/delegation_test.go @@ -171,7 +171,7 @@ func TestUnbondingDelegation(t *testing.T) { func TestUnbondDelegation(t *testing.T) { ctx, _, keeper := CreateTestInput(t, false, 0) pool := keeper.GetPool(ctx) - startTokens := types.TokensFromTendermintPower(10) + startTokens := sdk.TokensFromTendermintPower(10) pool.NotBondedTokens = startTokens //create a validator and a delegator to that validator @@ -188,7 +188,7 @@ func TestUnbondDelegation(t *testing.T) { delegation := types.NewDelegation(addrDels[0], addrVals[0], issuedShares) keeper.SetDelegation(ctx, delegation) - bondTokens := types.TokensFromTendermintPower(6) + bondTokens := sdk.TokensFromTendermintPower(6) amount, err := keeper.unbond(ctx, addrDels[0], addrVals[0], sdk.NewDecFromInt(bondTokens)) require.NoError(t, err) require.Equal(t, bondTokens, amount) // shares to be added to an unbonding delegation @@ -209,7 +209,7 @@ func TestUnbondDelegation(t *testing.T) { func TestUnbondingDelegationsMaxEntries(t *testing.T) { ctx, _, keeper := CreateTestInput(t, false, 0) pool := keeper.GetPool(ctx) - startTokens := types.TokensFromTendermintPower(10) + startTokens := sdk.TokensFromTendermintPower(10) pool.NotBondedTokens = startTokens // create a validator and a delegator to that validator @@ -256,13 +256,13 @@ func TestUndelegateSelfDelegationBelowMinSelfDelegation(t *testing.T) { ctx, _, keeper := CreateTestInput(t, false, 0) pool := keeper.GetPool(ctx) - startTokens := types.TokensFromTendermintPower(20) + startTokens := sdk.TokensFromTendermintPower(20) pool.NotBondedTokens = startTokens //create a validator with a self-delegation validator := types.NewValidator(addrVals[0], PKs[0], types.Description{}) - valTokens := types.TokensFromTendermintPower(10) + valTokens := sdk.TokensFromTendermintPower(10) validator.MinSelfDelegation = valTokens validator, pool, issuedShares := validator.AddTokensFromDel(pool, valTokens) require.Equal(t, valTokens, issuedShares.RoundInt()) @@ -275,7 +275,7 @@ func TestUndelegateSelfDelegationBelowMinSelfDelegation(t *testing.T) { // create a second delegation to this validator keeper.DeleteValidatorByPowerIndex(ctx, validator) - delTokens := types.TokensFromTendermintPower(10) + delTokens := sdk.TokensFromTendermintPower(10) validator, pool, issuedShares = validator.AddTokensFromDel(pool, delTokens) require.Equal(t, delTokens, issuedShares.RoundInt()) keeper.SetPool(ctx, pool) @@ -285,7 +285,7 @@ func TestUndelegateSelfDelegationBelowMinSelfDelegation(t *testing.T) { keeper.SetDelegation(ctx, delegation) val0AccAddr := sdk.AccAddress(addrVals[0].Bytes()) - _, err := keeper.Undelegate(ctx, val0AccAddr, addrVals[0], sdk.NewDecFromInt(types.TokensFromTendermintPower(6))) + _, err := keeper.Undelegate(ctx, val0AccAddr, addrVals[0], sdk.NewDecFromInt(sdk.TokensFromTendermintPower(6))) require.NoError(t, err) // end block @@ -294,7 +294,7 @@ func TestUndelegateSelfDelegationBelowMinSelfDelegation(t *testing.T) { validator, found := keeper.GetValidator(ctx, addrVals[0]) require.True(t, found) - require.Equal(t, types.TokensFromTendermintPower(14), validator.Tokens) + require.Equal(t, sdk.TokensFromTendermintPower(14), validator.Tokens) require.Equal(t, sdk.Unbonding, validator.Status) require.True(t, validator.Jailed) } @@ -302,13 +302,13 @@ func TestUndelegateSelfDelegationBelowMinSelfDelegation(t *testing.T) { func TestUndelegateFromUnbondingValidator(t *testing.T) { ctx, _, keeper := CreateTestInput(t, false, 0) pool := keeper.GetPool(ctx) - startTokens := types.TokensFromTendermintPower(20) + startTokens := sdk.TokensFromTendermintPower(20) pool.NotBondedTokens = startTokens //create a validator with a self-delegation validator := types.NewValidator(addrVals[0], PKs[0], types.Description{}) - valTokens := types.TokensFromTendermintPower(10) + valTokens := sdk.TokensFromTendermintPower(10) validator, pool, issuedShares := validator.AddTokensFromDel(pool, valTokens) require.Equal(t, valTokens, issuedShares.RoundInt()) keeper.SetPool(ctx, pool) @@ -319,7 +319,7 @@ func TestUndelegateFromUnbondingValidator(t *testing.T) { // create a second delegation to this validator keeper.DeleteValidatorByPowerIndex(ctx, validator) - delTokens := types.TokensFromTendermintPower(10) + delTokens := sdk.TokensFromTendermintPower(10) validator, pool, issuedShares = validator.AddTokensFromDel(pool, delTokens) require.Equal(t, delTokens, issuedShares.RoundInt()) keeper.SetPool(ctx, pool) @@ -374,13 +374,13 @@ func TestUndelegateFromUnbondingValidator(t *testing.T) { func TestUndelegateFromUnbondedValidator(t *testing.T) { ctx, _, keeper := CreateTestInput(t, false, 0) pool := keeper.GetPool(ctx) - startTokens := types.TokensFromTendermintPower(20) + startTokens := sdk.TokensFromTendermintPower(20) pool.NotBondedTokens = startTokens //create a validator with a self-delegation validator := types.NewValidator(addrVals[0], PKs[0], types.Description{}) - valTokens := types.TokensFromTendermintPower(10) + valTokens := sdk.TokensFromTendermintPower(10) validator, pool, issuedShares := validator.AddTokensFromDel(pool, valTokens) require.Equal(t, valTokens, issuedShares.RoundInt()) keeper.SetPool(ctx, pool) @@ -392,7 +392,7 @@ func TestUndelegateFromUnbondedValidator(t *testing.T) { // create a second delegation to this validator keeper.DeleteValidatorByPowerIndex(ctx, validator) - delTokens := types.TokensFromTendermintPower(10) + delTokens := sdk.TokensFromTendermintPower(10) validator, pool, issuedShares = validator.AddTokensFromDel(pool, delTokens) require.Equal(t, delTokens, issuedShares.RoundInt()) keeper.SetPool(ctx, pool) @@ -428,7 +428,7 @@ func TestUndelegateFromUnbondedValidator(t *testing.T) { require.Equal(t, validator.Status, sdk.Unbonded) // unbond some of the other delegation's shares - unbondTokens := types.TokensFromTendermintPower(6) + unbondTokens := sdk.TokensFromTendermintPower(6) _, err = keeper.Undelegate(ctx, addrDels[0], addrVals[0], sdk.NewDecFromInt(unbondTokens)) require.NoError(t, err) @@ -449,13 +449,13 @@ func TestUndelegateFromUnbondedValidator(t *testing.T) { func TestUnbondingAllDelegationFromValidator(t *testing.T) { ctx, _, keeper := CreateTestInput(t, false, 0) pool := keeper.GetPool(ctx) - startTokens := types.TokensFromTendermintPower(20) + startTokens := sdk.TokensFromTendermintPower(20) pool.NotBondedTokens = startTokens //create a validator with a self-delegation validator := types.NewValidator(addrVals[0], PKs[0], types.Description{}) - valTokens := types.TokensFromTendermintPower(10) + valTokens := sdk.TokensFromTendermintPower(10) validator, pool, issuedShares := validator.AddTokensFromDel(pool, valTokens) require.Equal(t, valTokens, issuedShares.RoundInt()) keeper.SetPool(ctx, pool) @@ -467,7 +467,7 @@ func TestUnbondingAllDelegationFromValidator(t *testing.T) { // create a second delegation to this validator keeper.DeleteValidatorByPowerIndex(ctx, validator) - delTokens := types.TokensFromTendermintPower(10) + delTokens := sdk.TokensFromTendermintPower(10) validator, pool, issuedShares = validator.AddTokensFromDel(pool, delTokens) require.Equal(t, delTokens, issuedShares.RoundInt()) keeper.SetPool(ctx, pool) @@ -593,12 +593,12 @@ func TestRedelegation(t *testing.T) { func TestRedelegateToSameValidator(t *testing.T) { ctx, _, keeper := CreateTestInput(t, false, 0) pool := keeper.GetPool(ctx) - startTokens := types.TokensFromTendermintPower(30) + startTokens := sdk.TokensFromTendermintPower(30) pool.NotBondedTokens = startTokens // create a validator with a self-delegation validator := types.NewValidator(addrVals[0], PKs[0], types.Description{}) - valTokens := types.TokensFromTendermintPower(10) + valTokens := sdk.TokensFromTendermintPower(10) validator, pool, issuedShares := validator.AddTokensFromDel(pool, valTokens) require.Equal(t, valTokens, issuedShares.RoundInt()) keeper.SetPool(ctx, pool) @@ -616,12 +616,12 @@ func TestRedelegateToSameValidator(t *testing.T) { func TestRedelegationMaxEntries(t *testing.T) { ctx, _, keeper := CreateTestInput(t, false, 0) pool := keeper.GetPool(ctx) - startTokens := types.TokensFromTendermintPower(20) + startTokens := sdk.TokensFromTendermintPower(20) pool.NotBondedTokens = startTokens // create a validator with a self-delegation validator := types.NewValidator(addrVals[0], PKs[0], types.Description{}) - valTokens := types.TokensFromTendermintPower(10) + valTokens := sdk.TokensFromTendermintPower(10) validator, pool, issuedShares := validator.AddTokensFromDel(pool, valTokens) require.Equal(t, valTokens, issuedShares.RoundInt()) keeper.SetPool(ctx, pool) @@ -667,12 +667,12 @@ func TestRedelegationMaxEntries(t *testing.T) { func TestRedelegateSelfDelegation(t *testing.T) { ctx, _, keeper := CreateTestInput(t, false, 0) pool := keeper.GetPool(ctx) - startTokens := types.TokensFromTendermintPower(30) + startTokens := sdk.TokensFromTendermintPower(30) pool.NotBondedTokens = startTokens //create a validator with a self-delegation validator := types.NewValidator(addrVals[0], PKs[0], types.Description{}) - valTokens := types.TokensFromTendermintPower(10) + valTokens := sdk.TokensFromTendermintPower(10) validator, pool, issuedShares := validator.AddTokensFromDel(pool, valTokens) require.Equal(t, valTokens, issuedShares.RoundInt()) keeper.SetPool(ctx, pool) @@ -692,7 +692,7 @@ func TestRedelegateSelfDelegation(t *testing.T) { require.Equal(t, sdk.Bonded, validator2.Status) // create a second delegation to validator 1 - delTokens := types.TokensFromTendermintPower(10) + delTokens := sdk.TokensFromTendermintPower(10) validator, pool, issuedShares = validator.AddTokensFromDel(pool, delTokens) require.Equal(t, delTokens, issuedShares.RoundInt()) keeper.SetPool(ctx, pool) @@ -718,13 +718,13 @@ func TestRedelegateSelfDelegation(t *testing.T) { func TestRedelegateFromUnbondingValidator(t *testing.T) { ctx, _, keeper := CreateTestInput(t, false, 0) pool := keeper.GetPool(ctx) - startTokens := types.TokensFromTendermintPower(30) + startTokens := sdk.TokensFromTendermintPower(30) pool.NotBondedTokens = startTokens //create a validator with a self-delegation validator := types.NewValidator(addrVals[0], PKs[0], types.Description{}) - valTokens := types.TokensFromTendermintPower(10) + valTokens := sdk.TokensFromTendermintPower(10) validator, pool, issuedShares := validator.AddTokensFromDel(pool, valTokens) require.Equal(t, valTokens, issuedShares.RoundInt()) keeper.SetPool(ctx, pool) @@ -736,7 +736,7 @@ func TestRedelegateFromUnbondingValidator(t *testing.T) { // create a second delegation to this validator keeper.DeleteValidatorByPowerIndex(ctx, validator) - delTokens := types.TokensFromTendermintPower(10) + delTokens := sdk.TokensFromTendermintPower(10) validator, pool, issuedShares = validator.AddTokensFromDel(pool, delTokens) require.Equal(t, delTokens, issuedShares.RoundInt()) keeper.SetPool(ctx, pool) @@ -782,7 +782,7 @@ func TestRedelegateFromUnbondingValidator(t *testing.T) { ctx = ctx.WithBlockHeader(header) // unbond some of the other delegation's shares - redelegateTokens := types.TokensFromTendermintPower(6) + redelegateTokens := sdk.TokensFromTendermintPower(6) _, err = keeper.BeginRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1], sdk.NewDecFromInt(redelegateTokens)) require.NoError(t, err) @@ -797,13 +797,13 @@ func TestRedelegateFromUnbondingValidator(t *testing.T) { func TestRedelegateFromUnbondedValidator(t *testing.T) { ctx, _, keeper := CreateTestInput(t, false, 0) pool := keeper.GetPool(ctx) - startTokens := types.TokensFromTendermintPower(30) + startTokens := sdk.TokensFromTendermintPower(30) pool.NotBondedTokens = startTokens //create a validator with a self-delegation validator := types.NewValidator(addrVals[0], PKs[0], types.Description{}) - valTokens := types.TokensFromTendermintPower(10) + valTokens := sdk.TokensFromTendermintPower(10) validator, pool, issuedShares := validator.AddTokensFromDel(pool, valTokens) require.Equal(t, valTokens, issuedShares.RoundInt()) keeper.SetPool(ctx, pool) @@ -815,7 +815,7 @@ func TestRedelegateFromUnbondedValidator(t *testing.T) { // create a second delegation to this validator keeper.DeleteValidatorByPowerIndex(ctx, validator) - delTokens := types.TokensFromTendermintPower(10) + delTokens := sdk.TokensFromTendermintPower(10) validator, pool, issuedShares = validator.AddTokensFromDel(pool, delTokens) require.Equal(t, delTokens, issuedShares.RoundInt()) keeper.SetPool(ctx, pool) @@ -853,7 +853,7 @@ func TestRedelegateFromUnbondedValidator(t *testing.T) { keeper.unbondingToUnbonded(ctx, validator) // redelegate some of the delegation's shares - redelegationTokens := types.TokensFromTendermintPower(6) + redelegationTokens := sdk.TokensFromTendermintPower(6) _, err = keeper.BeginRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1], sdk.NewDecFromInt(redelegationTokens)) require.NoError(t, err) diff --git a/x/staking/keeper/keeper.go b/x/staking/keeper/keeper.go index d1e82cb22..bfd60fa7b 100644 --- a/x/staking/keeper/keeper.go +++ b/x/staking/keeper/keeper.go @@ -6,7 +6,6 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/bank" "github.com/cosmos/cosmos-sdk/x/params" "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -18,7 +17,7 @@ type Keeper struct { storeKey sdk.StoreKey storeTKey sdk.StoreKey cdc *codec.Codec - bankKeeper bank.Keeper + bankKeeper types.BankKeeper hooks sdk.StakingHooks paramstore params.Subspace validatorCache map[string]cachedValidator @@ -28,14 +27,14 @@ type Keeper struct { codespace sdk.CodespaceType } -func NewKeeper(cdc *codec.Codec, key, tkey sdk.StoreKey, ck bank.Keeper, +func NewKeeper(cdc *codec.Codec, key, tkey sdk.StoreKey, bk types.BankKeeper, paramstore params.Subspace, codespace sdk.CodespaceType) Keeper { keeper := Keeper{ storeKey: key, storeTKey: tkey, cdc: cdc, - bankKeeper: ck, + bankKeeper: bk, paramstore: paramstore.WithKeyTable(ParamKeyTable()), hooks: nil, validatorCache: make(map[string]cachedValidator, aminoCacheSize), diff --git a/x/staking/keeper/slash.go b/x/staking/keeper/slash.go index 6156fbb4b..9793883f0 100644 --- a/x/staking/keeper/slash.go +++ b/x/staking/keeper/slash.go @@ -29,7 +29,7 @@ func (k Keeper) Slash(ctx sdk.Context, consAddr sdk.ConsAddress, infractionHeigh } // Amount of slashing = slash slashFactor * power at time of infraction - amount := types.TokensFromTendermintPower(power) + amount := sdk.TokensFromTendermintPower(power) slashAmountDec := sdk.NewDecFromInt(amount).Mul(slashFactor) slashAmount := slashAmountDec.TruncateInt() diff --git a/x/staking/keeper/slash_test.go b/x/staking/keeper/slash_test.go index 466edba8b..b2cec2ce8 100644 --- a/x/staking/keeper/slash_test.go +++ b/x/staking/keeper/slash_test.go @@ -21,7 +21,7 @@ func setupHelper(t *testing.T, power int64) (sdk.Context, Keeper, types.Params) params := keeper.GetParams(ctx) pool := keeper.GetPool(ctx) numVals := int64(3) - amt := types.TokensFromTendermintPower(power) + amt := sdk.TokensFromTendermintPower(power) pool.NotBondedTokens = amt.MulRaw(numVals) // add numVals validators @@ -199,7 +199,7 @@ func TestSlashAtNegativeHeight(t *testing.T) { // power decreased require.Equal(t, int64(5), validator.GetTendermintPower()) // pool bonded shares decreased - require.Equal(t, types.TokensFromTendermintPower(5), oldPool.BondedTokens.Sub(newPool.BondedTokens)) + require.Equal(t, sdk.TokensFromTendermintPower(5), oldPool.BondedTokens.Sub(newPool.BondedTokens)) } // tests Slash at the current height @@ -226,7 +226,7 @@ func TestSlashValidatorAtCurrentHeight(t *testing.T) { // power decreased require.Equal(t, int64(5), validator.GetTendermintPower()) // pool bonded shares decreased - require.Equal(t, types.TokensFromTendermintPower(5), oldPool.BondedTokens.Sub(newPool.BondedTokens)) + require.Equal(t, sdk.TokensFromTendermintPower(5), oldPool.BondedTokens.Sub(newPool.BondedTokens)) } // tests Slash at a previous height with an unbonding delegation @@ -237,7 +237,7 @@ func TestSlashWithUnbondingDelegation(t *testing.T) { // set an unbonding delegation with expiration timestamp beyond which the // unbonding delegation shouldn't be slashed - ubdTokens := types.TokensFromTendermintPower(4) + ubdTokens := sdk.TokensFromTendermintPower(4) ubd := types.NewUnbondingDelegation(addrDels[0], addrVals[0], 11, time.Unix(0, 0), ubdTokens) keeper.SetUnbondingDelegation(ctx, ubd) @@ -258,11 +258,11 @@ func TestSlashWithUnbondingDelegation(t *testing.T) { require.True(t, found) require.Len(t, ubd.Entries, 1) // balance decreased - require.Equal(t, types.TokensFromTendermintPower(2), ubd.Entries[0].Balance) + require.Equal(t, sdk.TokensFromTendermintPower(2), ubd.Entries[0].Balance) // read updated pool newPool := keeper.GetPool(ctx) // bonded tokens burned - require.Equal(t, types.TokensFromTendermintPower(3), oldPool.BondedTokens.Sub(newPool.BondedTokens)) + require.Equal(t, sdk.TokensFromTendermintPower(3), oldPool.BondedTokens.Sub(newPool.BondedTokens)) // read updated validator validator, found = keeper.GetValidatorByConsAddr(ctx, consAddr) require.True(t, found) @@ -283,7 +283,7 @@ func TestSlashWithUnbondingDelegation(t *testing.T) { // read updated pool newPool = keeper.GetPool(ctx) // bonded tokens burned again - require.Equal(t, types.TokensFromTendermintPower(6), oldPool.BondedTokens.Sub(newPool.BondedTokens)) + require.Equal(t, sdk.TokensFromTendermintPower(6), oldPool.BondedTokens.Sub(newPool.BondedTokens)) // read updated validator validator, found = keeper.GetValidatorByConsAddr(ctx, consAddr) require.True(t, found) @@ -304,7 +304,7 @@ func TestSlashWithUnbondingDelegation(t *testing.T) { // read updated pool newPool = keeper.GetPool(ctx) // bonded tokens burned again - require.Equal(t, types.TokensFromTendermintPower(9), oldPool.BondedTokens.Sub(newPool.BondedTokens)) + require.Equal(t, sdk.TokensFromTendermintPower(9), oldPool.BondedTokens.Sub(newPool.BondedTokens)) // read updated validator validator, found = keeper.GetValidatorByConsAddr(ctx, consAddr) require.True(t, found) @@ -325,7 +325,7 @@ func TestSlashWithUnbondingDelegation(t *testing.T) { // read updated pool newPool = keeper.GetPool(ctx) // just 1 bonded token burned again since that's all the validator now has - require.Equal(t, types.TokensFromTendermintPower(10), oldPool.BondedTokens.Sub(newPool.BondedTokens)) + require.Equal(t, sdk.TokensFromTendermintPower(10), oldPool.BondedTokens.Sub(newPool.BondedTokens)) // apply TM updates keeper.ApplyAndReturnValidatorSetUpdates(ctx) // read updated validator @@ -342,7 +342,7 @@ func TestSlashWithRedelegation(t *testing.T) { fraction := sdk.NewDecWithPrec(5, 1) // set a redelegation - rdTokens := types.TokensFromTendermintPower(6) + rdTokens := sdk.TokensFromTendermintPower(6) rd := types.NewRedelegation(addrDels[0], addrVals[0], addrVals[1], 11, time.Unix(0, 0), rdTokens, sdk.NewDecFromInt(rdTokens)) keeper.SetRedelegation(ctx, rd) @@ -370,7 +370,7 @@ func TestSlashWithRedelegation(t *testing.T) { // read updated pool newPool := keeper.GetPool(ctx) // bonded tokens burned - require.Equal(t, types.TokensFromTendermintPower(5), oldPool.BondedTokens.Sub(newPool.BondedTokens)) + require.Equal(t, sdk.TokensFromTendermintPower(5), oldPool.BondedTokens.Sub(newPool.BondedTokens)) // read updated validator validator, found = keeper.GetValidatorByConsAddr(ctx, consAddr) require.True(t, found) @@ -393,7 +393,7 @@ func TestSlashWithRedelegation(t *testing.T) { // read updated pool newPool = keeper.GetPool(ctx) // seven bonded tokens burned - require.Equal(t, types.TokensFromTendermintPower(12), oldPool.BondedTokens.Sub(newPool.BondedTokens)) + require.Equal(t, sdk.TokensFromTendermintPower(12), oldPool.BondedTokens.Sub(newPool.BondedTokens)) // read updated validator validator, found = keeper.GetValidatorByConsAddr(ctx, consAddr) require.True(t, found) @@ -413,7 +413,7 @@ func TestSlashWithRedelegation(t *testing.T) { // read updated pool newPool = keeper.GetPool(ctx) // four more bonded tokens burned - require.Equal(t, types.TokensFromTendermintPower(16), oldPool.BondedTokens.Sub(newPool.BondedTokens)) + require.Equal(t, sdk.TokensFromTendermintPower(16), oldPool.BondedTokens.Sub(newPool.BondedTokens)) // apply TM updates keeper.ApplyAndReturnValidatorSetUpdates(ctx) // read updated validator @@ -436,7 +436,7 @@ func TestSlashWithRedelegation(t *testing.T) { // read updated pool newPool = keeper.GetPool(ctx) // no more bonded tokens burned - require.Equal(t, types.TokensFromTendermintPower(16), oldPool.BondedTokens.Sub(newPool.BondedTokens)) + require.Equal(t, sdk.TokensFromTendermintPower(16), oldPool.BondedTokens.Sub(newPool.BondedTokens)) // read updated validator // power still zero, still in unbonding period validator, _ = keeper.GetValidatorByConsAddr(ctx, consAddr) @@ -450,7 +450,7 @@ func TestSlashBoth(t *testing.T) { // set a redelegation with expiration timestamp beyond which the // redelegation shouldn't be slashed - rdATokens := types.TokensFromTendermintPower(6) + rdATokens := sdk.TokensFromTendermintPower(6) rdA := types.NewRedelegation(addrDels[0], addrVals[0], addrVals[1], 11, time.Unix(0, 0), rdATokens, sdk.NewDecFromInt(rdATokens)) @@ -462,7 +462,7 @@ func TestSlashBoth(t *testing.T) { // set an unbonding delegation with expiration timestamp (beyond which the // unbonding delegation shouldn't be slashed) - ubdATokens := types.TokensFromTendermintPower(4) + ubdATokens := sdk.TokensFromTendermintPower(4) ubdA := types.NewUnbondingDelegation(addrDels[0], addrVals[0], 11, time.Unix(0, 0), ubdATokens) keeper.SetUnbondingDelegation(ctx, ubdA) @@ -482,9 +482,9 @@ func TestSlashBoth(t *testing.T) { // read updated pool newPool := keeper.GetPool(ctx) // not-bonded tokens burned - require.Equal(t, types.TokensFromTendermintPower(2), oldPool.NotBondedTokens.Sub(newPool.NotBondedTokens)) + require.Equal(t, sdk.TokensFromTendermintPower(2), oldPool.NotBondedTokens.Sub(newPool.NotBondedTokens)) // bonded tokens burned - require.Equal(t, types.TokensFromTendermintPower(3), oldPool.BondedTokens.Sub(newPool.BondedTokens)) + require.Equal(t, sdk.TokensFromTendermintPower(3), oldPool.BondedTokens.Sub(newPool.BondedTokens)) // read updated validator validator, found = keeper.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(PKs[0])) require.True(t, found) diff --git a/x/staking/keeper/test_common.go b/x/staking/keeper/test_common.go index 83b6eb3ed..853583acb 100644 --- a/x/staking/keeper/test_common.go +++ b/x/staking/keeper/test_common.go @@ -78,7 +78,7 @@ func MakeTestCodec() *codec.Codec { // init power is converted to an amount of tokens func CreateTestInput(t *testing.T, isCheckTx bool, initPower int64) (sdk.Context, auth.AccountKeeper, Keeper) { - initCoins := types.TokensFromTendermintPower(initPower) + initCoins := sdk.TokensFromTendermintPower(initPower) keyStaking := sdk.NewKVStoreKey(types.StoreKey) tkeyStaking := sdk.NewTransientStoreKey(types.TStoreKey) diff --git a/x/staking/keeper/validator_test.go b/x/staking/keeper/validator_test.go index 431b423bd..1528b1681 100644 --- a/x/staking/keeper/validator_test.go +++ b/x/staking/keeper/validator_test.go @@ -22,7 +22,7 @@ func TestSetValidator(t *testing.T) { valPubKey := PKs[0] valAddr := sdk.ValAddress(valPubKey.Address().Bytes()) - valTokens := types.TokensFromTendermintPower(10) + valTokens := sdk.TokensFromTendermintPower(10) // test how the validator is set from a purely unbonbed pool validator := types.NewValidator(valAddr, valPubKey, types.Description{}) @@ -124,15 +124,15 @@ func TestUpdateBondedValidatorsDecreaseCliff(t *testing.T) { keeper.SetParams(ctx, params) // create a random pool - pool.NotBondedTokens = types.TokensFromTendermintPower(10000) - pool.BondedTokens = types.TokensFromTendermintPower(1234) + pool.NotBondedTokens = sdk.TokensFromTendermintPower(10000) + pool.BondedTokens = sdk.TokensFromTendermintPower(1234) keeper.SetPool(ctx, pool) validators := make([]types.Validator, numVals) for i := 0; i < len(validators); i++ { moniker := fmt.Sprintf("val#%d", int64(i)) val := types.NewValidator(sdk.ValAddress(Addrs[i]), PKs[i], types.Description{Moniker: moniker}) - delTokens := types.TokensFromTendermintPower(int64((i + 1) * 10)) + delTokens := sdk.TokensFromTendermintPower(int64((i + 1) * 10)) val, pool, _ = val.AddTokensFromDel(pool, delTokens) keeper.SetPool(ctx, pool) @@ -145,7 +145,7 @@ func TestUpdateBondedValidatorsDecreaseCliff(t *testing.T) { // remove enough tokens to kick out the validator below the current cliff // validator and next in line cliff validator keeper.DeleteValidatorByPowerIndex(ctx, nextCliffVal) - shares := types.TokensFromTendermintPower(21) + shares := sdk.TokensFromTendermintPower(21) nextCliffVal, pool, _ = nextCliffVal.RemoveDelShares(pool, sdk.NewDecFromInt(shares)) keeper.SetPool(ctx, pool) nextCliffVal = TestingUpdateValidator(keeper, ctx, nextCliffVal, true) @@ -175,7 +175,7 @@ func TestSlashToZeroPowerRemoved(t *testing.T) { // add a validator validator := types.NewValidator(addrVals[0], PKs[0], types.Description{}) - valTokens := types.TokensFromTendermintPower(100) + valTokens := sdk.TokensFromTendermintPower(100) validator, pool, _ = validator.AddTokensFromDel(pool, valTokens) require.Equal(t, sdk.Unbonded, validator.Status) require.Equal(t, valTokens, validator.Tokens) @@ -206,13 +206,13 @@ func TestValidatorBasics(t *testing.T) { validators[i] = types.NewValidator(addrVals[i], PKs[i], types.Description{}) validators[i].Status = sdk.Unbonded validators[i].Tokens = sdk.ZeroInt() - tokens := types.TokensFromTendermintPower(power) + tokens := sdk.TokensFromTendermintPower(power) validators[i], pool, _ = validators[i].AddTokensFromDel(pool, tokens) keeper.SetPool(ctx, pool) } - assert.Equal(t, types.TokensFromTendermintPower(9), validators[0].Tokens) - assert.Equal(t, types.TokensFromTendermintPower(8), validators[1].Tokens) - assert.Equal(t, types.TokensFromTendermintPower(7), validators[2].Tokens) + assert.Equal(t, sdk.TokensFromTendermintPower(9), validators[0].Tokens) + assert.Equal(t, sdk.TokensFromTendermintPower(8), validators[1].Tokens) + assert.Equal(t, sdk.TokensFromTendermintPower(7), validators[2].Tokens) // check the empty keeper first _, found := keeper.GetValidator(ctx, addrVals[0]) @@ -245,14 +245,14 @@ func TestValidatorBasics(t *testing.T) { require.Equal(t, 1, len(resVals)) assert.True(ValEq(t, validators[0], resVals[0])) assert.Equal(t, sdk.Bonded, validators[0].Status) - assert.True(sdk.IntEq(t, types.TokensFromTendermintPower(9), validators[0].BondedTokens())) + assert.True(sdk.IntEq(t, sdk.TokensFromTendermintPower(9), validators[0].BondedTokens())) pool = keeper.GetPool(ctx) assert.True(sdk.IntEq(t, pool.BondedTokens, validators[0].BondedTokens())) // modify a records, save, and retrieve validators[0].Status = sdk.Bonded - validators[0].Tokens = types.TokensFromTendermintPower(10) + validators[0].Tokens = sdk.TokensFromTendermintPower(10) validators[0].DelegatorShares = sdk.NewDecFromInt(validators[0].Tokens) validators[0] = TestingUpdateValidator(keeper, ctx, validators[0], true) resVal, found = keeper.GetValidator(ctx, addrVals[0]) @@ -458,7 +458,7 @@ func TestGetValidatorsEdgeCases(t *testing.T) { pool := keeper.GetPool(ctx) moniker := fmt.Sprintf("val#%d", int64(i)) validators[i] = types.NewValidator(sdk.ValAddress(Addrs[i]), PKs[i], types.Description{Moniker: moniker}) - tokens := types.TokensFromTendermintPower(power) + tokens := sdk.TokensFromTendermintPower(power) validators[i], pool, _ = validators[i].AddTokensFromDel(pool, tokens) keeper.SetPool(ctx, pool) validators[i] = TestingUpdateValidator(keeper, ctx, validators[i], true) @@ -475,7 +475,7 @@ func TestGetValidatorsEdgeCases(t *testing.T) { pool := keeper.GetPool(ctx) keeper.DeleteValidatorByPowerIndex(ctx, validators[0]) - delTokens := types.TokensFromTendermintPower(500) + delTokens := sdk.TokensFromTendermintPower(500) validators[0], pool, _ = validators[0].AddTokensFromDel(pool, delTokens) keeper.SetPool(ctx, pool) validators[0] = TestingUpdateValidator(keeper, ctx, validators[0], true) @@ -540,9 +540,9 @@ func TestValidatorBondHeight(t *testing.T) { validators[1] = types.NewValidator(sdk.ValAddress(Addrs[1]), PKs[1], types.Description{}) validators[2] = types.NewValidator(sdk.ValAddress(Addrs[2]), PKs[2], types.Description{}) - tokens0 := types.TokensFromTendermintPower(200) - tokens1 := types.TokensFromTendermintPower(100) - tokens2 := types.TokensFromTendermintPower(100) + tokens0 := sdk.TokensFromTendermintPower(200) + tokens1 := sdk.TokensFromTendermintPower(100) + tokens2 := sdk.TokensFromTendermintPower(100) validators[0], pool, _ = validators[0].AddTokensFromDel(pool, tokens0) validators[1], pool, _ = validators[1].AddTokensFromDel(pool, tokens1) validators[2], pool, _ = validators[2].AddTokensFromDel(pool, tokens2) @@ -565,7 +565,7 @@ func TestValidatorBondHeight(t *testing.T) { assert.True(ValEq(t, validators[1], resValidators[1])) keeper.DeleteValidatorByPowerIndex(ctx, validators[1]) keeper.DeleteValidatorByPowerIndex(ctx, validators[2]) - delTokens := types.TokensFromTendermintPower(50) + delTokens := sdk.TokensFromTendermintPower(50) validators[1], pool, _ = validators[1].AddTokensFromDel(pool, delTokens) validators[2], pool, _ = validators[2].AddTokensFromDel(pool, delTokens) keeper.SetPool(ctx, pool) @@ -590,7 +590,7 @@ func TestFullValidatorSetPowerChange(t *testing.T) { for i, power := range powers { pool := keeper.GetPool(ctx) validators[i] = types.NewValidator(sdk.ValAddress(Addrs[i]), PKs[i], types.Description{}) - tokens := types.TokensFromTendermintPower(power) + tokens := sdk.TokensFromTendermintPower(power) validators[i], pool, _ = validators[i].AddTokensFromDel(pool, tokens) keeper.SetPool(ctx, pool) TestingUpdateValidator(keeper, ctx, validators[i], true) @@ -612,7 +612,7 @@ func TestFullValidatorSetPowerChange(t *testing.T) { // test a swap in voting power pool := keeper.GetPool(ctx) - tokens := types.TokensFromTendermintPower(600) + tokens := sdk.TokensFromTendermintPower(600) validators[0], pool, _ = validators[0].AddTokensFromDel(pool, tokens) keeper.SetPool(ctx, pool) validators[0] = TestingUpdateValidator(keeper, ctx, validators[0], true) @@ -634,7 +634,7 @@ func TestApplyAndReturnValidatorSetUpdatesAllNone(t *testing.T) { valAddr := sdk.ValAddress(valPubKey.Address().Bytes()) validators[i] = types.NewValidator(valAddr, valPubKey, types.Description{}) - tokens := types.TokensFromTendermintPower(power) + tokens := sdk.TokensFromTendermintPower(power) validators[i], pool, _ = validators[i].AddTokensFromDel(pool, tokens) keeper.SetPool(ctx, pool) } @@ -664,7 +664,7 @@ func TestApplyAndReturnValidatorSetUpdatesIdentical(t *testing.T) { pool := keeper.GetPool(ctx) validators[i] = types.NewValidator(sdk.ValAddress(Addrs[i]), PKs[i], types.Description{}) - tokens := types.TokensFromTendermintPower(power) + tokens := sdk.TokensFromTendermintPower(power) validators[i], pool, _ = validators[i].AddTokensFromDel(pool, tokens) keeper.SetPool(ctx, pool) } @@ -688,7 +688,7 @@ func TestApplyAndReturnValidatorSetUpdatesSingleValueChange(t *testing.T) { pool := keeper.GetPool(ctx) validators[i] = types.NewValidator(sdk.ValAddress(Addrs[i]), PKs[i], types.Description{}) - tokens := types.TokensFromTendermintPower(power) + tokens := sdk.TokensFromTendermintPower(power) validators[i], pool, _ = validators[i].AddTokensFromDel(pool, tokens) keeper.SetPool(ctx, pool) } @@ -699,7 +699,7 @@ func TestApplyAndReturnValidatorSetUpdatesSingleValueChange(t *testing.T) { // test single value change // tendermintUpdate set: {} -> {c1'} validators[0].Status = sdk.Bonded - validators[0].Tokens = types.TokensFromTendermintPower(600) + validators[0].Tokens = sdk.TokensFromTendermintPower(600) validators[0] = TestingUpdateValidator(keeper, ctx, validators[0], false) updates := keeper.ApplyAndReturnValidatorSetUpdates(ctx) @@ -717,7 +717,7 @@ func TestApplyAndReturnValidatorSetUpdatesMultipleValueChange(t *testing.T) { pool := keeper.GetPool(ctx) validators[i] = types.NewValidator(sdk.ValAddress(Addrs[i]), PKs[i], types.Description{}) - tokens := types.TokensFromTendermintPower(power) + tokens := sdk.TokensFromTendermintPower(power) validators[i], pool, _ = validators[i].AddTokensFromDel(pool, tokens) keeper.SetPool(ctx, pool) } @@ -728,8 +728,8 @@ func TestApplyAndReturnValidatorSetUpdatesMultipleValueChange(t *testing.T) { // test multiple value change // tendermintUpdate set: {c1, c3} -> {c1', c3'} pool := keeper.GetPool(ctx) - delTokens1 := types.TokensFromTendermintPower(190) - delTokens2 := types.TokensFromTendermintPower(80) + delTokens1 := sdk.TokensFromTendermintPower(190) + delTokens2 := sdk.TokensFromTendermintPower(80) validators[0], pool, _ = validators[0].AddTokensFromDel(pool, delTokens1) validators[1], pool, _ = validators[1].AddTokensFromDel(pool, delTokens2) keeper.SetPool(ctx, pool) @@ -751,7 +751,7 @@ func TestApplyAndReturnValidatorSetUpdatesInserted(t *testing.T) { pool := keeper.GetPool(ctx) validators[i] = types.NewValidator(sdk.ValAddress(Addrs[i]), PKs[i], types.Description{}) - tokens := types.TokensFromTendermintPower(power) + tokens := sdk.TokensFromTendermintPower(power) validators[i], pool, _ = validators[i].AddTokensFromDel(pool, tokens) keeper.SetPool(ctx, pool) } @@ -800,7 +800,7 @@ func TestApplyAndReturnValidatorSetUpdatesWithCliffValidator(t *testing.T) { pool := keeper.GetPool(ctx) validators[i] = types.NewValidator(sdk.ValAddress(Addrs[i]), PKs[i], types.Description{}) - tokens := types.TokensFromTendermintPower(power) + tokens := sdk.TokensFromTendermintPower(power) validators[i], pool, _ = validators[i].AddTokensFromDel(pool, tokens) keeper.SetPool(ctx, pool) } @@ -819,7 +819,7 @@ func TestApplyAndReturnValidatorSetUpdatesWithCliffValidator(t *testing.T) { require.Equal(t, 0, len(keeper.ApplyAndReturnValidatorSetUpdates(ctx))) pool := keeper.GetPool(ctx) - tokens := types.TokensFromTendermintPower(10) + tokens := sdk.TokensFromTendermintPower(10) validators[2], pool, _ = validators[2].AddTokensFromDel(pool, tokens) keeper.SetPool(ctx, pool) keeper.SetValidator(ctx, validators[2]) @@ -840,7 +840,7 @@ func TestApplyAndReturnValidatorSetUpdatesPowerDecrease(t *testing.T) { pool := keeper.GetPool(ctx) validators[i] = types.NewValidator(sdk.ValAddress(Addrs[i]), PKs[i], types.Description{}) - tokens := types.TokensFromTendermintPower(power) + tokens := sdk.TokensFromTendermintPower(power) validators[i], pool, _ = validators[i].AddTokensFromDel(pool, tokens) keeper.SetPool(ctx, pool) } @@ -855,8 +855,8 @@ func TestApplyAndReturnValidatorSetUpdatesPowerDecrease(t *testing.T) { // test multiple value change // tendermintUpdate set: {c1, c3} -> {c1', c3'} pool := keeper.GetPool(ctx) - delTokens1 := types.TokensFromTendermintPower(20) - delTokens2 := types.TokensFromTendermintPower(30) + delTokens1 := sdk.TokensFromTendermintPower(20) + delTokens2 := sdk.TokensFromTendermintPower(30) validators[0], pool, _ = validators[0].RemoveDelShares(pool, sdk.NewDecFromInt(delTokens1)) validators[1], pool, _ = validators[1].RemoveDelShares(pool, sdk.NewDecFromInt(delTokens2)) keeper.SetPool(ctx, pool) @@ -891,7 +891,7 @@ func TestApplyAndReturnValidatorSetUpdatesNewValidator(t *testing.T) { valAddr := sdk.ValAddress(valPubKey.Address().Bytes()) validators[i] = types.NewValidator(valAddr, valPubKey, types.Description{}) - tokens := types.TokensFromTendermintPower(power) + tokens := sdk.TokensFromTendermintPower(power) validators[i], pool, _ = validators[i].AddTokensFromDel(pool, tokens) keeper.SetPool(ctx, pool) @@ -913,7 +913,7 @@ func TestApplyAndReturnValidatorSetUpdatesNewValidator(t *testing.T) { for i, power := range powers { pool := keeper.GetPool(ctx) keeper.DeleteValidatorByPowerIndex(ctx, validators[i]) - tokens := types.TokensFromTendermintPower(power) + tokens := sdk.TokensFromTendermintPower(power) validators[i], pool, _ = validators[i].AddTokensFromDel(pool, tokens) keeper.SetPool(ctx, pool) @@ -943,7 +943,7 @@ func TestApplyAndReturnValidatorSetUpdatesNewValidator(t *testing.T) { valAddr = sdk.ValAddress(valPubKey.Address().Bytes()) validator = types.NewValidator(valAddr, valPubKey, types.Description{}) - tokens := types.TokensFromTendermintPower(500) + tokens := sdk.TokensFromTendermintPower(500) validator, pool, _ = validator.AddTokensFromDel(pool, tokens) keeper.SetValidator(ctx, validator) keeper.SetValidatorByPowerIndex(ctx, validator) @@ -978,7 +978,7 @@ func TestApplyAndReturnValidatorSetUpdatesBondTransition(t *testing.T) { valAddr := sdk.ValAddress(valPubKey.Address().Bytes()) validators[i] = types.NewValidator(valAddr, valPubKey, types.Description{Moniker: moniker}) - tokens := types.TokensFromTendermintPower(power) + tokens := sdk.TokensFromTendermintPower(power) validators[i], pool, _ = validators[i].AddTokensFromDel(pool, tokens) keeper.SetPool(ctx, pool) keeper.SetValidator(ctx, validators[i]) @@ -1004,7 +1004,7 @@ func TestApplyAndReturnValidatorSetUpdatesBondTransition(t *testing.T) { require.True(t, found) keeper.DeleteValidatorByPowerIndex(ctx, validators[0]) - tokens := types.TokensFromTendermintPower(1) + tokens := sdk.TokensFromTendermintPower(1) validators[0], pool, _ = validators[0].AddTokensFromDel(pool, tokens) keeper.SetPool(ctx, pool) keeper.SetValidator(ctx, validators[0]) @@ -1030,7 +1030,7 @@ func TestApplyAndReturnValidatorSetUpdatesBondTransition(t *testing.T) { require.Equal(t, 0, len(updates)) keeper.DeleteValidatorByPowerIndex(ctx, validators[1]) - tokens = types.TokensFromTendermintPower(250) + tokens = sdk.TokensFromTendermintPower(250) validators[1], pool, _ = validators[1].AddTokensFromDel(pool, tokens) keeper.SetPool(ctx, pool) keeper.SetValidator(ctx, validators[1]) diff --git a/x/staking/querier/querier_test.go b/x/staking/querier/querier_test.go index 5367f17c8..a2817335c 100644 --- a/x/staking/querier/querier_test.go +++ b/x/staking/querier/querier_test.go @@ -177,7 +177,7 @@ func TestQueryDelegation(t *testing.T) { keeper.SetValidator(ctx, val2) keeper.SetValidatorByPowerIndex(ctx, val2) - delTokens := types.TokensFromTendermintPower(20) + delTokens := sdk.TokensFromTendermintPower(20) keeper.Delegate(ctx, addrAcc2, delTokens, val1, true) // apply TM updates @@ -297,7 +297,7 @@ func TestQueryDelegation(t *testing.T) { require.Equal(t, delegationsRes[0], delegation) // Query unbonging delegation - unbondingTokens := types.TokensFromTendermintPower(10) + unbondingTokens := sdk.TokensFromTendermintPower(10) _, err = keeper.Undelegate(ctx, addrAcc2, val1.OperatorAddr, sdk.NewDecFromInt(unbondingTokens)) require.Nil(t, err) @@ -350,7 +350,7 @@ func TestQueryDelegation(t *testing.T) { require.NotNil(t, err) // Query redelegation - redelegationTokens := types.TokensFromTendermintPower(10) + redelegationTokens := sdk.TokensFromTendermintPower(10) _, err = keeper.BeginRedelegation(ctx, addrAcc2, val1.OperatorAddr, val2.OperatorAddr, sdk.NewDecFromInt(redelegationTokens)) require.Nil(t, err) @@ -385,11 +385,11 @@ func TestQueryRedelegations(t *testing.T) { keeper.SetValidator(ctx, val1) keeper.SetValidator(ctx, val2) - delAmount := types.TokensFromTendermintPower(100) + delAmount := sdk.TokensFromTendermintPower(100) keeper.Delegate(ctx, addrAcc2, delAmount, val1, true) _ = keeper.ApplyAndReturnValidatorSetUpdates(ctx) - rdAmount := types.TokensFromTendermintPower(20) + rdAmount := sdk.TokensFromTendermintPower(20) keeper.BeginRedelegation(ctx, addrAcc2, val1.GetOperator(), val2.GetOperator(), sdk.NewDecFromInt(rdAmount)) keeper.ApplyAndReturnValidatorSetUpdates(ctx) diff --git a/x/staking/simulation/invariants.go b/x/staking/simulation/invariants.go index 1f17b4a12..1368a61dc 100644 --- a/x/staking/simulation/invariants.go +++ b/x/staking/simulation/invariants.go @@ -6,21 +6,18 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/bank" - "github.com/cosmos/cosmos-sdk/x/distribution" - "github.com/cosmos/cosmos-sdk/x/mock/simulation" "github.com/cosmos/cosmos-sdk/x/staking" "github.com/cosmos/cosmos-sdk/x/staking/keeper" ) // AllInvariants runs all invariants of the staking module. // Currently: total supply, positive power -func AllInvariants(ck bank.Keeper, k staking.Keeper, - f auth.FeeCollectionKeeper, d distribution.Keeper, - am auth.AccountKeeper) simulation.Invariant { +func AllInvariants(k staking.Keeper, + f staking.FeeCollectionKeeper, d staking.DistributionKeeper, + am auth.AccountKeeper) sdk.Invariant { return func(ctx sdk.Context) error { - err := SupplyInvariants(ck, k, f, d, am)(ctx) + err := SupplyInvariants(k, f, d, am)(ctx) if err != nil { return err } @@ -46,8 +43,8 @@ func AllInvariants(ck bank.Keeper, k staking.Keeper, // SupplyInvariants checks that the total supply reflects all held not-bonded tokens, bonded tokens, and unbonding delegations // nolint: unparam -func SupplyInvariants(ck bank.Keeper, k staking.Keeper, - f auth.FeeCollectionKeeper, d distribution.Keeper, am auth.AccountKeeper) simulation.Invariant { +func SupplyInvariants(k staking.Keeper, + f staking.FeeCollectionKeeper, d staking.DistributionKeeper, am auth.AccountKeeper) sdk.Invariant { return func(ctx sdk.Context) error { pool := k.GetPool(ctx) @@ -73,16 +70,14 @@ func SupplyInvariants(ck bank.Keeper, k staking.Keeper, return false }) - feePool := d.GetFeePool(ctx) - // add outstanding fees loose = loose.Add(sdk.NewDecFromInt(f.GetCollectedFees(ctx).AmountOf(k.BondDenom(ctx)))) // add community pool - loose = loose.Add(feePool.CommunityPool.AmountOf(k.BondDenom(ctx))) + loose = loose.Add(d.GetFeePoolCommunityCoins(ctx).AmountOf(k.BondDenom(ctx))) // add yet-to-be-withdrawn - loose = loose.Add(d.GetOutstandingRewards(ctx).AmountOf(k.BondDenom(ctx))) + loose = loose.Add(d.GetOutstandingRewardsCoins(ctx).AmountOf(k.BondDenom(ctx))) // Not-bonded tokens should equal coin supply plus unbonding delegations // plus tokens on unbonded validators @@ -104,7 +99,7 @@ func SupplyInvariants(ck bank.Keeper, k staking.Keeper, } // NonNegativePowerInvariant checks that all stored validators have >= 0 power. -func NonNegativePowerInvariant(k staking.Keeper) simulation.Invariant { +func NonNegativePowerInvariant(k staking.Keeper) sdk.Invariant { return func(ctx sdk.Context) error { iterator := k.ValidatorsPowerStoreIterator(ctx) @@ -132,7 +127,7 @@ func NonNegativePowerInvariant(k staking.Keeper) simulation.Invariant { } // PositiveDelegationInvariant checks that all stored delegations have > 0 shares. -func PositiveDelegationInvariant(k staking.Keeper) simulation.Invariant { +func PositiveDelegationInvariant(k staking.Keeper) sdk.Invariant { return func(ctx sdk.Context) error { delegations := k.GetAllDelegations(ctx) for _, delegation := range delegations { @@ -151,7 +146,7 @@ func PositiveDelegationInvariant(k staking.Keeper) simulation.Invariant { // DelegatorSharesInvariant checks whether all the delegator shares which persist // in the delegator object add up to the correct total delegator shares // amount stored in each validator -func DelegatorSharesInvariant(k staking.Keeper) simulation.Invariant { +func DelegatorSharesInvariant(k staking.Keeper) sdk.Invariant { return func(ctx sdk.Context) error { validators := k.GetAllValidators(ctx) for _, validator := range validators { diff --git a/x/staking/test_common.go b/x/staking/test_common.go index aeb9ce626..2ddc53447 100644 --- a/x/staking/test_common.go +++ b/x/staking/test_common.go @@ -28,7 +28,7 @@ var ( func NewTestMsgCreateValidator(address sdk.ValAddress, pubKey crypto.PubKey, amt sdk.Int) MsgCreateValidator { return types.NewMsgCreateValidator( - address, pubKey, sdk.NewCoin(types.DefaultBondDenom, amt), Description{}, commissionMsg, sdk.OneInt(), + address, pubKey, sdk.NewCoin(sdk.DefaultBondDenom, amt), Description{}, commissionMsg, sdk.OneInt(), ) } @@ -38,7 +38,7 @@ func NewTestMsgCreateValidatorWithCommission(address sdk.ValAddress, pubKey cryp commission := NewCommissionMsg(commissionRate, sdk.OneDec(), sdk.ZeroDec()) return types.NewMsgCreateValidator( - address, pubKey, sdk.NewCoin(types.DefaultBondDenom, amt), Description{}, commission, sdk.OneInt(), + address, pubKey, sdk.NewCoin(sdk.DefaultBondDenom, amt), Description{}, commission, sdk.OneInt(), ) } @@ -46,18 +46,18 @@ func NewTestMsgCreateValidatorWithMinSelfDelegation(address sdk.ValAddress, pubK amt sdk.Int, minSelfDelegation sdk.Int) MsgCreateValidator { return types.NewMsgCreateValidator( - address, pubKey, sdk.NewCoin(types.DefaultBondDenom, amt), Description{}, commissionMsg, minSelfDelegation, + address, pubKey, sdk.NewCoin(sdk.DefaultBondDenom, amt), Description{}, commissionMsg, minSelfDelegation, ) } func NewTestMsgDelegate(delAddr sdk.AccAddress, valAddr sdk.ValAddress, amt sdk.Int) MsgDelegate { - amount := sdk.NewCoin(types.DefaultBondDenom, amt) + amount := sdk.NewCoin(sdk.DefaultBondDenom, amt) return NewMsgDelegate(delAddr, valAddr, amount) } func NewTestMsgCreateValidatorOnBehalfOf(delAddr sdk.AccAddress, valAddr sdk.ValAddress, valPubKey crypto.PubKey, amt sdk.Int) MsgCreateValidator { - amount := sdk.NewCoin(types.DefaultBondDenom, amt) + amount := sdk.NewCoin(sdk.DefaultBondDenom, amt) return NewMsgCreateValidatorOnBehalfOf(delAddr, valAddr, valPubKey, amount, Description{}, commissionMsg, sdk.OneInt()) } diff --git a/x/staking/types/expected_keepers.go b/x/staking/types/expected_keepers.go new file mode 100644 index 000000000..affa22070 --- /dev/null +++ b/x/staking/types/expected_keepers.go @@ -0,0 +1,20 @@ +package types + +import sdk "github.com/cosmos/cosmos-sdk/types" + +// expected coin keeper +type DistributionKeeper interface { + GetFeePoolCommunityCoins(ctx sdk.Context) sdk.DecCoins + GetOutstandingRewardsCoins(ctx sdk.Context) sdk.DecCoins +} + +// expected fee collection keeper +type FeeCollectionKeeper interface { + GetCollectedFees(ctx sdk.Context) sdk.Coins +} + +// expected bank keeper +type BankKeeper interface { + DelegateCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) (sdk.Tags, sdk.Error) + UndelegateCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) (sdk.Tags, sdk.Error) +} diff --git a/x/staking/types/genesis.go b/x/staking/types/genesis.go index fdc9b9677..e7c148346 100644 --- a/x/staking/types/genesis.go +++ b/x/staking/types/genesis.go @@ -10,8 +10,8 @@ type GenesisState struct { Params Params `json:"params"` LastTotalPower sdk.Int `json:"last_total_power"` LastValidatorPowers []LastValidatorPower `json:"last_validator_powers"` - Validators []Validator `json:"validators"` - Bonds []Delegation `json:"bonds"` + Validators Validators `json:"validators"` + Delegations Delegations `json:"delegations"` UnbondingDelegations []UnbondingDelegation `json:"unbonding_delegations"` Redelegations []Redelegation `json:"redelegations"` Exported bool `json:"exported"` @@ -23,12 +23,12 @@ type LastValidatorPower struct { Power int64 } -func NewGenesisState(pool Pool, params Params, validators []Validator, bonds []Delegation) GenesisState { +func NewGenesisState(pool Pool, params Params, validators []Validator, delegations []Delegation) GenesisState { return GenesisState{ - Pool: pool, - Params: params, - Validators: validators, - Bonds: bonds, + Pool: pool, + Params: params, + Validators: validators, + Delegations: delegations, } } diff --git a/x/staking/types/msg_test.go b/x/staking/types/msg_test.go index ce3e6383b..1e124e20e 100644 --- a/x/staking/types/msg_test.go +++ b/x/staking/types/msg_test.go @@ -11,8 +11,8 @@ import ( ) var ( - coinPos = sdk.NewInt64Coin(DefaultBondDenom, 1000) - coinZero = sdk.NewInt64Coin(DefaultBondDenom, 0) + coinPos = sdk.NewInt64Coin(sdk.DefaultBondDenom, 1000) + coinZero = sdk.NewInt64Coin(sdk.DefaultBondDenom, 0) ) // test ValidateBasic for MsgCreateValidator diff --git a/x/staking/types/params.go b/x/staking/types/params.go index 759efab52..3239bdc25 100644 --- a/x/staking/types/params.go +++ b/x/staking/types/params.go @@ -6,6 +6,7 @@ import ( "time" "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/params" ) @@ -20,16 +21,6 @@ const ( // Default maximum entries in a UBD/RED pair DefaultMaxEntries uint16 = 7 - - // Delay, in blocks, between when validator updates are returned to Tendermint and when they are applied - // For example, if this is 0, the validator set at the end of a block will sign the next block, or - // if this is 1, the validator set at the end of a block will sign the block after the next. - // Constant as this should not change without a hard fork. - // TODO: Link to some Tendermint docs, this is very unobvious. - ValidatorUpdateDelay int64 = 1 - - // Default bondable coin denomination - DefaultBondDenom = "stake" ) // nolint - Keys for parameter access @@ -82,7 +73,7 @@ func (p Params) Equal(p2 Params) bool { // DefaultParams returns a default set of parameters. func DefaultParams() Params { - return NewParams(DefaultUnbondingTime, DefaultMaxValidators, DefaultMaxEntries, DefaultBondDenom) + return NewParams(DefaultUnbondingTime, DefaultMaxValidators, DefaultMaxEntries, sdk.DefaultBondDenom) } // String returns a human readable string representation of the parameters. diff --git a/x/staking/types/validator.go b/x/staking/types/validator.go index 37e32b5d9..7d1f6fa80 100644 --- a/x/staking/types/validator.go +++ b/x/staking/types/validator.go @@ -3,7 +3,6 @@ package types import ( "bytes" "fmt" - "math/big" "strings" "time" @@ -55,6 +54,14 @@ func (v Validators) String() (out string) { return strings.TrimSpace(out) } +// ToSDKValidators - convenience function convert []Validators to []sdk.Validators +func (v Validators) ToSDKValidators() (validators []sdk.Validator) { + for _, val := range v { + validators = append(validators, val) + } + return validators +} + // NewValidator - initialize a new validator func NewValidator(operator sdk.ValAddress, pubKey crypto.PubKey, description Description) Validator { return Validator{ @@ -417,23 +424,9 @@ func (v Validator) TendermintPower() int64 { return 0 } -var powerReduction = sdk.NewIntFromBigInt(new(big.Int).Exp(big.NewInt(10), big.NewInt(6), nil)) - // potential Tendermint power func (v Validator) PotentialTendermintPower() int64 { - return (v.Tokens.Div(powerReduction)).Int64() -} - -// utility functions - -// TokensToTendermintPower - convert input tokens to potential tendermint power -func TokensToTendermintPower(tokens sdk.Int) int64 { - return (tokens.Div(powerReduction)).Int64() -} - -// TokensFromTendermintPower - convert input power to tokens -func TokensFromTendermintPower(power int64) sdk.Int { - return sdk.NewInt(power).Mul(powerReduction) + return sdk.TokensToTendermintPower(v.Tokens) } // ensure fulfills the sdk validator types