-
Notifications
You must be signed in to change notification settings - Fork 51
/
keeper.go
523 lines (430 loc) · 17.6 KB
/
keeper.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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
package keeper
import (
"fmt"
"github.com/cometbft/cometbft/libs/log"
"github.com/cosmos/cosmos-sdk/codec"
storetypes "github.com/cosmos/cosmos-sdk/store/types"
sdk "github.com/cosmos/cosmos-sdk/types"
errorsmod "cosmossdk.io/errors"
"cosmossdk.io/math"
ammtypes "github.com/elys-network/elys/x/amm/types"
pkeeper "github.com/elys-network/elys/x/parameter/keeper"
"github.com/elys-network/elys/x/perpetual/types"
)
type (
Keeper struct {
types.AuthorizationChecker
types.PositionChecker
types.PoolChecker
types.OpenChecker
types.OpenLongChecker
types.OpenShortChecker
types.CloseLongChecker
types.CloseShortChecker
cdc codec.BinaryCodec
storeKey storetypes.StoreKey
memKey storetypes.StoreKey
authority string
parameterKeeper *pkeeper.Keeper
amm types.AmmKeeper
bankKeeper types.BankKeeper
oracleKeeper ammtypes.OracleKeeper
assetProfileKeeper types.AssetProfileKeeper
hooks types.PerpetualHooks
}
)
func NewKeeper(
cdc codec.BinaryCodec,
storeKey,
memKey storetypes.StoreKey,
authority string,
amm types.AmmKeeper,
bk types.BankKeeper,
oracleKeeper ammtypes.OracleKeeper,
assetProfileKeeper types.AssetProfileKeeper,
parameterKeeper *pkeeper.Keeper,
) *Keeper {
// ensure that authority is a valid AccAddress
if _, err := sdk.AccAddressFromBech32(authority); err != nil {
panic("authority is not a valid acc address")
}
keeper := &Keeper{
cdc: cdc,
storeKey: storeKey,
memKey: memKey,
authority: authority,
amm: amm,
bankKeeper: bk,
oracleKeeper: oracleKeeper,
assetProfileKeeper: assetProfileKeeper,
parameterKeeper: parameterKeeper,
}
keeper.AuthorizationChecker = keeper
keeper.PositionChecker = keeper
keeper.PoolChecker = keeper
keeper.OpenChecker = keeper
keeper.OpenLongChecker = keeper
keeper.OpenShortChecker = keeper
keeper.CloseLongChecker = keeper
keeper.CloseShortChecker = keeper
return keeper
}
func (k Keeper) Logger(ctx sdk.Context) log.Logger {
return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName))
}
// Swap estimation using amm CalcInAmtGivenOut function
func (k Keeper) EstimateSwapGivenOut(ctx sdk.Context, tokenOutAmount sdk.Coin, tokenInDenom string, ammPool ammtypes.Pool) (math.Int, error) {
perpetualEnabled := k.IsPoolEnabled(ctx, ammPool.PoolId)
if !perpetualEnabled {
return sdk.ZeroInt(), errorsmod.Wrap(types.ErrPerpetualDisabled, "Perpetual disabled pool")
}
tokensOut := sdk.Coins{tokenOutAmount}
// Estimate swap
snapshot := k.amm.GetPoolSnapshotOrSet(ctx, ammPool)
swapResult, _, err := k.amm.CalcInAmtGivenOut(ctx, ammPool.PoolId, k.oracleKeeper, &snapshot, tokensOut, tokenInDenom, sdk.ZeroDec())
if err != nil {
return sdk.ZeroInt(), err
}
if swapResult.IsZero() {
return sdk.ZeroInt(), types.ErrAmountTooLow
}
return swapResult.Amount, nil
}
func (k Keeper) Borrow(ctx sdk.Context, collateralAmount math.Int, custodyAmount math.Int, mtp *types.MTP, ammPool *ammtypes.Pool, pool *types.Pool, eta sdk.Dec, baseCurrency string, isBroker bool) error {
senderAddress, err := sdk.AccAddressFromBech32(mtp.Address)
if err != nil {
return err
}
// if isBroker is true, then retrieve broker address and assign it to senderAddress
if isBroker {
brokerAddress, err := sdk.AccAddressFromBech32(k.parameterKeeper.GetParams(ctx).BrokerAddress)
if err != nil {
return err
}
senderAddress = brokerAddress
}
collateralCoin := sdk.NewCoin(mtp.CollateralAsset, collateralAmount)
if !k.bankKeeper.HasBalance(ctx, senderAddress, collateralCoin) {
return types.ErrBalanceNotAvailable
}
collateralAmountDec := sdk.NewDecFromBigInt(collateralAmount.BigInt())
liabilitiesDec := collateralAmountDec.Mul(eta)
// If collateral asset is not base currency, should calculate liability in base currency with the given out.
// Liability has to be in base currency
if mtp.CollateralAsset != baseCurrency {
// ATOM amount
etaAmt := liabilitiesDec.TruncateInt()
etaAmtToken := sdk.NewCoin(mtp.CollateralAsset, etaAmt)
// Calculate base currency amount given atom out amount and we use it liabilty amount in base currency
liabilityAmt, err := k.OpenLongChecker.EstimateSwapGivenOut(ctx, etaAmtToken, baseCurrency, *ammPool)
if err != nil {
return err
}
liabilitiesDec = sdk.NewDecFromInt(liabilityAmt)
}
// If position is short, liabilities should be swapped to liabilities asset
if mtp.Position == types.Position_SHORT {
liabilitiesAmtTokenIn := sdk.NewCoin(baseCurrency, liabilitiesDec.TruncateInt())
liabilitiesAmt, err := k.OpenShortChecker.EstimateSwap(ctx, liabilitiesAmtTokenIn, mtp.LiabilitiesAsset, *ammPool)
if err != nil {
return err
}
liabilitiesDec = sdk.NewDecFromInt(liabilitiesAmt)
}
mtp.Collateral = collateralAmount
mtp.Liabilities = sdk.NewIntFromBigInt(liabilitiesDec.TruncateInt().BigInt())
mtp.Custody = custodyAmount
// calculate mtp take profit custody, delta y_tp_c = delta x_l / take profit price (take profit custody = liabilities / take profit price)
mtp.TakeProfitCustody = types.CalcMTPTakeProfitCustody(mtp)
// calculate mtp take profit liabilities, delta x_tp_l = delta y_tp_c * current price (take profit liabilities = take profit custody * current price)
mtp.TakeProfitLiabilities, err = k.CalcMTPTakeProfitLiability(ctx, mtp, baseCurrency)
if err != nil {
return err
}
mtp.Leverage = eta.Add(sdk.OneDec())
h, err := k.GetMTPHealth(ctx, *mtp, *ammPool, baseCurrency) // set mtp in func or return h?
if err != nil {
return err
}
mtp.MtpHealth = h
ammPoolAddr, err := sdk.AccAddressFromBech32(ammPool.Address)
if err != nil {
return err
}
collateralCoins := sdk.NewCoins(collateralCoin)
err = k.bankKeeper.SendCoins(ctx, senderAddress, ammPoolAddr, collateralCoins)
if err != nil {
return err
}
err = pool.UpdateBalance(ctx, mtp.CollateralAsset, collateralAmount, true, mtp.Position)
if err != nil {
return err
}
// All liability has to be in liabilities asset
err = pool.UpdateLiabilities(ctx, mtp.LiabilitiesAsset, mtp.Liabilities, true, mtp.Position)
if err != nil {
return err
}
// All take profit liability has to be in liabilities asset
err = pool.UpdateTakeProfitLiabilities(ctx, mtp.LiabilitiesAsset, mtp.TakeProfitLiabilities, true, mtp.Position)
if err != nil {
return err
}
// All take profit custody has to be in custody asset
err = pool.UpdateTakeProfitCustody(ctx, mtp.CustodyAsset, mtp.TakeProfitCustody, true, mtp.Position)
if err != nil {
return err
}
k.SetPool(ctx, *pool)
return k.SetMTP(ctx, mtp)
}
func (k Keeper) UpdatePoolHealth(ctx sdk.Context, pool *types.Pool) error {
pool.Health = k.CalculatePoolHealth(ctx, pool)
k.SetPool(ctx, *pool)
return nil
}
func (k Keeper) CalculatePoolHealthByPosition(ctx sdk.Context, pool *types.Pool, ammPool ammtypes.Pool, position types.Position) sdk.Dec {
poolAssets := pool.GetPoolAssets(position)
H := sdk.NewDec(1)
for _, asset := range *poolAssets {
ammBalance, err := types.GetAmmPoolBalance(ammPool, asset.AssetDenom)
if err != nil {
return sdk.ZeroDec()
}
balance := sdk.NewDecFromInt(asset.AssetBalance.Add(ammBalance))
// X_L = X_P_L - X_TP_L (pool liabilities = pool synthetic liabilities - pool take profit liabilities)
liabilities := sdk.NewDecFromInt(asset.Liabilities.Sub(asset.TakeProfitLiabilities))
if balance.Add(liabilities).IsZero() {
return sdk.ZeroDec()
}
mul := balance.Quo(balance.Add(liabilities))
H = H.Mul(mul)
}
return H
}
func (k Keeper) CalculatePoolHealth(ctx sdk.Context, pool *types.Pool) sdk.Dec {
ammPool, found := k.amm.GetPool(ctx, pool.AmmPoolId)
if !found {
return sdk.ZeroDec()
}
H := k.CalculatePoolHealthByPosition(ctx, pool, ammPool, types.Position_LONG)
H = H.Mul(k.CalculatePoolHealthByPosition(ctx, pool, ammPool, types.Position_SHORT))
return H
}
func (k Keeper) TakeInCustody(ctx sdk.Context, mtp types.MTP, pool *types.Pool) error {
err := pool.UpdateBalance(ctx, mtp.CustodyAsset, mtp.Custody, false, mtp.Position)
if err != nil {
return nil
}
err = pool.UpdateCustody(ctx, mtp.CustodyAsset, mtp.Custody, true, mtp.Position)
if err != nil {
return nil
}
k.SetPool(ctx, *pool)
return nil
}
func (k Keeper) IncrementalBorrowInterestPayment(ctx sdk.Context, borrowInterestPayment math.Int, mtp *types.MTP, pool *types.Pool, ammPool ammtypes.Pool, baseCurrency string) (math.Int, error) {
// if mtp has unpaid borrow interest, add to payment
// convert it into base currency
if mtp.BorrowInterestUnpaidCollateral.IsPositive() {
if mtp.CollateralAsset == baseCurrency {
borrowInterestPayment = borrowInterestPayment.Add(mtp.BorrowInterestUnpaidCollateral)
} else {
unpaidCollateralIn := sdk.NewCoin(mtp.CollateralAsset, mtp.BorrowInterestUnpaidCollateral)
C, err := k.EstimateSwapGivenOut(ctx, unpaidCollateralIn, baseCurrency, ammPool)
if err != nil {
return sdk.ZeroInt(), err
}
borrowInterestPayment = borrowInterestPayment.Add(C)
}
}
borrowInterestPaymentTokenIn := sdk.NewCoin(baseCurrency, borrowInterestPayment)
// swap borrow interest payment to custody asset for payment
borrowInterestPaymentCustody, err := k.EstimateSwap(ctx, borrowInterestPaymentTokenIn, mtp.CustodyAsset, ammPool)
if err != nil {
return sdk.ZeroInt(), err
}
// If collateralAsset is not in base currency, convert it to original asset format
if mtp.CollateralAsset != baseCurrency {
// swap custody amount to collateral for updating borrow interest unpaid
amtTokenIn := sdk.NewCoin(baseCurrency, borrowInterestPayment)
borrowInterestPayment, err = k.EstimateSwap(ctx, amtTokenIn, mtp.CollateralAsset, ammPool) // may need spot price here to not deduct fee
if err != nil {
return sdk.ZeroInt(), err
}
}
// if paying unpaid borrow interest reset to 0
mtp.BorrowInterestUnpaidCollateral = sdk.ZeroInt()
// edge case, not enough custody to cover payment
if borrowInterestPaymentCustody.GT(mtp.Custody) {
// swap custody amount to collateral for updating borrow interest unpaid
custodyAmtTokenIn := sdk.NewCoin(mtp.CustodyAsset, mtp.Custody)
custodyAmountCollateral, err := k.EstimateSwap(ctx, custodyAmtTokenIn, mtp.CollateralAsset, ammPool) // may need spot price here to not deduct fee
if err != nil {
return sdk.ZeroInt(), err
}
mtp.BorrowInterestUnpaidCollateral = mtp.BorrowInterestUnpaidCollateral.Add(borrowInterestPayment).Sub(custodyAmountCollateral)
borrowInterestPayment = custodyAmountCollateral
borrowInterestPaymentCustody = mtp.Custody
}
// add payment to total paid - collateral
mtp.BorrowInterestPaidCollateral = mtp.BorrowInterestPaidCollateral.Add(borrowInterestPayment)
// add payment to total paid - custody
mtp.BorrowInterestPaidCustody = mtp.BorrowInterestPaidCustody.Add(borrowInterestPaymentCustody)
// deduct borrow interest payment from custody amount
mtp.Custody = mtp.Custody.Sub(borrowInterestPaymentCustody)
takePercentage := k.GetIncrementalBorrowInterestPaymentFundPercentage(ctx)
fundAddr := k.GetIncrementalBorrowInterestPaymentFundAddress(ctx)
takeAmount, err := k.TakeFundPayment(ctx, borrowInterestPaymentCustody, mtp.CustodyAsset, takePercentage, fundAddr, &ammPool)
if err != nil {
return sdk.ZeroInt(), err
}
actualBorrowInterestPaymentCustody := borrowInterestPaymentCustody.Sub(takeAmount)
if !takeAmount.IsZero() {
k.EmitFundPayment(ctx, mtp, takeAmount, mtp.CustodyAsset, types.EventIncrementalPayFund)
}
err = pool.UpdateCustody(ctx, mtp.CustodyAsset, borrowInterestPaymentCustody, false, mtp.Position)
if err != nil {
return sdk.ZeroInt(), err
}
err = pool.UpdateBalance(ctx, mtp.CustodyAsset, actualBorrowInterestPaymentCustody, true, mtp.Position)
if err != nil {
return sdk.ZeroInt(), err
}
err = k.SetMTP(ctx, mtp)
if err != nil {
return sdk.ZeroInt(), err
}
k.SetPool(ctx, *pool)
return actualBorrowInterestPaymentCustody, nil
}
func (k Keeper) BorrowInterestRateComputationByPosition(ctx sdk.Context, pool types.Pool, ammPool ammtypes.Pool, position types.Position) (sdk.Dec, error) {
poolAssets := pool.GetPoolAssets(position)
targetBorrowInterestRate := sdk.OneDec()
for _, asset := range *poolAssets {
ammBalance, err := types.GetAmmPoolBalance(ammPool, asset.AssetDenom)
if err != nil {
return sdk.ZeroDec(), err
}
balance := sdk.NewDecFromInt(asset.AssetBalance.Add(ammBalance))
liabilities := sdk.NewDecFromInt(asset.Liabilities)
// Ensure balance is not zero to avoid division by zero
if balance.IsZero() {
return sdk.ZeroDec(), nil
}
if balance.Add(liabilities).IsZero() {
return sdk.ZeroDec(), nil
}
mul := balance.Add(liabilities).Quo(balance)
targetBorrowInterestRate = targetBorrowInterestRate.Mul(mul)
}
return targetBorrowInterestRate, nil
}
func (k Keeper) BorrowInterestRateComputation(ctx sdk.Context, pool types.Pool) (sdk.Dec, error) {
ammPool, found := k.amm.GetPool(ctx, pool.AmmPoolId)
if !found {
return sdk.ZeroDec(), errorsmod.Wrap(types.ErrBalanceNotAvailable, "Balance not available")
}
borrowInterestRateMax := k.GetBorrowInterestRateMax(ctx)
borrowInterestRateMin := k.GetBorrowInterestRateMin(ctx)
borrowInterestRateIncrease := k.GetBorrowInterestRateIncrease(ctx)
borrowInterestRateDecrease := k.GetBorrowInterestRateDecrease(ctx)
healthGainFactor := k.GetHealthGainFactor(ctx)
prevBorrowInterestRate := pool.BorrowInterestRate
targetBorrowInterestRate := healthGainFactor
targetBorrowInterestRateLong, err := k.BorrowInterestRateComputationByPosition(ctx, pool, ammPool, types.Position_LONG)
if err != nil {
return sdk.ZeroDec(), err
}
targetBorrowInterestRateShort, err := k.BorrowInterestRateComputationByPosition(ctx, pool, ammPool, types.Position_SHORT)
if err != nil {
return sdk.ZeroDec(), err
}
targetBorrowInterestRate = targetBorrowInterestRate.Mul(targetBorrowInterestRateLong)
targetBorrowInterestRate = targetBorrowInterestRate.Mul(targetBorrowInterestRateShort)
borrowInterestRateChange := targetBorrowInterestRate.Sub(prevBorrowInterestRate)
borrowInterestRate := prevBorrowInterestRate
if borrowInterestRateChange.GTE(borrowInterestRateDecrease.Mul(sdk.NewDec(-1))) && borrowInterestRateChange.LTE(borrowInterestRateIncrease) {
borrowInterestRate = targetBorrowInterestRate
} else if borrowInterestRateChange.GT(borrowInterestRateIncrease) {
borrowInterestRate = prevBorrowInterestRate.Add(borrowInterestRateIncrease)
} else if borrowInterestRateChange.LT(borrowInterestRateDecrease.Mul(sdk.NewDec(-1))) {
borrowInterestRate = prevBorrowInterestRate.Sub(borrowInterestRateDecrease)
}
newBorrowInterestRate := borrowInterestRate
if borrowInterestRate.GT(borrowInterestRateMin) && borrowInterestRate.LT(borrowInterestRateMax) {
newBorrowInterestRate = borrowInterestRate
} else if borrowInterestRate.LTE(borrowInterestRateMin) {
newBorrowInterestRate = borrowInterestRateMin
} else if borrowInterestRate.GTE(borrowInterestRateMax) {
newBorrowInterestRate = borrowInterestRateMax
}
return newBorrowInterestRate, nil
}
func (k Keeper) CheckMinLiabilities(ctx sdk.Context, collateralAmount sdk.Coin, eta sdk.Dec, ammPool ammtypes.Pool, custodyAsset string, baseCurrency string) error {
minBorrowInterestRate := k.GetBorrowInterestRateMin(ctx)
// Ensure minBorrowInterestRate is not zero to avoid division by zero
if minBorrowInterestRate.IsZero() {
return types.ErrAmountTooLow
}
collateralAmountDec := sdk.NewDecFromInt(collateralAmount.Amount)
liabilitiesDec := collateralAmountDec.Mul(eta)
liabilities := sdk.NewInt(liabilitiesDec.TruncateInt64())
// liabilty has to be always in base currency
if collateralAmount.Denom != baseCurrency {
outAmt := liabilitiesDec.TruncateInt()
outAmtToken := sdk.NewCoin(collateralAmount.Denom, outAmt)
inAmt, err := k.OpenLongChecker.EstimateSwapGivenOut(ctx, outAmtToken, baseCurrency, ammPool)
if err != nil {
return types.ErrBorrowTooLow
}
liabilities = sdk.NewInt(inAmt.Int64())
}
minBorrowedInterest := liabilities.ToLegacyDec().Mul(minBorrowInterestRate)
samplePayment := sdk.NewInt(minBorrowedInterest.TruncateInt64())
if samplePayment.IsZero() {
return types.ErrBorrowTooLow
}
// If collateral is not base currency, custody amount is already checked in HasSufficientBalance function.
// its liability balance checked in the above if statement, so return
if collateralAmount.Denom != baseCurrency {
return nil
}
// If custodyAsset is base currency, custody amount is already checkid in HasSufficientBalance function.
// its liability balance checked in the above if statement, so return
if custodyAsset == baseCurrency {
return nil
}
samplePaymentTokenIn := sdk.NewCoin(collateralAmount.Denom, samplePayment)
// swap borrow interest payment to custody asset
_, err := k.EstimateSwap(ctx, samplePaymentTokenIn, custodyAsset, ammPool)
if err != nil {
return types.ErrBorrowTooLow
}
return nil
}
func (k Keeper) TakeFundPayment(ctx sdk.Context, returnAmount math.Int, returnAsset string, takePercentage sdk.Dec, fundAddr sdk.AccAddress, ammPool *ammtypes.Pool) (math.Int, error) {
returnAmountDec := sdk.NewDecFromBigInt(returnAmount.BigInt())
takeAmount := sdk.NewIntFromBigInt(takePercentage.Mul(returnAmountDec).TruncateInt().BigInt())
if !takeAmount.IsZero() {
takeCoins := sdk.NewCoins(sdk.NewCoin(returnAsset, sdk.NewIntFromBigInt(takeAmount.BigInt())))
ammPoolAddr, err := sdk.AccAddressFromBech32(ammPool.Address)
if err != nil {
return sdk.ZeroInt(), err
}
err = k.bankKeeper.SendCoins(ctx, ammPoolAddr, fundAddr, takeCoins)
//err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, ammPool.Address, fundAddr, takeCoins)
if err != nil {
return sdk.ZeroInt(), err
}
}
return takeAmount, nil
}
// Set the perpetual hooks.
func (k *Keeper) SetHooks(gh types.PerpetualHooks) *Keeper {
if k.hooks != nil {
panic("cannot set perpetual hooks twice")
}
k.hooks = gh
return k
}