From 292597a55200b364a164b6dd1ec7a5f69d960160 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Thu, 29 Nov 2018 23:29:41 -0500 Subject: [PATCH 01/18] Validator Power Dec-> Int, working --- types/int.go | 20 ++++++++++++++++ types/stake.go | 6 ++--- x/stake/types/pool.go | 23 ++++++++++--------- x/stake/types/validator.go | 47 +++++++++++++++++++++----------------- 4 files changed, 61 insertions(+), 35 deletions(-) diff --git a/types/int.go b/types/int.go index 417a1763d431..f08a7bce981e 100644 --- a/types/int.go +++ b/types/int.go @@ -153,6 +153,16 @@ func (i Int) IsZero() bool { return i.i.Sign() == 0 } +// IsNegative returns true if Int is negative +func (i Int) IsNegative() bool { + return i.i.Sign() == 0 +} + +// IsPositive returns true if Int is positive +func (i Int) IsPositive() bool { + return i.i.Sign() == 0 +} + // Sign returns sign of Int func (i Int) Sign() int { return i.i.Sign() @@ -386,6 +396,16 @@ func (i Uint) IsZero() bool { return i.i.Sign() == 0 } +// IsNegative returns true if Uint is negative +func (i Uint) IsNegative() bool { + return i.i.Sign() == -1 +} + +// IsPositive returns true if Uint is positive +func (i Uint) IsPositive() bool { + return i.i.Sign() == 1 +} + // Sign returns sign of Uint func (i Uint) Sign() int { return i.i.Sign() diff --git a/types/stake.go b/types/stake.go index 38f1c0c9baab..d88a20c5afeb 100644 --- a/types/stake.go +++ b/types/stake.go @@ -42,8 +42,8 @@ type Validator interface { GetOperator() ValAddress // operator address to receive/return validators coins GetConsPubKey() crypto.PubKey // validation consensus pubkey GetConsAddr() ConsAddress // validation consensus address - GetPower() Dec // validation power - GetTokens() Dec // validation tokens + GetPower() Int // validation power + GetTokens() Int // validation tokens GetCommission() Dec // validator commission rate GetDelegatorShares() Dec // Total out standing delegator shares GetBondHeight() int64 // height in which the validator became active @@ -53,7 +53,7 @@ type Validator interface { func ABCIValidator(v Validator) abci.Validator { return abci.Validator{ Address: v.GetConsPubKey().Address(), - Power: v.GetPower().RoundInt64(), + Power: v.GetPower().Int64(), } } diff --git a/x/stake/types/pool.go b/x/stake/types/pool.go index 4b227aa8051e..b6b86cfa9489 100644 --- a/x/stake/types/pool.go +++ b/x/stake/types/pool.go @@ -10,8 +10,8 @@ import ( // Pool - dynamic parameters of the current state type Pool struct { - LooseTokens sdk.Dec `json:"loose_tokens"` // tokens which are not bonded in a validator - BondedTokens sdk.Dec `json:"bonded_tokens"` // reserve of bonded tokens + LooseTokens sdk.Int `json:"loose_tokens"` // tokens which are not bonded in a validator + BondedTokens sdk.Int `json:"bonded_tokens"` // reserve of bonded tokens } // nolint @@ -24,15 +24,15 @@ func (p Pool) Equal(p2 Pool) bool { // initial pool for testing func InitialPool() Pool { return Pool{ - LooseTokens: sdk.ZeroDec(), - BondedTokens: sdk.ZeroDec(), + LooseTokens: sdk.ZeroInt(), + BondedTokens: sdk.ZeroInt(), } } //____________________________________________________________________ // Sum total of all staking tokens in the pool -func (p Pool) TokenSupply() sdk.Dec { +func (p Pool) TokenSupply() sdk.Int { return p.LooseTokens.Add(p.BondedTokens) } @@ -41,27 +41,28 @@ func (p Pool) TokenSupply() sdk.Dec { // get the bond ratio of the global state func (p Pool) BondedRatio() sdk.Dec { supply := p.TokenSupply() - if supply.GT(sdk.ZeroDec()) { - return p.BondedTokens.Quo(supply) + if supply.IsPositive() { + return sdk.NewDecFromInt(p.BondedTokens). + QuoInt(supply) } return sdk.ZeroDec() } //_______________________________________________________________________ -func (p Pool) looseTokensToBonded(bondedTokens sdk.Dec) Pool { +func (p Pool) looseTokensToBonded(bondedTokens sdk.Int) Pool { p.BondedTokens = p.BondedTokens.Add(bondedTokens) p.LooseTokens = p.LooseTokens.Sub(bondedTokens) - if p.LooseTokens.LT(sdk.ZeroDec()) { + if p.LooseTokens.IsNegative() { panic(fmt.Sprintf("sanity check: loose tokens negative, pool: %v", p)) } return p } -func (p Pool) bondedTokensToLoose(bondedTokens sdk.Dec) Pool { +func (p Pool) bondedTokensToLoose(bondedTokens sdk.Int) Pool { p.BondedTokens = p.BondedTokens.Sub(bondedTokens) p.LooseTokens = p.LooseTokens.Add(bondedTokens) - if p.BondedTokens.LT(sdk.ZeroDec()) { + if p.BondedTokens.IsNegative() { panic(fmt.Sprintf("sanity check: bonded tokens negative, pool: %v", p)) } return p diff --git a/x/stake/types/validator.go b/x/stake/types/validator.go index ca56e0ea4aae..ee2b74eede64 100644 --- a/x/stake/types/validator.go +++ b/x/stake/types/validator.go @@ -26,7 +26,7 @@ type Validator struct { Jailed bool `json:"jailed"` // has the validator been jailed from bonded status? Status sdk.BondStatus `json:"status"` // validator status (bonded/unbonding/unbonded) - Tokens sdk.Dec `json:"tokens"` // delegated tokens (incl. self-delegation) + Tokens sdk.Int `json:"tokens"` // delegated tokens (incl. self-delegation) DelegatorShares sdk.Dec `json:"delegator_shares"` // total shares issued to a validator's delegators Description Description `json:"description"` // description terms for the validator @@ -46,7 +46,7 @@ func NewValidator(operator sdk.ValAddress, pubKey crypto.PubKey, description Des ConsPubKey: pubKey, Jailed: false, Status: sdk.Unbonded, - Tokens: sdk.ZeroDec(), + Tokens: sdk.ZeroInt(), DelegatorShares: sdk.ZeroDec(), Description: description, BondHeight: int64(0), @@ -62,7 +62,7 @@ type validatorValue struct { ConsPubKey crypto.PubKey Jailed bool Status sdk.BondStatus - Tokens sdk.Dec + Tokens sdk.Int DelegatorShares sdk.Dec Description Description BondHeight int64 @@ -142,7 +142,7 @@ func (v Validator) HumanReadableString() (string, error) { resp += fmt.Sprintf("Jailed: %v\n", v.Jailed) resp += fmt.Sprintf("Status: %s\n", sdk.BondStatusToString(v.Status)) resp += fmt.Sprintf("Tokens: %s\n", v.Tokens) - resp += fmt.Sprintf("Delegator Shares: %s\n", v.DelegatorShares) + resp += fmt.Sprintf("Delegator Shares: %s\n", v.DelegatorShares.String()) resp += fmt.Sprintf("Description: %s\n", v.Description) resp += fmt.Sprintf("Bond Height: %d\n", v.BondHeight) resp += fmt.Sprintf("Unbonding Height: %d\n", v.UnbondingHeight) @@ -161,7 +161,7 @@ type bechValidator struct { Jailed bool `json:"jailed"` // has the validator been jailed from bonded status? Status sdk.BondStatus `json:"status"` // validator status (bonded/unbonding/unbonded) - Tokens sdk.Dec `json:"tokens"` // delegated tokens (incl. self-delegation) + Tokens sdk.Int `json:"tokens"` // delegated tokens (incl. self-delegation) DelegatorShares sdk.Dec `json:"delegator_shares"` // total shares issued to a validator's delegators Description Description `json:"description"` // description terms for the validator @@ -310,7 +310,7 @@ func (d Description) EnsureLength() (Description, sdk.Error) { func (v Validator) ABCIValidatorUpdate() abci.ValidatorUpdate { return abci.ValidatorUpdate{ PubKey: tmtypes.TM2PB.PubKey(v.ConsPubKey), - Power: v.BondedTokens().RoundInt64(), + Power: v.BondedTokens().Int64(), } } @@ -359,7 +359,7 @@ func (v Validator) UpdateStatus(pool Pool, NewStatus sdk.BondStatus) (Validator, } // removes tokens from a validator -func (v Validator) RemoveTokens(pool Pool, tokens sdk.Dec) (Validator, Pool) { +func (v Validator) RemoveTokens(pool Pool, tokens sdk.Int) (Validator, Pool) { if v.Status == sdk.Bonded { pool = pool.bondedTokensToLoose(tokens) } @@ -386,25 +386,30 @@ func (v Validator) AddTokensFromDel(pool Pool, amount sdk.Int) (Validator, Pool, // bondedShare/delegatedShare exRate := v.DelegatorShareExRate() - amountDec := sdk.NewDecFromInt(amount) + if exRate.IsZero() { + panic("zero exRate should not happen") + } if v.Status == sdk.Bonded { - pool = pool.looseTokensToBonded(amountDec) + pool = pool.looseTokensToBonded(amount) } - if exRate.IsZero() { - panic("zero exRate should not happen") - } - v.Tokens = v.Tokens.Add(amountDec) - issuedShares := amountDec.Quo(exRate) + v.Tokens = v.Tokens.Add(amount) + issuedShares := sdk.NewDecFromInt(amount).Quo(exRate) v.DelegatorShares = v.DelegatorShares.Add(issuedShares) return v, pool, issuedShares } // RemoveDelShares removes delegator shares from a validator. -func (v Validator) RemoveDelShares(pool Pool, delShares sdk.Dec) (Validator, Pool, sdk.Dec) { - issuedTokens := v.DelegatorShareExRate().Mul(delShares) +// NOTE: due to burning of excess tokens, the exchange rate +// of future shares of this validator can increase. +func (v Validator) RemoveDelShares(pool Pool, delShares sdk.Dec) (Validator, Pool, sdk.Int) { + issuedTokensDec := v.DelegatorShareExRate().Mul(delShares) + + // burn excess tokens + issuedTokens := issuedTokensDec.TruncateInt() + v.Tokens = v.Tokens.Sub(issuedTokens) v.DelegatorShares = v.DelegatorShares.Sub(delShares) @@ -421,15 +426,15 @@ func (v Validator) DelegatorShareExRate() sdk.Dec { if v.DelegatorShares.IsZero() { return sdk.OneDec() } - return v.Tokens.Quo(v.DelegatorShares) + return sdk.NewDecFromInt(v.Tokens).Quo(v.DelegatorShares) } // Get the bonded tokens which the validator holds -func (v Validator) BondedTokens() sdk.Dec { +func (v Validator) BondedTokens() sdk.Int { if v.Status == sdk.Bonded { return v.Tokens } - return sdk.ZeroDec() + return sdk.ZeroInt() } //______________________________________________________________________ @@ -444,8 +449,8 @@ func (v Validator) GetStatus() sdk.BondStatus { return v.Status } func (v Validator) GetOperator() sdk.ValAddress { return v.OperatorAddr } func (v Validator) GetConsPubKey() crypto.PubKey { return v.ConsPubKey } func (v Validator) GetConsAddr() sdk.ConsAddress { return sdk.ConsAddress(v.ConsPubKey.Address()) } -func (v Validator) GetPower() sdk.Dec { return v.BondedTokens() } -func (v Validator) GetTokens() sdk.Dec { return v.Tokens } +func (v Validator) GetPower() sdk.Int { return v.BondedTokens() } +func (v Validator) GetTokens() sdk.Int { return v.Tokens } func (v Validator) GetCommission() sdk.Dec { return v.Commission.Rate } func (v Validator) GetDelegatorShares() sdk.Dec { return v.DelegatorShares } func (v Validator) GetBondHeight() int64 { return v.BondHeight } From 1d52f450672647296b1bb2daf090b05b25c0be57 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Fri, 30 Nov 2018 01:41:23 -0500 Subject: [PATCH 02/18] non-test code compiles --- cmd/gaia/app/genesis.go | 2 +- types/int.go | 14 +++++++++++- types/stake.go | 2 +- x/distribution/keeper/test_common.go | 2 +- x/distribution/types/keepers.go | 2 +- x/gov/tally.go | 2 +- x/gov/test_common.go | 2 +- x/mint/abci_app.go | 2 +- x/mint/expected_keepers.go | 4 ++-- x/mint/minter.go | 4 ++-- x/slashing/test_common.go | 2 +- x/stake/genesis.go | 2 +- x/stake/keeper/delegation.go | 32 ++++++-------------------- x/stake/keeper/key.go | 2 +- x/stake/keeper/sdk_types.go | 4 ++-- x/stake/keeper/slash.go | 34 ++++++++++++++++------------ x/stake/keeper/test_common.go | 2 +- x/stake/keeper/val_state_change.go | 5 ++-- x/stake/keeper/validator.go | 19 ++++++++++------ x/stake/simulation/invariants.go | 12 ++++------ 20 files changed, 75 insertions(+), 75 deletions(-) diff --git a/cmd/gaia/app/genesis.go b/cmd/gaia/app/genesis.go index 60e96307bc89..f0a4ce881d8d 100644 --- a/cmd/gaia/app/genesis.go +++ b/cmd/gaia/app/genesis.go @@ -129,7 +129,7 @@ func GaiaAppGenState(cdc *codec.Codec, genDoc tmtypes.GenesisDoc, appGenTxs []js for _, coin := range acc.Coins { if coin.Denom == bondDenom { stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens. - Add(sdk.NewDecFromInt(coin.Amount)) // increase the supply + Add(coin.Amount) // increase the supply } } } diff --git a/types/int.go b/types/int.go index f08a7bce981e..8d94d9f066bb 100644 --- a/types/int.go +++ b/types/int.go @@ -40,6 +40,13 @@ func min(i *big.Int, i2 *big.Int) *big.Int { return new(big.Int).Set(i) } +func max(i *big.Int, i2 *big.Int) *big.Int { + if i.Cmp(i2) == 1 { + return new(big.Int).Set(i) + } + return new(big.Int).Set(i2) +} + // MarshalAmino for custom encoding scheme func marshalAmino(i *big.Int) (string, error) { bz, err := i.MarshalText() @@ -264,11 +271,16 @@ func (i Int) Neg() (res Int) { return Int{neg(i.i)} } -// Return the minimum of the ints +// return the minimum of the ints func MinInt(i1, i2 Int) Int { return Int{min(i1.BigInt(), i2.BigInt())} } +// return the maximum of the ints +func MaxInt(i1, i2 Int) Int { + return Int{max(i1.BigInt(), i2.BigInt())} +} + // Human readable string func (i Int) String() string { return i.i.String() diff --git a/types/stake.go b/types/stake.go index d88a20c5afeb..aeaa52d3465a 100644 --- a/types/stake.go +++ b/types/stake.go @@ -73,7 +73,7 @@ type ValidatorSet interface { Validator(Context, ValAddress) Validator // get a particular validator by operator address ValidatorByConsAddr(Context, ConsAddress) Validator // get a particular validator by consensus address - TotalPower(Context) Dec // total power of the validator set + TotalPower(Context) Int // total power of the validator set // slash the validator and delegators of the validator, specifying offence height, offence power, and slash fraction Slash(Context, ConsAddress, int64, int64, Dec) diff --git a/x/distribution/keeper/test_common.go b/x/distribution/keeper/test_common.go index 7cc68fcc42d9..4a4f192b9227 100644 --- a/x/distribution/keeper/test_common.go +++ b/x/distribution/keeper/test_common.go @@ -122,7 +122,7 @@ func CreateTestInputAdvanced(t *testing.T, isCheckTx bool, initCoins int64, {sk.GetParams(ctx).BondDenom, sdk.NewInt(initCoins)}, }) require.Nil(t, err) - pool.LooseTokens = pool.LooseTokens.Add(sdk.NewDec(initCoins)) + pool.LooseTokens = pool.LooseTokens.Add(sdk.NewInt(initCoins)) sk.SetPool(ctx, pool) } diff --git a/x/distribution/types/keepers.go b/x/distribution/types/keepers.go index 2578ea411360..c44c0dedf271 100644 --- a/x/distribution/types/keepers.go +++ b/x/distribution/types/keepers.go @@ -9,7 +9,7 @@ type StakeKeeper interface { Delegation(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) sdk.Delegation Validator(ctx sdk.Context, valAddr sdk.ValAddress) sdk.Validator ValidatorByConsAddr(ctx sdk.Context, consAddr sdk.ConsAddress) sdk.Validator - TotalPower(ctx sdk.Context) sdk.Dec + TotalPower(ctx sdk.Context) sdk.Int GetLastTotalPower(ctx sdk.Context) sdk.Int GetLastValidatorPower(ctx sdk.Context, valAddr sdk.ValAddress) sdk.Int } diff --git a/x/gov/tally.go b/x/gov/tally.go index d66237762ead..32a71c99eb96 100644 --- a/x/gov/tally.go +++ b/x/gov/tally.go @@ -26,7 +26,7 @@ func tally(ctx sdk.Context, keeper Keeper, proposal Proposal) (passes bool, tall keeper.vs.IterateBondedValidatorsByPower(ctx, func(index int64, validator sdk.Validator) (stop bool) { currValidators[validator.GetOperator().String()] = validatorGovInfo{ Address: validator.GetOperator(), - Power: validator.GetPower(), + Power: sdk.NewDecFromInt(validator.GetPower()), DelegatorShares: validator.GetDelegatorShares(), Minus: sdk.ZeroDec(), Vote: OptionEmpty, diff --git a/x/gov/test_common.go b/x/gov/test_common.go index 67b9fd902e63..cc12a9b62890 100644 --- a/x/gov/test_common.go +++ b/x/gov/test_common.go @@ -69,7 +69,7 @@ func getInitChainer(mapp *mock.App, keeper Keeper, stakeKeeper stake.Keeper) sdk mapp.InitChainer(ctx, req) stakeGenesis := stake.DefaultGenesisState() - stakeGenesis.Pool.LooseTokens = sdk.NewDec(100000) + stakeGenesis.Pool.LooseTokens = sdk.NewInt(100000) validators, err := stake.InitGenesis(ctx, stakeKeeper, stakeGenesis) if err != nil { diff --git a/x/mint/abci_app.go b/x/mint/abci_app.go index 963039961a6b..042bc7764dc0 100644 --- a/x/mint/abci_app.go +++ b/x/mint/abci_app.go @@ -15,7 +15,7 @@ func BeginBlocker(ctx sdk.Context, k Keeper) { mintedCoin := minter.BlockProvision(params) k.fck.AddCollectedFees(ctx, sdk.Coins{mintedCoin}) - k.sk.InflateSupply(ctx, sdk.NewDecFromInt(mintedCoin.Amount)) + k.sk.InflateSupply(ctx, mintedCoin.Amount) if blockTime.Sub(minter.LastUpdate) < time.Hour { return diff --git a/x/mint/expected_keepers.go b/x/mint/expected_keepers.go index 150e155cb3b5..995f9aafe588 100644 --- a/x/mint/expected_keepers.go +++ b/x/mint/expected_keepers.go @@ -6,9 +6,9 @@ import ( // expected stake keeper type StakeKeeper interface { - TotalPower(ctx sdk.Context) sdk.Dec + TotalPower(ctx sdk.Context) sdk.Int BondedRatio(ctx sdk.Context) sdk.Dec - InflateSupply(ctx sdk.Context, newTokens sdk.Dec) + InflateSupply(ctx sdk.Context, newTokens sdk.Int) } // expected fee collection keeper interface diff --git a/x/mint/minter.go b/x/mint/minter.go index 2edf1dabea38..04ab49b1c87c 100644 --- a/x/mint/minter.go +++ b/x/mint/minter.go @@ -81,10 +81,10 @@ func (m Minter) NextInflationRate(params Params, bondedRatio sdk.Dec) ( } // calculate the annual provisions based on current total supply and inflation rate -func (m Minter) NextAnnualProvisions(params Params, totalSupply sdk.Dec) ( +func (m Minter) NextAnnualProvisions(params Params, totalSupply sdk.Int) ( provisions sdk.Dec) { - return m.Inflation.Mul(totalSupply) + return m.Inflation.MulInt(totalSupply) } // get the provisions for a block based on the annual provisions rate diff --git a/x/slashing/test_common.go b/x/slashing/test_common.go index 72ee58e1b26b..34675947e61f 100644 --- a/x/slashing/test_common.go +++ b/x/slashing/test_common.go @@ -76,7 +76,7 @@ func createTestInput(t *testing.T, defaults Params) (sdk.Context, bank.Keeper, s sk := stake.NewKeeper(cdc, keyStake, tkeyStake, ck, paramsKeeper.Subspace(stake.DefaultParamspace), stake.DefaultCodespace) genesis := stake.DefaultGenesisState() - genesis.Pool.LooseTokens = sdk.NewDec(initCoins.MulRaw(int64(len(addrs))).Int64()) + genesis.Pool.LooseTokens = sdk.NewInt(initCoins.MulRaw(int64(len(addrs))).Int64()) _, err = stake.InitGenesis(ctx, sk, genesis) require.Nil(t, err) diff --git a/x/stake/genesis.go b/x/stake/genesis.go index bdd62d3769d4..5a7f828db69b 100644 --- a/x/stake/genesis.go +++ b/x/stake/genesis.go @@ -132,7 +132,7 @@ func WriteValidators(ctx sdk.Context, keeper Keeper) (vals []tmtypes.GenesisVali keeper.IterateLastValidators(ctx, func(_ int64, validator sdk.Validator) (stop bool) { vals = append(vals, tmtypes.GenesisValidator{ PubKey: validator.GetConsPubKey(), - Power: validator.GetPower().RoundInt64(), + Power: validator.GetPower().Int64(), Name: validator.GetMoniker(), }) diff --git a/x/stake/keeper/delegation.go b/x/stake/keeper/delegation.go index 811b1562937c..740fe73b7c44 100644 --- a/x/stake/keeper/delegation.go +++ b/x/stake/keeper/delegation.go @@ -422,28 +422,25 @@ func (k Keeper) Delegate(ctx sdk.Context, delAddr sdk.AccAddress, bondAmt sdk.Co // unbond the the delegation return func (k Keeper) unbond(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress, - shares sdk.Dec) (amount sdk.Dec, err sdk.Error) { + shares sdk.Dec) (amount sdk.Int, err sdk.Error) { // check if delegation has any shares in it unbond delegation, found := k.GetDelegation(ctx, delAddr, valAddr) if !found { - err = types.ErrNoDelegatorForAddress(k.Codespace()) - return + return amount, types.ErrNoDelegatorForAddress(k.Codespace()) } k.OnDelegationSharesModified(ctx, delAddr, valAddr) // retrieve the amount to remove if delegation.Shares.LT(shares) { - err = types.ErrNotEnoughDelegationShares(k.Codespace(), delegation.Shares.String()) - return + return amount, types.ErrNotEnoughDelegationShares(k.Codespace(), delegation.Shares.String()) } // get validator validator, found := k.GetValidator(ctx, valAddr) if !found { - err = types.ErrNoValidatorFound(k.Codespace()) - return + return amount, types.ErrNoValidatorFound(k.Codespace()) } // subtract shares from delegator @@ -522,15 +519,7 @@ func (k Keeper) BeginUnbonding(ctx sdk.Context, if err != nil { return types.UnbondingDelegation{}, err } - - rounded := returnAmount.TruncateInt() - balance := sdk.NewCoin(k.BondDenom(ctx), rounded) - change := returnAmount.Sub(sdk.NewDecFromInt(rounded)) - - // for now, change is just burned - pool := k.GetPool(ctx) - pool.LooseTokens = pool.LooseTokens.Sub(change) - k.SetPool(ctx, pool) + balance := sdk.NewCoin(k.BondDenom(ctx), returnAmount) // no need to create the ubd object just complete now if completeNow { @@ -597,17 +586,10 @@ func (k Keeper) BeginRedelegation(ctx sdk.Context, delAddr sdk.AccAddress, return types.Redelegation{}, err } - rounded := returnAmount.TruncateInt() - if rounded.IsZero() { //TODO design consideration + if returnAmount.IsZero() { return types.Redelegation{}, types.ErrVerySmallRedelegation(k.Codespace()) } - returnCoin := sdk.NewCoin(k.BondDenom(ctx), rounded) - change := returnAmount.Sub(sdk.NewDecFromInt(rounded)) - - // for now, change is just burned - pool := k.GetPool(ctx) - pool.LooseTokens = pool.LooseTokens.Sub(change) - k.SetPool(ctx, pool) + returnCoin := sdk.NewCoin(k.BondDenom(ctx), returnAmount) dstValidator, found := k.GetValidator(ctx, valDstAddr) if !found { diff --git a/x/stake/keeper/key.go b/x/stake/keeper/key.go index 243fe34ec57c..e8cd5317ad61 100644 --- a/x/stake/keeper/key.go +++ b/x/stake/keeper/key.go @@ -79,7 +79,7 @@ func getValidatorPowerRank(validator types.Validator) []byte { potentialPower := validator.Tokens // todo: deal with cases above 2**64, ref https://github.com/cosmos/cosmos-sdk/issues/2439#issuecomment-427167556 - tendermintPower := potentialPower.RoundInt64() + tendermintPower := potentialPower.Int64() tendermintPowerBytes := make([]byte, 8) binary.BigEndian.PutUint64(tendermintPowerBytes[:], uint64(tendermintPower)) diff --git a/x/stake/keeper/sdk_types.go b/x/stake/keeper/sdk_types.go index f777077d7d1f..dcef5c6d656e 100644 --- a/x/stake/keeper/sdk_types.go +++ b/x/stake/keeper/sdk_types.go @@ -89,7 +89,7 @@ func (k Keeper) ValidatorByConsAddr(ctx sdk.Context, addr sdk.ConsAddress) sdk.V } // total power from the bond (not last, but current) -func (k Keeper) TotalPower(ctx sdk.Context) sdk.Dec { +func (k Keeper) TotalPower(ctx sdk.Context) sdk.Int { pool := k.GetPool(ctx) return pool.BondedTokens } @@ -101,7 +101,7 @@ func (k Keeper) BondedRatio(ctx sdk.Context) sdk.Dec { } // when minting new tokens -func (k Keeper) InflateSupply(ctx sdk.Context, newTokens sdk.Dec) { +func (k Keeper) InflateSupply(ctx sdk.Context, newTokens sdk.Int) { pool := k.GetPool(ctx) pool.LooseTokens = pool.LooseTokens.Add(newTokens) k.SetPool(ctx, pool) diff --git a/x/stake/keeper/slash.go b/x/stake/keeper/slash.go index e7bd72764b5d..6d22c82fc986 100644 --- a/x/stake/keeper/slash.go +++ b/x/stake/keeper/slash.go @@ -29,7 +29,9 @@ func (k Keeper) Slash(ctx sdk.Context, consAddr sdk.ConsAddress, infractionHeigh } // Amount of slashing = slash slashFactor * power at time of infraction - slashAmount := sdk.NewDec(power).Mul(slashFactor) + slashAmountDec := sdk.NewDec(power).Mul(slashFactor) + slashAmount := slashAmountDec.TruncateInt() + // ref https://github.com/cosmos/cosmos-sdk/issues/1348 // ref https://github.com/cosmos/cosmos-sdk/issues/1471 @@ -97,8 +99,8 @@ func (k Keeper) Slash(ctx sdk.Context, consAddr sdk.ConsAddress, infractionHeigh } // cannot decrease balance below zero - tokensToBurn := sdk.MinDec(remainingSlashAmount, validator.Tokens) - tokensToBurn = sdk.MaxDec(tokensToBurn, sdk.ZeroDec()) // defensive. + tokensToBurn := sdk.MinInt(remainingSlashAmount, validator.Tokens) + tokensToBurn = sdk.MaxInt(tokensToBurn, sdk.ZeroInt()) // defensive. // Deduct from validator's bonded tokens and update the validator. // The deducted tokens are returned to pool.LooseTokens. @@ -143,29 +145,30 @@ func (k Keeper) Unjail(ctx sdk.Context, consAddr sdk.ConsAddress) { // (the amount actually slashed may be less if there's // insufficient stake remaining) func (k Keeper) slashUnbondingDelegation(ctx sdk.Context, unbondingDelegation types.UnbondingDelegation, - infractionHeight int64, slashFactor sdk.Dec) (slashAmount sdk.Dec) { + infractionHeight int64, slashFactor sdk.Dec) (slashAmount sdk.Int) { now := ctx.BlockHeader().Time // If unbonding started before this height, stake didn't contribute to infraction if unbondingDelegation.CreationHeight < infractionHeight { - return sdk.ZeroDec() + return sdk.ZeroInt() } if unbondingDelegation.MinTime.Before(now) { // Unbonding delegation no longer eligible for slashing, skip it // TODO Settle and delete it automatically? - return sdk.ZeroDec() + return sdk.ZeroInt() } // Calculate slash amount proportional to stake contributing to infraction - slashAmount = slashFactor.MulInt(unbondingDelegation.InitialBalance.Amount) + slashAmountDec := slashFactor.MulInt(unbondingDelegation.InitialBalance.Amount) + slashAmount = slashAmountDec.TruncateInt() // Don't slash more tokens than held // Possible since the unbonding delegation may already // have been slashed, and slash amounts are calculated // according to stake held at time of infraction - unbondingSlashAmount := sdk.MinInt(slashAmount.RoundInt(), unbondingDelegation.Balance.Amount) + unbondingSlashAmount := sdk.MinInt(slashAmount, unbondingDelegation.Balance.Amount) // Update unbonding delegation if necessary if !unbondingSlashAmount.IsZero() { @@ -175,11 +178,11 @@ func (k Keeper) slashUnbondingDelegation(ctx sdk.Context, unbondingDelegation ty // Burn loose tokens // Ref https://github.com/cosmos/cosmos-sdk/pull/1278#discussion_r198657760 - pool.LooseTokens = pool.LooseTokens.Sub(sdk.NewDecFromInt(unbondingSlashAmount)) + pool.LooseTokens = pool.LooseTokens.Sub(unbondingSlashAmount) k.SetPool(ctx, pool) } - return + return slashAmount } // slash a redelegation and update the pool @@ -189,29 +192,30 @@ func (k Keeper) slashUnbondingDelegation(ctx sdk.Context, unbondingDelegation ty // insufficient stake remaining) // nolint: unparam func (k Keeper) slashRedelegation(ctx sdk.Context, validator types.Validator, redelegation types.Redelegation, - infractionHeight int64, slashFactor sdk.Dec) (slashAmount sdk.Dec) { + infractionHeight int64, slashFactor sdk.Dec) (slashAmount sdk.Int) { now := ctx.BlockHeader().Time // If redelegation started before this height, stake didn't contribute to infraction if redelegation.CreationHeight < infractionHeight { - return sdk.ZeroDec() + return sdk.ZeroInt() } if redelegation.MinTime.Before(now) { // Redelegation no longer eligible for slashing, skip it // TODO Delete it automatically? - return sdk.ZeroDec() + return sdk.ZeroInt() } // Calculate slash amount proportional to stake contributing to infraction - slashAmount = slashFactor.MulInt(redelegation.InitialBalance.Amount) + slashAmountDec := slashFactor.MulInt(redelegation.InitialBalance.Amount) + slashAmount = slashAmountDec.TruncateInt() // Don't slash more tokens than held // Possible since the redelegation may already // have been slashed, and slash amounts are calculated // according to stake held at time of infraction - redelegationSlashAmount := sdk.MinInt(slashAmount.RoundInt(), redelegation.Balance.Amount) + redelegationSlashAmount := sdk.MinInt(slashAmount, redelegation.Balance.Amount) // Update redelegation if necessary if !redelegationSlashAmount.IsZero() { diff --git a/x/stake/keeper/test_common.go b/x/stake/keeper/test_common.go index 5a501f721070..aae4503312b6 100644 --- a/x/stake/keeper/test_common.go +++ b/x/stake/keeper/test_common.go @@ -116,7 +116,7 @@ func CreateTestInput(t *testing.T, isCheckTx bool, initCoins int64) (sdk.Context {keeper.BondDenom(ctx), sdk.NewInt(initCoins)}, }) require.Nil(t, err) - pool.LooseTokens = pool.LooseTokens.Add(sdk.NewDec(initCoins)) + pool.LooseTokens = pool.LooseTokens.Add(sdk.NewInt(initCoins)) keeper.SetPool(ctx, pool) } diff --git a/x/stake/keeper/val_state_change.go b/x/stake/keeper/val_state_change.go index 3f98f08c5601..cba87310054b 100644 --- a/x/stake/keeper/val_state_change.go +++ b/x/stake/keeper/val_state_change.go @@ -49,8 +49,7 @@ func (k Keeper) ApplyAndReturnValidatorSetUpdates(ctx sdk.Context) (updates []ab // if we get to a zero-power validator (which we don't bond), // there are no more possible bonded validators - // note: we must check the ABCI power, since we round before sending to Tendermint - if validator.Tokens.RoundInt64() == int64(0) { + if validator.Tokens.IsZero() { break } @@ -72,7 +71,7 @@ func (k Keeper) ApplyAndReturnValidatorSetUpdates(ctx sdk.Context) (updates []ab oldPowerBytes, found := last[valAddrBytes] // calculate the new power bytes - newPower := validator.BondedTokens().RoundInt64() + newPower := validator.BondedTokens().Int64() newPowerBytes := k.cdc.MustMarshalBinaryLengthPrefixed(sdk.NewInt(newPower)) // update the validator set if power has changed if !found || !bytes.Equal(oldPowerBytes, newPowerBytes) { diff --git a/x/stake/keeper/validator.go b/x/stake/keeper/validator.go index c7919537cf9c..917321a05784 100644 --- a/x/stake/keeper/validator.go +++ b/x/stake/keeper/validator.go @@ -143,7 +143,7 @@ func (k Keeper) AddValidatorTokensAndShares(ctx sdk.Context, validator types.Val // Update the tokens of an existing validator, update the validators power index key func (k Keeper) RemoveValidatorTokensAndShares(ctx sdk.Context, validator types.Validator, - sharesToRemove sdk.Dec) (valOut types.Validator, removedTokens sdk.Dec) { + sharesToRemove sdk.Dec) (valOut types.Validator, removedTokens sdk.Int) { pool := k.GetPool(ctx) k.DeleteValidatorByPowerIndex(ctx, validator, pool) @@ -155,7 +155,8 @@ func (k Keeper) RemoveValidatorTokensAndShares(ctx sdk.Context, validator types. } // Update the tokens of an existing validator, update the validators power index key -func (k Keeper) RemoveValidatorTokens(ctx sdk.Context, validator types.Validator, tokensToRemove sdk.Dec) types.Validator { +func (k Keeper) RemoveValidatorTokens(ctx sdk.Context, + validator types.Validator, tokensToRemove sdk.Int) types.Validator { pool := k.GetPool(ctx) k.DeleteValidatorByPowerIndex(ctx, validator, pool) @@ -168,7 +169,9 @@ func (k Keeper) RemoveValidatorTokens(ctx sdk.Context, validator types.Validator // UpdateValidatorCommission attempts to update a validator's commission rate. // An error is returned if the new commission rate is invalid. -func (k Keeper) UpdateValidatorCommission(ctx sdk.Context, validator types.Validator, newRate sdk.Dec) (types.Commission, sdk.Error) { +func (k Keeper) UpdateValidatorCommission(ctx sdk.Context, + validator types.Validator, newRate sdk.Dec) (types.Commission, sdk.Error) { + commission := validator.Commission blockTime := ctx.BlockHeader().Time @@ -335,12 +338,13 @@ func (k Keeper) DeleteValidatorQueueTimeSlice(ctx sdk.Context, timestamp time.Ti // Insert an validator address to the appropriate timeslice in the validator queue func (k Keeper) InsertValidatorQueue(ctx sdk.Context, val types.Validator) { timeSlice := k.GetValidatorQueueTimeSlice(ctx, val.UnbondingMinTime) + var keys []sdk.ValAddress if len(timeSlice) == 0 { - k.SetValidatorQueueTimeSlice(ctx, val.UnbondingMinTime, []sdk.ValAddress{val.OperatorAddr}) + keys = []sdk.ValAddress{val.OperatorAddr} } else { - timeSlice = append(timeSlice, val.OperatorAddr) - k.SetValidatorQueueTimeSlice(ctx, val.UnbondingMinTime, timeSlice) + keys = append(timeSlice, val.OperatorAddr) } + k.SetValidatorQueueTimeSlice(ctx, val.UnbondingMinTime, keys) } // Delete a validator address from the validator queue @@ -362,7 +366,8 @@ func (k Keeper) DeleteValidatorQueue(ctx sdk.Context, val types.Validator) { // Returns all the validator queue timeslices from time 0 until endTime func (k Keeper) ValidatorQueueIterator(ctx sdk.Context, endTime time.Time) sdk.Iterator { store := ctx.KVStore(k.storeKey) - return store.Iterator(ValidatorQueueKey, sdk.InclusiveEndBytes(GetValidatorQueueTimeKey(endTime))) + return store.Iterator(ValidatorQueueKey, + sdk.InclusiveEndBytes(GetValidatorQueueTimeKey(endTime))) } // Returns a concatenated list of all the timeslices before currTime, and deletes the timeslices from the queue diff --git a/x/stake/simulation/invariants.go b/x/stake/simulation/invariants.go index 8fac4df156e5..5c91820c1a1e 100644 --- a/x/stake/simulation/invariants.go +++ b/x/stake/simulation/invariants.go @@ -65,11 +65,9 @@ func SupplyInvariants(ck bank.Keeper, k stake.Keeper, k.IterateValidators(ctx, func(_ int64, validator sdk.Validator) bool { switch validator.GetStatus() { case sdk.Bonded: - bonded = bonded.Add(validator.GetPower()) - case sdk.Unbonding: - loose = loose.Add(validator.GetTokens()) - case sdk.Unbonded: - loose = loose.Add(validator.GetTokens()) + bonded = bonded.Add(sdk.NewDecFromInt(validator.GetPower())) + case sdk.Unbonding, sdk.Unbonded: + loose = loose.Add(sdk.NewDecFromInt(validator.GetTokens())) } return false }) @@ -96,13 +94,13 @@ func SupplyInvariants(ck bank.Keeper, k stake.Keeper, // Loose tokens should equal coin supply plus unbonding delegations // plus tokens on unbonded validators - if !pool.LooseTokens.Equal(loose) { + if !loose.Equal(sdk.NewDecFromInt(pool.LooseTokens)) { return fmt.Errorf("loose token invariance:\n\tpool.LooseTokens: %v"+ "\n\tsum of account tokens: %v", pool.LooseTokens, loose) } // Bonded tokens should equal sum of tokens with bonded validators - if !pool.BondedTokens.Equal(bonded) { + if !bonded.Equal(sdk.NewDecFromInt(pool.BondedTokens)) { return fmt.Errorf("bonded token invariance:\n\tpool.BondedTokens: %v"+ "\n\tsum of account tokens: %v", pool.BondedTokens, bonded) } From f536738ff7295c4951429c9e1bcd6122f58b0e85 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Fri, 30 Nov 2018 03:45:39 -0500 Subject: [PATCH 03/18] working, many test compile fixes --- client/lcd/lcd_test.go | 6 +- client/lcd/test_helpers.go | 2 +- cmd/gaia/app/genesis_test.go | 2 +- cmd/gaia/app/sim_test.go | 4 +- cmd/gaia/cli_test/cli_test.go | 8 +- docs/examples/democoin/mock/validator.go | 12 +-- .../democoin/x/assoc/validator_set_test.go | 4 +- docs/examples/democoin/x/oracle/keeper.go | 2 +- .../examples/democoin/x/oracle/oracle_test.go | 8 +- x/distribution/keeper/allocation_test.go | 8 +- x/slashing/app_test.go | 4 +- x/slashing/handler_test.go | 2 +- x/slashing/keeper_test.go | 46 +++++----- x/slashing/tick_test.go | 2 +- x/stake/app_test.go | 6 +- x/stake/genesis_test.go | 14 +-- x/stake/handler_test.go | 24 ++--- x/stake/keeper/delegation_test.go | 38 ++++---- x/stake/keeper/keeper_test.go | 2 +- x/stake/keeper/key_test.go | 8 +- x/stake/keeper/slash_test.go | 62 ++++++------- x/stake/keeper/validator_test.go | 74 +++++++-------- x/stake/types/pool_test.go | 22 ++--- x/stake/types/validator_test.go | 89 +++++++++---------- 24 files changed, 222 insertions(+), 227 deletions(-) diff --git a/client/lcd/lcd_test.go b/client/lcd/lcd_test.go index 04453111a90a..b93a3ac27b0f 100644 --- a/client/lcd/lcd_test.go +++ b/client/lcd/lcd_test.go @@ -456,9 +456,9 @@ func TestPoolParamsQuery(t *testing.T) { require.NotNil(t, body) initialPool := stake.InitialPool() - initialPool.LooseTokens = initialPool.LooseTokens.Add(sdk.NewDec(100)) - initialPool.BondedTokens = initialPool.BondedTokens.Add(sdk.NewDec(100)) // Delegate tx on GaiaAppGenState - initialPool.LooseTokens = initialPool.LooseTokens.Add(sdk.NewDec(int64(50))) // freeFermionsAcc = 50 on GaiaAppGenState + initialPool.LooseTokens = initialPool.LooseTokens.Add(sdk.NewInt(100)) + initialPool.BondedTokens = initialPool.BondedTokens.Add(sdk.NewInt(100)) // Delegate tx on GaiaAppGenState + initialPool.LooseTokens = initialPool.LooseTokens.Add(sdk.NewInt(50)) // freeFermionsAcc = 50 on GaiaAppGenState var pool stake.Pool err = cdc.UnmarshalJSON([]byte(body), &pool) diff --git a/client/lcd/test_helpers.go b/client/lcd/test_helpers.go index 921dc96ddb18..198743ce86fe 100644 --- a/client/lcd/test_helpers.go +++ b/client/lcd/test_helpers.go @@ -280,7 +280,7 @@ func InitializeTestLCD( accAuth.Coins = sdk.Coins{sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, 100)} acc := gapp.NewGenesisAccount(&accAuth) genesisState.Accounts = append(genesisState.Accounts, acc) - genesisState.StakeData.Pool.LooseTokens = genesisState.StakeData.Pool.LooseTokens.Add(sdk.NewDec(100)) + genesisState.StakeData.Pool.LooseTokens = genesisState.StakeData.Pool.LooseTokens.Add(sdk.NewInt(100)) } appState, err := codec.MarshalJSONIndent(cdc, genesisState) diff --git a/cmd/gaia/app/genesis_test.go b/cmd/gaia/app/genesis_test.go index 1b1c1964695a..5a4c7d2b0b4b 100644 --- a/cmd/gaia/app/genesis_test.go +++ b/cmd/gaia/app/genesis_test.go @@ -42,7 +42,7 @@ func makeGenesisState(t *testing.T, genTxs []auth.StdTx) GenesisState { acc := auth.NewBaseAccountWithAddress(sdk.AccAddress(msg.ValidatorAddr)) acc.Coins = sdk.Coins{sdk.NewInt64Coin(bondDenom, 150)} genAccs[i] = NewGenesisAccount(&acc) - stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens.Add(sdk.NewDec(150)) // increase the supply + stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens.Add(sdk.NewInt(150)) // increase the supply } // create the final app state diff --git a/cmd/gaia/app/sim_test.go b/cmd/gaia/app/sim_test.go index 52ac2ed1a867..beaaddcbd310 100644 --- a/cmd/gaia/app/sim_test.go +++ b/cmd/gaia/app/sim_test.go @@ -138,13 +138,13 @@ func appStateFn(r *rand.Rand, accs []simulation.Account) json.RawMessage { valAddrs[i] = valAddr validator := stake.NewValidator(valAddr, accs[i].PubKey, stake.Description{}) - validator.Tokens = sdk.NewDec(amount) + validator.Tokens = sdk.NewInt(amount) validator.DelegatorShares = sdk.NewDec(amount) delegation := stake.Delegation{accs[i].Address, valAddr, sdk.NewDec(amount)} validators = append(validators, validator) delegations = append(delegations, delegation) } - stakeGenesis.Pool.LooseTokens = sdk.NewDec((amount * numAccs) + (numInitiallyBonded * amount)) + stakeGenesis.Pool.LooseTokens = sdk.NewInt((amount * numAccs) + (numInitiallyBonded * amount)) stakeGenesis.Validators = validators stakeGenesis.Bonds = delegations diff --git a/cmd/gaia/cli_test/cli_test.go b/cmd/gaia/cli_test/cli_test.go index 25818025a894..a0bf08e237be 100644 --- a/cmd/gaia/cli_test/cli_test.go +++ b/cmd/gaia/cli_test/cli_test.go @@ -234,7 +234,7 @@ func TestGaiaCLICreateValidator(t *testing.T) { defaultParams := stake.DefaultParams() initialPool := stake.InitialPool() - initialPool.BondedTokens = initialPool.BondedTokens.Add(sdk.NewDec(100)) // Delegate tx on GaiaAppGenState + initialPool.BondedTokens = initialPool.BondedTokens.Add(sdk.NewInt(100)) // Delegate tx on GaiaAppGenState // create validator cvStr := fmt.Sprintf("gaiacli tx stake create-validator %v", flags) @@ -246,7 +246,7 @@ func TestGaiaCLICreateValidator(t *testing.T) { cvStr += fmt.Sprintf(" --commission-max-rate=%v", "0.20") cvStr += fmt.Sprintf(" --commission-max-change-rate=%v", "0.10") - initialPool.BondedTokens = initialPool.BondedTokens.Add(sdk.NewDec(1)) + initialPool.BondedTokens = initialPool.BondedTokens.Add(sdk.NewInt(1)) // Test --generate-only success, stdout, stderr := executeWriteRetStdStreams(t, cvStr+" --generate-only", app.DefaultKeyPass) @@ -270,7 +270,7 @@ func TestGaiaCLICreateValidator(t *testing.T) { validator := executeGetValidator(t, fmt.Sprintf("gaiacli query stake validator %s --output=json %v", sdk.ValAddress(barAddr), flags)) require.Equal(t, validator.OperatorAddr, sdk.ValAddress(barAddr)) - require.True(sdk.DecEq(t, sdk.NewDec(2), validator.Tokens)) + require.True(sdk.IntEq(t, sdk.NewInt(2), validator.Tokens)) validatorDelegations := executeGetValidatorDelegations(t, fmt.Sprintf("gaiacli query stake delegations-to %s --output=json %v", sdk.ValAddress(barAddr), flags)) require.Len(t, validatorDelegations, 1) @@ -291,7 +291,7 @@ func TestGaiaCLICreateValidator(t *testing.T) { require.Equal(t, int64(9), barAcc.GetCoins().AmountOf(stakeTypes.DefaultBondDenom).Int64(), "%v", barAcc) */ validator = executeGetValidator(t, fmt.Sprintf("gaiacli query stake validator %s --output=json %v", sdk.ValAddress(barAddr), flags)) - require.Equal(t, "1.0000000000", validator.Tokens.String()) + require.Equal(t, "1", validator.Tokens.String()) validatorUbds := executeGetValidatorUnbondingDelegations(t, fmt.Sprintf("gaiacli query stake unbonding-delegations-from %s --output=json %v", diff --git a/docs/examples/democoin/mock/validator.go b/docs/examples/democoin/mock/validator.go index 1d10c48b2459..3fbce1d43418 100644 --- a/docs/examples/democoin/mock/validator.go +++ b/docs/examples/democoin/mock/validator.go @@ -10,7 +10,7 @@ import ( // Validator implements sdk.Validator type Validator struct { Address sdk.ValAddress - Power sdk.Dec + Power sdk.Int } // Implements sdk.Validator @@ -34,12 +34,12 @@ func (v Validator) GetConsAddr() sdk.ConsAddress { } // Implements sdk.Validator -func (v Validator) GetTokens() sdk.Dec { - return sdk.ZeroDec() +func (v Validator) GetTokens() sdk.Int { + return sdk.ZeroInt() } // Implements sdk.Validator -func (v Validator) GetPower() sdk.Dec { +func (v Validator) GetPower() sdk.Int { return v.Power } @@ -113,8 +113,8 @@ func (vs *ValidatorSet) ValidatorByConsAddr(_ sdk.Context, _ sdk.ConsAddress) sd } // TotalPower implements sdk.ValidatorSet -func (vs *ValidatorSet) TotalPower(ctx sdk.Context) sdk.Dec { - res := sdk.ZeroDec() +func (vs *ValidatorSet) TotalPower(ctx sdk.Context) sdk.Int { + res := sdk.ZeroInt() for _, val := range vs.Validators { res = res.Add(val.Power) } diff --git a/docs/examples/democoin/x/assoc/validator_set_test.go b/docs/examples/democoin/x/assoc/validator_set_test.go index 66f03c840324..83a2e16ca03a 100644 --- a/docs/examples/democoin/x/assoc/validator_set_test.go +++ b/docs/examples/democoin/x/assoc/validator_set_test.go @@ -32,8 +32,8 @@ func TestValidatorSet(t *testing.T) { addr2 := []byte("addr2") base := &mock.ValidatorSet{[]mock.Validator{ - {addr1, sdk.NewDec(1)}, - {addr2, sdk.NewDec(2)}, + {addr1, sdk.NewInt(1)}, + {addr2, sdk.NewInt(2)}, }} valset := NewValidatorSet(codec.New(), ctx.KVStore(key).Prefix([]byte("assoc")), base, 1, 5) diff --git a/docs/examples/democoin/x/oracle/keeper.go b/docs/examples/democoin/x/oracle/keeper.go index d061d2f8ed4f..50f210eb5fed 100644 --- a/docs/examples/democoin/x/oracle/keeper.go +++ b/docs/examples/democoin/x/oracle/keeper.go @@ -46,7 +46,7 @@ const ( // Info for each payload type Info struct { - Power sdk.Dec + Power sdk.Int Hash []byte LastSigned int64 Status InfoStatus diff --git a/docs/examples/democoin/x/oracle/oracle_test.go b/docs/examples/democoin/x/oracle/oracle_test.go index b8b613e318d3..4a07e9e2c8e0 100644 --- a/docs/examples/democoin/x/oracle/oracle_test.go +++ b/docs/examples/democoin/x/oracle/oracle_test.go @@ -110,9 +110,9 @@ func TestOracle(t *testing.T) { addr3 := []byte("addr3") addr4 := []byte("addr4") valset := &mock.ValidatorSet{[]mock.Validator{ - {addr1, sdk.NewDec(7)}, - {addr2, sdk.NewDec(7)}, - {addr3, sdk.NewDec(1)}, + {addr1, sdk.NewInt(7)}, + {addr2, sdk.NewInt(7)}, + {addr3, sdk.NewInt(1)}, }} key := sdk.NewKVStoreKey("testkey") @@ -174,7 +174,7 @@ func TestOracle(t *testing.T) { require.Equal(t, 1, getSequence(ctx, key)) // Should handle mock.Validator set change - valset.AddValidator(mock.Validator{addr4, sdk.NewDec(12)}) + valset.AddValidator(mock.Validator{addr4, sdk.NewInt(12)}) bz, err = json.Marshal(valset) require.Nil(t, err) ctx = ctx.WithBlockHeader(abci.Header{ValidatorsHash: bz}) diff --git a/x/distribution/keeper/allocation_test.go b/x/distribution/keeper/allocation_test.go index 7d05e82b1ca3..fd169f5cee4c 100644 --- a/x/distribution/keeper/allocation_test.go +++ b/x/distribution/keeper/allocation_test.go @@ -18,7 +18,7 @@ func TestAllocateTokensBasic(t *testing.T) { //first make a validator totalPower := int64(10) - totalPowerDec := sdk.NewDec(totalPower) + totalPowerInt := sdk.NewInt(totalPower) msgCreateValidator := stake.NewTestMsgCreateValidator(valOpAddr1, valConsPk1, totalPower) got := stakeHandler(ctx, msgCreateValidator) require.True(t, got.IsOK(), "expected msg to be ok, got %v", got) @@ -28,10 +28,10 @@ func TestAllocateTokensBasic(t *testing.T) { validator, found := sk.GetValidator(ctx, valOpAddr1) require.True(t, found) require.Equal(t, sdk.Bonded, validator.Status) - assert.True(sdk.DecEq(t, totalPowerDec, validator.Tokens)) - assert.True(sdk.DecEq(t, totalPowerDec, validator.DelegatorShares)) + assert.True(sdk.IntEq(t, totalPowerInt, validator.Tokens)) + assert.True(sdk.DecEq(t, sdk.NewDec(totalPower), validator.DelegatorShares)) bondedTokens := sk.TotalPower(ctx) - assert.True(sdk.DecEq(t, totalPowerDec, bondedTokens)) + assert.True(sdk.IntEq(t, totalPowerInt, bondedTokens)) // initial fee pool should be empty feePool := keeper.GetFeePool(ctx) diff --git a/x/slashing/app_test.go b/x/slashing/app_test.go index 4f312acd85a4..c7a9c0720fce 100644 --- a/x/slashing/app_test.go +++ b/x/slashing/app_test.go @@ -65,7 +65,7 @@ func getInitChainer(mapp *mock.App, keeper stake.Keeper) sdk.InitChainer { return func(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { mapp.InitChainer(ctx, req) stakeGenesis := stake.DefaultGenesisState() - stakeGenesis.Pool.LooseTokens = sdk.NewDec(100000) + stakeGenesis.Pool.LooseTokens = sdk.NewInt(100000) validators, err := stake.InitGenesis(ctx, keeper, stakeGenesis) if err != nil { panic(err) @@ -119,7 +119,7 @@ func TestSlashingMsgs(t *testing.T) { validator := checkValidator(t, mapp, stakeKeeper, addr1, true) require.Equal(t, sdk.ValAddress(addr1), validator.OperatorAddr) require.Equal(t, sdk.Bonded, validator.Status) - require.True(sdk.DecEq(t, sdk.NewDec(10), validator.BondedTokens())) + require.True(sdk.IntEq(t, sdk.NewInt(10), validator.BondedTokens())) unjailMsg := MsgUnjail{ValidatorAddr: sdk.ValAddress(validator.ConsPubKey.Address())} // no signing info yet diff --git a/x/slashing/handler_test.go b/x/slashing/handler_test.go index bd19643ae3dc..b7a0e42ad061 100644 --- a/x/slashing/handler_test.go +++ b/x/slashing/handler_test.go @@ -25,7 +25,7 @@ func TestCannotUnjailUnlessJailed(t *testing.T) { t, ck.GetCoins(ctx, sdk.AccAddress(addr)), sdk.Coins{sdk.NewCoin(sk.GetParams(ctx).BondDenom, initCoins.Sub(amt))}, ) - require.True(t, sdk.NewDecFromInt(amt).Equal(sk.Validator(ctx, addr).GetPower())) + require.True(sdk.IntEq(t, amt, sk.Validator(ctx, addr).GetPower())) // assert non-jailed validator can't be unjailed got = slh(ctx, NewMsgUnjail(addr)) diff --git a/x/slashing/keeper_test.go b/x/slashing/keeper_test.go index 6dc9ab8008a5..7a805be4d093 100644 --- a/x/slashing/keeper_test.go +++ b/x/slashing/keeper_test.go @@ -39,7 +39,7 @@ func TestHandleDoubleSign(t *testing.T) { t, ck.GetCoins(ctx, sdk.AccAddress(operatorAddr)), sdk.Coins{sdk.NewCoin(sk.GetParams(ctx).BondDenom, initCoins.Sub(amt))}, ) - require.True(t, sdk.NewDecFromInt(amt).Equal(sk.Validator(ctx, operatorAddr).GetPower())) + require.True(sdk.IntEq(t, amt, sk.Validator(ctx, operatorAddr).GetPower())) // handle a signature to set signing info keeper.handleValidatorSignature(ctx, val.Address(), amtInt, true) @@ -83,7 +83,7 @@ func TestSlashingPeriodCap(t *testing.T) { t, ck.GetCoins(ctx, sdk.AccAddress(operatorAddr)), sdk.Coins{sdk.NewCoin(sk.GetParams(ctx).BondDenom, initCoins.Sub(amt))}, ) - require.True(t, sdk.NewDecFromInt(amt).Equal(sk.Validator(ctx, operatorAddr).GetPower())) + require.True(sdk.IntEq(t, amt, sk.Validator(ctx, operatorAddr).GetPower())) // handle a signature to set signing info keeper.handleValidatorSignature(ctx, valConsAddr, amtInt, true) @@ -139,8 +139,8 @@ func TestHandleAbsentValidator(t *testing.T) { // initial setup ctx, ck, sk, _, keeper := createTestInput(t, keeperTestParams()) - amtInt := int64(100) - addr, val, amt := addrs[0], pks[0], sdk.NewInt(amtInt) + amtInt64 := int64(100) + addr, val, amt := addrs[0], pks[0], sdk.NewInt(amtInt64) sh := stake.NewHandler(sk) slh := NewHandler(keeper) got := sh(ctx, NewTestMsgCreateValidator(addr, val, amt)) @@ -151,7 +151,7 @@ func TestHandleAbsentValidator(t *testing.T) { t, ck.GetCoins(ctx, sdk.AccAddress(addr)), sdk.Coins{sdk.NewCoin(sk.GetParams(ctx).BondDenom, initCoins.Sub(amt))}, ) - require.True(t, sdk.NewDecFromInt(amt).Equal(sk.Validator(ctx, addr).GetPower())) + require.True(sdk.IntEq(t, amt, sk.Validator(ctx, addr).GetPower())) // will exist since the validator has been bonded info, found := keeper.getValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address())) @@ -165,7 +165,7 @@ func TestHandleAbsentValidator(t *testing.T) { // 1000 first blocks OK for ; height < keeper.SignedBlocksWindow(ctx); height++ { ctx = ctx.WithBlockHeight(height) - keeper.handleValidatorSignature(ctx, val.Address(), amtInt, true) + keeper.handleValidatorSignature(ctx, val.Address(), amtInt64, true) } info, found = keeper.getValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address())) require.True(t, found) @@ -175,7 +175,7 @@ func TestHandleAbsentValidator(t *testing.T) { // 500 blocks missed for ; height < keeper.SignedBlocksWindow(ctx)+(keeper.SignedBlocksWindow(ctx)-keeper.MinSignedPerWindow(ctx)); height++ { ctx = ctx.WithBlockHeight(height) - keeper.handleValidatorSignature(ctx, val.Address(), amtInt, false) + keeper.handleValidatorSignature(ctx, val.Address(), amtInt64, false) } info, found = keeper.getValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address())) require.True(t, found) @@ -186,11 +186,11 @@ func TestHandleAbsentValidator(t *testing.T) { validator, _ := sk.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(val)) require.Equal(t, sdk.Bonded, validator.GetStatus()) pool := sk.GetPool(ctx) - require.Equal(t, amtInt, pool.BondedTokens.RoundInt64()) + require.Equal(sdk.IntEq(t, amt, pool.BondedTokens)) // 501st block missed ctx = ctx.WithBlockHeight(height) - keeper.handleValidatorSignature(ctx, val.Address(), amtInt, false) + keeper.handleValidatorSignature(ctx, val.Address(), amtInt64, false) info, found = keeper.getValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address())) require.True(t, found) require.Equal(t, int64(0), info.StartHeight) @@ -204,15 +204,15 @@ func TestHandleAbsentValidator(t *testing.T) { validator, _ = sk.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(val)) require.Equal(t, sdk.Unbonding, validator.GetStatus()) - slashAmt := sdk.NewDec(amtInt).Mul(keeper.SlashFractionDowntime(ctx)).RoundInt64() + slashAmt := sdk.NewDec(amtInt64).Mul(keeper.SlashFractionDowntime(ctx)).RoundInt64() // validator should have been slashed - require.Equal(t, amtInt-slashAmt, validator.GetTokens().RoundInt64()) + require.Equal(t, amtInt64-slashAmt, validator.GetTokens().Int64()) // 502nd block *also* missed (since the LastCommit would have still included the just-unbonded validator) height++ ctx = ctx.WithBlockHeight(height) - keeper.handleValidatorSignature(ctx, val.Address(), amtInt, false) + keeper.handleValidatorSignature(ctx, val.Address(), amtInt64, false) info, found = keeper.getValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address())) require.True(t, found) require.Equal(t, int64(0), info.StartHeight) @@ -223,15 +223,15 @@ func TestHandleAbsentValidator(t *testing.T) { // validator should not have been slashed any more, since it was already jailed validator, _ = sk.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(val)) - require.Equal(t, amtInt-slashAmt, validator.GetTokens().RoundInt64()) + require.Equal(t, amtInt64-slashAmt, validator.GetTokens().Int64()) // 502nd block *double signed* (oh no!) - keeper.handleDoubleSign(ctx, val.Address(), height, ctx.BlockHeader().Time, amtInt) + keeper.handleDoubleSign(ctx, val.Address(), height, ctx.BlockHeader().Time, amtInt64) // validator should have been slashed validator, _ = sk.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(val)) - secondSlashAmt := sdk.NewDec(amtInt).Mul(keeper.SlashFractionDoubleSign(ctx)).RoundInt64() - require.Equal(t, amtInt-slashAmt-secondSlashAmt, validator.GetTokens().RoundInt64()) + secondSlashAmt := sdk.NewDec(amtInt64).Mul(keeper.SlashFractionDoubleSign(ctx)).RoundInt64() + require.Equal(t, amtInt64-slashAmt-secondSlashAmt, validator.GetTokens().Int64()) // unrevocation should fail prior to jail expiration got = slh(ctx, NewMsgUnjail(addr)) @@ -251,7 +251,7 @@ func TestHandleAbsentValidator(t *testing.T) { // validator should have been slashed pool = sk.GetPool(ctx) - require.Equal(t, amtInt-slashAmt-secondSlashAmt, pool.BondedTokens.RoundInt64()) + require.Equal(t, amtInt64-slashAmt-secondSlashAmt, pool.BondedTokens.Int64()) // validator start height should not have been changed info, found = keeper.getValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address())) @@ -263,7 +263,7 @@ func TestHandleAbsentValidator(t *testing.T) { // validator should not be immediately jailed again height++ ctx = ctx.WithBlockHeight(height) - keeper.handleValidatorSignature(ctx, val.Address(), amtInt, false) + keeper.handleValidatorSignature(ctx, val.Address(), amtInt64, false) validator, _ = sk.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(val)) require.Equal(t, sdk.Bonded, validator.GetStatus()) @@ -271,7 +271,7 @@ func TestHandleAbsentValidator(t *testing.T) { nextHeight := height + keeper.MinSignedPerWindow(ctx) + 1 for ; height < nextHeight; height++ { ctx = ctx.WithBlockHeight(height) - keeper.handleValidatorSignature(ctx, val.Address(), amtInt, false) + keeper.handleValidatorSignature(ctx, val.Address(), amtInt64, false) } // end block @@ -281,7 +281,7 @@ func TestHandleAbsentValidator(t *testing.T) { nextHeight = height + keeper.MinSignedPerWindow(ctx) + 1 for ; height <= nextHeight; height++ { ctx = ctx.WithBlockHeight(height) - keeper.handleValidatorSignature(ctx, val.Address(), amtInt, false) + keeper.handleValidatorSignature(ctx, val.Address(), amtInt64, false) } // end block @@ -330,7 +330,7 @@ func TestHandleNewValidator(t *testing.T) { validator, _ := sk.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(val)) require.Equal(t, sdk.Bonded, validator.GetStatus()) pool := sk.GetPool(ctx) - require.Equal(t, int64(100), pool.BondedTokens.RoundInt64()) + require.Equal(t, int64(100), pool.BondedTokens.Int64()) } // Test a jailed validator being "down" twice @@ -367,7 +367,7 @@ func TestHandleAlreadyJailed(t *testing.T) { require.Equal(t, sdk.Unbonding, validator.GetStatus()) // validator should have been slashed - require.Equal(t, amtInt-1, validator.GetTokens().RoundInt64()) + require.Equal(t, amtInt-1, validator.GetTokens().Int64()) // another block missed ctx = ctx.WithBlockHeight(height) @@ -375,7 +375,7 @@ func TestHandleAlreadyJailed(t *testing.T) { // validator should not have been slashed twice validator, _ = sk.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(val)) - require.Equal(t, amtInt-1, validator.GetTokens().RoundInt64()) + require.Equal(t, amtInt-1, validator.GetTokens().Int64()) } diff --git a/x/slashing/tick_test.go b/x/slashing/tick_test.go index 932ac51a93ee..0afb6f5cd614 100644 --- a/x/slashing/tick_test.go +++ b/x/slashing/tick_test.go @@ -24,7 +24,7 @@ func TestBeginBlocker(t *testing.T) { t, ck.GetCoins(ctx, sdk.AccAddress(addr)), sdk.Coins{sdk.NewCoin(sk.GetParams(ctx).BondDenom, initCoins.Sub(amt))}, ) - require.True(t, sdk.NewDecFromInt(amt).Equal(sk.Validator(ctx, addr).GetPower())) + require.True(sdk.IntEq(t, amt, sk.Validator(ctx, addr).GetPower())) val := abci.Validator{ Address: pk.Address(), diff --git a/x/stake/app_test.go b/x/stake/app_test.go index de16afde3720..2f496934ac67 100644 --- a/x/stake/app_test.go +++ b/x/stake/app_test.go @@ -58,7 +58,7 @@ func getInitChainer(mapp *mock.App, keeper Keeper) sdk.InitChainer { mapp.InitChainer(ctx, req) stakeGenesis := DefaultGenesisState() - stakeGenesis.Pool.LooseTokens = sdk.NewDec(100000) + stakeGenesis.Pool.LooseTokens = sdk.NewInt(100000) validators, err := InitGenesis(ctx, keeper, stakeGenesis) if err != nil { @@ -133,7 +133,7 @@ func TestStakeMsgs(t *testing.T) { validator := checkValidator(t, mApp, keeper, sdk.ValAddress(addr1), true) require.Equal(t, sdk.ValAddress(addr1), validator.OperatorAddr) require.Equal(t, sdk.Bonded, validator.Status) - require.True(sdk.DecEq(t, sdk.NewDec(10), validator.BondedTokens())) + require.True(sdk.IntEq(t, sdk.NewInt(10), validator.BondedTokens())) // addr1 create validator on behalf of addr2 createValidatorMsgOnBehalfOf := NewMsgCreateValidatorOnBehalfOf( @@ -147,7 +147,7 @@ func TestStakeMsgs(t *testing.T) { validator = checkValidator(t, mApp, keeper, sdk.ValAddress(addr2), true) require.Equal(t, sdk.ValAddress(addr2), validator.OperatorAddr) require.Equal(t, sdk.Bonded, validator.Status) - require.True(sdk.DecEq(t, sdk.NewDec(10), validator.Tokens)) + require.True(sdk.IntEq(t, sdk.NewInt(10), validator.Tokens)) // check the bond that should have been created as well checkDelegation(t, mApp, keeper, addr1, sdk.ValAddress(addr1), true, sdk.NewDec(10)) diff --git a/x/stake/genesis_test.go b/x/stake/genesis_test.go index 3f7295a7a033..787e73ef0800 100644 --- a/x/stake/genesis_test.go +++ b/x/stake/genesis_test.go @@ -19,7 +19,7 @@ func TestInitGenesis(t *testing.T) { ctx, _, keeper := keep.CreateTestInput(t, false, 1000) pool := keeper.GetPool(ctx) - pool.BondedTokens = sdk.NewDec(2) + pool.BondedTokens = sdk.NewInt(2) params := keeper.GetParams(ctx) validators := make([]Validator, 2) @@ -30,13 +30,13 @@ func TestInitGenesis(t *testing.T) { validators[0].ConsPubKey = keep.PKs[0] validators[0].Description = Description{Moniker: "hoop"} validators[0].Status = sdk.Bonded - validators[0].Tokens = sdk.OneDec() + validators[0].Tokens = sdk.OneInt() validators[0].DelegatorShares = sdk.OneDec() validators[1].OperatorAddr = sdk.ValAddress(keep.Addrs[1]) validators[1].ConsPubKey = keep.PKs[1] validators[1].Description = Description{Moniker: "bloop"} validators[1].Status = sdk.Bonded - validators[1].Tokens = sdk.OneDec() + validators[1].Tokens = sdk.OneInt() validators[1].DelegatorShares = sdk.OneDec() genesisState := types.NewGenesisState(pool, params, validators, delegations) @@ -76,7 +76,7 @@ func TestInitGenesisLargeValidatorSet(t *testing.T) { // Assigning 2 to the first 100 vals, 1 to the rest pool := keeper.GetPool(ctx) - pool.BondedTokens = sdk.NewDec(int64(200 + (size - 100))) + pool.BondedTokens = sdk.NewInt(int64(200 + (size - 100))) params := keeper.GetParams(ctx) delegations := []Delegation{} @@ -87,10 +87,10 @@ func TestInitGenesisLargeValidatorSet(t *testing.T) { validators[i].Status = sdk.Bonded if i < 100 { - validators[i].Tokens = sdk.NewDec(2) + validators[i].Tokens = sdk.NewInt(2) validators[i].DelegatorShares = sdk.NewDec(2) } else { - validators[i].Tokens = sdk.OneDec() + validators[i].Tokens = sdk.OneInt() validators[i].DelegatorShares = sdk.OneDec() } } @@ -111,7 +111,7 @@ func TestValidateGenesis(t *testing.T) { genValidators1 := make([]types.Validator, 1, 5) pk := ed25519.GenPrivKey().PubKey() genValidators1[0] = types.NewValidator(sdk.ValAddress(pk.Address()), pk, types.NewDescription("", "", "", "")) - genValidators1[0].Tokens = sdk.OneDec() + genValidators1[0].Tokens = sdk.OneInt() genValidators1[0].DelegatorShares = sdk.OneDec() tests := []struct { diff --git a/x/stake/handler_test.go b/x/stake/handler_test.go index 2c82ee7add83..8d54bf973ae6 100644 --- a/x/stake/handler_test.go +++ b/x/stake/handler_test.go @@ -75,8 +75,8 @@ func TestValidatorByPowerIndex(t *testing.T) { keeper.ApplyAndReturnValidatorSetUpdates(ctx) validator, found = keeper.GetValidator(ctx, validatorAddr) require.True(t, found) - require.Equal(t, sdk.Unbonding, validator.Status) // ensure is unbonding - require.Equal(t, int64(500000), validator.Tokens.RoundInt64()) // ensure tokens slashed + require.Equal(t, sdk.Unbonding, validator.Status) // ensure is unbonding + require.Equal(t, int64(500000), validator.Tokens.Int64()) // ensure tokens slashed keeper.Unjail(ctx, consAddr0) // the old power record should have been deleted as the power changed @@ -127,7 +127,7 @@ func TestDuplicatesMsgCreateValidator(t *testing.T) { assert.Equal(t, sdk.Bonded, validator.Status) assert.Equal(t, addr1, validator.OperatorAddr) assert.Equal(t, pk1, validator.ConsPubKey) - assert.Equal(t, sdk.NewDec(10), validator.BondedTokens()) + assert.Equal(t, int64(10), validator.BondedTokens().Int64()) assert.Equal(t, sdk.NewDec(10), validator.DelegatorShares) assert.Equal(t, Description{}, validator.Description) @@ -156,7 +156,7 @@ func TestDuplicatesMsgCreateValidator(t *testing.T) { assert.Equal(t, sdk.Bonded, validator.Status) assert.Equal(t, addr2, validator.OperatorAddr) assert.Equal(t, pk2, validator.ConsPubKey) - assert.True(sdk.DecEq(t, sdk.NewDec(10), validator.Tokens)) + assert.True(sdk.IntEq(t, sdk.NewInt(10), validator.Tokens)) assert.True(sdk.DecEq(t, sdk.NewDec(10), validator.DelegatorShares)) assert.Equal(t, Description{}, validator.Description) } @@ -200,7 +200,7 @@ func TestDuplicatesMsgCreateValidatorOnBehalfOf(t *testing.T) { assert.Equal(t, sdk.Bonded, validator.Status) assert.Equal(t, validatorAddr, validator.OperatorAddr) assert.Equal(t, pk, validator.ConsPubKey) - assert.True(sdk.DecEq(t, sdk.NewDec(10), validator.Tokens)) + assert.True(sdk.IntEq(t, sdk.NewInt(10), validator.Tokens)) assert.True(sdk.DecEq(t, sdk.NewDec(10), validator.DelegatorShares)) assert.Equal(t, Description{}, validator.Description) @@ -234,7 +234,7 @@ func TestLegacyValidatorDelegations(t *testing.T) { require.True(t, found) require.Equal(t, sdk.Bonded, validator.Status) require.Equal(t, bondAmount, validator.DelegatorShares.RoundInt64()) - require.Equal(t, bondAmount, validator.BondedTokens().RoundInt64()) + require.Equal(t, bondAmount, validator.BondedTokens().Int64()) // delegate tokens to the validator msgDelegate := NewTestMsgDelegate(delAddr, valAddr, bondAmount) @@ -245,7 +245,7 @@ func TestLegacyValidatorDelegations(t *testing.T) { validator, found = keeper.GetValidator(ctx, valAddr) require.True(t, found) require.Equal(t, bondAmount*2, validator.DelegatorShares.RoundInt64()) - require.Equal(t, bondAmount*2, validator.BondedTokens().RoundInt64()) + require.Equal(t, bondAmount*2, validator.BondedTokens().Int64()) // unbond validator total self-delegations (which should jail the validator) unbondShares := sdk.NewDec(10) @@ -285,7 +285,7 @@ func TestLegacyValidatorDelegations(t *testing.T) { validator, found = keeper.GetValidator(ctx, valAddr) require.True(t, found) require.Equal(t, bondAmount*2, validator.DelegatorShares.RoundInt64()) - require.Equal(t, bondAmount*2, validator.Tokens.RoundInt64()) + require.Equal(t, bondAmount*2, validator.Tokens.Int64()) // unjail the validator now that is has non-zero self-delegated shares keeper.Unjail(ctx, valConsAddr) @@ -299,7 +299,7 @@ func TestLegacyValidatorDelegations(t *testing.T) { validator, found = keeper.GetValidator(ctx, valAddr) require.True(t, found) require.Equal(t, bondAmount*3, validator.DelegatorShares.RoundInt64()) - require.Equal(t, bondAmount*3, validator.Tokens.RoundInt64()) + require.Equal(t, bondAmount*3, validator.Tokens.Int64()) // verify new delegation bond, found = keeper.GetDelegation(ctx, delAddr, valAddr) @@ -328,7 +328,7 @@ func TestIncrementsMsgDelegate(t *testing.T) { require.True(t, found) require.Equal(t, sdk.Bonded, validator.Status) require.Equal(t, bondAmount, validator.DelegatorShares.RoundInt64()) - require.Equal(t, bondAmount, validator.BondedTokens().RoundInt64(), "validator: %v", validator) + require.Equal(t, bondAmount, validator.BondedTokens().Int64(), "validator: %v", validator) _, found = keeper.GetDelegation(ctx, delegatorAddr, validatorAddr) require.False(t, found) @@ -340,7 +340,7 @@ func TestIncrementsMsgDelegate(t *testing.T) { pool := keeper.GetPool(ctx) exRate := validator.DelegatorShareExRate() require.True(t, exRate.Equal(sdk.OneDec()), "expected exRate 1 got %v", exRate) - require.Equal(t, bondAmount, pool.BondedTokens.RoundInt64()) + require.Equal(t, bondAmount, pool.BondedTokens.Int64()) // just send the same msgbond multiple times msgDelegate := NewTestMsgDelegate(delegatorAddr, validatorAddr, bondAmount) @@ -410,7 +410,7 @@ func TestIncrementsMsgUnbond(t *testing.T) { validator, found := keeper.GetValidator(ctx, validatorAddr) require.True(t, found) require.Equal(t, initBond*2, validator.DelegatorShares.RoundInt64()) - require.Equal(t, initBond*2, validator.BondedTokens().RoundInt64()) + require.Equal(t, initBond*2, validator.BondedTokens().Int64()) // just send the same msgUnbond multiple times // TODO use decimals here diff --git a/x/stake/keeper/delegation_test.go b/x/stake/keeper/delegation_test.go index 2310f849fd62..95f54ebecfc4 100644 --- a/x/stake/keeper/delegation_test.go +++ b/x/stake/keeper/delegation_test.go @@ -181,7 +181,7 @@ func TestUnbondingDelegation(t *testing.T) { func TestUnbondDelegation(t *testing.T) { ctx, _, keeper := CreateTestInput(t, false, 0) pool := keeper.GetPool(ctx) - pool.LooseTokens = sdk.NewDec(10) + pool.LooseTokens = sdk.NewInt(10) //create a validator and a delegator to that validator validator := types.NewValidator(addrVals[0], PKs[0], types.Description{}) @@ -191,8 +191,8 @@ func TestUnbondDelegation(t *testing.T) { validator = TestingUpdateValidator(keeper, ctx, validator) pool = keeper.GetPool(ctx) - require.Equal(t, int64(10), pool.BondedTokens.RoundInt64()) - require.Equal(t, int64(10), validator.BondedTokens().RoundInt64()) + require.Equal(t, int64(10), pool.BondedTokens.Int64()) + require.Equal(t, int64(10), validator.BondedTokens().Int64()) delegation := types.Delegation{ DelegatorAddr: addrDels[0], @@ -203,7 +203,7 @@ func TestUnbondDelegation(t *testing.T) { amount, err := keeper.unbond(ctx, addrDels[0], addrVals[0], sdk.NewDec(6)) require.NoError(t, err) - require.Equal(t, int64(6), amount.RoundInt64()) // shares to be added to an unbonding delegation / redelegation + require.Equal(t, int64(6), amount.Int64()) // shares to be added to an unbonding delegation / redelegation delegation, found := keeper.GetDelegation(ctx, addrDels[0], addrVals[0]) require.True(t, found) @@ -212,9 +212,9 @@ func TestUnbondDelegation(t *testing.T) { pool = keeper.GetPool(ctx) require.Equal(t, int64(4), delegation.Shares.RoundInt64()) - require.Equal(t, int64(4), validator.BondedTokens().RoundInt64()) - require.Equal(t, int64(6), pool.LooseTokens.RoundInt64(), "%v", pool) - require.Equal(t, int64(4), pool.BondedTokens.RoundInt64()) + require.Equal(t, int64(4), validator.BondedTokens().Int64()) + require.Equal(t, int64(6), pool.LooseTokens.Int64(), "%v", pool) + require.Equal(t, int64(4), pool.BondedTokens.Int64()) } // test removing all self delegation from a validator which should @@ -223,7 +223,7 @@ func TestUndelegateSelfDelegation(t *testing.T) { ctx, _, keeper := CreateTestInput(t, false, 0) pool := keeper.GetPool(ctx) - pool.LooseTokens = sdk.NewDec(20) + pool.LooseTokens = sdk.NewInt(20) //create a validator with a self-delegation validator := types.NewValidator(addrVals[0], PKs[0], types.Description{}) @@ -263,14 +263,14 @@ func TestUndelegateSelfDelegation(t *testing.T) { validator, found := keeper.GetValidator(ctx, addrVals[0]) require.True(t, found) - require.Equal(t, int64(10), validator.Tokens.RoundInt64()) + require.Equal(t, int64(10), validator.Tokens.Int64()) require.Equal(t, sdk.Unbonding, validator.Status) } func TestUndelegateFromUnbondingValidator(t *testing.T) { ctx, _, keeper := CreateTestInput(t, false, 0) pool := keeper.GetPool(ctx) - pool.LooseTokens = sdk.NewDec(20) + pool.LooseTokens = sdk.NewInt(20) //create a validator with a self-delegation validator := types.NewValidator(addrVals[0], PKs[0], types.Description{}) @@ -346,7 +346,7 @@ func TestUndelegateFromUnbondingValidator(t *testing.T) { func TestUndelegateFromUnbondedValidator(t *testing.T) { ctx, _, keeper := CreateTestInput(t, false, 0) pool := keeper.GetPool(ctx) - pool.LooseTokens = sdk.NewDec(20) + pool.LooseTokens = sdk.NewInt(20) //create a validator with a self-delegation validator := types.NewValidator(addrVals[0], PKs[0], types.Description{}) @@ -425,7 +425,7 @@ func TestUndelegateFromUnbondedValidator(t *testing.T) { func TestUnbondingAllDelegationFromValidator(t *testing.T) { ctx, _, keeper := CreateTestInput(t, false, 0) pool := keeper.GetPool(ctx) - pool.LooseTokens = sdk.NewDec(20) + pool.LooseTokens = sdk.NewInt(20) //create a validator with a self-delegation validator := types.NewValidator(addrVals[0], PKs[0], types.Description{}) @@ -585,10 +585,9 @@ func TestRedelegation(t *testing.T) { } func TestRedelegateToSameValidator(t *testing.T) { - ctx, _, keeper := CreateTestInput(t, false, 0) pool := keeper.GetPool(ctx) - pool.LooseTokens = sdk.NewDec(30) + pool.LooseTokens = sdk.NewInt(30) // create a validator with a self-delegation validator := types.NewValidator(addrVals[0], PKs[0], types.Description{}) @@ -611,10 +610,9 @@ func TestRedelegateToSameValidator(t *testing.T) { } func TestRedelegateSelfDelegation(t *testing.T) { - ctx, _, keeper := CreateTestInput(t, false, 0) pool := keeper.GetPool(ctx) - pool.LooseTokens = sdk.NewDec(30) + pool.LooseTokens = sdk.NewInt(30) //create a validator with a self-delegation validator := types.NewValidator(addrVals[0], PKs[0], types.Description{}) @@ -635,7 +633,7 @@ func TestRedelegateSelfDelegation(t *testing.T) { validator2 := types.NewValidator(addrVals[1], PKs[1], types.Description{}) validator2, pool, issuedShares = validator2.AddTokensFromDel(pool, sdk.NewInt(10)) require.Equal(t, int64(10), issuedShares.RoundInt64()) - pool.BondedTokens = pool.BondedTokens.Add(sdk.NewDec(10)) + pool.BondedTokens = pool.BondedTokens.Add(sdk.NewInt(10)) keeper.SetPool(ctx, pool) validator2 = TestingUpdateValidator(keeper, ctx, validator2) require.Equal(t, sdk.Bonded, validator2.Status) @@ -662,14 +660,14 @@ func TestRedelegateSelfDelegation(t *testing.T) { validator, found := keeper.GetValidator(ctx, addrVals[0]) require.True(t, found) - require.Equal(t, int64(10), validator.Tokens.RoundInt64()) + require.Equal(t, int64(10), validator.Tokens.Int64()) require.Equal(t, sdk.Unbonding, validator.Status) } func TestRedelegateFromUnbondingValidator(t *testing.T) { ctx, _, keeper := CreateTestInput(t, false, 0) pool := keeper.GetPool(ctx) - pool.LooseTokens = sdk.NewDec(30) + pool.LooseTokens = sdk.NewInt(30) //create a validator with a self-delegation validator := types.NewValidator(addrVals[0], PKs[0], types.Description{}) @@ -754,7 +752,7 @@ func TestRedelegateFromUnbondingValidator(t *testing.T) { func TestRedelegateFromUnbondedValidator(t *testing.T) { ctx, _, keeper := CreateTestInput(t, false, 0) pool := keeper.GetPool(ctx) - pool.LooseTokens = sdk.NewDec(30) + pool.LooseTokens = sdk.NewInt(30) //create a validator with a self-delegation validator := types.NewValidator(addrVals[0], PKs[0], types.Description{}) diff --git a/x/stake/keeper/keeper_test.go b/x/stake/keeper/keeper_test.go index 9307ddddf252..be45fc20c191 100644 --- a/x/stake/keeper/keeper_test.go +++ b/x/stake/keeper/keeper_test.go @@ -33,7 +33,7 @@ func TestPool(t *testing.T) { require.True(t, expPool.Equal(resPool)) //modify a params, save, and retrieve - expPool.BondedTokens = sdk.NewDec(777) + expPool.BondedTokens = sdk.NewInt(777) keeper.SetPool(ctx, expPool) resPool = keeper.GetPool(ctx) require.True(t, expPool.Equal(resPool)) diff --git a/x/stake/keeper/key_test.go b/x/stake/keeper/key_test.go index 385f313c15b5..6e3e5e58dedf 100644 --- a/x/stake/keeper/key_test.go +++ b/x/stake/keeper/key_test.go @@ -24,12 +24,12 @@ func TestGetValidatorPowerRank(t *testing.T) { valAddr1 := sdk.ValAddress(addr1) emptyDesc := types.Description{} val1 := types.NewValidator(valAddr1, pk1, emptyDesc) - val1.Tokens = sdk.NewDec(0) + val1.Tokens = sdk.ZeroInt() val2, val3, val4 := val1, val1, val1 - val2.Tokens = sdk.NewDec(1) - val3.Tokens = sdk.NewDec(10) + val2.Tokens = sdk.NewInt(1) + val3.Tokens = sdk.NewInt(10) x := new(big.Int).Exp(big.NewInt(2), big.NewInt(40), big.NewInt(0)) - val4.Tokens = sdk.NewDecFromBigInt(x) + val4.Tokens = sdk.NewIntFromBigInt(x) tests := []struct { validator types.Validator diff --git a/x/stake/keeper/slash_test.go b/x/stake/keeper/slash_test.go index 9c23576c34ca..04459fffeb21 100644 --- a/x/stake/keeper/slash_test.go +++ b/x/stake/keeper/slash_test.go @@ -20,14 +20,14 @@ func setupHelper(t *testing.T, amt int64) (sdk.Context, Keeper, types.Params) { params := keeper.GetParams(ctx) pool := keeper.GetPool(ctx) numVals := 3 - pool.LooseTokens = sdk.NewDec(amt * int64(numVals)) + pool.LooseTokens = sdk.NewInt(amt * int64(numVals)) // add numVals validators for i := 0; i < numVals; i++ { validator := types.NewValidator(addrVals[i], PKs[i], types.Description{}) validator, pool, _ = validator.AddTokensFromDel(pool, sdk.NewInt(amt)) validator.BondIntraTxCounter = int16(i) - pool.BondedTokens = pool.BondedTokens.Add(sdk.NewDec(amt)) + pool.BondedTokens = pool.BondedTokens.Add(sdk.NewInt(amt)) keeper.SetPool(ctx, pool) validator = TestingUpdateValidator(keeper, ctx, validator) keeper.SetValidatorByConsAddr(ctx, validator) @@ -84,20 +84,20 @@ func TestSlashUnbondingDelegation(t *testing.T) { // unbonding started prior to the infraction height, stake didn't contribute slashAmount := keeper.slashUnbondingDelegation(ctx, ubd, 1, fraction) - require.Equal(t, int64(0), slashAmount.RoundInt64()) + require.Equal(t, int64(0), slashAmount.Int64()) // after the expiration time, no longer eligible for slashing ctx = ctx.WithBlockHeader(abci.Header{Time: time.Unix(10, 0)}) keeper.SetUnbondingDelegation(ctx, ubd) slashAmount = keeper.slashUnbondingDelegation(ctx, ubd, 0, fraction) - require.Equal(t, int64(0), slashAmount.RoundInt64()) + require.Equal(t, int64(0), slashAmount.Int64()) // test valid slash, before expiration timestamp and to which stake contributed oldPool := keeper.GetPool(ctx) ctx = ctx.WithBlockHeader(abci.Header{Time: time.Unix(0, 0)}) keeper.SetUnbondingDelegation(ctx, ubd) slashAmount = keeper.slashUnbondingDelegation(ctx, ubd, 0, fraction) - require.Equal(t, int64(5), slashAmount.RoundInt64()) + require.Equal(t, int64(5), slashAmount.Int64()) ubd, found := keeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0]) require.True(t, found) @@ -107,7 +107,7 @@ func TestSlashUnbondingDelegation(t *testing.T) { // balance decreased require.Equal(t, sdk.NewInt64Coin(params.BondDenom, 5), ubd.Balance) newPool := keeper.GetPool(ctx) - require.Equal(t, int64(5), oldPool.LooseTokens.Sub(newPool.LooseTokens).RoundInt64()) + require.Equal(t, int64(5), oldPool.LooseTokens.Sub(newPool.LooseTokens).Int64()) } // tests slashRedelegation @@ -142,7 +142,7 @@ func TestSlashRedelegation(t *testing.T) { validator, found := keeper.GetValidator(ctx, addrVals[1]) require.True(t, found) slashAmount := keeper.slashRedelegation(ctx, validator, rd, 1, fraction) - require.Equal(t, int64(0), slashAmount.RoundInt64()) + require.Equal(t, int64(0), slashAmount.Int64()) // after the expiration time, no longer eligible for slashing ctx = ctx.WithBlockHeader(abci.Header{Time: time.Unix(10, 0)}) @@ -150,7 +150,7 @@ func TestSlashRedelegation(t *testing.T) { validator, found = keeper.GetValidator(ctx, addrVals[1]) require.True(t, found) slashAmount = keeper.slashRedelegation(ctx, validator, rd, 0, fraction) - require.Equal(t, int64(0), slashAmount.RoundInt64()) + require.Equal(t, int64(0), slashAmount.Int64()) // test valid slash, before expiration timestamp and to which stake contributed oldPool := keeper.GetPool(ctx) @@ -159,7 +159,7 @@ func TestSlashRedelegation(t *testing.T) { validator, found = keeper.GetValidator(ctx, addrVals[1]) require.True(t, found) slashAmount = keeper.slashRedelegation(ctx, validator, rd, 0, fraction) - require.Equal(t, int64(5), slashAmount.RoundInt64()) + require.Equal(t, int64(5), slashAmount.Int64()) rd, found = keeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1]) require.True(t, found) @@ -180,7 +180,7 @@ func TestSlashRedelegation(t *testing.T) { // pool bonded tokens decreased newPool := keeper.GetPool(ctx) - require.Equal(t, int64(5), oldPool.BondedTokens.Sub(newPool.BondedTokens).RoundInt64()) + require.Equal(t, int64(5), oldPool.BondedTokens.Sub(newPool.BondedTokens).Int64()) } // tests Slash at a future height (must panic) @@ -214,9 +214,9 @@ func TestSlashAtNegativeHeight(t *testing.T) { validator = keeper.mustGetValidator(ctx, validator.OperatorAddr) // power decreased - require.Equal(t, sdk.NewDec(5), validator.GetPower()) + require.True(sdk.IntEq(t, sdk.NewInt(5), validator.GetPower())) // pool bonded shares decreased - require.Equal(t, sdk.NewDec(5).RoundInt64(), oldPool.BondedTokens.Sub(newPool.BondedTokens).RoundInt64()) + require.Equal(t, int64(5), oldPool.BondedTokens.Sub(newPool.BondedTokens).Int64()) } // tests Slash at the current height @@ -241,9 +241,9 @@ func TestSlashValidatorAtCurrentHeight(t *testing.T) { validator = keeper.mustGetValidator(ctx, validator.OperatorAddr) // power decreased - require.Equal(t, sdk.NewDec(5), validator.GetPower()) + require.True(sdk.IntEq(t, sdk.NewInt(5), validator.GetPower())) // pool bonded shares decreased - require.Equal(t, sdk.NewDec(5).RoundInt64(), oldPool.BondedTokens.Sub(newPool.BondedTokens).RoundInt64()) + require.Equal(t, int64(5), oldPool.BondedTokens.Sub(newPool.BondedTokens).Int64()) } // tests Slash at a previous height with an unbonding delegation @@ -283,7 +283,7 @@ func TestSlashWithUnbondingDelegation(t *testing.T) { // read updated pool newPool := keeper.GetPool(ctx) // bonded tokens burned - require.Equal(t, int64(3), oldPool.BondedTokens.Sub(newPool.BondedTokens).RoundInt64()) + require.Equal(t, int64(3), oldPool.BondedTokens.Sub(newPool.BondedTokens).Int64()) // read updated validator validator, found = keeper.GetValidatorByConsAddr(ctx, consAddr) require.True(t, found) @@ -291,7 +291,7 @@ func TestSlashWithUnbondingDelegation(t *testing.T) { // was still bonded at the time of discovery and was slashed by half, 4 stake // bonded at the time of discovery hadn't been bonded at the time of infraction // and wasn't slashed - require.Equal(t, sdk.NewDec(7), validator.GetPower()) + require.True(sdk.IntEq(t, sdk.NewInt(7), validator.GetPower())) // slash validator again ctx = ctx.WithBlockHeight(13) @@ -303,12 +303,12 @@ func TestSlashWithUnbondingDelegation(t *testing.T) { // read updated pool newPool = keeper.GetPool(ctx) // bonded tokens burned again - require.Equal(t, int64(6), oldPool.BondedTokens.Sub(newPool.BondedTokens).RoundInt64()) + require.Equal(t, int64(6), oldPool.BondedTokens.Sub(newPool.BondedTokens).Int64()) // read updated validator validator, found = keeper.GetValidatorByConsAddr(ctx, consAddr) require.True(t, found) // power decreased by 3 again - require.Equal(t, sdk.NewDec(4), validator.GetPower()) + require.True(sdk.IntEq(t, sdk.NewInt(4), validator.GetPower())) // slash validator again // all originally bonded stake has been slashed, so this will have no effect @@ -323,12 +323,12 @@ func TestSlashWithUnbondingDelegation(t *testing.T) { // read updated pool newPool = keeper.GetPool(ctx) // bonded tokens burned again - require.Equal(t, int64(9), oldPool.BondedTokens.Sub(newPool.BondedTokens).RoundInt64()) + require.Equal(t, int64(9), oldPool.BondedTokens.Sub(newPool.BondedTokens).Int64()) // read updated validator validator, found = keeper.GetValidatorByConsAddr(ctx, consAddr) require.True(t, found) // power decreased by 3 again - require.Equal(t, sdk.NewDec(1), validator.GetPower()) + require.True(sdk.IntEq(t, sdk.NewInt(1), validator.GetPower())) // slash validator again // all originally bonded stake has been slashed, so this will have no effect @@ -343,7 +343,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, int64(10), oldPool.BondedTokens.Sub(newPool.BondedTokens).RoundInt64()) + require.Equal(t, int64(10), oldPool.BondedTokens.Sub(newPool.BondedTokens).Int64()) // apply TM updates keeper.ApplyAndReturnValidatorSetUpdates(ctx) // read updated validator @@ -383,7 +383,7 @@ func TestSlashWithRedelegation(t *testing.T) { // update bonded tokens pool := keeper.GetPool(ctx) - pool.BondedTokens = pool.BondedTokens.Add(sdk.NewDec(6)) + pool.BondedTokens = pool.BondedTokens.Add(sdk.NewInt(6)) keeper.SetPool(ctx, pool) // slash validator @@ -401,7 +401,7 @@ func TestSlashWithRedelegation(t *testing.T) { // read updated pool newPool := keeper.GetPool(ctx) // bonded tokens burned - require.Equal(t, int64(5), oldPool.BondedTokens.Sub(newPool.BondedTokens).RoundInt64()) + require.Equal(t, int64(5), oldPool.BondedTokens.Sub(newPool.BondedTokens).Int64()) // read updated validator validator, found = keeper.GetValidatorByConsAddr(ctx, consAddr) require.True(t, found) @@ -409,7 +409,7 @@ func TestSlashWithRedelegation(t *testing.T) { // was still bonded at the time of discovery and was slashed by half, 4 stake // bonded at the time of discovery hadn't been bonded at the time of infraction // and wasn't slashed - require.Equal(t, sdk.NewDec(8), validator.GetPower()) + require.True(sdk.IntEq(t, sdk.NewInt(8), validator.GetPower())) // slash the validator again ctx = ctx.WithBlockHeight(12) @@ -425,12 +425,12 @@ func TestSlashWithRedelegation(t *testing.T) { // read updated pool newPool = keeper.GetPool(ctx) // seven bonded tokens burned - require.Equal(t, int64(12), oldPool.BondedTokens.Sub(newPool.BondedTokens).RoundInt64()) + require.Equal(t, int64(12), oldPool.BondedTokens.Sub(newPool.BondedTokens).Int64()) // read updated validator validator, found = keeper.GetValidatorByConsAddr(ctx, consAddr) require.True(t, found) // power decreased by 4 - require.Equal(t, sdk.NewDec(4), validator.GetPower()) + require.True(sdk.IntEq(t, sdk.NewInt(4), validator.GetPower())) // slash the validator again, by 100% ctx = ctx.WithBlockHeight(12) @@ -446,7 +446,7 @@ func TestSlashWithRedelegation(t *testing.T) { // read updated pool newPool = keeper.GetPool(ctx) // four more bonded tokens burned - require.Equal(t, int64(16), oldPool.BondedTokens.Sub(newPool.BondedTokens).RoundInt64()) + require.Equal(t, int64(16), oldPool.BondedTokens.Sub(newPool.BondedTokens).Int64()) // apply TM updates keeper.ApplyAndReturnValidatorSetUpdates(ctx) // read updated validator @@ -470,7 +470,7 @@ func TestSlashWithRedelegation(t *testing.T) { // read updated pool newPool = keeper.GetPool(ctx) // no more bonded tokens burned - require.Equal(t, int64(16), oldPool.BondedTokens.Sub(newPool.BondedTokens).RoundInt64()) + require.Equal(t, int64(16), oldPool.BondedTokens.Sub(newPool.BondedTokens).Int64()) // read updated validator // power still zero, still in unbonding period validator, _ = keeper.GetValidatorByConsAddr(ctx, consAddr) @@ -533,12 +533,12 @@ func TestSlashBoth(t *testing.T) { // read updated pool newPool := keeper.GetPool(ctx) // loose tokens burned - require.Equal(t, int64(2), oldPool.LooseTokens.Sub(newPool.LooseTokens).RoundInt64()) + require.Equal(t, int64(2), oldPool.LooseTokens.Sub(newPool.LooseTokens).Int64()) // bonded tokens burned - require.Equal(t, int64(3), oldPool.BondedTokens.Sub(newPool.BondedTokens).RoundInt64()) + require.Equal(t, int64(3), oldPool.BondedTokens.Sub(newPool.BondedTokens).Int64()) // read updated validator validator, found = keeper.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(PKs[0])) require.True(t, found) // power not decreased, all stake was bonded since - require.Equal(t, sdk.NewDec(10), validator.GetPower()) + require.True(sdk.IntEq(t, sdk.NewInt(10), validator.GetPower())) } diff --git a/x/stake/keeper/validator_test.go b/x/stake/keeper/validator_test.go index fe806335f093..bafd67273d06 100644 --- a/x/stake/keeper/validator_test.go +++ b/x/stake/keeper/validator_test.go @@ -26,7 +26,7 @@ func TestSetValidator(t *testing.T) { validator := types.NewValidator(valAddr, valPubKey, types.Description{}) validator, pool, _ = validator.AddTokensFromDel(pool, sdk.NewInt(10)) require.Equal(t, sdk.Unbonded, validator.Status) - assert.True(sdk.DecEq(t, sdk.NewDec(10), validator.Tokens)) + assert.True(sdk.IntEq(t, sdk.NewInt(10), validator.Tokens)) assert.True(sdk.DecEq(t, sdk.NewDec(10), validator.DelegatorShares)) keeper.SetPool(ctx, pool) keeper.SetValidator(ctx, validator) @@ -41,7 +41,7 @@ func TestSetValidator(t *testing.T) { // after the save the validator should be bonded require.Equal(t, sdk.Bonded, validator.Status) - assert.True(sdk.DecEq(t, sdk.NewDec(10), validator.Tokens)) + assert.True(sdk.IntEq(t, sdk.NewInt(10), validator.Tokens)) assert.True(sdk.DecEq(t, sdk.NewDec(10), validator.DelegatorShares)) // Check each store for being saved @@ -74,8 +74,8 @@ func TestUpdateValidatorByPowerIndex(t *testing.T) { pool := keeper.GetPool(ctx) // create a random pool - pool.LooseTokens = sdk.NewDec(10000) - pool.BondedTokens = sdk.NewDec(1234) + pool.LooseTokens = sdk.NewInt(10000) + pool.BondedTokens = sdk.NewInt(1234) keeper.SetPool(ctx, pool) // add a validator @@ -122,8 +122,8 @@ func TestUpdateBondedValidatorsDecreaseCliff(t *testing.T) { keeper.SetParams(ctx, params) // create a random pool - pool.LooseTokens = sdk.NewDec(10000) - pool.BondedTokens = sdk.NewDec(1234) + pool.LooseTokens = sdk.NewInt(10000) + pool.BondedTokens = sdk.NewInt(1234) keeper.SetPool(ctx, pool) validators := make([]types.Validator, numVals) @@ -206,9 +206,9 @@ func TestValidatorBasics(t *testing.T) { validators[i], pool, _ = validators[i].AddTokensFromDel(pool, sdk.NewInt(amt)) keeper.SetPool(ctx, pool) } - assert.True(sdk.DecEq(t, sdk.NewDec(9), validators[0].Tokens)) - assert.True(sdk.DecEq(t, sdk.NewDec(8), validators[1].Tokens)) - assert.True(sdk.DecEq(t, sdk.NewDec(7), validators[2].Tokens)) + assert.True(sdk.IntEq(t, sdk.NewInt(9), validators[0].Tokens)) + assert.True(sdk.IntEq(t, sdk.NewInt(8), validators[1].Tokens)) + assert.True(sdk.IntEq(t, sdk.NewInt(7), validators[2].Tokens)) // check the empty keeper first _, found := keeper.GetValidator(ctx, addrVals[0]) @@ -241,14 +241,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.DecEq(t, sdk.NewDec(9), validators[0].BondedTokens())) + assert.True(sdk.IntEq(t, sdk.NewInt(9), validators[0].BondedTokens())) pool = keeper.GetPool(ctx) assert.True(sdk.DecEq(t, pool.BondedTokens, validators[0].BondedTokens())) // modify a records, save, and retrieve validators[0].Status = sdk.Bonded - validators[0].Tokens = sdk.NewDec(10) + validators[0].Tokens = sdk.NewInt(10) validators[0].DelegatorShares = sdk.NewDec(10) validators[0] = TestingUpdateValidator(keeper, ctx, validators[0]) resVal, found = keeper.GetValidator(ctx, addrVals[0]) @@ -294,7 +294,7 @@ func GetValidatorSortingUnmixed(t *testing.T) { for i, amt := range amts { validators[i] = types.NewValidator(sdk.ValAddress(Addrs[i]), PKs[i], types.Description{}) validators[i].Status = sdk.Bonded - validators[i].Tokens = sdk.NewDec(amt) + validators[i].Tokens = sdk.NewInt(amt) validators[i].DelegatorShares = sdk.NewDec(amt) TestingUpdateValidator(keeper, ctx, validators[i]) } @@ -302,11 +302,11 @@ func GetValidatorSortingUnmixed(t *testing.T) { // first make sure everything made it in to the gotValidator group resValidators := keeper.GetBondedValidatorsByPower(ctx) assert.Equal(t, n, len(resValidators)) - assert.Equal(t, sdk.NewDec(400), resValidators[0].BondedTokens(), "%v", resValidators) - assert.Equal(t, sdk.NewDec(200), resValidators[1].BondedTokens(), "%v", resValidators) - assert.Equal(t, sdk.NewDec(100), resValidators[2].BondedTokens(), "%v", resValidators) - assert.Equal(t, sdk.NewDec(1), resValidators[3].BondedTokens(), "%v", resValidators) - assert.Equal(t, sdk.NewDec(0), resValidators[4].BondedTokens(), "%v", resValidators) + assert.Equal(t, sdk.NewInt(400), resValidators[0].BondedTokens(), "%v", resValidators) + assert.Equal(t, sdk.NewInt(200), resValidators[1].BondedTokens(), "%v", resValidators) + assert.Equal(t, sdk.NewInt(100), resValidators[2].BondedTokens(), "%v", resValidators) + assert.Equal(t, sdk.NewInt(1), resValidators[3].BondedTokens(), "%v", resValidators) + assert.Equal(t, sdk.NewInt(0), resValidators[4].BondedTokens(), "%v", resValidators) assert.Equal(t, validators[3].OperatorAddr, resValidators[0].OperatorAddr, "%v", resValidators) assert.Equal(t, validators[4].OperatorAddr, resValidators[1].OperatorAddr, "%v", resValidators) assert.Equal(t, validators[1].OperatorAddr, resValidators[2].OperatorAddr, "%v", resValidators) @@ -314,14 +314,14 @@ func GetValidatorSortingUnmixed(t *testing.T) { assert.Equal(t, validators[0].OperatorAddr, resValidators[4].OperatorAddr, "%v", resValidators) // test a basic increase in voting power - validators[3].Tokens = sdk.NewDec(500) + validators[3].Tokens = sdk.NewInt(500) TestingUpdateValidator(keeper, ctx, validators[3]) resValidators = keeper.GetBondedValidatorsByPower(ctx) require.Equal(t, len(resValidators), n) assert.True(ValEq(t, validators[3], resValidators[0])) // test a decrease in voting power - validators[3].Tokens = sdk.NewDec(300) + validators[3].Tokens = sdk.NewInt(300) TestingUpdateValidator(keeper, ctx, validators[3]) resValidators = keeper.GetBondedValidatorsByPower(ctx) require.Equal(t, len(resValidators), n) @@ -329,7 +329,7 @@ func GetValidatorSortingUnmixed(t *testing.T) { assert.True(ValEq(t, validators[4], resValidators[1])) // test equal voting power, different age - validators[3].Tokens = sdk.NewDec(200) + validators[3].Tokens = sdk.NewInt(200) ctx = ctx.WithBlockHeight(10) TestingUpdateValidator(keeper, ctx, validators[3]) resValidators = keeper.GetBondedValidatorsByPower(ctx) @@ -348,8 +348,8 @@ func GetValidatorSortingUnmixed(t *testing.T) { assert.True(ValEq(t, validators[4], resValidators[1])) // change in voting power of both validators, both still in v-set, no age change - validators[3].Tokens = sdk.NewDec(300) - validators[4].Tokens = sdk.NewDec(300) + validators[3].Tokens = sdk.NewInt(300) + validators[4].Tokens = sdk.NewInt(300) TestingUpdateValidator(keeper, ctx, validators[3]) resValidators = keeper.GetBondedValidatorsByPower(ctx) require.Equal(t, len(resValidators), n) @@ -382,14 +382,14 @@ func GetValidatorSortingMixed(t *testing.T) { validators[0].Status = sdk.Bonded validators[1].Status = sdk.Bonded validators[2].Status = sdk.Bonded - validators[0].Tokens = sdk.NewDec(amts[0]) - validators[1].Tokens = sdk.NewDec(amts[1]) - validators[2].Tokens = sdk.NewDec(amts[2]) + validators[0].Tokens = sdk.NewInt(amts[0]) + validators[1].Tokens = sdk.NewInt(amts[1]) + validators[2].Tokens = sdk.NewInt(amts[2]) validators[3].Status = sdk.Bonded validators[4].Status = sdk.Bonded - validators[3].Tokens = sdk.NewDec(amts[3]) - validators[4].Tokens = sdk.NewDec(amts[4]) + validators[3].Tokens = sdk.NewInt(amts[3]) + validators[4].Tokens = sdk.NewInt(amts[4]) for i := range amts { TestingUpdateValidator(keeper, ctx, validators[i]) @@ -413,11 +413,11 @@ func GetValidatorSortingMixed(t *testing.T) { // first make sure everything made it in to the gotValidator group resValidators := keeper.GetBondedValidatorsByPower(ctx) assert.Equal(t, n, len(resValidators)) - assert.Equal(t, sdk.NewDec(400), resValidators[0].BondedTokens(), "%v", resValidators) - assert.Equal(t, sdk.NewDec(200), resValidators[1].BondedTokens(), "%v", resValidators) - assert.Equal(t, sdk.NewDec(100), resValidators[2].BondedTokens(), "%v", resValidators) - assert.Equal(t, sdk.NewDec(1), resValidators[3].BondedTokens(), "%v", resValidators) - assert.Equal(t, sdk.NewDec(0), resValidators[4].BondedTokens(), "%v", resValidators) + assert.Equal(t, sdk.NewInt(400), resValidators[0].BondedTokens(), "%v", resValidators) + assert.Equal(t, sdk.NewInt(200), resValidators[1].BondedTokens(), "%v", resValidators) + assert.Equal(t, sdk.NewInt(100), resValidators[2].BondedTokens(), "%v", resValidators) + assert.Equal(t, sdk.NewInt(1), resValidators[3].BondedTokens(), "%v", resValidators) + assert.Equal(t, sdk.NewInt(0), resValidators[4].BondedTokens(), "%v", resValidators) assert.Equal(t, validators[3].OperatorAddr, resValidators[0].OperatorAddr, "%v", resValidators) assert.Equal(t, validators[4].OperatorAddr, resValidators[1].OperatorAddr, "%v", resValidators) assert.Equal(t, validators[1].OperatorAddr, resValidators[2].OperatorAddr, "%v", resValidators) @@ -678,7 +678,7 @@ func TestApplyAndReturnValidatorSetUpdatesSingleValueChange(t *testing.T) { // test single value change // tendermintUpdate set: {} -> {c1'} validators[0].Status = sdk.Bonded - validators[0].Tokens = sdk.NewDec(600) + validators[0].Tokens = sdk.NewInt(600) validators[0] = TestingUpdateValidator(keeper, ctx, validators[0]) updates := keeper.ApplyAndReturnValidatorSetUpdates(ctx) @@ -820,8 +820,8 @@ func TestApplyAndReturnValidatorSetUpdatesPowerDecrease(t *testing.T) { require.Equal(t, 0, len(keeper.ApplyAndReturnValidatorSetUpdates(ctx))) // check initial power - require.Equal(t, sdk.NewDec(100).RoundInt64(), validators[0].GetPower().RoundInt64()) - require.Equal(t, sdk.NewDec(100).RoundInt64(), validators[1].GetPower().RoundInt64()) + require.Equal(t, int64(100), validators[0].GetPower().Int64()) + require.Equal(t, int64(100), validators[1].GetPower().Int64()) // test multiple value change // tendermintUpdate set: {c1, c3} -> {c1', c3'} @@ -833,8 +833,8 @@ func TestApplyAndReturnValidatorSetUpdatesPowerDecrease(t *testing.T) { validators[1] = TestingUpdateValidator(keeper, ctx, validators[1]) // power has changed - require.Equal(t, sdk.NewDec(80).RoundInt64(), validators[0].GetPower().RoundInt64()) - require.Equal(t, sdk.NewDec(70).RoundInt64(), validators[1].GetPower().RoundInt64()) + require.Equal(t, int64(80), validators[0].GetPower().Int64()) + require.Equal(t, int64(70), validators[1].GetPower().Int64()) // Tendermint updates should reflect power change updates := keeper.ApplyAndReturnValidatorSetUpdates(ctx) diff --git a/x/stake/types/pool_test.go b/x/stake/types/pool_test.go index 4541edd3d9c7..34850f29fba9 100644 --- a/x/stake/types/pool_test.go +++ b/x/stake/types/pool_test.go @@ -11,28 +11,28 @@ func TestPoolEqual(t *testing.T) { p1 := InitialPool() p2 := InitialPool() require.True(t, p1.Equal(p2)) - p2.BondedTokens = sdk.NewDec(3) + p2.BondedTokens = sdk.NewInt(3) require.False(t, p1.Equal(p2)) } func TestAddBondedTokens(t *testing.T) { pool := InitialPool() - pool.LooseTokens = sdk.NewDec(10) - pool.BondedTokens = sdk.NewDec(10) + pool.LooseTokens = sdk.NewInt(10) + pool.BondedTokens = sdk.NewInt(10) - pool = pool.looseTokensToBonded(sdk.NewDec(10)) + pool = pool.looseTokensToBonded(sdk.NewInt(10)) - require.True(sdk.DecEq(t, sdk.NewDec(20), pool.BondedTokens)) - require.True(sdk.DecEq(t, sdk.NewDec(0), pool.LooseTokens)) + require.True(sdk.IntEq(t, sdk.NewInt(20), pool.BondedTokens)) + require.True(sdk.IntEq(t, sdk.NewInt(0), pool.LooseTokens)) } func TestRemoveBondedTokens(t *testing.T) { pool := InitialPool() - pool.LooseTokens = sdk.NewDec(10) - pool.BondedTokens = sdk.NewDec(10) + pool.LooseTokens = sdk.NewInt(10) + pool.BondedTokens = sdk.NewInt(10) - pool = pool.bondedTokensToLoose(sdk.NewDec(5)) + pool = pool.bondedTokensToLoose(sdk.NewInt(5)) - require.True(sdk.DecEq(t, sdk.NewDec(5), pool.BondedTokens)) - require.True(sdk.DecEq(t, sdk.NewDec(15), pool.LooseTokens)) + require.True(sdk.IntEq(t, sdk.NewInt(5), pool.BondedTokens)) + require.True(sdk.IntEq(t, sdk.NewInt(15), pool.LooseTokens)) } diff --git a/x/stake/types/validator_test.go b/x/stake/types/validator_test.go index b01b2b7444fc..9a5f686ca391 100644 --- a/x/stake/types/validator_test.go +++ b/x/stake/types/validator_test.go @@ -59,7 +59,7 @@ func TestABCIValidatorUpdate(t *testing.T) { abciVal := validator.ABCIValidatorUpdate() require.Equal(t, tmtypes.TM2PB.PubKey(validator.ConsPubKey), abciVal.PubKey) - require.Equal(t, validator.BondedTokens().RoundInt64(), abciVal.Power) + require.Equal(t, validator.BondedTokens().Int64(), abciVal.Power) } func TestABCIValidatorUpdateZero(t *testing.T) { @@ -76,38 +76,38 @@ func TestRemoveTokens(t *testing.T) { OperatorAddr: addr1, ConsPubKey: pk1, Status: sdk.Bonded, - Tokens: sdk.NewDec(100), + Tokens: sdk.NewInt(100), DelegatorShares: sdk.NewDec(100), } pool := InitialPool() - pool.LooseTokens = sdk.NewDec(10) + pool.LooseTokens = sdk.NewInt(10) pool.BondedTokens = validator.BondedTokens() validator, pool = validator.UpdateStatus(pool, sdk.Bonded) require.Equal(t, sdk.Bonded, validator.Status) // remove tokens and test check everything - validator, pool = validator.RemoveTokens(pool, sdk.NewDec(10)) - require.Equal(t, int64(90), validator.Tokens.RoundInt64()) - require.Equal(t, int64(90), pool.BondedTokens.RoundInt64()) - require.Equal(t, int64(20), pool.LooseTokens.RoundInt64()) + validator, pool = validator.RemoveTokens(pool, sdk.NewInt(10)) + require.Equal(t, int64(90), validator.Tokens.Int64()) + require.Equal(t, int64(90), pool.BondedTokens.Int64()) + require.Equal(t, int64(20), pool.LooseTokens.Int64()) // update validator to unbonded and remove some more tokens validator, pool = validator.UpdateStatus(pool, sdk.Unbonded) require.Equal(t, sdk.Unbonded, validator.Status) - require.Equal(t, int64(0), pool.BondedTokens.RoundInt64()) - require.Equal(t, int64(110), pool.LooseTokens.RoundInt64()) + require.Equal(t, int64(0), pool.BondedTokens.Int64()) + require.Equal(t, int64(110), pool.LooseTokens.Int64()) - validator, pool = validator.RemoveTokens(pool, sdk.NewDec(10)) - require.Equal(t, int64(80), validator.Tokens.RoundInt64()) - require.Equal(t, int64(0), pool.BondedTokens.RoundInt64()) - require.Equal(t, int64(110), pool.LooseTokens.RoundInt64()) + validator, pool = validator.RemoveTokens(pool, sdk.NewInt(10)) + require.Equal(t, int64(80), validator.Tokens.Int64()) + require.Equal(t, int64(0), pool.BondedTokens.Int64()) + require.Equal(t, int64(110), pool.LooseTokens.Int64()) } func TestAddTokensValidatorBonded(t *testing.T) { pool := InitialPool() - pool.LooseTokens = sdk.NewDec(10) + pool.LooseTokens = sdk.NewInt(10) validator := NewValidator(addr1, pk1, Description{}) validator, pool = validator.UpdateStatus(pool, sdk.Bonded) validator, pool, delShares := validator.AddTokensFromDel(pool, sdk.NewInt(10)) @@ -115,12 +115,12 @@ func TestAddTokensValidatorBonded(t *testing.T) { require.Equal(t, sdk.OneDec(), validator.DelegatorShareExRate()) assert.True(sdk.DecEq(t, sdk.NewDec(10), delShares)) - assert.True(sdk.DecEq(t, sdk.NewDec(10), validator.BondedTokens())) + assert.True(sdk.IntEq(t, sdk.NewInt(10), validator.BondedTokens())) } func TestAddTokensValidatorUnbonding(t *testing.T) { pool := InitialPool() - pool.LooseTokens = sdk.NewDec(10) + pool.LooseTokens = sdk.NewInt(10) validator := NewValidator(addr1, pk1, Description{}) validator, pool = validator.UpdateStatus(pool, sdk.Unbonding) validator, pool, delShares := validator.AddTokensFromDel(pool, sdk.NewInt(10)) @@ -129,12 +129,12 @@ func TestAddTokensValidatorUnbonding(t *testing.T) { assert.True(sdk.DecEq(t, sdk.NewDec(10), delShares)) assert.Equal(t, sdk.Unbonding, validator.Status) - assert.True(sdk.DecEq(t, sdk.NewDec(10), validator.Tokens)) + assert.True(sdk.IntEq(t, sdk.NewInt(10), validator.Tokens)) } func TestAddTokensValidatorUnbonded(t *testing.T) { pool := InitialPool() - pool.LooseTokens = sdk.NewDec(10) + pool.LooseTokens = sdk.NewInt(10) validator := NewValidator(addr1, pk1, Description{}) validator, pool = validator.UpdateStatus(pool, sdk.Unbonded) validator, pool, delShares := validator.AddTokensFromDel(pool, sdk.NewInt(10)) @@ -143,7 +143,7 @@ func TestAddTokensValidatorUnbonded(t *testing.T) { assert.True(sdk.DecEq(t, sdk.NewDec(10), delShares)) assert.Equal(t, sdk.Unbonded, validator.Status) - assert.True(sdk.DecEq(t, sdk.NewDec(10), validator.Tokens)) + assert.True(sdk.IntEq(t, sdk.NewInt(10), validator.Tokens)) } // TODO refactor to make simpler like the AddToken tests above @@ -152,29 +152,29 @@ func TestRemoveDelShares(t *testing.T) { OperatorAddr: addr1, ConsPubKey: pk1, Status: sdk.Bonded, - Tokens: sdk.NewDec(100), + Tokens: sdk.NewInt(100), DelegatorShares: sdk.NewDec(100), } poolA := InitialPool() - poolA.LooseTokens = sdk.NewDec(10) + poolA.LooseTokens = sdk.NewInt(10) poolA.BondedTokens = valA.BondedTokens() require.Equal(t, valA.DelegatorShareExRate(), sdk.OneDec()) // Remove delegator shares valB, poolB, coinsB := valA.RemoveDelShares(poolA, sdk.NewDec(10)) - assert.Equal(t, int64(10), coinsB.RoundInt64()) + assert.Equal(t, int64(10), coinsB.Int64()) assert.Equal(t, int64(90), valB.DelegatorShares.RoundInt64()) - assert.Equal(t, int64(90), valB.BondedTokens().RoundInt64()) - assert.Equal(t, int64(90), poolB.BondedTokens.RoundInt64()) - assert.Equal(t, int64(20), poolB.LooseTokens.RoundInt64()) + assert.Equal(t, int64(90), valB.BondedTokens().Int64()) + assert.Equal(t, int64(90), poolB.BondedTokens.Int64()) + assert.Equal(t, int64(20), poolB.LooseTokens.Int64()) // conservation of tokens - require.True(sdk.DecEq(t, + require.True(sdk.IntEq(t, poolB.LooseTokens.Add(poolB.BondedTokens), poolA.LooseTokens.Add(poolA.BondedTokens))) // specific case from random tests - poolTokens := sdk.NewDec(5102) + poolTokens := sdk.NewInt(5102) delShares := sdk.NewDec(115) validator := Validator{ OperatorAddr: addr1, @@ -184,48 +184,45 @@ func TestRemoveDelShares(t *testing.T) { DelegatorShares: delShares, } pool := Pool{ - BondedTokens: sdk.NewDec(248305), - LooseTokens: sdk.NewDec(232147), + BondedTokens: sdk.NewInt(248305), + LooseTokens: sdk.NewInt(232147), } shares := sdk.NewDec(29) _, newPool, tokens := validator.RemoveDelShares(pool, shares) - exp, err := sdk.NewDecFromStr("1286.5913043477") - require.NoError(t, err) - - require.True(sdk.DecEq(t, exp, tokens)) + require.True(sdk.IntEq(t, sdk.NewInt(1286), tokens)) - require.True(sdk.DecEq(t, + require.True(sdk.IntEq(t, newPool.LooseTokens.Add(newPool.BondedTokens), pool.LooseTokens.Add(pool.BondedTokens))) } func TestUpdateStatus(t *testing.T) { pool := InitialPool() - pool.LooseTokens = sdk.NewDec(100) + pool.LooseTokens = sdk.NewInt(100) validator := NewValidator(addr1, pk1, Description{}) validator, pool, _ = validator.AddTokensFromDel(pool, sdk.NewInt(100)) require.Equal(t, sdk.Unbonded, validator.Status) - require.Equal(t, int64(100), validator.Tokens.RoundInt64()) - require.Equal(t, int64(0), pool.BondedTokens.RoundInt64()) - require.Equal(t, int64(100), pool.LooseTokens.RoundInt64()) + require.Equal(t, int64(100), validator.Tokens.Int64()) + require.Equal(t, int64(0), pool.BondedTokens.Int64()) + require.Equal(t, int64(100), pool.LooseTokens.Int64()) validator, pool = validator.UpdateStatus(pool, sdk.Bonded) require.Equal(t, sdk.Bonded, validator.Status) - require.Equal(t, int64(100), validator.Tokens.RoundInt64()) - require.Equal(t, int64(100), pool.BondedTokens.RoundInt64()) - require.Equal(t, int64(0), pool.LooseTokens.RoundInt64()) + require.Equal(t, int64(100), validator.Tokens.Int64()) + require.Equal(t, int64(100), pool.BondedTokens.Int64()) + require.Equal(t, int64(0), pool.LooseTokens.Int64()) validator, pool = validator.UpdateStatus(pool, sdk.Unbonding) require.Equal(t, sdk.Unbonding, validator.Status) - require.Equal(t, int64(100), validator.Tokens.RoundInt64()) - require.Equal(t, int64(0), pool.BondedTokens.RoundInt64()) - require.Equal(t, int64(100), pool.LooseTokens.RoundInt64()) + require.Equal(t, int64(100), validator.Tokens.Int64()) + require.Equal(t, int64(0), pool.BondedTokens.Int64()) + require.Equal(t, int64(100), pool.LooseTokens.Int64()) } func TestPossibleOverflow(t *testing.T) { - poolTokens := sdk.NewDec(2159) + poolTokens := sdk.NewInt(2159) delShares := sdk.NewDec(391432570689183511).Quo(sdk.NewDec(40113011844664)) validator := Validator{ OperatorAddr: addr1, @@ -235,7 +232,7 @@ func TestPossibleOverflow(t *testing.T) { DelegatorShares: delShares, } pool := Pool{ - LooseTokens: sdk.NewDec(100), + LooseTokens: sdk.NewInt(100), BondedTokens: poolTokens, } tokens := int64(71) From 56a63876a76e7e2144530f22f30fded1056457a7 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Fri, 30 Nov 2018 03:56:12 -0500 Subject: [PATCH 04/18] all test compile errors resolved --- docs/examples/democoin/x/oracle/handler.go | 6 +++--- docs/examples/democoin/x/oracle/keeper.go | 2 +- x/slashing/keeper_test.go | 12 ++++++------ x/stake/keeper/validator_test.go | 16 ++++++++-------- 4 files changed, 18 insertions(+), 18 deletions(-) diff --git a/docs/examples/democoin/x/oracle/handler.go b/docs/examples/democoin/x/oracle/handler.go index fb7587a12683..818ca32fbab8 100644 --- a/docs/examples/democoin/x/oracle/handler.go +++ b/docs/examples/democoin/x/oracle/handler.go @@ -14,7 +14,7 @@ func (keeper Keeper) update(ctx sdk.Context, val sdk.Validator, valset sdk.Valid // Return if the voted power is not bigger than required power totalPower := valset.TotalPower(ctx) - requiredPower := totalPower.Mul(keeper.supermaj) + requiredPower := keeper.supermaj.MulInt(totalPower).RoundInt() if !info.Power.GT(requiredPower) { return info } @@ -23,7 +23,7 @@ func (keeper Keeper) update(ctx sdk.Context, val sdk.Validator, valset sdk.Valid // and recalculate voted power hash := ctx.BlockHeader().ValidatorsHash if !bytes.Equal(hash, info.Hash) { - info.Power = sdk.ZeroDec() + info.Power = sdk.ZeroInt() info.Hash = hash prefix := GetSignPrefix(p, keeper.cdc) store := ctx.KVStore(keeper.key) @@ -36,7 +36,7 @@ func (keeper Keeper) update(ctx sdk.Context, val sdk.Validator, valset sdk.Valid } info.Power = info.Power.Add(val.GetPower()) } - if !info.Power.GT(totalPower.Mul(keeper.supermaj)) { + if !info.Power.GT(keeper.supermaj.MulInt(totalPower).RoundInt()) { return info } } diff --git a/docs/examples/democoin/x/oracle/keeper.go b/docs/examples/democoin/x/oracle/keeper.go index 50f210eb5fed..1b87db319349 100644 --- a/docs/examples/democoin/x/oracle/keeper.go +++ b/docs/examples/democoin/x/oracle/keeper.go @@ -55,7 +55,7 @@ type Info struct { // EmptyInfo construct an empty Info func EmptyInfo(ctx sdk.Context) Info { return Info{ - Power: sdk.ZeroDec(), + Power: sdk.ZeroInt(), Hash: ctx.BlockHeader().ValidatorsHash, LastSigned: ctx.BlockHeight(), Status: Pending, diff --git a/x/slashing/keeper_test.go b/x/slashing/keeper_test.go index 7a805be4d093..638147e5d083 100644 --- a/x/slashing/keeper_test.go +++ b/x/slashing/keeper_test.go @@ -52,18 +52,18 @@ func TestHandleDoubleSign(t *testing.T) { // unjail to measure power sk.Unjail(ctx, sdk.ConsAddress(val.Address())) // power should be reduced - require.Equal( - t, sdk.NewDecFromInt(amt).Mul(sdk.NewDec(19).Quo(sdk.NewDec(20))), + require.True(sdk.IntEq( + t, amt.Mul(sdk.NewInt(19)).Div(sdk.NewInt(20)), sk.Validator(ctx, operatorAddr).GetPower(), - ) + )) ctx = ctx.WithBlockHeader(abci.Header{Time: time.Unix(1, 0).Add(keeper.MaxEvidenceAge(ctx))}) // double sign past max age keeper.handleDoubleSign(ctx, val.Address(), 0, time.Unix(0, 0), amtInt) - require.Equal( - t, sdk.NewDecFromInt(amt).Mul(sdk.NewDec(19).Quo(sdk.NewDec(20))), + require.True(sdk.IntEq( + t, amt.Mul(sdk.NewInt(19)).Div(sdk.NewInt(20)), sk.Validator(ctx, operatorAddr).GetPower(), - ) + )) } // Test that the amount a validator is slashed for multiple double signs diff --git a/x/stake/keeper/validator_test.go b/x/stake/keeper/validator_test.go index bafd67273d06..31698e30fb68 100644 --- a/x/stake/keeper/validator_test.go +++ b/x/stake/keeper/validator_test.go @@ -82,12 +82,12 @@ func TestUpdateValidatorByPowerIndex(t *testing.T) { validator := types.NewValidator(addrVals[0], PKs[0], types.Description{}) validator, pool, delSharesCreated := validator.AddTokensFromDel(pool, sdk.NewInt(100)) require.Equal(t, sdk.Unbonded, validator.Status) - require.Equal(t, int64(100), validator.Tokens.RoundInt64()) + require.Equal(t, int64(100), validator.Tokens.Int64()) keeper.SetPool(ctx, pool) TestingUpdateValidator(keeper, ctx, validator) validator, found := keeper.GetValidator(ctx, addrVals[0]) require.True(t, found) - require.Equal(t, int64(100), validator.Tokens.RoundInt64(), "\nvalidator %v\npool %v", validator, pool) + require.Equal(t, int64(100), validator.Tokens.Int64(), "\nvalidator %v\npool %v", validator, pool) pool = keeper.GetPool(ctx) power := GetValidatorsByPowerIndexKey(validator, pool) @@ -96,7 +96,7 @@ func TestUpdateValidatorByPowerIndex(t *testing.T) { // burn half the delegator shares keeper.DeleteValidatorByPowerIndex(ctx, validator, pool) validator, pool, burned := validator.RemoveDelShares(pool, delSharesCreated.Quo(sdk.NewDec(2))) - require.Equal(t, int64(50), burned.RoundInt64()) + require.Equal(t, int64(50), burned.Int64()) keeper.SetPool(ctx, pool) // update the pool TestingUpdateValidator(keeper, ctx, validator) // update the validator, possibly kicking it out require.False(t, validatorByPowerIndexExists(keeper, ctx, power)) @@ -175,11 +175,11 @@ func TestSlashToZeroPowerRemoved(t *testing.T) { validator := types.NewValidator(addrVals[0], PKs[0], types.Description{}) validator, pool, _ = validator.AddTokensFromDel(pool, sdk.NewInt(100)) require.Equal(t, sdk.Unbonded, validator.Status) - require.Equal(t, int64(100), validator.Tokens.RoundInt64()) + require.Equal(t, int64(100), validator.Tokens.Int64()) keeper.SetPool(ctx, pool) keeper.SetValidatorByConsAddr(ctx, validator) validator = TestingUpdateValidator(keeper, ctx, validator) - require.Equal(t, int64(100), validator.Tokens.RoundInt64(), "\nvalidator %v\npool %v", validator, pool) + require.Equal(t, int64(100), validator.Tokens.Int64(), "\nvalidator %v\npool %v", validator, pool) // slash the validator by 100% consAddr0 := sdk.ConsAddress(PKs[0].Address()) @@ -202,7 +202,7 @@ func TestValidatorBasics(t *testing.T) { for i, amt := range amts { validators[i] = types.NewValidator(addrVals[i], PKs[i], types.Description{}) validators[i].Status = sdk.Unbonded - validators[i].Tokens = sdk.ZeroDec() + validators[i].Tokens = sdk.ZeroInt() validators[i], pool, _ = validators[i].AddTokensFromDel(pool, sdk.NewInt(amt)) keeper.SetPool(ctx, pool) } @@ -220,7 +220,7 @@ func TestValidatorBasics(t *testing.T) { require.Zero(t, len(resVals)) pool = keeper.GetPool(ctx) - assert.True(sdk.DecEq(t, sdk.ZeroDec(), pool.BondedTokens)) + assert.True(sdk.IntEq(t, sdk.ZeroInt(), pool.BondedTokens)) // set and retrieve a record validators[0] = TestingUpdateValidator(keeper, ctx, validators[0]) @@ -244,7 +244,7 @@ func TestValidatorBasics(t *testing.T) { assert.True(sdk.IntEq(t, sdk.NewInt(9), validators[0].BondedTokens())) pool = keeper.GetPool(ctx) - assert.True(sdk.DecEq(t, pool.BondedTokens, validators[0].BondedTokens())) + assert.True(sdk.IntEq(t, pool.BondedTokens, validators[0].BondedTokens())) // modify a records, save, and retrieve validators[0].Status = sdk.Bonded From 9cf02b4a2d34b818af2f9416d8dff5cf6cf22418 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Fri, 30 Nov 2018 13:09:37 -0500 Subject: [PATCH 05/18] ... --- types/int.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/int.go b/types/int.go index 8d94d9f066bb..8be38055f558 100644 --- a/types/int.go +++ b/types/int.go @@ -162,12 +162,12 @@ func (i Int) IsZero() bool { // IsNegative returns true if Int is negative func (i Int) IsNegative() bool { - return i.i.Sign() == 0 + return i.i.Sign() == -1 } // IsPositive returns true if Int is positive func (i Int) IsPositive() bool { - return i.i.Sign() == 0 + return i.i.Sign() == 1 } // Sign returns sign of Int From 2105432032dd94da7439f8b1c5216ed25483dfd2 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Fri, 30 Nov 2018 13:25:58 -0500 Subject: [PATCH 06/18] slashing test fixes minor --- x/slashing/keeper_test.go | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/x/slashing/keeper_test.go b/x/slashing/keeper_test.go index 638147e5d083..c85472acd86f 100644 --- a/x/slashing/keeper_test.go +++ b/x/slashing/keeper_test.go @@ -101,8 +101,8 @@ func TestSlashingPeriodCap(t *testing.T) { // end block stake.EndBlocker(ctx, sk) // power should be reduced - expectedPower := sdk.NewDecFromInt(amt).Mul(sdk.NewDec(19).Quo(sdk.NewDec(20))) - require.Equal(t, expectedPower, sk.Validator(ctx, operatorAddr).GetPower()) + expectedPower := amt.Mul(sdk.NewInt(19)).Div(sdk.NewInt(20)) + require.True(sdk.IntEq(t, expectedPower, sk.Validator(ctx, operatorAddr).GetPower())) // double sign again, same slashing period keeper.handleDoubleSign(ctx, valConsAddr, 1, time.Unix(0, 0), amtInt) @@ -117,8 +117,8 @@ func TestSlashingPeriodCap(t *testing.T) { // end block stake.EndBlocker(ctx, sk) // power should be equal, no more should have been slashed - expectedPower = sdk.NewDecFromInt(amt).Mul(sdk.NewDec(19).Quo(sdk.NewDec(20))) - require.Equal(t, expectedPower, sk.Validator(ctx, operatorAddr).GetPower()) + expectedPower = amt.Mul(sdk.NewInt(19)).Div(sdk.NewInt(20)) + require.True(sdk.IntEq(t, expectedPower, sk.Validator(ctx, operatorAddr).GetPower())) // double sign again, new slashing period keeper.handleDoubleSign(ctx, valConsAddr, 3, time.Unix(0, 0), amtInt) @@ -129,8 +129,8 @@ func TestSlashingPeriodCap(t *testing.T) { // end block stake.EndBlocker(ctx, sk) // power should be reduced - expectedPower = sdk.NewDecFromInt(amt).Mul(sdk.NewDec(18).Quo(sdk.NewDec(20))) - require.Equal(t, expectedPower, sk.Validator(ctx, operatorAddr).GetPower()) + expectedPower = amt.Mul(sdk.NewInt(18)).Div(sdk.NewInt(20)) + require.True(sdk.IntEq(t, expectedPower, sk.Validator(ctx, operatorAddr).GetPower())) } // Test a validator through uptime, downtime, revocation, @@ -186,7 +186,7 @@ func TestHandleAbsentValidator(t *testing.T) { validator, _ := sk.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(val)) require.Equal(t, sdk.Bonded, validator.GetStatus()) pool := sk.GetPool(ctx) - require.Equal(sdk.IntEq(t, amt, pool.BondedTokens)) + require.True(sdk.IntEq(t, amt, pool.BondedTokens)) // 501st block missed ctx = ctx.WithBlockHeight(height) @@ -312,7 +312,7 @@ func TestHandleNewValidator(t *testing.T) { t, ck.GetCoins(ctx, sdk.AccAddress(addr)), sdk.Coins{sdk.NewCoin(sk.GetParams(ctx).BondDenom, initCoins.SubRaw(amt))}, ) - require.Equal(t, sdk.NewDec(amt), sk.Validator(ctx, addr).GetPower()) + require.Equal(t, amt, sk.Validator(ctx, addr).GetPower().Int64()) // Now a validator, for two blocks keeper.handleValidatorSignature(ctx, val.Address(), 100, true) From cd7d179e4ad4592c2b5673606b6e3676288aa3bb Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Fri, 30 Nov 2018 13:38:57 -0500 Subject: [PATCH 07/18] test cover passes --- x/stake/handler_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/x/stake/handler_test.go b/x/stake/handler_test.go index 8d54bf973ae6..c537ac2d56da 100644 --- a/x/stake/handler_test.go +++ b/x/stake/handler_test.go @@ -263,7 +263,7 @@ func TestLegacyValidatorDelegations(t *testing.T) { validator, found = keeper.GetValidator(ctx, valAddr) require.True(t, found) require.True(t, validator.Jailed) - require.Equal(t, sdk.NewDec(10), validator.Tokens) + require.Equal(t, int64(10), validator.Tokens.Int64()) // verify delegation still exists bond, found := keeper.GetDelegation(ctx, delAddr, valAddr) @@ -1010,7 +1010,7 @@ func TestBondUnbondRedelegateSlashTwice(t *testing.T) { // validator power should have been reduced by half validator, found := keeper.GetValidator(ctx, valA) require.True(t, found) - require.Equal(t, sdk.NewDec(5), validator.GetPower()) + require.Equal(t, int64(5), validator.GetPower().Int64()) // slash the validator for an infraction committed after the unbonding and redelegation begin ctx = ctx.WithBlockHeight(3) From 3cc979a583d03f45bce3e8ba6eabf6c6ee9b7d9d Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Fri, 30 Nov 2018 13:56:10 -0500 Subject: [PATCH 08/18] invariant rounding issue --- x/stake/simulation/invariants.go | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/x/stake/simulation/invariants.go b/x/stake/simulation/invariants.go index 5c91820c1a1e..c29c0e5aebeb 100644 --- a/x/stake/simulation/invariants.go +++ b/x/stake/simulation/invariants.go @@ -92,17 +92,22 @@ func SupplyInvariants(ck bank.Keeper, k stake.Keeper, }, ) + // XXX TODO investigate why go test TestGaiaSimulationAfterImport + // loses decimal fractions if RoundInt is not used below here + // Loose tokens should equal coin supply plus unbonding delegations // plus tokens on unbonded validators - if !loose.Equal(sdk.NewDecFromInt(pool.LooseTokens)) { - return fmt.Errorf("loose token invariance:\n\tpool.LooseTokens: %v"+ - "\n\tsum of account tokens: %v", pool.LooseTokens, loose) + if !pool.LooseTokens.Equal(loose.RoundInt()) { + return fmt.Errorf("loose token invariance:\n"+ + "\tpool.LooseTokens: %v\n"+ + "\tsum of account tokens: %v", pool.LooseTokens, loose) } // Bonded tokens should equal sum of tokens with bonded validators - if !bonded.Equal(sdk.NewDecFromInt(pool.BondedTokens)) { - return fmt.Errorf("bonded token invariance:\n\tpool.BondedTokens: %v"+ - "\n\tsum of account tokens: %v", pool.BondedTokens, bonded) + if !pool.BondedTokens.Equal(bonded.RoundInt()) { + return fmt.Errorf("bonded token invariance:\n"+ + "\tpool.BondedTokens: %v\n"+ + "\tsum of account tokens: %v", pool.BondedTokens, bonded) } return nil From 824f945f9f3bbaa8793f2e694cfd28c64bc7e5eb Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Fri, 30 Nov 2018 14:03:57 -0500 Subject: [PATCH 09/18] comment update --- x/stake/types/validator.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/x/stake/types/validator.go b/x/stake/types/validator.go index ee2b74eede64..ba5634450e36 100644 --- a/x/stake/types/validator.go +++ b/x/stake/types/validator.go @@ -402,14 +402,14 @@ func (v Validator) AddTokensFromDel(pool Pool, amount sdk.Int) (Validator, Pool, } // RemoveDelShares removes delegator shares from a validator. -// NOTE: due to burning of excess tokens, the exchange rate -// of future shares of this validator can increase. +// NOTE: because token fractions are left in the valiadator, +// the exchange rate of future shares of this validator can increase. func (v Validator) RemoveDelShares(pool Pool, delShares sdk.Dec) (Validator, Pool, sdk.Int) { issuedTokensDec := v.DelegatorShareExRate().Mul(delShares) - // burn excess tokens + // leave excess tokens in the validator + // however burn all the delegator shares issuedTokens := issuedTokensDec.TruncateInt() - v.Tokens = v.Tokens.Sub(issuedTokens) v.DelegatorShares = v.DelegatorShares.Sub(delShares) From 63af5db6489d64dafd231321974547e8f72235ca Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Fri, 30 Nov 2018 14:12:46 -0500 Subject: [PATCH 10/18] PENDING and doc updates --- PENDING.md | 1 + docs/spec/staking/state.md | 7 +++---- docs/spec/staking/transactions.md | 1 + 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/PENDING.md b/PENDING.md index 8ea9e15e3aac..c40c99e70e69 100644 --- a/PENDING.md +++ b/PENDING.md @@ -10,6 +10,7 @@ BREAKING CHANGES * Gaia * SDK + * [stake] \#2513 Validator power type from Dec -> Int * Tendermint diff --git a/docs/spec/staking/state.md b/docs/spec/staking/state.md index 6568293cc3f0..d2f461e103b8 100644 --- a/docs/spec/staking/state.md +++ b/docs/spec/staking/state.md @@ -10,8 +10,8 @@ inflation information, etc. ```golang type Pool struct { - LooseTokens int64 // tokens not associated with any bonded validator - BondedTokens int64 // reserve of bonded tokens + LooseTokens sdk.Int // tokens not associated with any bonded validator + BondedTokens sdk.Int // reserve of bonded tokens } ``` @@ -65,9 +65,8 @@ type Validator struct { Jailed bool // has the validator been jailed? Status sdk.BondStatus // validator status (bonded/unbonding/unbonded) - Tokens sdk.Dec // delegated tokens (incl. self-delegation) + Tokens sdk.Int // delegated tokens (incl. self-delegation) DelegatorShares sdk.Dec // total shares issued to a validator's delegators - SlashRatio sdk.Dec // increases each time the validator is slashed Description Description // description terms for the validator diff --git a/docs/spec/staking/transactions.md b/docs/spec/staking/transactions.md index ee5b2dc938d8..55dc2deb3dbc 100644 --- a/docs/spec/staking/transactions.md +++ b/docs/spec/staking/transactions.md @@ -20,6 +20,7 @@ Other notes: * `getXxx`, `setXxx`, and `removeXxx` functions are used to retrieve and modify objects from the store * `sdk.Dec` refers to a decimal type specified by the SDK. +* `sdk.Int` refers to an integer type specified by the SDK. ## TxCreateValidator From 4ac4f03083c8c824dc404725235bcebde4a1a3c5 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Thu, 6 Dec 2018 04:19:03 -0500 Subject: [PATCH 11/18] @cwgoes comments --- types/int.go | 5 ----- x/stake/simulation/invariants.go | 6 +++--- 2 files changed, 3 insertions(+), 8 deletions(-) diff --git a/types/int.go b/types/int.go index 8be38055f558..63ed51fd9f33 100644 --- a/types/int.go +++ b/types/int.go @@ -408,11 +408,6 @@ func (i Uint) IsZero() bool { return i.i.Sign() == 0 } -// IsNegative returns true if Uint is negative -func (i Uint) IsNegative() bool { - return i.i.Sign() == -1 -} - // IsPositive returns true if Uint is positive func (i Uint) IsPositive() bool { return i.i.Sign() == 1 diff --git a/x/stake/simulation/invariants.go b/x/stake/simulation/invariants.go index c29c0e5aebeb..2fd0a428b7a1 100644 --- a/x/stake/simulation/invariants.go +++ b/x/stake/simulation/invariants.go @@ -93,18 +93,18 @@ func SupplyInvariants(ck bank.Keeper, k stake.Keeper, ) // XXX TODO investigate why go test TestGaiaSimulationAfterImport - // loses decimal fractions if RoundInt is not used below here + // loses decimal fractions in below two checks // Loose tokens should equal coin supply plus unbonding delegations // plus tokens on unbonded validators - if !pool.LooseTokens.Equal(loose.RoundInt()) { + if !sdk.NewDecFromInt(pool.LooseTokens).Equal(loose) { return fmt.Errorf("loose token invariance:\n"+ "\tpool.LooseTokens: %v\n"+ "\tsum of account tokens: %v", pool.LooseTokens, loose) } // Bonded tokens should equal sum of tokens with bonded validators - if !pool.BondedTokens.Equal(bonded.RoundInt()) { + if !sdk.NewDecFromInt(pool.BondedTokens).Equal(bonded) { return fmt.Errorf("bonded token invariance:\n"+ "\tpool.BondedTokens: %v\n"+ "\tsum of account tokens: %v", pool.BondedTokens, bonded) From 60386486f2f584752475fa2940ab1348546e6c93 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Thu, 6 Dec 2018 04:26:28 -0500 Subject: [PATCH 12/18] RemoveDelShares trimmings to the final delegation share --- x/stake/types/validator.go | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/x/stake/types/validator.go b/x/stake/types/validator.go index ba5634450e36..91019a9d3b18 100644 --- a/x/stake/types/validator.go +++ b/x/stake/types/validator.go @@ -405,14 +405,21 @@ func (v Validator) AddTokensFromDel(pool Pool, amount sdk.Int) (Validator, Pool, // NOTE: because token fractions are left in the valiadator, // the exchange rate of future shares of this validator can increase. func (v Validator) RemoveDelShares(pool Pool, delShares sdk.Dec) (Validator, Pool, sdk.Int) { - issuedTokensDec := v.DelegatorShareExRate().Mul(delShares) - // leave excess tokens in the validator - // however burn all the delegator shares - issuedTokens := issuedTokensDec.TruncateInt() - v.Tokens = v.Tokens.Sub(issuedTokens) v.DelegatorShares = v.DelegatorShares.Sub(delShares) + var issuedTokens sdk.Int + if v.DelegatorShares.IsZero() { + + // last delegation share gets any trimmings + issuedTokens = v.Tokens + } else { + // leave excess tokens in the validator + // however burn all the delegator shares + issuedTokens := v.DelegatorShareExRate().Mul(delShares).TruncateInt() + } + + v.Tokens = v.Tokens.Sub(issuedTokens) if v.Status == sdk.Bonded { pool = pool.bondedTokensToLoose(issuedTokens) } From 297f8e40b655d8d8ff907848e26fe3059f8ff469 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Thu, 6 Dec 2018 04:30:09 -0500 Subject: [PATCH 13/18] fixes --- x/stake/simulation/invariants.go | 3 --- x/stake/types/validator.go | 2 +- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/x/stake/simulation/invariants.go b/x/stake/simulation/invariants.go index 2fd0a428b7a1..dd42684790b8 100644 --- a/x/stake/simulation/invariants.go +++ b/x/stake/simulation/invariants.go @@ -92,9 +92,6 @@ func SupplyInvariants(ck bank.Keeper, k stake.Keeper, }, ) - // XXX TODO investigate why go test TestGaiaSimulationAfterImport - // loses decimal fractions in below two checks - // Loose tokens should equal coin supply plus unbonding delegations // plus tokens on unbonded validators if !sdk.NewDecFromInt(pool.LooseTokens).Equal(loose) { diff --git a/x/stake/types/validator.go b/x/stake/types/validator.go index 91019a9d3b18..9f8e0856ad83 100644 --- a/x/stake/types/validator.go +++ b/x/stake/types/validator.go @@ -416,7 +416,7 @@ func (v Validator) RemoveDelShares(pool Pool, delShares sdk.Dec) (Validator, Poo // leave excess tokens in the validator // however burn all the delegator shares - issuedTokens := v.DelegatorShareExRate().Mul(delShares).TruncateInt() + issuedTokens = v.DelegatorShareExRate().Mul(delShares).TruncateInt() } v.Tokens = v.Tokens.Sub(issuedTokens) From 74e7a1d14bb1b7bebcb83c32e80ca5117764683c Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Thu, 6 Dec 2018 12:05:11 -0500 Subject: [PATCH 14/18] ... --- x/mint/minter_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x/mint/minter_test.go b/x/mint/minter_test.go index 18540862899d..0245c71972fb 100644 --- a/x/mint/minter_test.go +++ b/x/mint/minter_test.go @@ -121,7 +121,7 @@ func BenchmarkNextInflation(b *testing.B) { func BenchmarkNextAnnualProvisions(b *testing.B) { minter := InitialMinter(sdk.NewDecWithPrec(1, 1)) params := DefaultParams() - totalSupply := sdk.NewDec(100000000000000) + totalSupply := sdk.NewInt(100000000000000) // run the NextAnnualProvisions function b.N times for n := 0; n < b.N; n++ { From 10a45823df78df57d7d64b67231df80a0adf51d5 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Thu, 6 Dec 2018 17:37:55 -0500 Subject: [PATCH 15/18] fix the oopsie --- x/stake/types/validator.go | 5 +++-- x/stake/types/validator_test.go | 10 +++++----- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/x/stake/types/validator.go b/x/stake/types/validator.go index 9f8e0856ad83..7cffd6598db0 100644 --- a/x/stake/types/validator.go +++ b/x/stake/types/validator.go @@ -406,9 +406,9 @@ func (v Validator) AddTokensFromDel(pool Pool, amount sdk.Int) (Validator, Pool, // the exchange rate of future shares of this validator can increase. func (v Validator) RemoveDelShares(pool Pool, delShares sdk.Dec) (Validator, Pool, sdk.Int) { - v.DelegatorShares = v.DelegatorShares.Sub(delShares) + remainingShares := v.DelegatorShares.Sub(delShares) var issuedTokens sdk.Int - if v.DelegatorShares.IsZero() { + if remainingShares.IsZero() { // last delegation share gets any trimmings issuedTokens = v.Tokens @@ -419,6 +419,7 @@ func (v Validator) RemoveDelShares(pool Pool, delShares sdk.Dec) (Validator, Poo issuedTokens = v.DelegatorShareExRate().Mul(delShares).TruncateInt() } + v.DelegatorShares = remainingShares v.Tokens = v.Tokens.Sub(issuedTokens) if v.Status == sdk.Bonded { pool = pool.bondedTokensToLoose(issuedTokens) diff --git a/x/stake/types/validator_test.go b/x/stake/types/validator_test.go index 9a5f686ca391..9fd76b9db4dc 100644 --- a/x/stake/types/validator_test.go +++ b/x/stake/types/validator_test.go @@ -162,11 +162,11 @@ func TestRemoveDelShares(t *testing.T) { // Remove delegator shares valB, poolB, coinsB := valA.RemoveDelShares(poolA, sdk.NewDec(10)) - assert.Equal(t, int64(10), coinsB.Int64()) - assert.Equal(t, int64(90), valB.DelegatorShares.RoundInt64()) - assert.Equal(t, int64(90), valB.BondedTokens().Int64()) - assert.Equal(t, int64(90), poolB.BondedTokens.Int64()) - assert.Equal(t, int64(20), poolB.LooseTokens.Int64()) + require.Equal(t, int64(10), coinsB.Int64()) + require.Equal(t, int64(90), valB.DelegatorShares.RoundInt64()) + require.Equal(t, int64(90), valB.BondedTokens().Int64()) + require.Equal(t, int64(90), poolB.BondedTokens.Int64()) + require.Equal(t, int64(20), poolB.LooseTokens.Int64()) // conservation of tokens require.True(sdk.IntEq(t, From 7ad96ce35a02f15ba50c89d5df2752e2ed26d7b9 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Thu, 6 Dec 2018 18:10:57 -0500 Subject: [PATCH 16/18] @alexanderbez comments --- types/int.go | 5 ----- x/stake/types/validator.go | 5 +++-- 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/types/int.go b/types/int.go index 63ed51fd9f33..7baf5d2acce9 100644 --- a/types/int.go +++ b/types/int.go @@ -408,11 +408,6 @@ func (i Uint) IsZero() bool { return i.i.Sign() == 0 } -// IsPositive returns true if Uint is positive -func (i Uint) IsPositive() bool { - return i.i.Sign() == 1 -} - // Sign returns sign of Uint func (i Uint) Sign() int { return i.i.Sign() diff --git a/x/stake/types/validator.go b/x/stake/types/validator.go index 7cffd6598db0..33c35d898a97 100644 --- a/x/stake/types/validator.go +++ b/x/stake/types/validator.go @@ -412,15 +412,16 @@ func (v Validator) RemoveDelShares(pool Pool, delShares sdk.Dec) (Validator, Poo // last delegation share gets any trimmings issuedTokens = v.Tokens + v.Tokens = sdk.ZeroInt() } else { // leave excess tokens in the validator - // however burn all the delegator shares + // however fully use all the delegator shares issuedTokens = v.DelegatorShareExRate().Mul(delShares).TruncateInt() + v.Tokens = v.Tokens.Sub(issuedTokens) } v.DelegatorShares = remainingShares - v.Tokens = v.Tokens.Sub(issuedTokens) if v.Status == sdk.Bonded { pool = pool.bondedTokensToLoose(issuedTokens) } From 7160e18cf329c8705ed67c469caf59a54abc4473 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Thu, 20 Dec 2018 19:13:27 -0500 Subject: [PATCH 17/18] merge fixes --- x/gov/tally.go | 5 +++-- x/stake/simulation/invariants.go | 2 +- x/stake/types/validator.go | 2 +- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/x/gov/tally.go b/x/gov/tally.go index f07e5a75000a..8b44b034c84d 100644 --- a/x/gov/tally.go +++ b/x/gov/tally.go @@ -94,11 +94,12 @@ func tally(ctx sdk.Context, keeper Keeper, proposal Proposal) (passes bool, tall } // If there is no staked coins, the proposal fails - if keeper.vs.TotalPower(ctx).Equal(sdk.ZeroDec()) { + if keeper.vs.TotalPower(ctx).IsZero() { return false, tallyResults } // If there is not enough quorum of votes, the proposal fails - if totalVotingPower.Quo(keeper.vs.TotalPower(ctx)).LT(tallyParams.Quorum) { + percentVoting := totalVotingPower.Quo(sdk.NewDecFromInt(keeper.vs.TotalPower(ctx))) + if percentVoting.LT(tallyParams.Quorum) { return false, tallyResults } // If no one votes (everyone abstains), proposal fails diff --git a/x/stake/simulation/invariants.go b/x/stake/simulation/invariants.go index c8dfd7660605..52775d268cc6 100644 --- a/x/stake/simulation/invariants.go +++ b/x/stake/simulation/invariants.go @@ -129,7 +129,7 @@ func NonNegativePowerInvariant(k stake.Keeper) simulation.Invariant { "\n\tkey should be: %v\n\tkey in store: %v", validator.GetPower(), powerKey, iterator.Key()) } - if validator.Tokens.LT(sdk.ZeroDec()) { + if validator.Tokens.IsNegative() { return fmt.Errorf("negative tokens for validator: %v", validator) } } diff --git a/x/stake/types/validator.go b/x/stake/types/validator.go index 173d05b4cf0c..ff5aaf889358 100644 --- a/x/stake/types/validator.go +++ b/x/stake/types/validator.go @@ -415,7 +415,7 @@ func (v Validator) RemoveDelShares(pool Pool, delShares sdk.Dec) (Validator, Poo // leave excess tokens in the validator // however fully use all the delegator shares issuedTokens = v.DelegatorShareExRate().Mul(delShares).TruncateInt() - issuedTokens = sdk.Min(issuedTokens, v.Tokens) // defensive should not occur + issuedTokens = sdk.MinInt(issuedTokens, v.Tokens) // defensive should not occur v.Tokens = v.Tokens.Sub(issuedTokens) } From 567e734e237dc5d2d587cd74e699e502f8496864 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Sun, 23 Dec 2018 12:53:57 -0500 Subject: [PATCH 18/18] address @cwgoes comments --- x/stake/types/validator.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/x/stake/types/validator.go b/x/stake/types/validator.go index ff5aaf889358..065e4d42bd8f 100644 --- a/x/stake/types/validator.go +++ b/x/stake/types/validator.go @@ -415,8 +415,10 @@ func (v Validator) RemoveDelShares(pool Pool, delShares sdk.Dec) (Validator, Poo // leave excess tokens in the validator // however fully use all the delegator shares issuedTokens = v.DelegatorShareExRate().Mul(delShares).TruncateInt() - issuedTokens = sdk.MinInt(issuedTokens, v.Tokens) // defensive should not occur v.Tokens = v.Tokens.Sub(issuedTokens) + if v.Tokens.IsNegative() { + panic("attempting to remove more tokens than available in validator") + } } v.DelegatorShares = remainingShares