forked from cosmos/cosmos-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pool.go
93 lines (81 loc) · 2.48 KB
/
pool.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package types
import (
"bytes"
"fmt"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
)
// Pool - tracking bonded and not-bonded token supply of the bond denomination
type Pool struct {
NotBondedTokens sdk.Int `json:"not_bonded_tokens"` // tokens which are not bonded to a validator (unbonded or unbonding)
BondedTokens sdk.Int `json:"bonded_tokens"` // tokens which are currently bonded to a validator
}
// nolint
// TODO: This is slower than comparing struct fields directly
func (p Pool) Equal(p2 Pool) bool {
bz1 := MsgCdc.MustMarshalBinaryLengthPrefixed(&p)
bz2 := MsgCdc.MustMarshalBinaryLengthPrefixed(&p2)
return bytes.Equal(bz1, bz2)
}
// initial pool for testing
func InitialPool() Pool {
return Pool{
NotBondedTokens: sdk.ZeroInt(),
BondedTokens: sdk.ZeroInt(),
}
}
// Sum total of all staking tokens in the pool
func (p Pool) TokenSupply() sdk.Int {
return p.NotBondedTokens.Add(p.BondedTokens)
}
// Get the fraction of the staking token which is currently bonded
func (p Pool) BondedRatio() sdk.Dec {
supply := p.TokenSupply()
if supply.IsPositive() {
return sdk.NewDecFromInt(p.BondedTokens).
QuoInt(supply)
}
return sdk.ZeroDec()
}
func (p Pool) notBondedTokensToBonded(bondedTokens sdk.Int) Pool {
p.BondedTokens = p.BondedTokens.Add(bondedTokens)
p.NotBondedTokens = p.NotBondedTokens.Sub(bondedTokens)
if p.NotBondedTokens.IsNegative() {
panic(fmt.Sprintf("sanity check: not-bonded tokens negative, pool: %v", p))
}
return p
}
func (p Pool) bondedTokensToNotBonded(bondedTokens sdk.Int) Pool {
p.BondedTokens = p.BondedTokens.Sub(bondedTokens)
p.NotBondedTokens = p.NotBondedTokens.Add(bondedTokens)
if p.BondedTokens.IsNegative() {
panic(fmt.Sprintf("sanity check: bonded tokens negative, pool: %v", p))
}
return p
}
// String returns a human readable string representation of a pool.
func (p Pool) String() string {
return fmt.Sprintf(`Pool:
Loose Tokens: %s
Bonded Tokens: %s
Token Supply: %s
Bonded Ratio: %v`, p.NotBondedTokens,
p.BondedTokens, p.TokenSupply(),
p.BondedRatio())
}
// unmarshal the current pool value from store key or panics
func MustUnmarshalPool(cdc *codec.Codec, value []byte) Pool {
pool, err := UnmarshalPool(cdc, value)
if err != nil {
panic(err)
}
return pool
}
// unmarshal the current pool value from store key
func UnmarshalPool(cdc *codec.Codec, value []byte) (pool Pool, err error) {
err = cdc.UnmarshalBinaryLengthPrefixed(value, &pool)
if err != nil {
return
}
return
}