From ab9de3a7f126bd572bf8523c51420f97eac906f2 Mon Sep 17 00:00:00 2001 From: frog power 4000 Date: Thu, 21 Feb 2019 03:05:31 -0500 Subject: [PATCH] Merge PR #3680: Convenience ToDec() * NewDecFromInt -> ToDec * pending * Update PENDING.md Co-Authored-By: rigelrozanski * test typo * typo --- PENDING.md | 1 + client/lcd/lcd_test.go | 4 +-- client/lcd/test_helpers.go | 4 +-- types/dec_coin.go | 6 ++-- types/int.go | 5 +++ x/auth/account.go | 2 +- x/distribution/keeper/delegation_test.go | 16 ++++----- x/distribution/keeper/validator.go | 2 +- x/gov/tally.go | 2 +- x/slashing/handler_test.go | 2 +- x/slashing/keeper_test.go | 2 +- x/staking/app_test.go | 6 ++-- x/staking/genesis_test.go | 6 ++-- x/staking/handler_test.go | 42 ++++++++++++------------ x/staking/keeper/delegation_test.go | 26 +++++++-------- x/staking/keeper/slash.go | 4 +-- x/staking/keeper/slash_test.go | 8 ++--- x/staking/keeper/validator_test.go | 10 +++--- x/staking/querier/querier_test.go | 6 ++-- x/staking/simulation/invariants.go | 14 ++++---- x/staking/simulation/msgs.go | 2 +- x/staking/types/pool.go | 3 +- x/staking/types/validator.go | 4 +-- 23 files changed, 91 insertions(+), 86 deletions(-) diff --git a/PENDING.md b/PENDING.md index 003685c6feae..4402fa0f65e5 100644 --- a/PENDING.md +++ b/PENDING.md @@ -45,6 +45,7 @@ ### SDK +* \#3456 Integrate in the Int.ToDec() convenience function * [\#3300] Update the spec-spec, spec file reorg, and TOC updates. * [\#3665] Overhaul sdk.Uint type in preparation for Coins's Int -> Uint migration. diff --git a/client/lcd/lcd_test.go b/client/lcd/lcd_test.go index 77dd2f879443..90083c98abf4 100644 --- a/client/lcd/lcd_test.go +++ b/client/lcd/lcd_test.go @@ -441,7 +441,7 @@ func TestBonding(t *testing.T) { require.Equal(t, 2, len(operAddrs)) amt := sdk.TokensFromTendermintPower(60) - amtDec := sdk.NewDecFromInt(amt) + amtDec := amt.ToDec() validator := getValidator(t, port, operAddrs[0]) acc := getAccount(t, port, addr) @@ -545,7 +545,7 @@ func TestBonding(t *testing.T) { require.Equal(t, resultTx.Height, txs[0].Height) // query delegations, unbondings and redelegations from validator and delegator - rdShares := sdk.NewDecFromInt(rdTokens) + rdShares := rdTokens.ToDec() delegatorDels = getDelegatorDelegations(t, port, addr) require.Len(t, delegatorDels, 1) require.Equal(t, rdShares, delegatorDels[0].GetShares()) diff --git a/client/lcd/test_helpers.go b/client/lcd/test_helpers.go index 0f26a18517b8..372739386873 100644 --- a/client/lcd/test_helpers.go +++ b/client/lcd/test_helpers.go @@ -861,7 +861,7 @@ func doUndelegate( BaseReq: baseReq, DelegatorAddr: delAddr, ValidatorAddr: valAddr, - SharesAmount: sdk.NewDecFromInt(amount), + SharesAmount: amount.ToDec(), } req, err := cdc.MarshalJSON(msg) @@ -905,7 +905,7 @@ func doBeginRedelegation( DelegatorAddr: delAddr, ValidatorSrcAddr: valSrcAddr, ValidatorDstAddr: valDstAddr, - SharesAmount: sdk.NewDecFromInt(amount), + SharesAmount: amount.ToDec(), } req, err := cdc.MarshalJSON(msg) diff --git a/types/dec_coin.go b/types/dec_coin.go index 9634b85360c9..8a687e8d30fe 100644 --- a/types/dec_coin.go +++ b/types/dec_coin.go @@ -27,7 +27,7 @@ func NewDecCoin(denom string, amount Int) DecCoin { return DecCoin{ Denom: denom, - Amount: NewDecFromInt(amount), + Amount: amount.ToDec(), } } @@ -54,7 +54,7 @@ func NewDecCoinFromCoin(coin Coin) DecCoin { return DecCoin{ Denom: coin.Denom, - Amount: NewDecFromInt(coin.Amount), + Amount: coin.Amount.ToDec(), } } @@ -117,7 +117,7 @@ func (coin DecCoin) Minus(coinB DecCoin) DecCoin { // return the decimal coins with trunctated decimals, and return the change func (coin DecCoin) TruncateDecimal() (Coin, DecCoin) { truncated := coin.Amount.TruncateInt() - change := coin.Amount.Sub(NewDecFromInt(truncated)) + change := coin.Amount.Sub(truncated.ToDec()) return NewCoin(coin.Denom, truncated), DecCoin{coin.Denom, change} } diff --git a/types/int.go b/types/int.go index 907b492b7702..00dbef2d14e0 100644 --- a/types/int.go +++ b/types/int.go @@ -162,6 +162,11 @@ func ZeroInt() Int { return Int{big.NewInt(0)} } // OneInt returns Int value with one func OneInt() Int { return Int{big.NewInt(1)} } +// ToDec converts Int to Dec +func (i Int) ToDec() Dec { + return NewDecFromInt(i) +} + // Int64 converts Int to int64 // Panics if the value is out of range func (i Int) Int64() int64 { diff --git a/x/auth/account.go b/x/auth/account.go index bc5c75da640c..a17f1758bec5 100644 --- a/x/auth/account.go +++ b/x/auth/account.go @@ -407,7 +407,7 @@ func (cva ContinuousVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coin s := sdk.NewDec(x).Quo(sdk.NewDec(y)) for _, ovc := range cva.OriginalVesting { - vestedAmt := sdk.NewDecFromInt(ovc.Amount).Mul(s).RoundInt() + vestedAmt := ovc.Amount.ToDec().Mul(s).RoundInt() vestedCoins = append(vestedCoins, sdk.NewCoin(ovc.Denom, vestedAmt)) } diff --git a/x/distribution/keeper/delegation_test.go b/x/distribution/keeper/delegation_test.go index 5286a141f17b..c4a422f7522b 100644 --- a/x/distribution/keeper/delegation_test.go +++ b/x/distribution/keeper/delegation_test.go @@ -108,7 +108,7 @@ func TestCalculateRewardsAfterSlash(t *testing.T) { // allocate some rewards initial := sdk.TokensFromTendermintPower(10) - tokens := sdk.DecCoins{{sdk.DefaultBondDenom, sdk.NewDecFromInt(initial)}} + tokens := sdk.DecCoins{{sdk.DefaultBondDenom, initial.ToDec()}} 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{{sdk.DefaultBondDenom, sdk.NewDecFromInt(initial.DivRaw(2))}}, rewards) + require.Equal(t, sdk.DecCoins{{sdk.DefaultBondDenom, initial.DivRaw(2).ToDec()}}, rewards) // commission should be the other half - require.Equal(t, sdk.DecCoins{{sdk.DefaultBondDenom, sdk.NewDecFromInt(initial.DivRaw(2))}}, + require.Equal(t, sdk.DecCoins{{sdk.DefaultBondDenom, initial.DivRaw(2).ToDec()}}, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1)) } @@ -170,7 +170,7 @@ func TestCalculateRewardsAfterManySlashes(t *testing.T) { // allocate some rewards initial := sdk.TokensFromTendermintPower(10) - tokens := sdk.DecCoins{{sdk.DefaultBondDenom, sdk.NewDecFromInt(initial)}} + tokens := sdk.DecCoins{{sdk.DefaultBondDenom, initial.ToDec()}} 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{{sdk.DefaultBondDenom, sdk.NewDecFromInt(initial)}}, rewards) + require.Equal(t, sdk.DecCoins{{sdk.DefaultBondDenom, initial.ToDec()}}, rewards) // commission should be the other half - require.Equal(t, sdk.DecCoins{{sdk.DefaultBondDenom, sdk.NewDecFromInt(initial)}}, + require.Equal(t, sdk.DecCoins{{sdk.DefaultBondDenom, initial.ToDec()}}, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1)) } @@ -359,7 +359,7 @@ func TestCalculateRewardsAfterManySlashesInSameBlock(t *testing.T) { ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) // allocate some rewards - initial := sdk.NewDecFromInt(sdk.TokensFromTendermintPower(10)) + initial := sdk.TokensFromTendermintPower(10).ToDec() tokens := sdk.DecCoins{{sdk.DefaultBondDenom, initial}} k.AllocateTokensToValidator(ctx, val, tokens) @@ -414,7 +414,7 @@ func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { del1 := sk.Delegation(ctx, sdk.AccAddress(valOpAddr1), valOpAddr1) // allocate some rewards - initial := sdk.NewDecFromInt(sdk.TokensFromTendermintPower(30)) + initial := sdk.TokensFromTendermintPower(30).ToDec() tokens := sdk.DecCoins{{sdk.DefaultBondDenom, initial}} k.AllocateTokensToValidator(ctx, val, tokens) diff --git a/x/distribution/keeper/validator.go b/x/distribution/keeper/validator.go index 05326ff12262..fcb54651f69b 100644 --- a/x/distribution/keeper/validator.go +++ b/x/distribution/keeper/validator.go @@ -39,7 +39,7 @@ func (k Keeper) incrementValidatorPeriod(ctx sdk.Context, val sdk.Validator) uin current = sdk.DecCoins{} } else { // note: necessary to truncate so we don't allow withdrawing more rewards than owed - current = rewards.Rewards.QuoDecTruncate(sdk.NewDecFromInt(val.GetTokens())) + current = rewards.Rewards.QuoDecTruncate(val.GetTokens().ToDec()) } // fetch historical rewards for last period diff --git a/x/gov/tally.go b/x/gov/tally.go index 1bf28e493fbe..bdc5003fac01 100644 --- a/x/gov/tally.go +++ b/x/gov/tally.go @@ -107,7 +107,7 @@ func tally(ctx sdk.Context, keeper Keeper, proposal Proposal) (passes bool, tall return false, tallyResults } // If there is not enough quorum of votes, the proposal fails - percentVoting := totalVotingPower.Quo(sdk.NewDecFromInt(keeper.vs.TotalBondedTokens(ctx))) + percentVoting := totalVotingPower.Quo(keeper.vs.TotalBondedTokens(ctx).ToDec()) if percentVoting.LT(tallyParams.Quorum) { return false, tallyResults } diff --git a/x/slashing/handler_test.go b/x/slashing/handler_test.go index 569fb54ad76a..07cf45001aa0 100644 --- a/x/slashing/handler_test.go +++ b/x/slashing/handler_test.go @@ -92,7 +92,7 @@ func TestJailedValidatorDelegations(t *testing.T) { got = staking.NewHandler(stakingKeeper)(ctx, msgDelegate) require.True(t, got.IsOK(), "expected delegation to be ok, got %v", got) - unbondShares := sdk.NewDecFromInt(bondAmount) + unbondShares := bondAmount.ToDec() // unbond validator total self-delegations (which should jail the validator) msgUndelegate := staking.NewMsgUndelegate(sdk.AccAddress(valAddr), valAddr, unbondShares) diff --git a/x/slashing/keeper_test.go b/x/slashing/keeper_test.go index 266e443cab01..4dbc1e727d91 100644 --- a/x/slashing/keeper_test.go +++ b/x/slashing/keeper_test.go @@ -189,7 +189,7 @@ func TestHandleAbsentValidator(t *testing.T) { validator, _ = sk.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(val)) require.Equal(t, sdk.Unbonding, validator.GetStatus()) - slashAmt := sdk.NewDecFromInt(amt).Mul(keeper.SlashFractionDowntime(ctx)).RoundInt64() + slashAmt := amt.ToDec().Mul(keeper.SlashFractionDowntime(ctx)).RoundInt64() // validator should have been slashed require.Equal(t, amt.Int64()-slashAmt, validator.GetTokens().Int64()) diff --git a/x/staking/app_test.go b/x/staking/app_test.go index d9781201d23c..9ed74d3d6507 100644 --- a/x/staking/app_test.go +++ b/x/staking/app_test.go @@ -146,7 +146,7 @@ func TestStakingMsgs(t *testing.T) { require.True(sdk.IntEq(t, bondTokens, validator.Tokens)) // check the bond that should have been created as well - checkDelegation(t, mApp, keeper, addr1, sdk.ValAddress(addr1), true, sdk.NewDecFromInt(bondTokens)) + checkDelegation(t, mApp, keeper, addr1, sdk.ValAddress(addr1), true, bondTokens.ToDec()) // edit the validator description = NewDescription("bar_moniker", "", "", "") @@ -162,10 +162,10 @@ func TestStakingMsgs(t *testing.T) { mock.SignCheckDeliver(t, mApp.Cdc, mApp.BaseApp, []sdk.Msg{delegateMsg}, []uint64{0}, []uint64{1}, true, true, priv2) mock.CheckBalance(t, mApp, addr2, sdk.Coins{genCoin.Minus(bondCoin)}) - checkDelegation(t, mApp, keeper, addr2, sdk.ValAddress(addr1), true, sdk.NewDecFromInt(bondTokens)) + checkDelegation(t, mApp, keeper, addr2, sdk.ValAddress(addr1), true, bondTokens.ToDec()) // begin unbonding - beginUnbondingMsg := NewMsgUndelegate(addr2, sdk.ValAddress(addr1), sdk.NewDecFromInt(bondTokens)) + beginUnbondingMsg := NewMsgUndelegate(addr2, sdk.ValAddress(addr1), bondTokens.ToDec()) mock.SignCheckDeliver(t, mApp.Cdc, mApp.BaseApp, []sdk.Msg{beginUnbondingMsg}, []uint64{0}, []uint64{2}, true, true, priv2) // delegation should exist anymore diff --git a/x/staking/genesis_test.go b/x/staking/genesis_test.go index 82b076104a66..092abaa67641 100644 --- a/x/staking/genesis_test.go +++ b/x/staking/genesis_test.go @@ -33,13 +33,13 @@ func TestInitGenesis(t *testing.T) { validators[0].Description = NewDescription("hoop", "", "", "") validators[0].Status = sdk.Bonded validators[0].Tokens = valTokens - validators[0].DelegatorShares = sdk.NewDecFromInt(valTokens) + validators[0].DelegatorShares = valTokens.ToDec() validators[1].OperatorAddr = sdk.ValAddress(keep.Addrs[1]) validators[1].ConsPubKey = keep.PKs[1] validators[1].Description = NewDescription("bloop", "", "", "") validators[1].Status = sdk.Bonded validators[1].Tokens = valTokens - validators[1].DelegatorShares = sdk.NewDecFromInt(valTokens) + validators[1].DelegatorShares = valTokens.ToDec() genesisState := types.NewGenesisState(pool, params, validators, delegations) vals, err := InitGenesis(ctx, keeper, genesisState) @@ -94,7 +94,7 @@ func TestInitGenesisLargeValidatorSet(t *testing.T) { tokens = sdk.TokensFromTendermintPower(2) } validators[i].Tokens = tokens - validators[i].DelegatorShares = sdk.NewDecFromInt(tokens) + validators[i].DelegatorShares = tokens.ToDec() } genesisState := types.NewGenesisState(pool, params, validators, delegations) diff --git a/x/staking/handler_test.go b/x/staking/handler_test.go index 2daea30e62c8..523f0311d4e9 100644 --- a/x/staking/handler_test.go +++ b/x/staking/handler_test.go @@ -91,7 +91,7 @@ func TestValidatorByPowerIndex(t *testing.T) { require.Equal(t, power2, power3) // unbond self-delegation - msgUndelegate := NewMsgUndelegate(sdk.AccAddress(validatorAddr), validatorAddr, sdk.NewDecFromInt(initBond)) + msgUndelegate := NewMsgUndelegate(sdk.AccAddress(validatorAddr), validatorAddr, initBond.ToDec()) got = handleMsgUndelegate(ctx, msgUndelegate, keeper) require.True(t, got.IsOK(), "expected msg to be ok, got %v", got) var finishTime time.Time @@ -126,7 +126,7 @@ func TestDuplicatesMsgCreateValidator(t *testing.T) { assert.Equal(t, addr1, validator.OperatorAddr) assert.Equal(t, pk1, validator.ConsPubKey) assert.Equal(t, valTokens, validator.BondedTokens()) - assert.Equal(t, sdk.NewDecFromInt(valTokens), validator.DelegatorShares) + assert.Equal(t, valTokens.ToDec(), validator.DelegatorShares) assert.Equal(t, Description{}, validator.Description) // two validators can't have the same operator address @@ -155,7 +155,7 @@ func TestDuplicatesMsgCreateValidator(t *testing.T) { assert.Equal(t, addr2, validator.OperatorAddr) assert.Equal(t, pk2, validator.ConsPubKey) assert.True(sdk.IntEq(t, valTokens, validator.Tokens)) - assert.True(sdk.DecEq(t, sdk.NewDecFromInt(valTokens), validator.DelegatorShares)) + assert.True(sdk.DecEq(t, valTokens.ToDec(), validator.DelegatorShares)) assert.Equal(t, Description{}, validator.Description) } @@ -200,7 +200,7 @@ func TestDuplicatesMsgCreateValidatorOnBehalfOf(t *testing.T) { assert.Equal(t, validatorAddr, validator.OperatorAddr) assert.Equal(t, pk, validator.ConsPubKey) assert.True(sdk.IntEq(t, valTokens, validator.Tokens)) - assert.True(sdk.DecEq(t, sdk.NewDecFromInt(valTokens), validator.DelegatorShares)) + assert.True(sdk.DecEq(t, valTokens.ToDec(), validator.DelegatorShares)) assert.Equal(t, Description{}, validator.Description) // one validator cannot be created twice even from different delegator @@ -248,7 +248,7 @@ func TestLegacyValidatorDelegations(t *testing.T) { // unbond validator total self-delegations (which should jail the validator) unbondShares := sdk.TokensFromTendermintPower(10) - msgUndelegate := NewMsgUndelegate(sdk.AccAddress(valAddr), valAddr, sdk.NewDecFromInt(unbondShares)) + msgUndelegate := NewMsgUndelegate(sdk.AccAddress(valAddr), valAddr, unbondShares.ToDec()) got = handleMsgUndelegate(ctx, msgUndelegate, keeper) require.True(t, got.IsOK(), "expected begin unbonding validator msg to be ok, got %v", got) @@ -520,7 +520,7 @@ func TestIncrementsMsgUnbond(t *testing.T) { initBond, } for i, c := range errorCases { - unbondShares := sdk.NewDecFromInt(c) + unbondShares := c.ToDec() msgUndelegate := NewMsgUndelegate(delegatorAddr, validatorAddr, unbondShares) got = handleMsgUndelegate(ctx, msgUndelegate, keeper) require.False(t, got.IsOK(), "expected unbond msg to fail, index: %v", i) @@ -529,14 +529,14 @@ func TestIncrementsMsgUnbond(t *testing.T) { leftBonded := initBond.Sub(unbondShares.MulInt64(numUnbonds).RoundInt()) // should be unable to unbond one more than we have - unbondShares = sdk.NewDecFromInt(leftBonded.AddRaw(1)) + unbondShares = leftBonded.AddRaw(1).ToDec() msgUndelegate = NewMsgUndelegate(delegatorAddr, validatorAddr, unbondShares) got = handleMsgUndelegate(ctx, msgUndelegate, keeper) require.False(t, got.IsOK(), "got: %v\nmsgUnbond: %v\nshares: %v\nleftBonded: %v\n", got, msgUndelegate, unbondShares.String(), leftBonded) // should be able to unbond just what we have - unbondShares = sdk.NewDecFromInt(leftBonded) + unbondShares = leftBonded.ToDec() msgUndelegate = NewMsgUndelegate(delegatorAddr, validatorAddr, unbondShares) got = handleMsgUndelegate(ctx, msgUndelegate, keeper) require.True(t, got.IsOK(), @@ -584,7 +584,7 @@ func TestMultipleMsgCreateValidator(t *testing.T) { _, found := keeper.GetValidator(ctx, validatorAddr) require.True(t, found) unbondingTokens := sdk.TokensFromTendermintPower(10) - msgUndelegate := NewMsgUndelegate(delegatorAddrs[i], validatorAddr, sdk.NewDecFromInt(unbondingTokens)) // remove delegation + msgUndelegate := NewMsgUndelegate(delegatorAddrs[i], validatorAddr, unbondingTokens.ToDec()) // remove delegation got := handleMsgUndelegate(ctx, msgUndelegate, keeper) require.True(t, got.IsOK(), "expected msg %d to be ok, got %v", i, got) var finishTime time.Time @@ -710,7 +710,7 @@ func TestValidatorQueue(t *testing.T) { // unbond the all self-delegation to put validator in unbonding state msgUndelegateValidator := NewMsgUndelegate(sdk.AccAddress(validatorAddr), - validatorAddr, sdk.NewDecFromInt(delTokens)) + validatorAddr, delTokens.ToDec()) got = handleMsgUndelegate(ctx, msgUndelegateValidator, keeper) require.True(t, got.IsOK(), "expected no error: %v", got) var finishTime time.Time @@ -758,7 +758,7 @@ func TestUnbondingPeriod(t *testing.T) { // begin unbonding unbondingTokens := sdk.TokensFromTendermintPower(10) msgUndelegate := NewMsgUndelegate(sdk.AccAddress(validatorAddr), - validatorAddr, sdk.NewDecFromInt(unbondingTokens)) + validatorAddr, unbondingTokens.ToDec()) got = handleMsgUndelegate(ctx, msgUndelegate, keeper) require.True(t, got.IsOK(), "expected no error") origHeader := ctx.BlockHeader() @@ -951,7 +951,7 @@ func TestMultipleRedelegationAtSameTime(t *testing.T) { // begin a redelegate selfDelAddr := sdk.AccAddress(valAddr) // (the validator is it's own delegator) msgBeginRedelegate := NewMsgBeginRedelegate(selfDelAddr, - valAddr, valAddr2, sdk.NewDecFromInt(valTokens.DivRaw(2))) + valAddr, valAddr2, valTokens.DivRaw(2).ToDec()) got = handleMsgBeginRedelegate(ctx, msgBeginRedelegate, keeper) require.True(t, got.IsOK(), "expected no error, %v", got) @@ -1003,7 +1003,7 @@ func TestMultipleRedelegationAtUniqueTimes(t *testing.T) { // begin a redelegate selfDelAddr := sdk.AccAddress(valAddr) // (the validator is it's own delegator) msgBeginRedelegate := NewMsgBeginRedelegate(selfDelAddr, - valAddr, valAddr2, sdk.NewDecFromInt(valTokens.DivRaw(2))) + valAddr, valAddr2, valTokens.DivRaw(2).ToDec()) got = handleMsgBeginRedelegate(ctx, msgBeginRedelegate, keeper) require.True(t, got.IsOK(), "expected no error, %v", got) @@ -1051,7 +1051,7 @@ func TestMultipleUnbondingDelegationAtSameTime(t *testing.T) { // begin an unbonding delegation selfDelAddr := sdk.AccAddress(valAddr) // (the validator is it's own delegator) - msgUndelegate := NewMsgUndelegate(selfDelAddr, valAddr, sdk.NewDecFromInt(valTokens.DivRaw(2))) + msgUndelegate := NewMsgUndelegate(selfDelAddr, valAddr, valTokens.DivRaw(2).ToDec()) got = handleMsgUndelegate(ctx, msgUndelegate, keeper) require.True(t, got.IsOK(), "expected no error, %v", got) @@ -1097,7 +1097,7 @@ func TestMultipleUnbondingDelegationAtUniqueTimes(t *testing.T) { // begin an unbonding delegation selfDelAddr := sdk.AccAddress(valAddr) // (the validator is it's own delegator) - msgUndelegate := NewMsgUndelegate(selfDelAddr, valAddr, sdk.NewDecFromInt(valTokens.DivRaw(2))) + msgUndelegate := NewMsgUndelegate(selfDelAddr, valAddr, valTokens.DivRaw(2).ToDec()) got = handleMsgUndelegate(ctx, msgUndelegate, keeper) require.True(t, got.IsOK(), "expected no error, %v", got) @@ -1168,7 +1168,7 @@ func TestUnbondingWhenExcessValidators(t *testing.T) { require.Equal(t, 2, len(keeper.GetLastValidators(ctx))) // unbond the valdator-2 - msgUndelegate := NewMsgUndelegate(sdk.AccAddress(validatorAddr2), validatorAddr2, sdk.NewDecFromInt(valTokens2)) + msgUndelegate := NewMsgUndelegate(sdk.AccAddress(validatorAddr2), validatorAddr2, valTokens2.ToDec()) got = handleMsgUndelegate(ctx, msgUndelegate, keeper) require.True(t, got.IsOK(), "expected no error on runMsgUndelegate") @@ -1213,20 +1213,20 @@ func TestBondUnbondRedelegateSlashTwice(t *testing.T) { // begin unbonding 4 stake ubdTokens := sdk.TokensFromTendermintPower(4) - msgUndelegate := NewMsgUndelegate(del, valA, sdk.NewDecFromInt(ubdTokens)) + msgUndelegate := NewMsgUndelegate(del, valA, ubdTokens.ToDec()) got = handleMsgUndelegate(ctx, msgUndelegate, keeper) require.True(t, got.IsOK(), "expected no error on runMsgUndelegate") // begin redelegate 6 stake rdTokens := sdk.TokensFromTendermintPower(6) - msgBeginRedelegate := NewMsgBeginRedelegate(del, valA, valB, sdk.NewDecFromInt(rdTokens)) + msgBeginRedelegate := NewMsgBeginRedelegate(del, valA, valB, rdTokens.ToDec()) got = handleMsgBeginRedelegate(ctx, msgBeginRedelegate, keeper) require.True(t, got.IsOK(), "expected no error on runMsgBeginRedelegate") // destination delegation should have 6 shares delegation, found := keeper.GetDelegation(ctx, del, valB) require.True(t, found) - require.Equal(t, sdk.NewDecFromInt(rdTokens), delegation.Shares) + require.Equal(t, rdTokens.ToDec(), delegation.Shares) // must apply validator updates updates = keeper.ApplyAndReturnValidatorSetUpdates(ctx) @@ -1249,7 +1249,7 @@ func TestBondUnbondRedelegateSlashTwice(t *testing.T) { // destination delegation should have been slashed by half delegation, found = keeper.GetDelegation(ctx, del, valB) require.True(t, found) - require.Equal(t, sdk.NewDecFromInt(rdTokens.DivRaw(2)), delegation.Shares) + require.Equal(t, rdTokens.DivRaw(2).ToDec(), delegation.Shares) // validator power should have been reduced by half validator, found := keeper.GetValidator(ctx, valA) @@ -1274,7 +1274,7 @@ func TestBondUnbondRedelegateSlashTwice(t *testing.T) { // destination delegation should be unchanged delegation, found = keeper.GetDelegation(ctx, del, valB) require.True(t, found) - require.Equal(t, sdk.NewDecFromInt(rdTokens.DivRaw(2)), delegation.Shares) + require.Equal(t, rdTokens.DivRaw(2).ToDec(), delegation.Shares) // end blocker EndBlocker(ctx, keeper) diff --git a/x/staking/keeper/delegation_test.go b/x/staking/keeper/delegation_test.go index 45c6320c50d1..1c1d8dcb143c 100644 --- a/x/staking/keeper/delegation_test.go +++ b/x/staking/keeper/delegation_test.go @@ -189,7 +189,7 @@ func TestUnbondDelegation(t *testing.T) { keeper.SetDelegation(ctx, delegation) bondTokens := sdk.TokensFromTendermintPower(6) - amount, err := keeper.unbond(ctx, addrDels[0], addrVals[0], sdk.NewDecFromInt(bondTokens)) + amount, err := keeper.unbond(ctx, addrDels[0], addrVals[0], bondTokens.ToDec()) require.NoError(t, err) require.Equal(t, bondTokens, amount) // shares to be added to an unbonding delegation @@ -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(sdk.TokensFromTendermintPower(6))) + _, err := keeper.Undelegate(ctx, val0AccAddr, addrVals[0], sdk.TokensFromTendermintPower(6).ToDec()) require.NoError(t, err) // end block @@ -337,7 +337,7 @@ func TestUndelegateFromUnbondingValidator(t *testing.T) { // unbond the all self-delegation to put validator in unbonding state val0AccAddr := sdk.AccAddress(addrVals[0].Bytes()) - _, err := keeper.Undelegate(ctx, val0AccAddr, addrVals[0], sdk.NewDecFromInt(valTokens)) + _, err := keeper.Undelegate(ctx, val0AccAddr, addrVals[0], valTokens.ToDec()) require.NoError(t, err) // end block @@ -405,7 +405,7 @@ func TestUndelegateFromUnbondedValidator(t *testing.T) { ctx = ctx.WithBlockTime(time.Unix(333, 0)) // unbond the all self-delegation to put validator in unbonding state - _, err := keeper.Undelegate(ctx, val0AccAddr, addrVals[0], sdk.NewDecFromInt(valTokens)) + _, err := keeper.Undelegate(ctx, val0AccAddr, addrVals[0], valTokens.ToDec()) require.NoError(t, err) // end block @@ -429,7 +429,7 @@ func TestUndelegateFromUnbondedValidator(t *testing.T) { // unbond some of the other delegation's shares unbondTokens := sdk.TokensFromTendermintPower(6) - _, err = keeper.Undelegate(ctx, addrDels[0], addrVals[0], sdk.NewDecFromInt(unbondTokens)) + _, err = keeper.Undelegate(ctx, addrDels[0], addrVals[0], unbondTokens.ToDec()) require.NoError(t, err) // no ubd should have been found, coins should have been returned direcly to account @@ -438,7 +438,7 @@ func TestUndelegateFromUnbondedValidator(t *testing.T) { // unbond rest of the other delegation's shares remainingTokens := delTokens.Sub(unbondTokens) - _, err = keeper.Undelegate(ctx, addrDels[0], addrVals[0], sdk.NewDecFromInt(remainingTokens)) + _, err = keeper.Undelegate(ctx, addrDels[0], addrVals[0], remainingTokens.ToDec()) require.NoError(t, err) // now validator should now be deleted from state @@ -480,7 +480,7 @@ func TestUnbondingAllDelegationFromValidator(t *testing.T) { ctx = ctx.WithBlockTime(time.Unix(333, 0)) // unbond the all self-delegation to put validator in unbonding state - _, err := keeper.Undelegate(ctx, val0AccAddr, addrVals[0], sdk.NewDecFromInt(valTokens)) + _, err := keeper.Undelegate(ctx, val0AccAddr, addrVals[0], valTokens.ToDec()) require.NoError(t, err) // end block @@ -488,7 +488,7 @@ func TestUnbondingAllDelegationFromValidator(t *testing.T) { require.Equal(t, 1, len(updates)) // unbond all the remaining delegation - _, err = keeper.Undelegate(ctx, addrDels[0], addrVals[0], sdk.NewDecFromInt(delTokens)) + _, err = keeper.Undelegate(ctx, addrDels[0], addrVals[0], delTokens.ToDec()) require.NoError(t, err) // validator should still be in state and still be in unbonding state @@ -702,7 +702,7 @@ func TestRedelegateSelfDelegation(t *testing.T) { delegation := types.NewDelegation(addrDels[0], addrVals[0], issuedShares) keeper.SetDelegation(ctx, delegation) - _, err := keeper.BeginRedelegation(ctx, val0AccAddr, addrVals[0], addrVals[1], sdk.NewDecFromInt(delTokens)) + _, err := keeper.BeginRedelegation(ctx, val0AccAddr, addrVals[0], addrVals[1], delTokens.ToDec()) require.NoError(t, err) // end block @@ -760,7 +760,7 @@ func TestRedelegateFromUnbondingValidator(t *testing.T) { ctx = ctx.WithBlockHeader(header) // unbond the all self-delegation to put validator in unbonding state - _, err := keeper.Undelegate(ctx, val0AccAddr, addrVals[0], sdk.NewDecFromInt(delTokens)) + _, err := keeper.Undelegate(ctx, val0AccAddr, addrVals[0], delTokens.ToDec()) require.NoError(t, err) // end block @@ -783,7 +783,7 @@ func TestRedelegateFromUnbondingValidator(t *testing.T) { // unbond some of the other delegation's shares redelegateTokens := sdk.TokensFromTendermintPower(6) - _, err = keeper.BeginRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1], sdk.NewDecFromInt(redelegateTokens)) + _, err = keeper.BeginRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1], redelegateTokens.ToDec()) require.NoError(t, err) // retrieve the unbonding delegation @@ -836,7 +836,7 @@ func TestRedelegateFromUnbondedValidator(t *testing.T) { ctx = ctx.WithBlockTime(time.Unix(333, 0)) // unbond the all self-delegation to put validator in unbonding state - _, err := keeper.Undelegate(ctx, val0AccAddr, addrVals[0], sdk.NewDecFromInt(delTokens)) + _, err := keeper.Undelegate(ctx, val0AccAddr, addrVals[0], delTokens.ToDec()) require.NoError(t, err) // end block @@ -854,7 +854,7 @@ func TestRedelegateFromUnbondedValidator(t *testing.T) { // redelegate some of the delegation's shares redelegationTokens := sdk.TokensFromTendermintPower(6) - _, err = keeper.BeginRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1], sdk.NewDecFromInt(redelegationTokens)) + _, err = keeper.BeginRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1], redelegationTokens.ToDec()) require.NoError(t, err) // no red should have been found diff --git a/x/staking/keeper/slash.go b/x/staking/keeper/slash.go index 9793883f0c10..5b10ed68152b 100644 --- a/x/staking/keeper/slash.go +++ b/x/staking/keeper/slash.go @@ -30,7 +30,7 @@ func (k Keeper) Slash(ctx sdk.Context, consAddr sdk.ConsAddress, infractionHeigh // Amount of slashing = slash slashFactor * power at time of infraction amount := sdk.TokensFromTendermintPower(power) - slashAmountDec := sdk.NewDecFromInt(amount).Mul(slashFactor) + slashAmountDec := amount.ToDec().Mul(slashFactor) slashAmount := slashAmountDec.TruncateInt() // ref https://github.com/cosmos/cosmos-sdk/issues/1348 @@ -59,7 +59,7 @@ func (k Keeper) Slash(ctx sdk.Context, consAddr sdk.ConsAddress, infractionHeigh // we need to calculate the *effective* slash fraction for distribution if validator.Tokens.GT(sdk.ZeroInt()) { - effectiveFraction := slashAmountDec.Quo(sdk.NewDecFromInt(validator.Tokens)) + effectiveFraction := slashAmountDec.Quo(validator.Tokens.ToDec()) // possible if power has changed if effectiveFraction.GT(sdk.OneDec()) { effectiveFraction = sdk.OneDec() diff --git a/x/staking/keeper/slash_test.go b/x/staking/keeper/slash_test.go index b2cec2ce823b..51b67c505cec 100644 --- a/x/staking/keeper/slash_test.go +++ b/x/staking/keeper/slash_test.go @@ -344,11 +344,11 @@ func TestSlashWithRedelegation(t *testing.T) { // set a redelegation rdTokens := sdk.TokensFromTendermintPower(6) rd := types.NewRedelegation(addrDels[0], addrVals[0], addrVals[1], 11, - time.Unix(0, 0), rdTokens, sdk.NewDecFromInt(rdTokens)) + time.Unix(0, 0), rdTokens, rdTokens.ToDec()) keeper.SetRedelegation(ctx, rd) // set the associated delegation - del := types.NewDelegation(addrDels[0], addrVals[1], sdk.NewDecFromInt(rdTokens)) + del := types.NewDelegation(addrDels[0], addrVals[1], rdTokens.ToDec()) keeper.SetDelegation(ctx, del) // update bonded tokens @@ -453,11 +453,11 @@ func TestSlashBoth(t *testing.T) { rdATokens := sdk.TokensFromTendermintPower(6) rdA := types.NewRedelegation(addrDels[0], addrVals[0], addrVals[1], 11, time.Unix(0, 0), rdATokens, - sdk.NewDecFromInt(rdATokens)) + rdATokens.ToDec()) keeper.SetRedelegation(ctx, rdA) // set the associated delegation - delA := types.NewDelegation(addrDels[0], addrVals[1], sdk.NewDecFromInt(rdATokens)) + delA := types.NewDelegation(addrDels[0], addrVals[1], rdATokens.ToDec()) keeper.SetDelegation(ctx, delA) // set an unbonding delegation with expiration timestamp (beyond which the diff --git a/x/staking/keeper/validator_test.go b/x/staking/keeper/validator_test.go index 1528b16811cd..4b07816725c4 100644 --- a/x/staking/keeper/validator_test.go +++ b/x/staking/keeper/validator_test.go @@ -146,7 +146,7 @@ func TestUpdateBondedValidatorsDecreaseCliff(t *testing.T) { // validator and next in line cliff validator keeper.DeleteValidatorByPowerIndex(ctx, nextCliffVal) shares := sdk.TokensFromTendermintPower(21) - nextCliffVal, pool, _ = nextCliffVal.RemoveDelShares(pool, sdk.NewDecFromInt(shares)) + nextCliffVal, pool, _ = nextCliffVal.RemoveDelShares(pool, shares.ToDec()) keeper.SetPool(ctx, pool) nextCliffVal = TestingUpdateValidator(keeper, ctx, nextCliffVal, true) @@ -253,7 +253,7 @@ func TestValidatorBasics(t *testing.T) { // modify a records, save, and retrieve validators[0].Status = sdk.Bonded validators[0].Tokens = sdk.TokensFromTendermintPower(10) - validators[0].DelegatorShares = sdk.NewDecFromInt(validators[0].Tokens) + validators[0].DelegatorShares = validators[0].Tokens.ToDec() validators[0] = TestingUpdateValidator(keeper, ctx, validators[0], true) resVal, found = keeper.GetValidator(ctx, addrVals[0]) require.True(t, found) @@ -857,8 +857,8 @@ func TestApplyAndReturnValidatorSetUpdatesPowerDecrease(t *testing.T) { pool := keeper.GetPool(ctx) 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)) + validators[0], pool, _ = validators[0].RemoveDelShares(pool, delTokens1.ToDec()) + validators[1], pool, _ = validators[1].RemoveDelShares(pool, delTokens2.ToDec()) keeper.SetPool(ctx, pool) validators[0] = TestingUpdateValidator(keeper, ctx, validators[0], false) validators[1] = TestingUpdateValidator(keeper, ctx, validators[1], false) @@ -934,7 +934,7 @@ func TestApplyAndReturnValidatorSetUpdatesNewValidator(t *testing.T) { keeper.SetPool(ctx, pool) keeper.SetValidator(ctx, validator) - validator, pool, _ = validator.RemoveDelShares(pool, sdk.NewDecFromInt(amt)) + validator, pool, _ = validator.RemoveDelShares(pool, amt.ToDec()) keeper.SetValidator(ctx, validator) keeper.SetValidatorByPowerIndex(ctx, validator) diff --git a/x/staking/querier/querier_test.go b/x/staking/querier/querier_test.go index a2817335c0ac..7775bfdb4acf 100644 --- a/x/staking/querier/querier_test.go +++ b/x/staking/querier/querier_test.go @@ -298,7 +298,7 @@ func TestQueryDelegation(t *testing.T) { // Query unbonging delegation unbondingTokens := sdk.TokensFromTendermintPower(10) - _, err = keeper.Undelegate(ctx, addrAcc2, val1.OperatorAddr, sdk.NewDecFromInt(unbondingTokens)) + _, err = keeper.Undelegate(ctx, addrAcc2, val1.OperatorAddr, unbondingTokens.ToDec()) require.Nil(t, err) queryBondParams = NewQueryBondsParams(addrAcc2, addrVal1) @@ -352,7 +352,7 @@ func TestQueryDelegation(t *testing.T) { // Query redelegation redelegationTokens := sdk.TokensFromTendermintPower(10) _, err = keeper.BeginRedelegation(ctx, addrAcc2, val1.OperatorAddr, - val2.OperatorAddr, sdk.NewDecFromInt(redelegationTokens)) + val2.OperatorAddr, redelegationTokens.ToDec()) require.Nil(t, err) redel, found := keeper.GetRedelegation(ctx, addrAcc2, val1.OperatorAddr, val2.OperatorAddr) require.True(t, found) @@ -390,7 +390,7 @@ func TestQueryRedelegations(t *testing.T) { _ = keeper.ApplyAndReturnValidatorSetUpdates(ctx) rdAmount := sdk.TokensFromTendermintPower(20) - keeper.BeginRedelegation(ctx, addrAcc2, val1.GetOperator(), val2.GetOperator(), sdk.NewDecFromInt(rdAmount)) + keeper.BeginRedelegation(ctx, addrAcc2, val1.GetOperator(), val2.GetOperator(), rdAmount.ToDec()) keeper.ApplyAndReturnValidatorSetUpdates(ctx) redelegation, found := keeper.GetRedelegation(ctx, addrAcc2, val1.OperatorAddr, val2.OperatorAddr) diff --git a/x/staking/simulation/invariants.go b/x/staking/simulation/invariants.go index 1368a61dca20..d0d11e8124f2 100644 --- a/x/staking/simulation/invariants.go +++ b/x/staking/simulation/invariants.go @@ -51,27 +51,27 @@ func SupplyInvariants(k staking.Keeper, loose := sdk.ZeroDec() bonded := sdk.ZeroDec() am.IterateAccounts(ctx, func(acc auth.Account) bool { - loose = loose.Add(sdk.NewDecFromInt(acc.GetCoins().AmountOf(k.BondDenom(ctx)))) + loose = loose.Add(acc.GetCoins().AmountOf(k.BondDenom(ctx)).ToDec()) return false }) k.IterateUnbondingDelegations(ctx, func(_ int64, ubd staking.UnbondingDelegation) bool { for _, entry := range ubd.Entries { - loose = loose.Add(sdk.NewDecFromInt(entry.Balance)) + loose = loose.Add(entry.Balance.ToDec()) } return false }) k.IterateValidators(ctx, func(_ int64, validator sdk.Validator) bool { switch validator.GetStatus() { case sdk.Bonded: - bonded = bonded.Add(sdk.NewDecFromInt(validator.GetBondedTokens())) + bonded = bonded.Add(validator.GetBondedTokens().ToDec()) case sdk.Unbonding, sdk.Unbonded: - loose = loose.Add(sdk.NewDecFromInt(validator.GetTokens())) + loose = loose.Add(validator.GetTokens().ToDec()) } return false }) // add outstanding fees - loose = loose.Add(sdk.NewDecFromInt(f.GetCollectedFees(ctx).AmountOf(k.BondDenom(ctx)))) + loose = loose.Add(f.GetCollectedFees(ctx).AmountOf(k.BondDenom(ctx)).ToDec()) // add community pool loose = loose.Add(d.GetFeePoolCommunityCoins(ctx).AmountOf(k.BondDenom(ctx))) @@ -81,14 +81,14 @@ func SupplyInvariants(k staking.Keeper, // Not-bonded tokens should equal coin supply plus unbonding delegations // plus tokens on unbonded validators - if !sdk.NewDecFromInt(pool.NotBondedTokens).Equal(loose) { + if !pool.NotBondedTokens.ToDec().Equal(loose) { return fmt.Errorf("loose token invariance:\n"+ "\tpool.NotBondedTokens: %v\n"+ "\tsum of account tokens: %v", pool.NotBondedTokens, loose) } // Bonded tokens should equal sum of tokens with bonded validators - if !sdk.NewDecFromInt(pool.BondedTokens).Equal(bonded) { + if !pool.BondedTokens.ToDec().Equal(bonded) { return fmt.Errorf("bonded token invariance:\n"+ "\tpool.BondedTokens: %v\n"+ "\tsum of account tokens: %v", pool.BondedTokens, bonded) diff --git a/x/staking/simulation/msgs.go b/x/staking/simulation/msgs.go index 69be7d330145..d1735482d631 100644 --- a/x/staking/simulation/msgs.go +++ b/x/staking/simulation/msgs.go @@ -204,7 +204,7 @@ func SimulateMsgBeginRedelegate(m auth.AccountKeeper, k staking.Keeper) simulati DelegatorAddr: delegatorAddress, ValidatorSrcAddr: srcValidatorAddress, ValidatorDstAddr: destValidatorAddress, - SharesAmount: sdk.NewDecFromInt(amount), + SharesAmount: amount.ToDec(), } if msg.ValidateBasic() != nil { return "", nil, fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) diff --git a/x/staking/types/pool.go b/x/staking/types/pool.go index 6f108e8b36be..d3905085a6c7 100644 --- a/x/staking/types/pool.go +++ b/x/staking/types/pool.go @@ -39,8 +39,7 @@ func (p Pool) TokenSupply() sdk.Int { func (p Pool) BondedRatio() sdk.Dec { supply := p.TokenSupply() if supply.IsPositive() { - return sdk.NewDecFromInt(p.BondedTokens). - QuoInt(supply) + return p.BondedTokens.ToDec().QuoInt(supply) } return sdk.ZeroDec() } diff --git a/x/staking/types/validator.go b/x/staking/types/validator.go index 08c095cd49a9..bb5a7921ebc2 100644 --- a/x/staking/types/validator.go +++ b/x/staking/types/validator.go @@ -359,7 +359,7 @@ func (v Validator) AddTokensFromDel(pool Pool, amount sdk.Int) (Validator, Pool, } v.Tokens = v.Tokens.Add(amount) - issuedShares := sdk.NewDecFromInt(amount).Quo(exRate) + issuedShares := amount.ToDec().Quo(exRate) v.DelegatorShares = v.DelegatorShares.Add(issuedShares) return v, pool, issuedShares @@ -404,7 +404,7 @@ func (v Validator) DelegatorShareExRate() sdk.Dec { // the first delegation to a validator sets the exchange rate to one return sdk.OneDec() } - return sdk.NewDecFromInt(v.Tokens).Quo(v.DelegatorShares) + return v.Tokens.ToDec().Quo(v.DelegatorShares) } // get the bonded tokens which the validator holds