-
Notifications
You must be signed in to change notification settings - Fork 568
/
pot.go
366 lines (319 loc) · 12.2 KB
/
pot.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
package keeper
import (
"encoding/json"
"fmt"
"time"
"github.com/c-osmosis/osmosis/x/incentives/types"
lockuptypes "github.com/c-osmosis/osmosis/x/lockup/types"
sdk "github.com/cosmos/cosmos-sdk/types"
db "github.com/tendermint/tm-db"
)
// Iterate over everything in a pots iterator, until it reaches the end. Return all pots iterated over.
func (k Keeper) getPotsFromIterator(ctx sdk.Context, iterator db.Iterator) []types.Pot {
pots := []types.Pot{}
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
potIDs := []uint64{}
err := json.Unmarshal(iterator.Value(), &potIDs)
if err != nil {
panic(err)
}
for _, potID := range potIDs {
pot, err := k.GetPotByID(ctx, potID)
if err != nil {
panic(err)
}
pots = append(pots, *pot)
}
}
return pots
}
// Compute the total amount of coins in all the pots
func (k Keeper) getCoinsFromPots(pots []types.Pot) sdk.Coins {
coins := sdk.Coins{}
for _, pot := range pots {
coins = coins.Add(pot.Coins...)
}
return coins
}
func (k Keeper) getDistributedCoinsFromPots(pots []types.Pot) sdk.Coins {
coins := sdk.Coins{}
for _, pot := range pots {
coins = coins.Add(pot.DistributedCoins...)
}
return coins
}
func (k Keeper) getToDistributeCoinsFromPots(pots []types.Pot) sdk.Coins {
// TODO: Consider optimizing this in the future to only require one iteration over all pots.
coins := k.getCoinsFromPots(pots)
distributed := k.getDistributedCoinsFromPots(pots)
return coins.Sub(distributed)
}
func (k Keeper) getCoinsFromIterator(ctx sdk.Context, iterator db.Iterator) sdk.Coins {
return k.getCoinsFromPots(k.getPotsFromIterator(ctx, iterator))
}
func (k Keeper) getToDistributeCoinsFromIterator(ctx sdk.Context, iterator db.Iterator) sdk.Coins {
return k.getToDistributeCoinsFromPots(k.getPotsFromIterator(ctx, iterator))
}
func (k Keeper) getDistributedCoinsFromIterator(ctx sdk.Context, iterator db.Iterator) sdk.Coins {
return k.getDistributedCoinsFromPots(k.getPotsFromIterator(ctx, iterator))
}
// setPot set the pot inside store
func (k Keeper) setPot(ctx sdk.Context, pot *types.Pot) error {
store := ctx.KVStore(k.storeKey)
store.Set(potStoreKey(pot.Id), k.cdc.MustMarshalJSON(pot))
return nil
}
func (k Keeper) SetPotWithRefKey(ctx sdk.Context, pot *types.Pot) error {
k.setPot(ctx, pot)
curTime := ctx.BlockTime()
timeKey := getTimeKey(pot.StartTime)
if pot.IsUpcomingPot(curTime) {
k.addPotRefByKey(ctx, combineKeys(types.KeyPrefixUpcomingPots, timeKey), pot.Id)
} else if pot.IsActivePot(curTime) {
k.addPotRefByKey(ctx, combineKeys(types.KeyPrefixActivePots, timeKey), pot.Id)
} else {
k.addPotRefByKey(ctx, combineKeys(types.KeyPrefixFinishedPots, timeKey), pot.Id)
}
store := ctx.KVStore(k.storeKey)
store.Set(potStoreKey(pot.Id), k.cdc.MustMarshalJSON(pot))
return nil
}
// CreatePot create a pot and send coins to the pot
func (k Keeper) CreatePot(ctx sdk.Context, isPerpetual bool, owner sdk.AccAddress, coins sdk.Coins, distrTo lockuptypes.QueryCondition, startTime time.Time, numEpochsPaidOver uint64) (uint64, error) {
pot := types.Pot{
Id: k.getLastPotID(ctx) + 1,
IsPerpetual: isPerpetual,
DistributeTo: distrTo,
Coins: coins,
StartTime: startTime,
NumEpochsPaidOver: numEpochsPaidOver,
}
if err := k.bk.SendCoinsFromAccountToModule(ctx, owner, types.ModuleName, pot.Coins); err != nil {
return 0, err
}
k.setPot(ctx, &pot)
k.setLastPotID(ctx, pot.Id)
if err := k.addPotRefByKey(ctx, combineKeys(types.KeyPrefixUpcomingPots, getTimeKey(pot.StartTime)), pot.Id); err != nil {
return 0, err
}
k.hooks.AfterCreatePot(ctx, pot.Id)
return pot.Id, nil
}
// AddToPot add coins to pot
func (k Keeper) AddToPotRewards(ctx sdk.Context, owner sdk.AccAddress, coins sdk.Coins, potID uint64) error {
pot, err := k.GetPotByID(ctx, potID)
if err != nil {
return err
}
if err := k.bk.SendCoinsFromAccountToModule(ctx, owner, types.ModuleName, coins); err != nil {
return err
}
pot.Coins = pot.Coins.Add(coins...)
k.setPot(ctx, pot)
k.hooks.AfterAddToPot(ctx, pot.Id)
return nil
}
// BeginDistribution is a utility to begin distribution for a specific pot
func (k Keeper) BeginDistribution(ctx sdk.Context, pot types.Pot) error {
// validation for current time and distribution start time
curTime := ctx.BlockTime()
if curTime.Before(pot.StartTime) {
return fmt.Errorf("pot is not able to start distribution yet: %s >= %s", curTime.String(), pot.StartTime.String())
}
timeKey := getTimeKey(pot.StartTime)
k.deletePotRefByKey(ctx, combineKeys(types.KeyPrefixUpcomingPots, timeKey), pot.Id)
k.addPotRefByKey(ctx, combineKeys(types.KeyPrefixActivePots, timeKey), pot.Id)
k.hooks.AfterFinishDistribution(ctx, pot.Id)
return nil
}
// FinishDistribution is a utility to finish distribution for a specific pot
func (k Keeper) FinishDistribution(ctx sdk.Context, pot types.Pot) error {
timeKey := getTimeKey(pot.StartTime)
k.deletePotRefByKey(ctx, combineKeys(types.KeyPrefixActivePots, timeKey), pot.Id)
k.addPotRefByKey(ctx, combineKeys(types.KeyPrefixFinishedPots, timeKey), pot.Id)
k.hooks.AfterFinishDistribution(ctx, pot.Id)
return nil
}
// GetLocksToDistribution get locks that are associated to a condition
func (k Keeper) GetLocksToDistribution(ctx sdk.Context, distrTo lockuptypes.QueryCondition) []lockuptypes.PeriodLock {
switch distrTo.LockQueryType {
case lockuptypes.ByDuration:
return k.lk.GetLocksLongerThanDurationDenom(ctx, distrTo.Denom, distrTo.Duration)
case lockuptypes.ByTime:
return k.lk.GetLocksPastTimeDenom(ctx, distrTo.Denom, distrTo.Timestamp)
default:
}
return []lockuptypes.PeriodLock{}
}
// FilteredLocksDistributionEst estimate distribution amount coins from pot for fitting conditions
func (k Keeper) FilteredLocksDistributionEst(ctx sdk.Context, pot types.Pot, filteredLocks []lockuptypes.PeriodLock) (types.Pot, sdk.Coins, error) {
filteredLockIDs := make(map[uint64]bool)
for _, lock := range filteredLocks {
filteredLockIDs[lock.ID] = true
}
totalDistrCoins := sdk.NewCoins()
filteredDistrCoins := sdk.NewCoins()
locks := k.GetLocksToDistribution(ctx, pot.DistributeTo)
lockSum := lockuptypes.SumLocksByDenom(locks, pot.DistributeTo.Denom)
if lockSum.IsZero() {
return types.Pot{}, nil, nil
}
remainCoins := pot.Coins.Sub(pot.DistributedCoins)
remainEpochs := uint64(1)
if !pot.IsPerpetual { // set remain epochs when it's not perpetual pot
remainEpochs = pot.NumEpochsPaidOver - pot.FilledEpochs
}
for _, lock := range locks {
distrCoins := sdk.Coins{}
for _, coin := range remainCoins {
// distribution amount = pot_size * denom_lock_amount / (total_denom_lock_amount * remain_epochs)
denomLockAmt := lock.Coins.AmountOf(pot.DistributeTo.Denom)
amt := coin.Amount.Mul(denomLockAmt).Quo(lockSum.Mul(sdk.NewInt(int64(remainEpochs))))
if amt.IsPositive() {
distrCoins = distrCoins.Add(sdk.NewCoin(coin.Denom, amt))
}
}
distrCoins = distrCoins.Sort()
if !distrCoins.Empty() && (len(filteredLocks) == 0 || filteredLockIDs[lock.ID]) {
filteredDistrCoins = filteredDistrCoins.Add(distrCoins...)
}
totalDistrCoins = totalDistrCoins.Add(distrCoins...)
}
// increase filled epochs after distribution
pot.FilledEpochs += 1
pot.DistributedCoins = pot.DistributedCoins.Add(totalDistrCoins...)
return pot, filteredDistrCoins, nil
}
// Distribute coins from pot according to its conditions
func (k Keeper) Distribute(ctx sdk.Context, pot types.Pot) (sdk.Coins, error) {
totalDistrCoins := sdk.NewCoins()
locks := k.GetLocksToDistribution(ctx, pot.DistributeTo)
lockSum := lockuptypes.SumLocksByDenom(locks, pot.DistributeTo.Denom)
if lockSum.IsZero() {
return nil, nil
}
remainCoins := pot.Coins.Sub(pot.DistributedCoins)
remainEpochs := uint64(1)
if !pot.IsPerpetual { // set remain epochs when it's not perpetual pot
remainEpochs = pot.NumEpochsPaidOver - pot.FilledEpochs
}
for _, lock := range locks {
distrCoins := sdk.Coins{}
for _, coin := range remainCoins {
// distribution amount = pot_size * denom_lock_amount / (total_denom_lock_amount * remain_epochs)
denomLockAmt := lock.Coins.AmountOf(pot.DistributeTo.Denom)
amt := coin.Amount.Mul(denomLockAmt).Quo(lockSum.Mul(sdk.NewInt(int64(remainEpochs))))
if amt.IsPositive() {
distrCoins = distrCoins.Add(sdk.NewCoin(coin.Denom, amt))
}
}
distrCoins = distrCoins.Sort()
if distrCoins.Empty() {
continue
}
owner, err := sdk.AccAddressFromBech32(lock.Owner)
if err != nil {
return nil, err
}
if err := k.bk.SendCoinsFromModuleToAccount(ctx, types.ModuleName, owner, distrCoins); err != nil {
return nil, err
}
totalDistrCoins = totalDistrCoins.Add(distrCoins...)
}
// increase filled epochs after distribution
pot.FilledEpochs += 1
pot.DistributedCoins = pot.DistributedCoins.Add(totalDistrCoins...)
k.setPot(ctx, &pot)
k.hooks.AfterDistribute(ctx, pot.Id)
return totalDistrCoins, nil
}
// GetModuleToDistributeCoins returns sum of to distribute coins for all of the module
func (k Keeper) GetModuleToDistributeCoins(ctx sdk.Context) sdk.Coins {
activePotsDistr := k.getToDistributeCoinsFromIterator(ctx, k.ActivePotsIterator(ctx))
upcomingPotsDistr := k.getToDistributeCoinsFromIterator(ctx, k.UpcomingPotsIteratorAfterTime(ctx, ctx.BlockTime()))
return activePotsDistr.Add(upcomingPotsDistr...)
}
// GetModuleDistributedCoins returns sum of distributed coins so far
func (k Keeper) GetModuleDistributedCoins(ctx sdk.Context) sdk.Coins {
activePotsDistr := k.getDistributedCoinsFromIterator(ctx, k.ActivePotsIterator(ctx))
finishedPotsDistr := k.getDistributedCoinsFromIterator(ctx, k.FinishedPotsIterator(ctx))
return activePotsDistr.Add(finishedPotsDistr...)
}
// GetPotByID Returns pot from pot ID
func (k Keeper) GetPotByID(ctx sdk.Context, potID uint64) (*types.Pot, error) {
pot := types.Pot{}
store := ctx.KVStore(k.storeKey)
potKey := potStoreKey(potID)
if !store.Has(potKey) {
return nil, fmt.Errorf("pot with ID %d does not exist", potID)
}
bz := store.Get(potKey)
k.cdc.MustUnmarshalJSON(bz, &pot)
return &pot, nil
}
// GetPotFromIDs returns pots from pot ids reference
func (k Keeper) GetPotFromIDs(ctx sdk.Context, refValue []byte) ([]types.Pot, error) {
pots := []types.Pot{}
potIDs := []uint64{}
err := json.Unmarshal(refValue, &potIDs)
if err != nil {
return pots, err
}
for _, potID := range potIDs {
pot, err := k.GetPotByID(ctx, potID)
if err != nil {
panic(err)
}
pots = append(pots, *pot)
}
return pots, nil
}
// GetPots returns pots both upcoming and active
func (k Keeper) GetPots(ctx sdk.Context) []types.Pot {
return k.getPotsFromIterator(ctx, k.PotsIterator(ctx))
}
func (k Keeper) GetNotFinishedPots(ctx sdk.Context) []types.Pot {
return append(k.GetActivePots(ctx), k.GetUpcomingPots(ctx)...)
}
// GetActivePots returns active pots
func (k Keeper) GetActivePots(ctx sdk.Context) []types.Pot {
return k.getPotsFromIterator(ctx, k.ActivePotsIterator(ctx))
}
// GetUpcomingPots returns scheduled pots
func (k Keeper) GetUpcomingPots(ctx sdk.Context) []types.Pot {
return k.getPotsFromIterator(ctx, k.UpcomingPotsIterator(ctx))
}
// GetFinishedPots returns finished pots
func (k Keeper) GetFinishedPots(ctx sdk.Context) []types.Pot {
return k.getPotsFromIterator(ctx, k.FinishedPotsIterator(ctx))
}
// GetRewardsEst returns rewards estimation at a future specific time
func (k Keeper) GetRewardsEst(ctx sdk.Context, addr sdk.AccAddress, locks []lockuptypes.PeriodLock, pots []types.Pot, endEpoch int64) sdk.Coins {
// initialize pots to active and upcomings if not set
if len(pots) == 0 {
pots = k.GetNotFinishedPots(ctx)
}
// estimate rewards
estimatedRewards := sdk.Coins{}
params := k.GetParams(ctx)
epochInfo := k.ek.GetEpochInfo(ctx, params.DistrEpochIdentifier)
// no need to change storage while doing estimation and we use cached context
cacheCtx, _ := ctx.CacheContext()
for _, pot := range pots {
distrBeginEpoch := epochInfo.CurrentEpoch
blockTime := ctx.BlockTime()
if pot.StartTime.After(blockTime) {
distrBeginEpoch = epochInfo.CurrentEpoch + 1 + int64(pot.StartTime.Sub(blockTime)/epochInfo.Duration)
}
for epoch := distrBeginEpoch; epoch <= endEpoch; epoch++ {
newPot, distrCoins, err := k.FilteredLocksDistributionEst(cacheCtx, pot, locks)
if err != nil {
continue
}
estimatedRewards = estimatedRewards.Add(distrCoins...)
pot = newPot
}
}
return estimatedRewards
}