Skip to content

Commit

Permalink
Merge pull request #1819: rational -> decimal
Browse files Browse the repository at this point in the history
* changelog

* ...

* decimal func working

* decimal complete, untested

* fixing tests

* decimal compile errors resolved

* test compile errors

* precision multiplier test

* 1% laptop battery

* fixed TestNewDecFromStr

* equalities working

* fix bankers round chop

* ...

* working, some decimal issues resolved

* fix rounding error

* rounding works

* decimal works

* ...

* deleted rational

* rational conversion working

* revert changelog

* code compiles (not tests)

* went through all NewDec, made sure they were converted from NewRat properly

* test debugging

* all testing bugs besides the json marshalling fixed

* json unmarshal

* lint

* document update

* fix lcd test

* cli test fix

* mostly undo Dece -> Rate

* val comments

* Efficiency improvements

This now caches all of the precision multipliers (as they were all
used in non-mutative functions), and caches the precisionInt calculation.
(Now it just copies the already calculated value)

* Cache another precisionInt() call.

* Improve banker rounding efficiency

* remove defer, make negation in-place.

* chris val comments

* bez comments

* Aditya comments

* ...

* val comments

* rebasing start

* ...

* compiling

* tests pass

* cli fix

* anton, cwgoes, val comments

* val and jae comments

* type

* undo reuse quo
  • Loading branch information
rigelrozanski authored Aug 15, 2018
1 parent 0adbd60 commit d9dc061
Show file tree
Hide file tree
Showing 66 changed files with 1,254 additions and 1,213 deletions.
1 change: 1 addition & 0 deletions PENDING.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ BREAKING CHANGES
* `gaiacli gov vote --voter`
* [x/gov] Added tags sub-package, changed tags to use dash-case
* [x/gov] Governance parameters are now stored in globalparams store
* [core] \#1807 Switch from use of rational to decimal
* [lcd] \#1866 Updated lcd /slashing/signing_info endpoint to take cosmosvalpub instead of cosmosvaladdr
* [types] sdk.NewCoin now takes sdk.Int, sdk.NewInt64Coin takes int64
* [cli] #1551: Officially removed `--name` from CLI commands
Expand Down
2 changes: 1 addition & 1 deletion client/lcd/test_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ func InitializeTestLCD(t *testing.T, nValidators int, initAddrs []sdk.AccAddress
accAuth.Coins = sdk.Coins{sdk.NewInt64Coin("steak", 100)}
acc := gapp.NewGenesisAccount(&accAuth)
genesisState.Accounts = append(genesisState.Accounts, acc)
genesisState.StakeData.Pool.LooseTokens = genesisState.StakeData.Pool.LooseTokens.Add(sdk.NewRat(100))
genesisState.StakeData.Pool.LooseTokens = genesisState.StakeData.Pool.LooseTokens.Add(sdk.NewDec(100))
}

appState, err := wire.MarshalJSONIndent(cdc, genesisState)
Expand Down
6 changes: 3 additions & 3 deletions cmd/gaia/app/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -185,18 +185,18 @@ func GaiaAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState
}
acc := NewGenesisAccount(&accAuth)
genaccs[i] = acc
stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens.Add(sdk.NewRat(freeFermionsAcc)) // increase the supply
stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens.Add(sdk.NewDec(freeFermionsAcc)) // increase the supply

