/
plan.go
389 lines (328 loc) 路 12.1 KB
/
plan.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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
package keeper
import (
"fmt"
"strconv"
gogotypes "github.com/gogo/protobuf/types"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/crescent-network/crescent/v3/x/farming/types"
)
// GetPlan returns a plan for a given plan id.
func (k Keeper) GetPlan(ctx sdk.Context, id uint64) (plan types.PlanI, found bool) {
store := ctx.KVStore(k.storeKey)
bz := store.Get(types.GetPlanKey(id))
if bz == nil {
return plan, false
}
return k.decodePlan(bz), true
}
// GetPlans returns all plans in the store.
func (k Keeper) GetPlans(ctx sdk.Context) (plans []types.PlanI) {
k.IteratePlans(ctx, func(plan types.PlanI) (stop bool) {
plans = append(plans, plan)
return false
})
return plans
}
// SetPlan sets a plan for a given plan id.
func (k Keeper) SetPlan(ctx sdk.Context, plan types.PlanI) {
id := plan.GetId()
store := ctx.KVStore(k.storeKey)
bz, err := k.MarshalPlan(plan)
if err != nil {
panic(err)
}
store.Set(types.GetPlanKey(id), bz)
}
// DeletePlan deletes a plan from the store.
// NOTE: this will cause supply invariant violation if called
func (k Keeper) DeletePlan(ctx sdk.Context, plan types.PlanI) {
id := plan.GetId()
store := ctx.KVStore(k.storeKey)
store.Delete(types.GetPlanKey(id))
}
// IteratePlans iterates over all the stored plans and performs a callback function.
// Stops iteration when callback returns true.
func (k Keeper) IteratePlans(ctx sdk.Context, cb func(plan types.PlanI) (stop bool)) {
store := ctx.KVStore(k.storeKey)
iterator := sdk.KVStorePrefixIterator(store, types.PlanKeyPrefix)
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
plan := k.decodePlan(iterator.Value())
if cb(plan) {
break
}
}
}
// GetNextPlanIdWithUpdate returns and increments the global Plan ID counter.
// If the global plan number is not set, it initializes it with value 0.
func (k Keeper) GetNextPlanIdWithUpdate(ctx sdk.Context) uint64 {
id := k.GetGlobalPlanId(ctx) + 1
k.SetGlobalPlanId(ctx, id)
return id
}
// SetGlobalPlanId sets the global Plan ID counter.
func (k Keeper) SetGlobalPlanId(ctx sdk.Context, id uint64) {
store := ctx.KVStore(k.storeKey)
bz := k.cdc.MustMarshal(&gogotypes.UInt64Value{Value: id})
store.Set(types.GlobalPlanIdKey, bz)
}
// GetGlobalPlanId returns the global Plan ID counter.
func (k Keeper) GetGlobalPlanId(ctx sdk.Context) uint64 {
var id uint64
store := ctx.KVStore(k.storeKey)
bz := store.Get(types.GlobalPlanIdKey)
if bz == nil {
// initialize the PlanId
id = 0
} else {
val := gogotypes.UInt64Value{}
k.cdc.MustUnmarshal(bz, &val)
id = val.GetValue()
}
return id
}
func (k Keeper) DeleteGlobalPlanId(ctx sdk.Context) {
store := ctx.KVStore(k.storeKey)
store.Delete(types.GlobalPlanIdKey)
}
func (k Keeper) decodePlan(bz []byte) types.PlanI {
acc, err := k.UnmarshalPlan(bz)
if err != nil {
panic(err)
}
return acc
}
// GetNumActivePrivatePlans returns the number of active(non-terminated)
// private plans.
func (k Keeper) GetNumActivePrivatePlans(ctx sdk.Context) int {
num := 0
k.IteratePlans(ctx, func(plan types.PlanI) (stop bool) {
if plan.GetType() == types.PlanTypePrivate && !plan.IsTerminated() {
num++
}
return false
})
return num
}
// MarshalPlan serializes a plan.
func (k Keeper) MarshalPlan(plan types.PlanI) ([]byte, error) { // nolint:interfacer
return k.cdc.MarshalInterface(plan)
}
// UnmarshalPlan returns a plan from raw serialized
// bytes of a Proto-based Plan type.
func (k Keeper) UnmarshalPlan(bz []byte) (plan types.PlanI, err error) {
return plan, k.cdc.UnmarshalInterface(bz, &plan)
}
// CreateFixedAmountPlan sets fixed amount plan.
func (k Keeper) CreateFixedAmountPlan(ctx sdk.Context, msg *types.MsgCreateFixedAmountPlan, farmingPoolAcc, terminationAcc sdk.AccAddress, typ types.PlanType) (types.PlanI, error) {
if !ctx.BlockTime().Before(msg.EndTime) { // EndTime <= BlockTime
return nil, sdkerrors.Wrap(types.ErrInvalidPlanEndTime, "end time has already passed")
}
for _, coin := range msg.StakingCoinWeights {
if k.bankKeeper.GetSupply(ctx, coin.Denom).Amount.IsZero() {
return nil, sdkerrors.Wrapf(types.ErrInvalidStakingCoinWeights, "denom %s has no supply", coin.Denom)
}
}
for _, coin := range msg.EpochAmount {
if k.bankKeeper.GetSupply(ctx, coin.Denom).Amount.IsZero() {
return nil, sdkerrors.Wrapf(types.ErrInvalidEpochAmount, "denom %s has no supply", coin.Denom)
}
}
var maxNumDenoms int
switch typ {
case types.PlanTypePrivate:
maxNumDenoms = types.PrivatePlanMaxNumDenoms
case types.PlanTypePublic:
maxNumDenoms = types.PublicPlanMaxNumDenoms
}
if len(msg.StakingCoinWeights) > maxNumDenoms {
return nil, sdkerrors.Wrapf(
types.ErrNumMaxDenomsLimit,
"number of denoms in staking coin weights is %d, which exceeds the limit %d",
len(msg.StakingCoinWeights), maxNumDenoms)
}
if len(msg.EpochAmount) > maxNumDenoms {
return nil, sdkerrors.Wrapf(
types.ErrNumMaxDenomsLimit,
"number of denoms in epoch amount is %d, which exceeds the limit %d",
len(msg.EpochAmount), maxNumDenoms)
}
params := k.GetParams(ctx)
if typ == types.PlanTypePrivate {
if uint32(k.GetNumActivePrivatePlans(ctx)) >= params.MaxNumPrivatePlans {
return nil, types.ErrNumPrivatePlansLimit
}
feeCollectorAcc, _ := sdk.AccAddressFromBech32(params.FarmingFeeCollector) // Already validated
if err := k.bankKeeper.SendCoins(ctx, msg.GetCreator(), feeCollectorAcc, params.PrivatePlanCreationFee); err != nil {
return nil, sdkerrors.Wrap(err, "failed to pay private plan creation fee")
}
}
nextId := k.GetNextPlanIdWithUpdate(ctx)
basePlan := types.NewBasePlan(
nextId,
msg.Name,
typ,
farmingPoolAcc.String(),
terminationAcc.String(),
msg.StakingCoinWeights,
msg.StartTime,
msg.EndTime,
)
fixedPlan := types.NewFixedAmountPlan(basePlan, msg.EpochAmount)
k.SetPlan(ctx, fixedPlan)
ctx.EventManager().EmitEvents(sdk.Events{
sdk.NewEvent(
types.EventTypeCreateFixedAmountPlan,
sdk.NewAttribute(types.AttributeKeyPlanId, strconv.FormatUint(nextId, 10)),
sdk.NewAttribute(types.AttributeKeyPlanName, msg.Name),
sdk.NewAttribute(types.AttributeKeyFarmingPoolAddress, farmingPoolAcc.String()),
sdk.NewAttribute(types.AttributeKeyStartTime, msg.StartTime.String()),
sdk.NewAttribute(types.AttributeKeyEndTime, msg.EndTime.String()),
sdk.NewAttribute(types.AttributeKeyEpochAmount, msg.EpochAmount.String()),
),
})
return fixedPlan, nil
}
// CreateRatioPlan sets ratio plan.
func (k Keeper) CreateRatioPlan(ctx sdk.Context, msg *types.MsgCreateRatioPlan, farmingPoolAcc, terminationAcc sdk.AccAddress, typ types.PlanType) (types.PlanI, error) {
if !ctx.BlockTime().Before(msg.EndTime) { // EndTime <= BlockTime
return nil, sdkerrors.Wrap(types.ErrInvalidPlanEndTime, "end time has already passed")
}
for _, coin := range msg.StakingCoinWeights {
if k.bankKeeper.GetSupply(ctx, coin.Denom).Amount.IsZero() {
return nil, sdkerrors.Wrapf(types.ErrInvalidStakingCoinWeights, "denom %s has no supply", coin.Denom)
}
}
var maxNumDenoms int
switch typ {
case types.PlanTypePrivate:
maxNumDenoms = types.PrivatePlanMaxNumDenoms
case types.PlanTypePublic:
maxNumDenoms = types.PublicPlanMaxNumDenoms
}
if len(msg.StakingCoinWeights) > maxNumDenoms {
return nil, sdkerrors.Wrapf(
types.ErrNumMaxDenomsLimit,
"number of denoms in staking coin weights is %d, which exceeds the limit %d",
len(msg.StakingCoinWeights), maxNumDenoms)
}
params := k.GetParams(ctx)
if typ == types.PlanTypePrivate {
if uint32(k.GetNumActivePrivatePlans(ctx)) >= params.MaxNumPrivatePlans {
return nil, types.ErrNumPrivatePlansLimit
}
feeCollectorAcc, _ := sdk.AccAddressFromBech32(params.FarmingFeeCollector) // Already validated
if err := k.bankKeeper.SendCoins(ctx, msg.GetCreator(), feeCollectorAcc, params.PrivatePlanCreationFee); err != nil {
return nil, sdkerrors.Wrap(err, "failed to pay private plan creation fee")
}
}
nextId := k.GetNextPlanIdWithUpdate(ctx)
basePlan := types.NewBasePlan(
nextId,
msg.Name,
typ,
farmingPoolAcc.String(),
terminationAcc.String(),
msg.StakingCoinWeights,
msg.StartTime,
msg.EndTime,
)
ratioPlan := types.NewRatioPlan(basePlan, msg.EpochRatio)
k.SetPlan(ctx, ratioPlan)
ctx.EventManager().EmitEvents(sdk.Events{
sdk.NewEvent(
types.EventTypeCreateRatioPlan,
sdk.NewAttribute(types.AttributeKeyPlanId, strconv.FormatUint(nextId, 10)),
sdk.NewAttribute(types.AttributeKeyPlanName, msg.Name),
sdk.NewAttribute(types.AttributeKeyFarmingPoolAddress, farmingPoolAcc.String()),
sdk.NewAttribute(types.AttributeKeyStartTime, msg.StartTime.String()),
sdk.NewAttribute(types.AttributeKeyEndTime, msg.EndTime.String()),
sdk.NewAttribute(types.AttributeKeyEpochRatio, msg.EpochRatio.String()),
),
})
return ratioPlan, nil
}
// TerminatePlan marks the plan as terminated.
// It moves the plan under different store key, which is for terminated plans.
func (k Keeper) TerminatePlan(ctx sdk.Context, plan types.PlanI) error {
if plan.GetFarmingPoolAddress().String() != plan.GetTerminationAddress().String() {
balances := k.bankKeeper.SpendableCoins(ctx, plan.GetFarmingPoolAddress())
if !balances.IsZero() {
if err := k.bankKeeper.SendCoins(ctx, plan.GetFarmingPoolAddress(), plan.GetTerminationAddress(), balances); err != nil {
return err
}
}
}
switch plan.GetType() {
case types.PlanTypePrivate:
// For private plans, mark the plan as terminated so that it can be removed
// later by the creator.
_ = plan.SetTerminated(true)
k.SetPlan(ctx, plan)
case types.PlanTypePublic:
// Delete the public plan immediately after terminating it.
k.DeletePlan(ctx, plan)
}
ctx.EventManager().EmitEvents(sdk.Events{
sdk.NewEvent(
types.EventTypePlanTerminated,
sdk.NewAttribute(types.AttributeKeyPlanId, strconv.FormatUint(plan.GetId(), 10)),
),
})
return nil
}
// TerminateEndedPlans terminates plans that have been ended.
func (k Keeper) TerminateEndedPlans(ctx sdk.Context) error {
for _, plan := range k.GetPlans(ctx) {
if !plan.IsTerminated() && !ctx.BlockTime().Before(plan.GetEndTime()) {
if err := k.TerminatePlan(ctx, plan); err != nil {
return fmt.Errorf("terminate plan %d: %w", plan.GetId(), err)
}
}
}
return nil
}
// RemovePlan removes a terminated plan and sends all remaining coins in the
// farming pool address to the termination address.
func (k Keeper) RemovePlan(ctx sdk.Context, creator sdk.AccAddress, planId uint64) error {
plan, found := k.GetPlan(ctx, planId)
if !found {
return sdkerrors.Wrapf(sdkerrors.ErrNotFound, "plan %d not found", planId)
}
if !plan.IsTerminated() {
return sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, "plan %d is not terminated yet", planId)
}
if plan.GetType() != types.PlanTypePrivate {
return sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, "plan %d is not a private plan", planId)
}
if !plan.GetTerminationAddress().Equals(creator) {
return sdkerrors.Wrap(sdkerrors.ErrUnauthorized, "only the plan creator can remove the plan")
}
// Refund private plan creation fee.
params := k.GetParams(ctx)
feeCollectorAcc, _ := sdk.AccAddressFromBech32(params.FarmingFeeCollector) // Already validated
if err := k.bankKeeper.SendCoins(ctx, feeCollectorAcc, creator, params.PrivatePlanCreationFee); err != nil {
return sdkerrors.Wrap(err, "failed to refund private plan creation fee")
}
k.DeletePlan(ctx, plan)
ctx.EventManager().EmitEvents(sdk.Events{
sdk.NewEvent(
types.EventTypeRemovePlan,
sdk.NewAttribute(types.AttributeKeyPlanId, strconv.FormatUint(plan.GetId(), 10)),
sdk.NewAttribute(types.AttributeKeyFarmingPoolAddress, plan.GetFarmingPoolAddress().String()),
sdk.NewAttribute(types.AttributeKeyTerminationAddress, plan.GetTerminationAddress().String()),
),
})
return nil
}
// DerivePrivatePlanFarmingPoolAcc returns a unique account address
// of a farming pool for a private plan.
func (k Keeper) DerivePrivatePlanFarmingPoolAcc(ctx sdk.Context, name string) (sdk.AccAddress, error) {
nextPlanId := k.GetGlobalPlanId(ctx) + 1
poolAcc := types.PrivatePlanFarmingPoolAcc(name, nextPlanId)
if !k.bankKeeper.GetAllBalances(ctx, poolAcc).Empty() {
return nil, types.ErrConflictPrivatePlanFarmingPool
}
return poolAcc, nil
}