-
Notifications
You must be signed in to change notification settings - Fork 55
/
plan.go
242 lines (217 loc) 路 7.29 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
package keeper
import (
"time"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/crescent-network/crescent/v3/x/lpfarm/types"
)
// CreatePrivatePlan creates a new private farming plan.
func (k Keeper) CreatePrivatePlan(
ctx sdk.Context, creatorAddr sdk.AccAddress, description string,
rewardAllocs []types.RewardAllocation, startTime, endTime time.Time,
) (types.Plan, error) {
if !k.CanCreatePrivatePlan(ctx) {
return types.Plan{}, sdkerrors.Wrapf(
sdkerrors.ErrInvalidRequest,
"maximum number of active private plans reached")
}
fee := k.GetPrivatePlanCreationFee(ctx)
feeCollectorAddr, err := sdk.AccAddressFromBech32(k.GetFeeCollector(ctx))
if err != nil {
return types.Plan{}, err
}
if err := k.bankKeeper.SendCoins(ctx, creatorAddr, feeCollectorAddr, fee); err != nil {
return types.Plan{}, err
}
id, _ := k.GetLastPlanId(ctx)
farmingPoolAddr := types.DeriveFarmingPoolAddress(id + 1)
plan, err := k.createPlan(
ctx, description, farmingPoolAddr, creatorAddr,
rewardAllocs, startTime, endTime, true)
if err != nil {
return types.Plan{}, err
}
if err := ctx.EventManager().EmitTypedEvent(&types.EventCreatePrivatePlan{
Creator: creatorAddr.String(),
PlanId: plan.Id,
FarmingPoolAddress: plan.FarmingPoolAddress,
}); err != nil {
return types.Plan{}, err
}
return plan, nil
}
// CreatePublicPlan creates a new public farming plan.
func (k Keeper) CreatePublicPlan(
ctx sdk.Context, description string,
farmingPoolAddr sdk.AccAddress,
rewardAllocs []types.RewardAllocation, startTime, endTime time.Time,
) (types.Plan, error) {
return k.createPlan(
ctx, description, farmingPoolAddr, farmingPoolAddr,
rewardAllocs, startTime, endTime, false)
}
func (k Keeper) createPlan(
ctx sdk.Context, description string, farmingPoolAddr, termAddr sdk.AccAddress,
rewardAllocs []types.RewardAllocation, startTime, endTime time.Time, isPrivate bool,
) (types.Plan, error) {
// Check if end time > block time
if !endTime.After(ctx.BlockTime()) {
return types.Plan{}, sdkerrors.Wrap(
sdkerrors.ErrInvalidRequest, "end time is past")
}
for _, rewardAlloc := range rewardAllocs {
if rewardAlloc.PairId > 0 {
_, found := k.liquidityKeeper.GetPair(ctx, rewardAlloc.PairId)
if !found {
return types.Plan{}, sdkerrors.Wrapf(
sdkerrors.ErrNotFound, "pair %d not found", rewardAlloc.PairId)
}
} else {
if !k.bankKeeper.HasSupply(ctx, rewardAlloc.Denom) {
return types.Plan{}, sdkerrors.Wrapf(
sdkerrors.ErrInvalidRequest, "denom %s has no supply", rewardAlloc.Denom)
}
}
}
// Generate the next plan id and update the last plan id.
id, _ := k.GetLastPlanId(ctx)
id++
k.SetLastPlanId(ctx, id)
plan := types.NewPlan(
id, description, farmingPoolAddr, termAddr, rewardAllocs,
startTime, endTime, isPrivate)
k.SetPlan(ctx, plan)
if plan.IsPrivate {
k.SetNumPrivatePlans(ctx, k.GetNumPrivatePlans(ctx)+1)
}
return plan, nil
}
// TerminateEndedPlans iterates through all plans and terminate the plans
// which should be ended by the current block time.
func (k Keeper) TerminateEndedPlans(ctx sdk.Context) (err error) {
k.IterateAllPlans(ctx, func(plan types.Plan) (stop bool) {
if plan.IsTerminated {
return false
}
if !ctx.BlockTime().Before(plan.EndTime) {
if err = k.TerminatePlan(ctx, plan); err != nil {
return true
}
}
return false
})
return err
}
// TerminatePlan mark the plan as terminated and send remaining balances
// in the farming pool to the termination address.
func (k Keeper) TerminatePlan(ctx sdk.Context, plan types.Plan) error {
if plan.IsTerminated {
return types.ErrPlanAlreadyTerminated
}
farmingPoolAddr := plan.GetFarmingPoolAddress()
if plan.FarmingPoolAddress != plan.TerminationAddress {
balances := k.bankKeeper.SpendableCoins(ctx, farmingPoolAddr)
if !balances.IsZero() {
if err := k.bankKeeper.SendCoins(
ctx, farmingPoolAddr, plan.GetTerminationAddress(), balances); err != nil {
return err
}
}
}
plan.IsTerminated = true
k.SetPlan(ctx, plan)
if plan.IsPrivate {
k.SetNumPrivatePlans(ctx, k.GetNumPrivatePlans(ctx)-1)
}
if err := ctx.EventManager().EmitTypedEvent(&types.EventTerminatePlan{
PlanId: plan.Id,
}); err != nil {
return err
}
return nil
}
// AllocateRewards allocates the current block's rewards to the farms
// based on active plans.
func (k Keeper) AllocateRewards(ctx sdk.Context) error {
lastBlockTime, found := k.GetLastBlockTime(ctx)
if !found {
// For the very first block, just skip it.
return nil
}
blockDuration := ctx.BlockTime().Sub(lastBlockTime)
// Constrain the block duration to the max block duration param.
if maxBlockDuration := k.GetMaxBlockDuration(ctx); blockDuration > maxBlockDuration {
blockDuration = maxBlockDuration
}
// If the block duration is 0, skip this block for rewards allocation.
if blockDuration == 0 {
return nil
}
ck := newCachingKeeper(k)
ra := newRewardAllocator(ctx, k, ck)
k.IterateAllPlans(ctx, func(plan types.Plan) (stop bool) {
if plan.IsTerminated || !plan.IsActiveAt(ctx.BlockTime()) {
return false // Skip
}
for _, rewardAlloc := range plan.RewardAllocations {
rewards := types.RewardsForBlock(rewardAlloc.RewardsPerDay, blockDuration)
// TODO: allocate sdk.DecCoins instead of sdk.Coins in future
truncatedRewards, _ := rewards.TruncateDecimal()
if truncatedRewards.IsAllPositive() {
if rewardAlloc.Denom != "" {
ra.allocateRewardsToDenom(plan.GetFarmingPoolAddress(), rewardAlloc.Denom, truncatedRewards)
} else if rewardAlloc.PairId > 0 {
pair, found := ck.getPair(ctx, rewardAlloc.PairId)
if !found { // It should never happen
panic("pair not found")
}
if pair.LastPrice == nil { // If the pair doesn't have the last price, skip.
continue
}
ra.allocateRewardsToPair(plan.GetFarmingPoolAddress(), pair, truncatedRewards)
}
}
}
return false
})
rewardsByDenom := map[string]sdk.DecCoins{}
for _, farmingPoolAddr := range ra.farmingPoolAddrs {
farmingPool := farmingPoolAddr.String()
totalRewards := ra.totalRewardsByFarmingPool[farmingPool]
balances := k.bankKeeper.SpendableCoins(ctx, farmingPoolAddr)
if !balances.IsAllGTE(totalRewards) {
continue
}
if err := k.bankKeeper.SendCoins(
ctx, farmingPoolAddr, types.RewardsPoolAddress, totalRewards); err != nil {
return err
}
for denom, rewards := range ra.allocatedRewards[farmingPool] {
rewardsByDenom[denom] = rewardsByDenom[denom].Add(rewards...)
}
}
k.IterateAllFarms(ctx, func(denom string, farm types.Farm) (stop bool) {
if _, ok := rewardsByDenom[denom]; ok {
farm.CurrentRewards = farm.CurrentRewards.Add(rewardsByDenom[denom]...)
farm.OutstandingRewards = farm.OutstandingRewards.Add(rewardsByDenom[denom]...)
if pi, ok := ra.poolInfoByPoolCoinDenom[denom]; ok {
farm.PreviousShare = &pi.rewardsShare
} else {
farm.PreviousShare = nil
}
k.SetFarm(ctx, denom, farm)
} else {
if farm.PreviousShare != nil {
farm.PreviousShare = nil
k.SetFarm(ctx, denom, farm)
}
}
return false
})
return nil
}
// CanCreatePrivatePlan returns true if the current number of non-terminated
// private plans is less than the limit.
func (k Keeper) CanCreatePrivatePlan(ctx sdk.Context) bool {
return k.GetNumPrivatePlans(ctx) < uint64(k.GetMaxNumPrivatePlans(ctx))
}