// add the validator
if len(genTx.Name) > 0 {
desc := stake.NewDescription(genTx.Name, "", "", "")
validator := stake.NewValidator(genTx.Address,
sdk.MustGetAccPubKeyBech32(genTx.PubKey), desc)

stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens.Add(sdk.NewRat(freeFermionVal)) // increase the supply
stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens.Add(sdk.NewDec(freeFermionVal)) // increase the supply

// add some new shares to the validator
var issuedDelShares sdk.Rat
var issuedDelShares sdk.Dec
validator, stakeData.Pool, issuedDelShares = validator.AddTokensFromDel(stakeData.Pool, freeFermionVal)
stakeData.Validators = append(stakeData.Validators, validator)

Expand Down
2 changes: 1 addition & 1 deletion cmd/gaia/app/sim_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ func appStateFn(r *rand.Rand, accs []sdk.AccAddress) json.RawMessage {

// Default genesis state
stakeGenesis := stake.DefaultGenesisState()
stakeGenesis.Pool.LooseTokens = sdk.NewRat(1000)
stakeGenesis.Pool.LooseTokens = sdk.NewDec(1000)
genesis := GenesisState{
Accounts: genesisAccounts,
StakeData: stakeGenesis,
Expand Down
4 changes: 2 additions & 2 deletions cmd/gaia/cli_test/cli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ func TestGaiaCLICreateValidator(t *testing.T) {

validator := executeGetValidator(t, fmt.Sprintf("gaiacli stake validator %s --output=json %v", barAddr, flags))
require.Equal(t, validator.Owner, barAddr)
require.True(sdk.RatEq(t, sdk.NewRat(2), validator.Tokens))
require.True(sdk.DecEq(t, sdk.NewDec(2), validator.Tokens))

// unbond a single share
unbondStr := fmt.Sprintf("gaiacli stake unbond begin %v", flags)
Expand All @@ -149,7 +149,7 @@ func TestGaiaCLICreateValidator(t *testing.T) {
require.Equal(t, int64(9), barAcc.GetCoins().AmountOf("steak").Int64(), "%v", barAcc)
*/
validator = executeGetValidator(t, fmt.Sprintf("gaiacli stake validator %s --output=json %v", barAddr, flags))
require.Equal(t, "1/1", validator.Tokens.String())
require.Equal(t, "1.0000000000", validator.Tokens.String())
}

func TestGaiaCLISubmitProposal(t *testing.T) {
Expand Down
18 changes: 9 additions & 9 deletions docs/spec/governance/state.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ type VotingProcedure struct {

```go
type TallyingProcedure struct {
Threshold rational.Rational // Minimum propotion of Yes votes for proposal to pass. Initial value: 0.5
Veto rational.Rational // Minimum proportion of Veto votes to Total votes ratio for proposal to be vetoed. Initial value: 1/3
GovernancePenalty sdk.Rat // Penalty if validator does not vote
Threshold sdk.Dec // Minimum propotion of Yes votes for proposal to pass. Initial value: 0.5
Veto sdk.Dec // Minimum proportion of Veto votes to Total votes ratio for proposal to be vetoed. Initial value: 1/3
GovernancePenalty sdk.Dec // Penalty if validator does not vote
GracePeriod int64 // If validator entered validator set in this period of blocks before vote ended, governance penalty does not apply
}
```
Expand Down Expand Up @@ -81,7 +81,7 @@ This type is used in a temp map when tallying

```go
type ValidatorGovInfo struct {
Minus sdk.Rat
Minus sdk.Dec
Vote Vote
}
```
Expand All @@ -103,17 +103,17 @@ type Proposal struct {
VotingStartBlock int64 // Height of the block where MinDeposit was reached. -1 if MinDeposit is not reached
CurrentStatus ProposalStatus // Current status of the proposal

YesVotes sdk.Rat
NoVotes sdk.Rat
NoWithVetoVotes sdk.Rat
AbstainVotes sdk.Rat
YesVotes sdk.Dec
NoVotes sdk.Dec
NoWithVetoVotes sdk.Dec
AbstainVotes sdk.Dec
}
```

We also mention a method to update the tally for a given proposal:

```go
func (proposal Proposal) updateTally(vote byte, amount sdk.Rat)
func (proposal Proposal) updateTally(vote byte, amount sdk.Dec)
```

### Stores
Expand Down
2 changes: 1 addition & 1 deletion docs/spec/inflation/state.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
The current annual inflation rate.

```golang
type Inflation sdk.Rat
type Inflation sdk.Dec
```

### InflationLastTime
Expand Down
1 change: 0 additions & 1 deletion docs/spec/staking/end_block.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,3 @@ EndBlock() ValidatorSetChanges
ClearTendermintUpdates()
return vsc
```

30 changes: 15 additions & 15 deletions docs/spec/staking/state.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ type Pool struct {
LooseTokens int64 // tokens not associated with any bonded validator
BondedTokens int64 // reserve of bonded tokens
InflationLastTime int64 // block which the last inflation was processed // TODO make time
Inflation sdk.Rat // current annual inflation rate
Inflation sdk.Dec // current annual inflation rate

DateLastCommissionReset int64 // unix timestamp for last commission accounting reset (daily)
}
Expand All @@ -28,10 +28,10 @@ overall functioning of the stake module.

```golang
type Params struct {
InflationRateChange sdk.Rat // maximum annual change in inflation rate
InflationMax sdk.Rat // maximum inflation rate
InflationMin sdk.Rat // minimum inflation rate
GoalBonded sdk.Rat // Goal of percent bonded atoms
InflationRateChange sdk.Dec // maximum annual change in inflation rate
InflationMax sdk.Dec // maximum inflation rate
InflationMin sdk.Dec // minimum inflation rate
GoalBonded sdk.Dec // Goal of percent bonded atoms

MaxValidators uint16 // maximum number of validators
BondDenom string // bondable coin denomination
Expand Down Expand Up @@ -74,9 +74,9 @@ type Validator struct {
Revoked bool // has the validator been revoked?

Status sdk.BondStatus // validator status (bonded/unbonding/unbonded)
Tokens sdk.Rat // delegated tokens (incl. self-delegation)
DelegatorShares sdk.Rat // total shares issued to a validator's delegators
SlashRatio sdk.Rat // increases each time the validator is slashed
Tokens sdk.Dec // 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

Expand All @@ -88,10 +88,10 @@ type Validator struct {
}

type CommissionInfo struct {
Rate sdk.Rat // the commission rate of fees charged to any delegators
Max sdk.Rat // maximum commission rate which this validator can ever charge
ChangeRate sdk.Rat // maximum daily increase of the validator commission
ChangeToday sdk.Rat // commission rate change today, reset each day (UTC time)
Rate sdk.Dec // the commission rate of fees charged to any delegators
Max sdk.Dec // maximum commission rate which this validator can ever charge
ChangeRate sdk.Dec // maximum daily increase of the validator commission
ChangeToday sdk.Dec // commission rate change today, reset each day (UTC time)
LastChange int64 // unix timestamp of last commission change
}

Expand All @@ -117,7 +117,7 @@ the transaction is the owner of the bond.

```golang
type Delegation struct {
Shares sdk.Rat // delegation shares recieved
Shares sdk.Dec // delegation shares recieved
Height int64 // last height bond updated
}
```
Expand Down Expand Up @@ -178,8 +178,8 @@ the original redelegation has been completed.

```golang
type Redelegation struct {
SourceShares sdk.Rat // amount of source shares redelegating
DestinationShares sdk.Rat // amount of destination shares created at redelegation
SourceShares sdk.Dec // amount of source shares redelegating
DestinationShares sdk.Dec // amount of destination shares created at redelegation
CompleteTime int64 // unix time to complete redelegation
}
```
12 changes: 6 additions & 6 deletions docs/spec/staking/transactions.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ Other notes:
- `sender` denotes the address of the sender of the transaction
- `getXxx`, `setXxx`, and `removeXxx` functions are used to retrieve and
modify objects from the store
- `sdk.Rat` refers to a rational numeric type specified by the SDK.
- `sdk.Dec` refers to a decimal type specified by the SDK.

### TxCreateValidator

Expand All @@ -34,9 +34,9 @@ type TxCreateValidator struct {
SelfDelegation coin.Coin

Description Description
Commission sdk.Rat
CommissionMax sdk.Rat
CommissionMaxChange sdk.Rat
Commission sdk.Dec
CommissionMax sdk.Dec
CommissionMaxChange sdk.Dec
}


Expand Down Expand Up @@ -65,7 +65,7 @@ If either the `Description` (excluding `DateBonded` which is constant),
```golang
type TxEditCandidacy struct {
GovernancePubKey crypto.PubKey
Commission sdk.Rat
Commission sdk.Dec
Description Description
}

Expand Down Expand Up @@ -199,7 +199,7 @@ type TxRedelegate struct {
DelegatorAddr Address
ValidatorFrom Validator
ValidatorTo Validator
Shares sdk.Rat
Shares sdk.Dec
CompletedTime int64
}

Expand Down
18 changes: 9 additions & 9 deletions examples/democoin/mock/validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
// Validator implements sdk.Validator
type Validator struct {
Address sdk.AccAddress
Power sdk.Rat
Power sdk.Dec
}

// Implements sdk.Validator
Expand All @@ -29,18 +29,18 @@ func (v Validator) GetPubKey() crypto.PubKey {
}

// Implements sdk.Validator
func (v Validator) GetTokens() sdk.Rat {
return sdk.ZeroRat()
func (v Validator) GetTokens() sdk.Dec {
return sdk.ZeroDec()
}

// Implements sdk.Validator
func (v Validator) GetPower() sdk.Rat {
func (v Validator) GetPower() sdk.Dec {
return v.Power
}

// Implements sdk.Validator
func (v Validator) GetDelegatorShares() sdk.Rat {
return sdk.ZeroRat()
func (v Validator) GetDelegatorShares() sdk.Dec {
return sdk.ZeroDec()
}

// Implements sdk.Validator
Expand Down Expand Up @@ -93,8 +93,8 @@ func (vs *ValidatorSet) ValidatorByPubKey(ctx sdk.Context, pubkey crypto.PubKey)
}

// TotalPower implements sdk.ValidatorSet
func (vs *ValidatorSet) TotalPower(ctx sdk.Context) sdk.Rat {
res := sdk.ZeroRat()
func (vs *ValidatorSet) TotalPower(ctx sdk.Context) sdk.Dec {
res := sdk.ZeroDec()
for _, val := range vs.Validators {
res = res.Add(val.Power)
}
Expand Down Expand Up @@ -122,7 +122,7 @@ func (vs *ValidatorSet) RemoveValidator(addr sdk.AccAddress) {
}

// Implements sdk.ValidatorSet
func (vs *ValidatorSet) Slash(ctx sdk.Context, pubkey crypto.PubKey, height int64, power int64, amt sdk.Rat) {
func (vs *ValidatorSet) Slash(ctx sdk.Context, pubkey crypto.PubKey, height int64, power int64, amt sdk.Dec) {
panic("not implemented")
}

Expand Down
4 changes: 2 additions & 2 deletions examples/democoin/x/assoc/validator_set_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ func TestValidatorSet(t *testing.T) {
addr2 := []byte("addr2")

base := &mock.ValidatorSet{[]mock.Validator{
{addr1, sdk.NewRat(1)},
{addr2, sdk.NewRat(2)},
{addr1, sdk.NewDec(1)},
{addr2, sdk.NewDec(2)},
}}

valset := NewValidatorSet(wire.NewCodec(), ctx.KVStore(key).Prefix([]byte("assoc")), base, 1, 5)
Expand Down
2 changes: 1 addition & 1 deletion examples/democoin/x/oracle/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ func NewHandler(keeper Keeper) sdk.Handler {
In the previous example, the keeper has an `oracle.Keeper`. `oracle.Keeper`s are generated by `NewKeeper`.

```go
func NewKeeper(key sdk.StoreKey, cdc *wire.Codec, valset sdk.ValidatorSet, supermaj sdk.Rat, timeout int64) Keeper {
func NewKeeper(key sdk.StoreKey, cdc *wire.Codec, valset sdk.ValidatorSet, supermaj sdk.Dec, timeout int64) Keeper {
return Keeper {
cdc: cdc,
key: key,
Expand Down
2 changes: 1 addition & 1 deletion examples/democoin/x/oracle/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.ZeroRat()
info.Power = sdk.ZeroDec()
info.Hash = hash
prefix := GetSignPrefix(p, keeper.cdc)
store := ctx.KVStore(keeper.key)
Expand Down
8 changes: 4 additions & 4 deletions examples/democoin/x/oracle/keeper.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@ type Keeper struct {

valset sdk.ValidatorSet

supermaj sdk.Rat
supermaj sdk.Dec
timeout int64
}

// NewKeeper constructs a new keeper
func NewKeeper(key sdk.StoreKey, cdc *wire.Codec, valset sdk.ValidatorSet, supermaj sdk.Rat, timeout int64) Keeper {
func NewKeeper(key sdk.StoreKey, cdc *wire.Codec, valset sdk.ValidatorSet, supermaj sdk.Dec, timeout int64) Keeper {
if timeout < 0 {
panic("Timeout should not be negative")
}
Expand Down Expand Up @@ -46,7 +46,7 @@ const (

// Info for each payload
type Info struct {
Power sdk.Rat
Power sdk.Dec
Hash []byte
LastSigned int64
Status InfoStatus
Expand All @@ -55,7 +55,7 @@ type Info struct {
// EmptyInfo construct an empty Info
func EmptyInfo(ctx sdk.Context) Info {
return Info{
Power: sdk.ZeroRat(),
Power: sdk.ZeroDec(),
Hash: ctx.BlockHeader().ValidatorsHash,
LastSigned: ctx.BlockHeight(),
Status: Pending,
Expand Down
10 changes: 5 additions & 5 deletions examples/democoin/x/oracle/oracle_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,9 +107,9 @@ func TestOracle(t *testing.T) {
addr3 := []byte("addr3")
addr4 := []byte("addr4")
valset := &mock.ValidatorSet{[]mock.Validator{
{addr1, sdk.NewRat(7)},
{addr2, sdk.NewRat(7)},
{addr3, sdk.NewRat(1)},
{addr1, sdk.NewDec(7)},
{addr2, sdk.NewDec(7)},
{addr3, sdk.NewDec(1)},
}}

key := sdk.NewKVStoreKey("testkey")
Expand All @@ -119,7 +119,7 @@ func TestOracle(t *testing.T) {
require.Nil(t, err)
ctx = ctx.WithBlockHeader(abci.Header{ValidatorsHash: bz})

ork := NewKeeper(key, cdc, valset, sdk.NewRat(2, 3), 100)
ork := NewKeeper(key, cdc, valset, sdk.NewDecWithPrec(667, 3), 100) // 66.7%
h := seqHandler(ork, key, sdk.CodespaceRoot)

// Nonmock.Validator signed, transaction failed
Expand Down Expand Up @@ -171,7 +171,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.NewRat(12)})
valset.AddValidator(mock.Validator{addr4, sdk.NewDec(12)})
bz, err = json.Marshal(valset)
require.Nil(t, err)
ctx = ctx.WithBlockHeader(abci.Header{ValidatorsHash: bz})
Expand Down
Loading

0 comments on commit d9dc061

Please sign in to comment.