/
liquidate.go
421 lines (362 loc) · 12.7 KB
/
liquidate.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
package keeper
import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/NibiruChain/collections"
"github.com/NibiruChain/nibiru/x/common/asset"
"github.com/NibiruChain/nibiru/x/perp/types"
vpooltypes "github.com/NibiruChain/nibiru/x/vpool/types"
)
/*
Liquidate allows to liquidate the trader position if the margin is below the
required margin maintenance ratio.
args:
- liquidator: the liquidator who is executing the liquidation
- pair: the asset pair
- trader: the trader who owns the position being liquidated
ret:
- liquidatorFee: the amount of coins given to the liquidator
- perpEcosystemFundFee: the amount of coins given to the ecosystem fund
- err: error
*/
func (k Keeper) Liquidate(
ctx sdk.Context,
liquidator sdk.AccAddress,
pair asset.Pair,
trader sdk.AccAddress,
) (liquidatorFee sdk.Coin, perpEcosystemFundFee sdk.Coin, err error) {
err = k.requireVpool(ctx, pair)
if err != nil {
ctx.EventManager().EmitTypedEvent(&types.LiquidationFailedEvent{
Pair: pair,
Trader: trader.String(),
Liquidator: liquidator.String(),
Reason: types.LiquidationFailedEvent_NONEXISTENT_PAIR,
})
return
}
position, err := k.Positions.Get(ctx, collections.Join(pair, trader))
if err != nil {
ctx.EventManager().EmitTypedEvent(&types.LiquidationFailedEvent{
Pair: pair,
Trader: trader.String(),
Liquidator: liquidator.String(),
Reason: types.LiquidationFailedEvent_NONEXISTENT_POSITION,
})
return
}
marginRatio, err := k.GetMarginRatio(
ctx,
position,
types.MarginCalculationPriceOption_MAX_PNL,
)
if err != nil {
return
}
isOverSpreadLimit, err := k.VpoolKeeper.IsOverSpreadLimit(ctx, pair)
if err != nil {
return
}
if isOverSpreadLimit {
marginRatioBasedOnOracle, err := k.GetMarginRatio(
ctx, position, types.MarginCalculationPriceOption_INDEX)
if err != nil {
return liquidatorFee, perpEcosystemFundFee, err
}
marginRatio = sdk.MaxDec(marginRatio, marginRatioBasedOnOracle)
}
params := k.GetParams(ctx)
maintenanceMarginRatio, err := k.VpoolKeeper.GetMaintenanceMarginRatio(ctx, pair)
if err != nil {
return
}
err = validateMarginRatio(marginRatio, maintenanceMarginRatio, false)
if err != nil {
ctx.EventManager().EmitTypedEvent(&types.LiquidationFailedEvent{
Pair: pair,
Trader: trader.String(),
Liquidator: liquidator.String(),
Reason: types.LiquidationFailedEvent_POSITION_HEALTHY,
})
return
}
marginRatioBasedOnSpot, err := k.GetMarginRatio(
ctx, position, types.MarginCalculationPriceOption_SPOT)
if err != nil {
return
}
var liquidationResponse types.LiquidateResp
if marginRatioBasedOnSpot.GTE(params.LiquidationFeeRatio) {
liquidationResponse, err = k.ExecutePartialLiquidation(ctx, liquidator, &position)
} else {
liquidationResponse, err = k.ExecuteFullLiquidation(ctx, liquidator, &position)
}
if err != nil {
return
}
liquidatorFee = sdk.NewCoin(
pair.QuoteDenom(),
liquidationResponse.FeeToLiquidator,
)
perpEcosystemFundFee = sdk.NewCoin(
pair.QuoteDenom(),
liquidationResponse.FeeToPerpEcosystemFund,
)
return liquidatorFee, perpEcosystemFundFee, nil
}
/*
Fully liquidates a position. It is assumed that the margin ratio has already been
checked prior to calling this method.
args:
- ctx: cosmos-sdk context
- liquidator: the liquidator's address
- position: the position to liquidate
ret:
- liquidationResp: a response object containing the results of the liquidation
- err: error
*/
func (k Keeper) ExecuteFullLiquidation(
ctx sdk.Context, liquidator sdk.AccAddress, position *types.Position,
) (liquidationResp types.LiquidateResp, err error) {
params := k.GetParams(ctx)
traderAddr, err := sdk.AccAddressFromBech32(position.TraderAddress)
if err != nil {
return types.LiquidateResp{}, err
}
positionResp, err := k.closePositionEntirely(
ctx,
/* currentPosition */ *position,
/* quoteAssetAmountLimit */ sdk.ZeroDec(),
/* skipFluctuationLimitCheck */ true,
)
if err != nil {
return types.LiquidateResp{}, err
}
remainMargin := positionResp.MarginToVault.Abs()
feeToLiquidator := params.LiquidationFeeRatio.
Mul(positionResp.ExchangedNotionalValue).
QuoInt64(2)
totalBadDebt := positionResp.BadDebt
if feeToLiquidator.GT(remainMargin) {
// if the remainMargin is not enough for liquidationFee, count it as bad debt
totalBadDebt = totalBadDebt.Add(feeToLiquidator.Sub(remainMargin))
remainMargin = sdk.ZeroDec()
} else {
// Otherwise, the remaining margin will be transferred to ecosystemFund
remainMargin = remainMargin.Sub(feeToLiquidator)
}
// Realize bad debt
if totalBadDebt.IsPositive() {
if err = k.realizeBadDebt(
ctx,
position.Pair.QuoteDenom(),
totalBadDebt.RoundInt(),
); err != nil {
return types.LiquidateResp{}, err
}
}
feeToPerpEcosystemFund := sdk.ZeroDec()
if remainMargin.IsPositive() {
feeToPerpEcosystemFund = remainMargin
}
liquidationResp = types.LiquidateResp{
BadDebt: totalBadDebt.RoundInt(),
FeeToLiquidator: feeToLiquidator.RoundInt(),
FeeToPerpEcosystemFund: feeToPerpEcosystemFund.RoundInt(),
Liquidator: liquidator.String(),
PositionResp: positionResp,
}
err = k.distributeLiquidateRewards(ctx, liquidationResp)
if err != nil {
return types.LiquidateResp{}, err
}
markPrice, err := k.VpoolKeeper.GetMarkPrice(ctx, position.Pair)
if err != nil {
return types.LiquidateResp{}, err
}
err = ctx.EventManager().EmitTypedEvent(&types.PositionLiquidatedEvent{
Pair: position.Pair,
TraderAddress: traderAddr.String(),
ExchangedQuoteAmount: positionResp.ExchangedNotionalValue,
ExchangedPositionSize: positionResp.ExchangedPositionSize,
LiquidatorAddress: liquidator.String(),
FeeToLiquidator: sdk.NewCoin(position.Pair.QuoteDenom(), feeToLiquidator.RoundInt()),
FeeToEcosystemFund: sdk.NewCoin(position.Pair.QuoteDenom(), feeToPerpEcosystemFund.RoundInt()),
BadDebt: sdk.NewCoin(position.Pair.QuoteDenom(), totalBadDebt.RoundInt()),
Margin: sdk.NewCoin(position.Pair.QuoteDenom(), liquidationResp.PositionResp.Position.Margin.RoundInt()),
PositionNotional: liquidationResp.PositionResp.PositionNotional,
PositionSize: liquidationResp.PositionResp.Position.Size_,
UnrealizedPnl: liquidationResp.PositionResp.UnrealizedPnlAfter,
MarkPrice: markPrice,
BlockHeight: ctx.BlockHeight(),
BlockTimeMs: ctx.BlockTime().UnixMilli(),
})
return liquidationResp, err
}
func (k Keeper) distributeLiquidateRewards(
ctx sdk.Context, liquidateResp types.LiquidateResp) (err error) {
// --------------------------------------------------------------
// Preliminary validations
// --------------------------------------------------------------
// validate response
err = liquidateResp.Validate()
if err != nil {
return err
}
liquidator, err := sdk.AccAddressFromBech32(liquidateResp.Liquidator)
if err != nil {
return err
}
// validate pair
pair := liquidateResp.PositionResp.Position.Pair
err = k.requireVpool(ctx, pair)
if err != nil {
return err
}
// --------------------------------------------------------------
// Distribution of rewards
// --------------------------------------------------------------
// Transfer fee from vault to PerpEF
feeToPerpEF := liquidateResp.FeeToPerpEcosystemFund
if feeToPerpEF.IsPositive() {
coinToPerpEF := sdk.NewCoin(
pair.QuoteDenom(), feeToPerpEF)
if err = k.BankKeeper.SendCoinsFromModuleToModule(
ctx,
/* from */ types.VaultModuleAccount,
/* to */ types.PerpEFModuleAccount,
sdk.NewCoins(coinToPerpEF),
); err != nil {
return err
}
}
// Transfer fee from vault to liquidator
feeToLiquidator := liquidateResp.FeeToLiquidator
if feeToLiquidator.IsPositive() {
err = k.Withdraw(ctx, pair.QuoteDenom(), liquidator, feeToLiquidator)
if err != nil {
return err
}
}
return nil
}
// ExecutePartialLiquidation partially liquidates a position
func (k Keeper) ExecutePartialLiquidation(
ctx sdk.Context, liquidator sdk.AccAddress, currentPosition *types.Position,
) (types.LiquidateResp, error) {
params := k.GetParams(ctx)
traderAddr, err := sdk.AccAddressFromBech32(currentPosition.TraderAddress)
if err != nil {
return types.LiquidateResp{}, err
}
var baseAssetDir vpooltypes.Direction
if currentPosition.Size_.IsPositive() {
baseAssetDir = vpooltypes.Direction_ADD_TO_POOL
} else {
baseAssetDir = vpooltypes.Direction_REMOVE_FROM_POOL
}
partiallyLiquidatedPositionNotional, err := k.VpoolKeeper.GetBaseAssetPrice(
ctx,
currentPosition.Pair,
baseAssetDir,
/* abs= */ currentPosition.Size_.Mul(params.PartialLiquidationRatio),
)
if err != nil {
return types.LiquidateResp{}, err
}
positionResp, err := k.decreasePosition(
/* ctx */ ctx,
/* currentPosition */ *currentPosition,
/* quoteAssetAmount */ partiallyLiquidatedPositionNotional,
/* baseAmtLimit */ sdk.ZeroDec(),
/* skipFluctuationLimitCheck */ true,
)
if err != nil {
return types.LiquidateResp{}, err
}
// Remove the liquidation fee from the margin of the position
liquidationFeeAmount := positionResp.ExchangedNotionalValue.
Mul(params.LiquidationFeeRatio)
positionResp.Position.Margin = positionResp.Position.Margin.
Sub(liquidationFeeAmount)
k.Positions.Insert(ctx, collections.Join(positionResp.Position.Pair, traderAddr), *positionResp.Position)
// Compute splits for the liquidation fee
feeToLiquidator := liquidationFeeAmount.QuoInt64(2)
feeToPerpEcosystemFund := liquidationFeeAmount.Sub(feeToLiquidator)
liquidationResponse := types.LiquidateResp{
BadDebt: sdk.ZeroInt(),
FeeToLiquidator: feeToLiquidator.RoundInt(),
FeeToPerpEcosystemFund: feeToPerpEcosystemFund.RoundInt(),
Liquidator: liquidator.String(),
PositionResp: positionResp,
}
err = k.distributeLiquidateRewards(ctx, liquidationResponse)
if err != nil {
return types.LiquidateResp{}, err
}
markPrice, err := k.VpoolKeeper.GetMarkPrice(ctx, currentPosition.Pair)
if err != nil {
return types.LiquidateResp{}, err
}
err = ctx.EventManager().EmitTypedEvent(&types.PositionLiquidatedEvent{
Pair: currentPosition.Pair,
TraderAddress: traderAddr.String(),
ExchangedQuoteAmount: positionResp.ExchangedNotionalValue,
ExchangedPositionSize: positionResp.ExchangedPositionSize,
LiquidatorAddress: liquidator.String(),
FeeToLiquidator: sdk.NewCoin(currentPosition.Pair.QuoteDenom(), feeToLiquidator.RoundInt()),
FeeToEcosystemFund: sdk.NewCoin(currentPosition.Pair.QuoteDenom(), feeToPerpEcosystemFund.RoundInt()),
BadDebt: sdk.NewCoin(currentPosition.Pair.QuoteDenom(), liquidationResponse.BadDebt),
Margin: sdk.NewCoin(currentPosition.Pair.QuoteDenom(), liquidationResponse.PositionResp.Position.Margin.RoundInt()),
PositionNotional: liquidationResponse.PositionResp.PositionNotional,
PositionSize: liquidationResponse.PositionResp.Position.Size_,
UnrealizedPnl: liquidationResponse.PositionResp.UnrealizedPnlAfter,
MarkPrice: markPrice,
BlockHeight: ctx.BlockHeight(),
BlockTimeMs: ctx.BlockTime().UnixMilli(),
})
return liquidationResponse, err
}
func (k Keeper) MultiLiquidate(
ctx sdk.Context, liquidator sdk.AccAddress, liquidationRequests []*types.MsgMultiLiquidate_Liquidation,
) ([]*types.MsgMultiLiquidateResponse_LiquidationResponse, error) {
if !k.isWhitelistedLiquidator(ctx, liquidator) {
return nil, types.ErrUnauthorized.Wrapf("%s is not a whitelisted liquidator", liquidator.String())
}
resp := make([]*types.MsgMultiLiquidateResponse_LiquidationResponse, len(liquidationRequests))
var allFailed bool = true
for i, req := range liquidationRequests {
traderAddr := sdk.MustAccAddressFromBech32(req.Trader)
cachedCtx, commit := ctx.CacheContext()
liquidatorFee, perpEfFee, err := k.Liquidate(cachedCtx, liquidator, req.Pair, traderAddr)
if err != nil {
resp[i] = &types.MsgMultiLiquidateResponse_LiquidationResponse{
Success: false,
Error: err.Error(),
}
} else {
allFailed = false
resp[i] = &types.MsgMultiLiquidateResponse_LiquidationResponse{
Success: true,
LiquidatorFee: liquidatorFee,
PerpEfFee: perpEfFee,
}
ctx.EventManager().EmitEvents(cachedCtx.EventManager().Events())
commit()
}
}
if allFailed {
return nil, types.ErrAllLiquidationsFailed.Wrapf("%d liquidations failed", len(liquidationRequests))
}
return resp, nil
}
func (k Keeper) isWhitelistedLiquidator(ctx sdk.Context, addr sdk.AccAddress) bool {
addrStr := addr.String()
params := k.GetParams(ctx)
// TODO(k-yang): look into an O(1) lookup data structure here
for _, whitelisted := range params.WhitelistedLiquidators {
if addrStr == whitelisted {
return true
}
}
return false
}