-
Notifications
You must be signed in to change notification settings - Fork 97
/
core.go
629 lines (538 loc) · 17.3 KB
/
core.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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
package keeper
import (
"context"
"errors"
"fmt"
"time"
sdkerrors "cosmossdk.io/errors"
"cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/neutron-org/neutron/v4/utils"
math_utils "github.com/neutron-org/neutron/v4/utils/math"
"github.com/neutron-org/neutron/v4/x/dex/types"
)
// NOTE: Currently we are using TruncateInt in multiple places for converting Decs back into math.Ints.
// This may create some accounting anomalies but seems preferable to other alternatives.
// See full ADR here: https://www.notion.so/dualityxyz/A-Modest-Proposal-For-Truncating-696a919d59254876a617f82fb9567895
// Handles core logic for MsgDeposit, checking and initializing data structures (tick, pair), calculating
// shares based on amount deposited, and sending funds to moduleAddress.
func (k Keeper) DepositCore(
goCtx context.Context,
pairID *types.PairID,
callerAddr sdk.AccAddress,
receiverAddr sdk.AccAddress,
amounts0 []math.Int,
amounts1 []math.Int,
tickIndices []int64,
fees []uint64,
options []*types.DepositOptions,
) (amounts0Deposit, amounts1Deposit []math.Int, sharesIssued sdk.Coins, failedDeposits []*types.FailedDeposit, err error) {
ctx := sdk.UnwrapSDKContext(goCtx)
totalAmountReserve0 := math.ZeroInt()
totalAmountReserve1 := math.ZeroInt()
amounts0Deposited := make([]math.Int, len(amounts0))
amounts1Deposited := make([]math.Int, len(amounts1))
sharesIssued = sdk.Coins{}
for i := 0; i < len(amounts0); i++ {
amounts0Deposited[i] = math.ZeroInt()
amounts1Deposited[i] = math.ZeroInt()
}
for i, amount0 := range amounts0 {
amount1 := amounts1[i]
tickIndex := tickIndices[i]
fee := fees[i]
option := options[i]
if option == nil {
option = &types.DepositOptions{}
}
autoswap := !option.DisableAutoswap
if err := k.ValidateFee(ctx, fee); err != nil {
return nil, nil, nil, failedDeposits, err
}
if k.IsPoolBehindEnemyLines(ctx, pairID, tickIndex, fee, amount0, amount1) {
err = sdkerrors.Wrapf(types.ErrDepositBehindEnemyLines,
"deposit failed at tick %d fee %d", tickIndex, fee)
if option.FailTxOnBel {
return nil, nil, nil, failedDeposits, err
}
failedDeposits = append(failedDeposits, &types.FailedDeposit{DepositIdx: uint64(i), Error: err.Error()})
continue
}
pool, err := k.GetOrInitPool(
ctx,
pairID,
tickIndex,
fee,
)
if err != nil {
return nil, nil, nil, failedDeposits, err
}
existingShares := k.bankKeeper.GetSupply(ctx, pool.GetPoolDenom()).Amount
inAmount0, inAmount1, outShares := pool.Deposit(amount0, amount1, existingShares, autoswap)
k.SetPool(ctx, pool)
if inAmount0.IsZero() && inAmount1.IsZero() {
return nil, nil, nil, failedDeposits, types.ErrZeroTrueDeposit
}
if outShares.IsZero() {
return nil, nil, nil, failedDeposits, types.ErrDepositShareUnderflow
}
sharesIssued = append(sharesIssued, outShares)
amounts0Deposited[i] = inAmount0
amounts1Deposited[i] = inAmount1
totalAmountReserve0 = totalAmountReserve0.Add(inAmount0)
totalAmountReserve1 = totalAmountReserve1.Add(inAmount1)
ctx.EventManager().EmitEvent(types.CreateDepositEvent(
callerAddr,
receiverAddr,
pairID.Token0,
pairID.Token1,
tickIndex,
fee,
inAmount0,
inAmount1,
outShares.Amount,
))
}
// At this point shares issued is not sorted and may have duplicates
// we must sanitize to convert it to a valid set of coins
sharesIssued = utils.SanitizeCoins(sharesIssued)
if totalAmountReserve0.IsPositive() {
coin0 := sdk.NewCoin(pairID.Token0, totalAmountReserve0)
if err := k.bankKeeper.SendCoinsFromAccountToModule(ctx, callerAddr, types.ModuleName, sdk.Coins{coin0}); err != nil {
return nil, nil, nil, failedDeposits, err
}
}
if totalAmountReserve1.IsPositive() {
coin1 := sdk.NewCoin(pairID.Token1, totalAmountReserve1)
if err := k.bankKeeper.SendCoinsFromAccountToModule(ctx, callerAddr, types.ModuleName, sdk.Coins{coin1}); err != nil {
return nil, nil, nil, failedDeposits, err
}
}
if err := k.MintShares(ctx, receiverAddr, sharesIssued); err != nil {
return nil, nil, nil, failedDeposits, err
}
return amounts0Deposited, amounts1Deposited, sharesIssued, failedDeposits, nil
}
// Handles core logic for MsgWithdrawal; calculating and withdrawing reserve0,reserve1 from a specified tick
// given a specified number of shares to remove.
// Calculates the amount of reserve0, reserve1 to withdraw based on the percentage of the desired
// number of shares to remove compared to the total number of shares at the given tick.
func (k Keeper) WithdrawCore(
goCtx context.Context,
pairID *types.PairID,
callerAddr sdk.AccAddress,
receiverAddr sdk.AccAddress,
sharesToRemoveList []math.Int,
tickIndicesNormalized []int64,
fees []uint64,
) error {
ctx := sdk.UnwrapSDKContext(goCtx)
totalReserve0ToRemove := math.ZeroInt()
totalReserve1ToRemove := math.ZeroInt()
for i, fee := range fees {
sharesToRemove := sharesToRemoveList[i]
tickIndex := tickIndicesNormalized[i]
pool, err := k.GetOrInitPool(ctx, pairID, tickIndex, fee)
if err != nil {
return err
}
poolDenom := pool.GetPoolDenom()
totalShares := k.bankKeeper.GetSupply(ctx, poolDenom).Amount
if totalShares.LT(sharesToRemove) {
return sdkerrors.Wrapf(
types.ErrInsufficientShares,
"%s does not have %s shares of type %s",
callerAddr,
sharesToRemove,
poolDenom,
)
}
outAmount0, outAmount1 := pool.Withdraw(sharesToRemove, totalShares)
k.SetPool(ctx, pool)
if sharesToRemove.IsPositive() {
if err := k.BurnShares(ctx, callerAddr, sharesToRemove, poolDenom); err != nil {
return err
}
}
totalReserve0ToRemove = totalReserve0ToRemove.Add(outAmount0)
totalReserve1ToRemove = totalReserve1ToRemove.Add(outAmount1)
ctx.EventManager().EmitEvent(types.CreateWithdrawEvent(
callerAddr,
receiverAddr,
pairID.Token0,
pairID.Token1,
tickIndex,
fee,
outAmount0,
outAmount1,
sharesToRemove,
))
}
if totalReserve0ToRemove.IsPositive() {
coin0 := sdk.NewCoin(pairID.Token0, totalReserve0ToRemove)
err := k.bankKeeper.SendCoinsFromModuleToAccount(
ctx,
types.ModuleName,
receiverAddr,
sdk.Coins{coin0},
)
ctx.EventManager().EmitEvents(types.GetEventsWithdrawnAmount(sdk.Coins{coin0}))
if err != nil {
return err
}
}
// sends totalReserve1ToRemove to receiverAddr
if totalReserve1ToRemove.IsPositive() {
coin1 := sdk.NewCoin(pairID.Token1, totalReserve1ToRemove)
err := k.bankKeeper.SendCoinsFromModuleToAccount(
ctx,
types.ModuleName,
receiverAddr,
sdk.Coins{coin1},
)
ctx.EventManager().EmitEvents(types.GetEventsWithdrawnAmount(sdk.Coins{coin1}))
if err != nil {
return err
}
}
return nil
}
func (k Keeper) MultiHopSwapCore(
goCtx context.Context,
amountIn math.Int,
routes []*types.MultiHopRoute,
exitLimitPrice math_utils.PrecDec,
pickBestRoute bool,
callerAddr sdk.AccAddress,
receiverAddr sdk.AccAddress,
) (coinOut sdk.Coin, err error) {
ctx := sdk.UnwrapSDKContext(goCtx)
var routeErrors []error
initialInCoin := sdk.NewCoin(routes[0].Hops[0], amountIn)
stepCache := make(map[multihopCacheKey]StepResult)
var bestRoute struct {
write func()
coinOut sdk.Coin
route []string
dust sdk.Coins
}
bestRoute.coinOut = sdk.Coin{Amount: math.ZeroInt()}
for _, route := range routes {
routeDust, routeCoinOut, writeRoute, err := k.RunMultihopRoute(
ctx,
*route,
initialInCoin,
exitLimitPrice,
stepCache,
)
if err != nil {
routeErrors = append(routeErrors, err)
continue
}
if !pickBestRoute || bestRoute.coinOut.Amount.LT(routeCoinOut.Amount) {
bestRoute.coinOut = routeCoinOut
bestRoute.write = writeRoute
bestRoute.route = route.Hops
bestRoute.dust = routeDust
}
if !pickBestRoute {
break
}
}
if len(routeErrors) == len(routes) {
// All routes have failed
allErr := errors.Join(append([]error{types.ErrAllMultiHopRoutesFailed}, routeErrors...)...)
return sdk.Coin{}, allErr
}
bestRoute.write()
err = k.bankKeeper.SendCoinsFromAccountToModule(
ctx,
callerAddr,
types.ModuleName,
sdk.Coins{initialInCoin},
)
if err != nil {
return sdk.Coin{}, err
}
// send both dust and coinOut to receiver
// note that dust can be multiple coins collected from multiple hops.
err = k.bankKeeper.SendCoinsFromModuleToAccount(
ctx,
types.ModuleName,
receiverAddr,
bestRoute.dust.Add(bestRoute.coinOut),
)
if err != nil {
return sdk.Coin{}, fmt.Errorf("failed to send out coin and dust to the receiver: %w", err)
}
ctx.EventManager().EmitEvent(types.CreateMultihopSwapEvent(
callerAddr,
receiverAddr,
initialInCoin.Denom,
bestRoute.coinOut.Denom,
initialInCoin.Amount,
bestRoute.coinOut.Amount,
bestRoute.route,
bestRoute.dust,
))
return bestRoute.coinOut, nil
}
// PlaceLimitOrderCore handles MsgPlaceLimitOrder, initializing (tick, pair) data structures if needed, calculating and
// storing information for a new limit order at a specific tick.
func (k Keeper) PlaceLimitOrderCore(
goCtx context.Context,
tokenIn string,
tokenOut string,
amountIn math.Int,
tickIndexInToOut int64,
orderType types.LimitOrderType,
goodTil *time.Time,
maxAmountOut *math.Int,
callerAddr sdk.AccAddress,
receiverAddr sdk.AccAddress,
) (trancheKey string, totalInCoin, swapInCoin, swapOutCoin sdk.Coin, err error) {
ctx := sdk.UnwrapSDKContext(goCtx)
var pairID *types.PairID
pairID, err = types.NewPairIDFromUnsorted(tokenIn, tokenOut)
if err != nil {
return trancheKey, totalInCoin, swapInCoin, swapOutCoin, err
}
amountLeft := amountIn
// This is ok because tokenOut is provided to the constructor of PairID above
takerTradePairID := pairID.MustTradePairIDFromMaker(tokenOut)
var limitPrice math_utils.PrecDec
limitPrice, err = types.CalcPrice(tickIndexInToOut)
if err != nil {
return trancheKey, totalInCoin, swapInCoin, swapOutCoin, err
}
// Ensure that after rounding user will get at least 1 token out.
err = types.ValidateFairOutput(amountIn, limitPrice)
if err != nil {
return trancheKey, totalInCoin, swapInCoin, swapOutCoin, err
}
var orderFilled bool
if orderType.IsTakerOnly() {
swapInCoin, swapOutCoin, err = k.TakerLimitOrderSwap(ctx, *takerTradePairID, amountIn, maxAmountOut, limitPrice, orderType)
} else {
swapInCoin, swapOutCoin, orderFilled, err = k.MakerLimitOrderSwap(ctx, *takerTradePairID, amountIn, limitPrice)
}
if err != nil {
return trancheKey, totalInCoin, swapInCoin, swapOutCoin, err
}
totalIn := swapInCoin.Amount
amountLeft = amountLeft.Sub(swapInCoin.Amount)
if swapOutCoin.IsPositive() {
err = k.bankKeeper.SendCoinsFromModuleToAccount(
ctx,
types.ModuleName,
receiverAddr,
sdk.Coins{swapOutCoin},
)
if err != nil {
return trancheKey, totalInCoin, swapInCoin, swapOutCoin, err
}
}
// This is ok because pairID was constructed from tokenIn above.
makerTradePairID := pairID.MustTradePairIDFromMaker(tokenIn)
makerTickIndexTakerToMaker := tickIndexInToOut * -1
var placeTranche *types.LimitOrderTranche
placeTranche, err = k.GetOrInitPlaceTranche(
ctx,
makerTradePairID,
makerTickIndexTakerToMaker,
goodTil,
orderType,
)
if err != nil {
return trancheKey, totalInCoin, swapInCoin, swapOutCoin, err
}
trancheKey = placeTranche.Key.TrancheKey
trancheUser := k.GetOrInitLimitOrderTrancheUser(
ctx,
makerTradePairID,
makerTickIndexTakerToMaker,
trancheKey,
orderType,
receiverAddr.String(),
)
sharesIssued := math.ZeroInt()
// FOR GTC, JIT & GoodTil try to place a maker limitOrder with remaining Amount
if amountLeft.IsPositive() && !orderFilled &&
(orderType.IsGTC() || orderType.IsJIT() || orderType.IsGoodTil()) {
// Ensure that the maker portion will generate at least 1 token of output
// NOTE: This does mean that a successful taker leg of the trade will be thrown away since the entire tx will fail.
// In most circumstances this seems preferable to executing the taker leg and exiting early before placing a maker
// order with the remaining liquidity.
err = types.ValidateFairOutput(amountLeft, limitPrice)
if err != nil {
return trancheKey, totalInCoin, swapInCoin, swapOutCoin, err
}
placeTranche.PlaceMakerLimitOrder(amountLeft)
trancheUser.SharesOwned = trancheUser.SharesOwned.Add(amountLeft)
if orderType.HasExpiration() {
goodTilRecord := NewLimitOrderExpiration(placeTranche)
k.SetLimitOrderExpiration(ctx, goodTilRecord)
ctx.GasMeter().ConsumeGas(types.ExpiringLimitOrderGas, "Expiring LimitOrder Fee")
}
k.SaveTranche(ctx, placeTranche)
totalIn = totalIn.Add(amountLeft)
sharesIssued = amountLeft
}
k.SaveTrancheUser(ctx, trancheUser)
if totalIn.IsPositive() {
totalInCoin = sdk.NewCoin(tokenIn, totalIn)
err = k.bankKeeper.SendCoinsFromAccountToModule(
ctx,
callerAddr,
types.ModuleName,
sdk.Coins{totalInCoin},
)
if err != nil {
return trancheKey, totalInCoin, swapInCoin, swapOutCoin, err
}
}
if orderType.IsJIT() {
err = k.AssertCanPlaceJIT(ctx)
if err != nil {
return trancheKey, totalInCoin, swapInCoin, swapOutCoin, err
}
k.IncrementJITsInBlock(ctx)
}
ctx.EventManager().EmitEvent(types.CreatePlaceLimitOrderEvent(
callerAddr,
receiverAddr,
pairID.Token0,
pairID.Token1,
tokenIn,
tokenOut,
totalIn,
tickIndexInToOut,
orderType.String(),
sharesIssued,
trancheKey,
))
return trancheKey, totalInCoin, swapInCoin, swapOutCoin, nil
}
// CancelLimitOrderCore handles MsgCancelLimitOrder, removing a specified number of shares from a limit order
// and returning the respective amount in terms of the reserve to the user.
func (k Keeper) CancelLimitOrderCore(
goCtx context.Context,
trancheKey string,
callerAddr sdk.AccAddress,
) error {
ctx := sdk.UnwrapSDKContext(goCtx)
trancheUser, found := k.GetLimitOrderTrancheUser(ctx, callerAddr.String(), trancheKey)
if !found {
return types.ErrActiveLimitOrderNotFound
}
tradePairID, tickIndex := trancheUser.TradePairId, trancheUser.TickIndexTakerToMaker
tranche := k.GetLimitOrderTranche(
ctx,
&types.LimitOrderTrancheKey{
TradePairId: tradePairID,
TickIndexTakerToMaker: tickIndex,
TrancheKey: trancheKey,
},
)
if tranche == nil {
return types.ErrActiveLimitOrderNotFound
}
amountToCancel := tranche.RemoveTokenIn(trancheUser)
trancheUser.SharesCancelled = trancheUser.SharesCancelled.Add(amountToCancel)
if amountToCancel.IsPositive() {
coinOut := sdk.NewCoin(tradePairID.MakerDenom, amountToCancel)
err := k.bankKeeper.SendCoinsFromModuleToAccount(
ctx,
types.ModuleName,
callerAddr,
sdk.Coins{coinOut},
)
if err != nil {
return err
}
k.SaveTrancheUser(ctx, trancheUser)
k.SaveTranche(ctx, tranche)
if trancheUser.OrderType.HasExpiration() {
k.RemoveLimitOrderExpiration(ctx, *tranche.ExpirationTime, tranche.Key.KeyMarshal())
}
} else {
return sdkerrors.Wrapf(types.ErrCancelEmptyLimitOrder, "%s", tranche.Key.TrancheKey)
}
pairID := tradePairID.MustPairID()
ctx.EventManager().EmitEvent(types.CancelLimitOrderEvent(
callerAddr,
pairID.Token0,
pairID.Token1,
tradePairID.MakerDenom,
tradePairID.TakerDenom,
amountToCancel,
trancheKey,
))
return nil
}
// WithdrawFilledLimitOrderCore handles MsgWithdrawFilledLimitOrder, calculates and sends filled liquidity from module to user
// for a limit order based on amount wished to receive.
func (k Keeper) WithdrawFilledLimitOrderCore(
goCtx context.Context,
trancheKey string,
callerAddr sdk.AccAddress,
) error {
ctx := sdk.UnwrapSDKContext(goCtx)
trancheUser, found := k.GetLimitOrderTrancheUser(
ctx,
callerAddr.String(),
trancheKey,
)
if !found {
return sdkerrors.Wrapf(types.ErrValidLimitOrderTrancheNotFound, "%s", trancheKey)
}
tradePairID, tickIndex := trancheUser.TradePairId, trancheUser.TickIndexTakerToMaker
pairID := tradePairID.MustPairID()
tranche, wasFilled, found := k.FindLimitOrderTranche(
ctx,
&types.LimitOrderTrancheKey{
TradePairId: tradePairID,
TickIndexTakerToMaker: tickIndex,
TrancheKey: trancheKey,
},
)
amountOutTokenOut := math.ZeroInt()
remainingTokenIn := math.ZeroInt()
// It's possible that a TrancheUser exists but tranche does not if LO was filled entirely through a swap
if found {
var amountOutTokenIn math.Int
amountOutTokenIn, amountOutTokenOut = tranche.Withdraw(trancheUser)
if wasFilled {
// This is only relevant for inactive JIT and GoodTil limit orders
remainingTokenIn = tranche.RemoveTokenIn(trancheUser)
k.SaveInactiveTranche(ctx, tranche)
// Treat the removed tokenIn as cancelled shares
trancheUser.SharesCancelled = trancheUser.SharesCancelled.Add(remainingTokenIn)
} else {
k.SetLimitOrderTranche(ctx, tranche)
}
trancheUser.SharesWithdrawn = trancheUser.SharesWithdrawn.Add(amountOutTokenIn)
}
k.SaveTrancheUser(ctx, trancheUser)
if amountOutTokenOut.IsPositive() || remainingTokenIn.IsPositive() {
coinTakerDenomOut := sdk.NewCoin(tradePairID.TakerDenom, amountOutTokenOut)
coinMakerDenomRefund := sdk.NewCoin(tradePairID.MakerDenom, remainingTokenIn)
coins := sdk.NewCoins(coinTakerDenomOut, coinMakerDenomRefund)
ctx.EventManager().EmitEvents(types.GetEventsWithdrawnAmount(sdk.NewCoins(coinTakerDenomOut)))
if err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, callerAddr, coins); err != nil {
return err
}
} else {
return types.ErrWithdrawEmptyLimitOrder
}
ctx.EventManager().EmitEvent(types.WithdrawFilledLimitOrderEvent(
callerAddr,
pairID.Token0,
pairID.Token1,
tradePairID.MakerDenom,
tradePairID.TakerDenom,
amountOutTokenOut,
trancheKey,
))
return nil
}