-
Notifications
You must be signed in to change notification settings - Fork 568
/
total_liquidity.go
81 lines (68 loc) · 1.97 KB
/
total_liquidity.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
package keeper
import (
"github.com/cosmos/cosmos-sdk/store/prefix"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/osmosis-labs/osmosis/v12/x/gamm/types"
)
func (k Keeper) GetTotalLiquidity(ctx sdk.Context) sdk.Coins {
coins := sdk.Coins{}
k.IterateDenomLiquidity(ctx, func(coin sdk.Coin) bool {
coins = coins.Add(coin)
return false
})
return coins
}
func (k Keeper) setTotalLiquidity(ctx sdk.Context, coins sdk.Coins) {
for _, coin := range coins {
k.setDenomLiquidity(ctx, coin.Denom, coin.Amount)
}
}
func (k Keeper) setDenomLiquidity(ctx sdk.Context, denom string, amount sdk.Int) {
store := ctx.KVStore(k.storeKey)
bz, err := amount.Marshal()
if err != nil {
panic(err)
}
store.Set(types.GetDenomPrefix(denom), bz)
}
func (k Keeper) GetDenomLiquidity(ctx sdk.Context, denom string) sdk.Int {
store := ctx.KVStore(k.storeKey)
bz := store.Get(types.GetDenomPrefix(denom))
if bz == nil {
return sdk.NewInt(0)
}
var amount sdk.Int
if err := amount.Unmarshal(bz); err != nil {
panic(err)
}
return amount
}
func (k Keeper) IterateDenomLiquidity(ctx sdk.Context, cb func(sdk.Coin) bool) {
store := ctx.KVStore(k.storeKey)
prefixStore := prefix.NewStore(store, types.KeyTotalLiquidity)
iterator := prefixStore.Iterator(nil, nil)
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
var amount sdk.Int
if err := amount.Unmarshal(iterator.Value()); err != nil {
panic(err)
}
if cb(sdk.NewCoin(string(iterator.Key()), amount)) {
break
}
}
}
func (k Keeper) RecordTotalLiquidityIncrease(ctx sdk.Context, coins sdk.Coins) {
for _, coin := range coins {
amount := k.GetDenomLiquidity(ctx, coin.Denom)
amount = amount.Add(coin.Amount)
k.setDenomLiquidity(ctx, coin.Denom, amount)
}
}
func (k Keeper) RecordTotalLiquidityDecrease(ctx sdk.Context, coins sdk.Coins) {
for _, coin := range coins {
amount := k.GetDenomLiquidity(ctx, coin.Denom)
amount = amount.Sub(coin.Amount)
k.setDenomLiquidity(ctx, coin.Denom, amount)
}
}