/
swap.go
763 lines (683 loc) 路 29.1 KB
/
swap.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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
package keeper
import (
"fmt"
"strconv"
"strings"
"time"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/crescent-network/crescent/v3/x/liquidity/amm"
"github.com/crescent-network/crescent/v3/x/liquidity/types"
)
func (k Keeper) PriceLimits(ctx sdk.Context, lastPrice sdk.Dec) (lowest, highest sdk.Dec) {
return types.PriceLimits(lastPrice, k.GetMaxPriceLimitRatio(ctx), int(k.GetTickPrecision(ctx)))
}
// ValidateMsgLimitOrder validates types.MsgLimitOrder with state and returns
// calculated offer coin and price that is fit into ticks.
func (k Keeper) ValidateMsgLimitOrder(ctx sdk.Context, msg *types.MsgLimitOrder) (offerCoin sdk.Coin, price sdk.Dec, err error) {
spendable := k.bankKeeper.SpendableCoins(ctx, msg.GetOrderer())
if spendableAmt := spendable.AmountOf(msg.OfferCoin.Denom); spendableAmt.LT(msg.OfferCoin.Amount) {
return sdk.Coin{}, sdk.Dec{}, sdkerrors.Wrapf(
sdkerrors.ErrInsufficientFunds, "%s is smaller than %s",
sdk.NewCoin(msg.OfferCoin.Denom, spendableAmt), msg.OfferCoin)
}
tickPrec := k.GetTickPrecision(ctx)
maxOrderLifespan := k.GetMaxOrderLifespan(ctx)
if msg.OrderLifespan > maxOrderLifespan {
return sdk.Coin{}, sdk.Dec{},
sdkerrors.Wrapf(types.ErrTooLongOrderLifespan, "%s is longer than %s", msg.OrderLifespan, maxOrderLifespan)
}
pair, found := k.GetPair(ctx, msg.PairId)
if !found {
return sdk.Coin{}, sdk.Dec{}, sdkerrors.Wrapf(sdkerrors.ErrNotFound, "pair %d not found", msg.PairId)
}
var upperPriceLimit, lowerPriceLimit sdk.Dec
if pair.LastPrice != nil {
lowerPriceLimit, upperPriceLimit = k.PriceLimits(ctx, *pair.LastPrice)
} else {
upperPriceLimit = amm.HighestTick(int(tickPrec))
lowerPriceLimit = amm.LowestTick(int(tickPrec))
}
switch {
case msg.Price.GT(upperPriceLimit):
return sdk.Coin{}, sdk.Dec{}, sdkerrors.Wrapf(types.ErrPriceOutOfRange, "%s is higher than %s", msg.Price, upperPriceLimit)
case msg.Price.LT(lowerPriceLimit):
return sdk.Coin{}, sdk.Dec{}, sdkerrors.Wrapf(types.ErrPriceOutOfRange, "%s is lower than %s", msg.Price, lowerPriceLimit)
}
switch msg.Direction {
case types.OrderDirectionBuy:
if msg.OfferCoin.Denom != pair.QuoteCoinDenom || msg.DemandCoinDenom != pair.BaseCoinDenom {
return sdk.Coin{}, sdk.Dec{},
sdkerrors.Wrapf(types.ErrWrongPair, "denom pair (%s, %s) != (%s, %s)",
msg.DemandCoinDenom, msg.OfferCoin.Denom, pair.BaseCoinDenom, pair.QuoteCoinDenom)
}
price = amm.PriceToDownTick(msg.Price, int(tickPrec))
offerCoin = sdk.NewCoin(msg.OfferCoin.Denom, amm.OfferCoinAmount(amm.Buy, price, msg.Amount))
if msg.OfferCoin.IsLT(offerCoin) {
return sdk.Coin{}, sdk.Dec{}, sdkerrors.Wrapf(
types.ErrInsufficientOfferCoin, "%s is smaller than %s", msg.OfferCoin, offerCoin)
}
case types.OrderDirectionSell:
if msg.OfferCoin.Denom != pair.BaseCoinDenom || msg.DemandCoinDenom != pair.QuoteCoinDenom {
return sdk.Coin{}, sdk.Dec{},
sdkerrors.Wrapf(types.ErrWrongPair, "denom pair (%s, %s) != (%s, %s)",
msg.OfferCoin.Denom, msg.DemandCoinDenom, pair.BaseCoinDenom, pair.QuoteCoinDenom)
}
price = amm.PriceToUpTick(msg.Price, int(tickPrec))
offerCoin = sdk.NewCoin(msg.OfferCoin.Denom, msg.Amount)
if msg.OfferCoin.Amount.LT(msg.Amount) {
return sdk.Coin{}, sdk.Dec{}, sdkerrors.Wrapf(
types.ErrInsufficientOfferCoin, "%s is smaller than %s", msg.OfferCoin, sdk.NewCoin(msg.OfferCoin.Denom, msg.Amount))
}
}
if types.IsTooSmallOrderAmount(msg.Amount, price) {
return sdk.Coin{}, sdk.Dec{}, types.ErrTooSmallOrder
}
return offerCoin, price, nil
}
// LimitOrder handles types.MsgLimitOrder and stores types.Order.
func (k Keeper) LimitOrder(ctx sdk.Context, msg *types.MsgLimitOrder) (types.Order, error) {
offerCoin, price, err := k.ValidateMsgLimitOrder(ctx, msg)
if err != nil {
return types.Order{}, err
}
refundedCoin := msg.OfferCoin.Sub(offerCoin)
pair, _ := k.GetPair(ctx, msg.PairId)
if err := k.bankKeeper.SendCoins(ctx, msg.GetOrderer(), pair.GetEscrowAddress(), sdk.NewCoins(offerCoin)); err != nil {
return types.Order{}, err
}
requestId := k.getNextOrderIdWithUpdate(ctx, pair)
expireAt := ctx.BlockTime().Add(msg.OrderLifespan)
order := types.NewOrderForLimitOrder(msg, requestId, pair, offerCoin, price, expireAt, ctx.BlockHeight())
k.SetOrder(ctx, order)
k.SetOrderIndex(ctx, order)
ctx.GasMeter().ConsumeGas(k.GetOrderExtraGas(ctx), "OrderExtraGas")
ctx.EventManager().EmitEvents(sdk.Events{
sdk.NewEvent(
types.EventTypeLimitOrder,
sdk.NewAttribute(types.AttributeKeyOrderer, msg.Orderer),
sdk.NewAttribute(types.AttributeKeyPairId, strconv.FormatUint(msg.PairId, 10)),
sdk.NewAttribute(types.AttributeKeyOrderDirection, msg.Direction.String()),
sdk.NewAttribute(types.AttributeKeyOfferCoin, offerCoin.String()),
sdk.NewAttribute(types.AttributeKeyDemandCoinDenom, msg.DemandCoinDenom),
sdk.NewAttribute(types.AttributeKeyPrice, price.String()),
sdk.NewAttribute(types.AttributeKeyAmount, msg.Amount.String()),
sdk.NewAttribute(types.AttributeKeyOrderId, strconv.FormatUint(order.Id, 10)),
sdk.NewAttribute(types.AttributeKeyBatchId, strconv.FormatUint(order.BatchId, 10)),
sdk.NewAttribute(types.AttributeKeyExpireAt, order.ExpireAt.Format(time.RFC3339)),
sdk.NewAttribute(types.AttributeKeyRefundedCoins, refundedCoin.String()),
),
})
return order, nil
}
// ValidateMsgMarketOrder validates types.MsgMarketOrder with state and returns
// calculated offer coin and price.
func (k Keeper) ValidateMsgMarketOrder(ctx sdk.Context, msg *types.MsgMarketOrder) (offerCoin sdk.Coin, price sdk.Dec, err error) {
spendable := k.bankKeeper.SpendableCoins(ctx, msg.GetOrderer())
if spendableAmt := spendable.AmountOf(msg.OfferCoin.Denom); spendableAmt.LT(msg.OfferCoin.Amount) {
return sdk.Coin{}, sdk.Dec{}, sdkerrors.Wrapf(
sdkerrors.ErrInsufficientFunds, "%s is smaller than %s",
sdk.NewCoin(msg.OfferCoin.Denom, spendableAmt), msg.OfferCoin)
}
maxOrderLifespan := k.GetMaxOrderLifespan(ctx)
maxPriceLimitRatio := k.GetMaxPriceLimitRatio(ctx)
tickPrec := k.GetTickPrecision(ctx)
if msg.OrderLifespan > maxOrderLifespan {
return sdk.Coin{}, sdk.Dec{},
sdkerrors.Wrapf(types.ErrTooLongOrderLifespan, "%s is longer than %s", msg.OrderLifespan, maxOrderLifespan)
}
pair, found := k.GetPair(ctx, msg.PairId)
if !found {
return sdk.Coin{}, sdk.Dec{}, sdkerrors.Wrapf(sdkerrors.ErrNotFound, "pair %d not found", msg.PairId)
}
if pair.LastPrice == nil {
return sdk.Coin{}, sdk.Dec{}, types.ErrNoLastPrice
}
lastPrice := *pair.LastPrice
switch msg.Direction {
case types.OrderDirectionBuy:
if msg.OfferCoin.Denom != pair.QuoteCoinDenom || msg.DemandCoinDenom != pair.BaseCoinDenom {
return sdk.Coin{}, sdk.Dec{},
sdkerrors.Wrapf(types.ErrWrongPair, "denom pair (%s, %s) != (%s, %s)",
msg.DemandCoinDenom, msg.OfferCoin.Denom, pair.BaseCoinDenom, pair.QuoteCoinDenom)
}
price = amm.PriceToDownTick(lastPrice.Mul(sdk.OneDec().Add(maxPriceLimitRatio)), int(tickPrec))
offerCoin = sdk.NewCoin(msg.OfferCoin.Denom, amm.OfferCoinAmount(amm.Buy, price, msg.Amount))
if msg.OfferCoin.IsLT(offerCoin) {
return sdk.Coin{}, sdk.Dec{}, sdkerrors.Wrapf(
types.ErrInsufficientOfferCoin, "%s is smaller than %s", msg.OfferCoin, offerCoin)
}
case types.OrderDirectionSell:
if msg.OfferCoin.Denom != pair.BaseCoinDenom || msg.DemandCoinDenom != pair.QuoteCoinDenom {
return sdk.Coin{}, sdk.Dec{},
sdkerrors.Wrapf(types.ErrWrongPair, "denom pair (%s, %s) != (%s, %s)",
msg.OfferCoin.Denom, msg.DemandCoinDenom, pair.BaseCoinDenom, pair.QuoteCoinDenom)
}
price = amm.PriceToUpTick(lastPrice.Mul(sdk.OneDec().Sub(maxPriceLimitRatio)), int(tickPrec))
offerCoin = sdk.NewCoin(msg.OfferCoin.Denom, msg.Amount)
if msg.OfferCoin.Amount.LT(msg.Amount) {
return sdk.Coin{}, sdk.Dec{}, sdkerrors.Wrapf(
types.ErrInsufficientOfferCoin, "%s is smaller than %s", msg.OfferCoin, sdk.NewCoin(msg.OfferCoin.Denom, msg.Amount))
}
}
if types.IsTooSmallOrderAmount(msg.Amount, price) {
return sdk.Coin{}, sdk.Dec{}, types.ErrTooSmallOrder
}
return offerCoin, price, nil
}
// MarketOrder handles types.MsgMarketOrder and stores types.Order.
func (k Keeper) MarketOrder(ctx sdk.Context, msg *types.MsgMarketOrder) (types.Order, error) {
offerCoin, price, err := k.ValidateMsgMarketOrder(ctx, msg)
if err != nil {
return types.Order{}, err
}
refundedCoin := msg.OfferCoin.Sub(offerCoin)
pair, _ := k.GetPair(ctx, msg.PairId)
if err := k.bankKeeper.SendCoins(ctx, msg.GetOrderer(), pair.GetEscrowAddress(), sdk.NewCoins(offerCoin)); err != nil {
return types.Order{}, err
}
requestId := k.getNextOrderIdWithUpdate(ctx, pair)
expireAt := ctx.BlockTime().Add(msg.OrderLifespan)
order := types.NewOrderForMarketOrder(msg, requestId, pair, offerCoin, price, expireAt, ctx.BlockHeight())
k.SetOrder(ctx, order)
k.SetOrderIndex(ctx, order)
ctx.GasMeter().ConsumeGas(k.GetOrderExtraGas(ctx), "OrderExtraGas")
ctx.EventManager().EmitEvents(sdk.Events{
sdk.NewEvent(
types.EventTypeMarketOrder,
sdk.NewAttribute(types.AttributeKeyOrderer, msg.Orderer),
sdk.NewAttribute(types.AttributeKeyPairId, strconv.FormatUint(msg.PairId, 10)),
sdk.NewAttribute(types.AttributeKeyOrderDirection, msg.Direction.String()),
sdk.NewAttribute(types.AttributeKeyOfferCoin, offerCoin.String()),
sdk.NewAttribute(types.AttributeKeyDemandCoinDenom, msg.DemandCoinDenom),
sdk.NewAttribute(types.AttributeKeyPrice, price.String()),
sdk.NewAttribute(types.AttributeKeyAmount, msg.Amount.String()),
sdk.NewAttribute(types.AttributeKeyOrderId, strconv.FormatUint(order.Id, 10)),
sdk.NewAttribute(types.AttributeKeyBatchId, strconv.FormatUint(order.BatchId, 10)),
sdk.NewAttribute(types.AttributeKeyExpireAt, order.ExpireAt.Format(time.RFC3339)),
sdk.NewAttribute(types.AttributeKeyRefundedCoins, refundedCoin.String()),
),
})
return order, nil
}
func (k Keeper) MMOrder(ctx sdk.Context, msg *types.MsgMMOrder) (orders []types.Order, err error) {
tickPrec := int(k.GetTickPrecision(ctx))
if msg.SellAmount.IsPositive() {
if !amm.PriceToDownTick(msg.MinSellPrice, tickPrec).Equal(msg.MinSellPrice) {
return nil, sdkerrors.Wrapf(types.ErrPriceNotOnTicks, "min sell price is not on ticks")
}
if !amm.PriceToDownTick(msg.MaxSellPrice, tickPrec).Equal(msg.MaxSellPrice) {
return nil, sdkerrors.Wrapf(types.ErrPriceNotOnTicks, "max sell price is not on ticks")
}
}
if msg.BuyAmount.IsPositive() {
if !amm.PriceToDownTick(msg.MinBuyPrice, tickPrec).Equal(msg.MinBuyPrice) {
return nil, sdkerrors.Wrapf(types.ErrPriceNotOnTicks, "min buy price is not on ticks")
}
if !amm.PriceToDownTick(msg.MaxBuyPrice, tickPrec).Equal(msg.MaxBuyPrice) {
return nil, sdkerrors.Wrapf(types.ErrPriceNotOnTicks, "max buy price is not on ticks")
}
}
pair, found := k.GetPair(ctx, msg.PairId)
if !found {
return nil, sdkerrors.Wrapf(sdkerrors.ErrNotFound, "pair %d not found", msg.PairId)
}
var lowestPrice, highestPrice sdk.Dec
if pair.LastPrice != nil {
lowestPrice, highestPrice = types.PriceLimits(*pair.LastPrice, k.GetMaxPriceLimitRatio(ctx), tickPrec)
} else {
lowestPrice = amm.LowestTick(tickPrec)
highestPrice = amm.HighestTick(tickPrec)
}
if msg.SellAmount.IsPositive() {
if msg.MinSellPrice.LT(lowestPrice) || msg.MinSellPrice.GT(highestPrice) {
return nil, sdkerrors.Wrapf(types.ErrPriceOutOfRange, "min sell price is out of range [%s, %s]", lowestPrice, highestPrice)
}
if msg.MaxSellPrice.LT(lowestPrice) || msg.MaxSellPrice.GT(highestPrice) {
return nil, sdkerrors.Wrapf(types.ErrPriceOutOfRange, "max sell price is out of range [%s, %s]", lowestPrice, highestPrice)
}
}
if msg.BuyAmount.IsPositive() {
if msg.MinBuyPrice.LT(lowestPrice) || msg.MinBuyPrice.GT(highestPrice) {
return nil, sdkerrors.Wrapf(types.ErrPriceOutOfRange, "min buy price is out of range [%s, %s]", lowestPrice, highestPrice)
}
if msg.MaxBuyPrice.LT(lowestPrice) || msg.MaxBuyPrice.GT(highestPrice) {
return nil, sdkerrors.Wrapf(types.ErrPriceOutOfRange, "max buy price is out of range [%s, %s]", lowestPrice, highestPrice)
}
}
maxNumTicks := int(k.GetMaxNumMarketMakingOrderTicks(ctx))
var buyTicks, sellTicks []types.MMOrderTick
offerBaseCoin := sdk.NewInt64Coin(pair.BaseCoinDenom, 0)
offerQuoteCoin := sdk.NewInt64Coin(pair.QuoteCoinDenom, 0)
if msg.BuyAmount.IsPositive() {
buyTicks = types.MMOrderTicks(
types.OrderDirectionBuy, msg.MinBuyPrice, msg.MaxBuyPrice, msg.BuyAmount, maxNumTicks, tickPrec)
for _, tick := range buyTicks {
offerQuoteCoin = offerQuoteCoin.AddAmount(tick.OfferCoinAmount)
}
}
if msg.SellAmount.IsPositive() {
sellTicks = types.MMOrderTicks(
types.OrderDirectionSell, msg.MinSellPrice, msg.MaxSellPrice, msg.SellAmount, maxNumTicks, tickPrec)
for _, tick := range sellTicks {
offerBaseCoin = offerBaseCoin.AddAmount(tick.OfferCoinAmount)
}
}
orderer := msg.GetOrderer()
spendable := k.bankKeeper.SpendableCoins(ctx, orderer)
if spendableAmt := spendable.AmountOf(pair.BaseCoinDenom); spendableAmt.LT(offerBaseCoin.Amount) {
return nil, sdkerrors.Wrapf(
sdkerrors.ErrInsufficientFunds, "%s is smaller than %s",
sdk.NewCoin(pair.BaseCoinDenom, spendableAmt), offerBaseCoin)
}
if spendableAmt := spendable.AmountOf(pair.QuoteCoinDenom); spendableAmt.LT(offerQuoteCoin.Amount) {
return nil, sdkerrors.Wrapf(
sdkerrors.ErrInsufficientFunds, "%s is smaller than %s",
sdk.NewCoin(pair.QuoteCoinDenom, spendableAmt), offerQuoteCoin)
}
maxOrderLifespan := k.GetMaxOrderLifespan(ctx)
if msg.OrderLifespan > maxOrderLifespan {
return nil, sdkerrors.Wrapf(
types.ErrTooLongOrderLifespan, "%s is longer than %s", msg.OrderLifespan, maxOrderLifespan)
}
// First, cancel existing market making orders in the pair from the orderer.
canceledOrderIds, err := k.cancelMMOrder(ctx, orderer, pair, true)
if err != nil {
return nil, err
}
if err := k.bankKeeper.SendCoins(ctx, orderer, pair.GetEscrowAddress(), sdk.NewCoins(offerBaseCoin, offerQuoteCoin)); err != nil {
return nil, err
}
expireAt := ctx.BlockTime().Add(msg.OrderLifespan)
lastOrderId := pair.LastOrderId
var orderIds []uint64
for _, tick := range buyTicks {
lastOrderId++
offerCoin := sdk.NewCoin(pair.QuoteCoinDenom, tick.OfferCoinAmount)
order := types.NewOrder(
types.OrderTypeMM, lastOrderId, pair, orderer,
offerCoin, tick.Price, tick.Amount, expireAt, ctx.BlockHeight())
k.SetOrder(ctx, order)
k.SetOrderIndex(ctx, order)
orders = append(orders, order)
orderIds = append(orderIds, order.Id)
}
for _, tick := range sellTicks {
lastOrderId++
offerCoin := sdk.NewCoin(pair.BaseCoinDenom, tick.OfferCoinAmount)
order := types.NewOrder(
types.OrderTypeMM, lastOrderId, pair, orderer,
offerCoin, tick.Price, tick.Amount, expireAt, ctx.BlockHeight())
k.SetOrder(ctx, order)
k.SetOrderIndex(ctx, order)
orders = append(orders, order)
orderIds = append(orderIds, order.Id)
}
pair.LastOrderId = lastOrderId
k.SetPair(ctx, pair)
k.SetMMOrderIndex(ctx, types.NewMMOrderIndex(orderer, pair.Id, orderIds))
ctx.EventManager().EmitEvents(sdk.Events{
sdk.NewEvent(
types.EventTypeMMOrder,
sdk.NewAttribute(types.AttributeKeyOrderer, msg.Orderer),
sdk.NewAttribute(types.AttributeKeyPairId, strconv.FormatUint(msg.PairId, 10)),
sdk.NewAttribute(types.AttributeKeyBatchId, strconv.FormatUint(pair.CurrentBatchId, 10)),
sdk.NewAttribute(types.AttributeKeyOrderIds, types.FormatUint64s(orderIds)),
sdk.NewAttribute(types.AttributeKeyCanceledOrderIds, types.FormatUint64s(canceledOrderIds)),
),
})
return
}
// ValidateMsgCancelOrder validates types.MsgCancelOrder and returns the order.
func (k Keeper) ValidateMsgCancelOrder(ctx sdk.Context, msg *types.MsgCancelOrder) (order types.Order, err error) {
var found bool
order, found = k.GetOrder(ctx, msg.PairId, msg.OrderId)
if !found {
return types.Order{},
sdkerrors.Wrapf(sdkerrors.ErrNotFound, "order %d not found in pair %d", msg.OrderId, msg.PairId)
}
if msg.Orderer != order.Orderer {
return types.Order{}, sdkerrors.Wrap(sdkerrors.ErrUnauthorized, "mismatching orderer")
}
if order.Status == types.OrderStatusCanceled {
return types.Order{}, types.ErrAlreadyCanceled
}
pair, _ := k.GetPair(ctx, msg.PairId)
if order.BatchId == pair.CurrentBatchId {
return types.Order{}, types.ErrSameBatch
}
return order, nil
}
// CancelOrder handles types.MsgCancelOrder and cancels an order.
func (k Keeper) CancelOrder(ctx sdk.Context, msg *types.MsgCancelOrder) error {
order, err := k.ValidateMsgCancelOrder(ctx, msg)
if err != nil {
return err
}
if err := k.FinishOrder(ctx, order, types.OrderStatusCanceled); err != nil {
return err
}
ctx.EventManager().EmitEvents(sdk.Events{
sdk.NewEvent(
types.EventTypeCancelOrder,
sdk.NewAttribute(types.AttributeKeyOrderer, msg.Orderer),
sdk.NewAttribute(types.AttributeKeyPairId, strconv.FormatUint(msg.PairId, 10)),
sdk.NewAttribute(types.AttributeKeyOrderId, strconv.FormatUint(msg.OrderId, 10)),
),
})
return nil
}
// CancelAllOrders handles types.MsgCancelAllOrders and cancels all orders.
func (k Keeper) CancelAllOrders(ctx sdk.Context, msg *types.MsgCancelAllOrders) error {
orderPairCache := map[uint64]types.Pair{} // maps order's pair id to pair, to cache the result
pairIdSet := map[uint64]struct{}{} // set of pairs where to cancel orders
var pairIds []string // needed to emit an event
for _, pairId := range msg.PairIds {
pair, found := k.GetPair(ctx, pairId)
if !found { // check if the pair exists
return sdkerrors.Wrapf(sdkerrors.ErrNotFound, "pair %d not found", pairId)
}
pairIdSet[pairId] = struct{}{} // add pair id to the set
pairIds = append(pairIds, strconv.FormatUint(pairId, 10))
orderPairCache[pairId] = pair // also cache the pair to use at below
}
var canceledOrderIds []string
if err := k.IterateOrdersByOrderer(ctx, msg.GetOrderer(), func(order types.Order) (stop bool, err error) {
_, ok := pairIdSet[order.PairId] // is the pair included in the pair set?
if len(pairIdSet) == 0 || ok { // pair ids not specified(cancel all), or the pair is in the set
pair, ok := orderPairCache[order.PairId]
if !ok {
pair, _ = k.GetPair(ctx, order.PairId)
orderPairCache[order.PairId] = pair
}
if order.Status != types.OrderStatusCanceled && order.BatchId < pair.CurrentBatchId {
if err := k.FinishOrder(ctx, order, types.OrderStatusCanceled); err != nil {
return false, err
}
canceledOrderIds = append(canceledOrderIds, strconv.FormatUint(order.Id, 10))
}
}
return false, nil
}); err != nil {
return err
}
ctx.EventManager().EmitEvents(sdk.Events{
sdk.NewEvent(
types.EventTypeCancelAllOrders,
sdk.NewAttribute(types.AttributeKeyOrderer, msg.Orderer),
sdk.NewAttribute(types.AttributeKeyPairIds, strings.Join(pairIds, ",")),
sdk.NewAttribute(types.AttributeKeyCanceledOrderIds, strings.Join(canceledOrderIds, ",")),
),
})
return nil
}
func (k Keeper) cancelMMOrder(ctx sdk.Context, orderer sdk.AccAddress, pair types.Pair, skipIfNotFound bool) (canceledOrderIds []uint64, err error) {
index, found := k.GetMMOrderIndex(ctx, orderer, pair.Id)
if found {
for _, orderId := range index.OrderIds {
order, found := k.GetOrder(ctx, pair.Id, orderId)
if !found {
// The order has already been deleted from store.
continue
}
if order.BatchId == pair.CurrentBatchId {
return nil, sdkerrors.Wrap(types.ErrSameBatch, "couldn't cancel previously placed orders")
}
if order.Status.CanBeCanceled() {
if err := k.FinishOrder(ctx, order, types.OrderStatusCanceled); err != nil {
return nil, err
}
canceledOrderIds = append(canceledOrderIds, order.Id)
}
}
k.DeleteMMOrderIndex(ctx, index)
} else if !skipIfNotFound {
return nil, sdkerrors.Wrap(sdkerrors.ErrNotFound, "previous market making orders not found")
}
return
}
// CancelMMOrder handles types.MsgCancelMMOrder and cancels previous market making
// orders.
func (k Keeper) CancelMMOrder(ctx sdk.Context, msg *types.MsgCancelMMOrder) (canceledOrderIds []uint64, err error) {
pair, found := k.GetPair(ctx, msg.PairId)
if !found {
return nil, sdkerrors.Wrapf(sdkerrors.ErrNotFound, "pair %d not found", msg.PairId)
}
canceledOrderIds, err = k.cancelMMOrder(ctx, msg.GetOrderer(), pair, false)
if err != nil {
return
}
ctx.EventManager().EmitEvents(sdk.Events{
sdk.NewEvent(
types.EventTypeCancelMMOrder,
sdk.NewAttribute(types.AttributeKeyOrderer, msg.Orderer),
sdk.NewAttribute(types.AttributeKeyPairId, strconv.FormatUint(pair.Id, 10)),
sdk.NewAttribute(types.AttributeKeyCanceledOrderIds, types.FormatUint64s(canceledOrderIds)),
),
})
return canceledOrderIds, nil
}
func (k Keeper) ExecuteMatching(ctx sdk.Context, pair types.Pair) error {
ob := amm.NewOrderBook()
if err := k.IterateOrdersByPair(ctx, pair.Id, func(order types.Order) (stop bool, err error) {
switch order.Status {
case types.OrderStatusNotExecuted,
types.OrderStatusNotMatched,
types.OrderStatusPartiallyMatched:
if order.Status != types.OrderStatusNotExecuted && order.ExpiredAt(ctx.BlockTime()) {
if err := k.FinishOrder(ctx, order, types.OrderStatusExpired); err != nil {
return false, err
}
return false, nil
}
// TODO: add orders only when price is in the range?
ob.AddOrder(types.NewUserOrder(order))
if order.Status == types.OrderStatusNotExecuted {
order.SetStatus(types.OrderStatusNotMatched)
k.SetOrder(ctx, order)
}
case types.OrderStatusCanceled:
default:
return false, fmt.Errorf("invalid order status: %s", order.Status)
}
return false, nil
}); err != nil {
return err
}
var pools []*types.PoolOrderer
_ = k.IteratePoolsByPair(ctx, pair.Id, func(pool types.Pool) (stop bool, err error) {
if pool.Disabled {
return false, nil
}
rx, ry := k.getPoolBalances(ctx, pool, pair)
ps := k.GetPoolCoinSupply(ctx, pool)
ammPool := types.NewPoolOrderer(
pool.AMMPool(rx.Amount, ry.Amount, ps),
pool.Id, pool.GetReserveAddress(), pair.BaseCoinDenom, pair.QuoteCoinDenom)
if ammPool.IsDepleted() {
k.MarkPoolAsDisabled(ctx, pool)
return false, nil
}
pools = append(pools, ammPool)
return false, nil
})
matchPrice, quoteCoinDiff, matched := k.Match(ctx, ob, pools, pair.LastPrice)
if matched {
orders := ob.Orders()
if err := k.ApplyMatchResult(ctx, pair, orders, quoteCoinDiff); err != nil {
return err
}
pair.LastPrice = &matchPrice
}
pair.CurrentBatchId++
k.SetPair(ctx, pair)
return nil
}
func (k Keeper) Match(ctx sdk.Context, ob *amm.OrderBook, pools []*types.PoolOrderer, lastPrice *sdk.Dec) (matchPrice sdk.Dec, quoteCoinDiff sdk.Int, matched bool) {
tickPrec := int(k.GetTickPrecision(ctx))
if lastPrice == nil {
ov := amm.MultipleOrderViews{ob.MakeView()}
for _, pool := range pools {
ov = append(ov, pool)
}
var found bool
matchPrice, found = amm.FindMatchPrice(ov, tickPrec)
if !found {
return sdk.Dec{}, sdk.Int{}, false
}
for _, pool := range pools {
buyAmt := pool.BuyAmountOver(matchPrice, true)
if buyAmt.IsPositive() {
ob.AddOrder(pool.Order(amm.Buy, matchPrice, buyAmt))
}
sellAmt := pool.SellAmountUnder(matchPrice, true)
if sellAmt.IsPositive() {
ob.AddOrder(pool.Order(amm.Sell, matchPrice, sellAmt))
}
}
quoteCoinDiff, matched = ob.MatchAtSinglePrice(matchPrice)
} else {
lowestPrice, highestPrice := k.PriceLimits(ctx, *lastPrice)
for _, pool := range pools {
poolOrders := amm.PoolOrders(pool, pool, lowestPrice, highestPrice, tickPrec)
ob.AddOrder(poolOrders...)
}
matchPrice, quoteCoinDiff, matched = ob.Match(*lastPrice)
}
return
}
func (k Keeper) ApplyMatchResult(ctx sdk.Context, pair types.Pair, orders []amm.Order, quoteCoinDiff sdk.Int) error {
bulkOp := types.NewBulkSendCoinsOperation()
for _, order := range orders { // TODO: need optimization to filter matched orders only
order, ok := order.(*types.PoolOrder)
if !ok {
continue
}
if !order.IsMatched() {
continue
}
paidCoin := sdk.NewCoin(order.OfferCoinDenom, order.PaidOfferCoinAmount)
bulkOp.QueueSendCoins(order.ReserveAddress, pair.GetEscrowAddress(), sdk.NewCoins(paidCoin))
}
if err := bulkOp.Run(ctx, k.bankKeeper); err != nil {
return err
}
bulkOp = types.NewBulkSendCoinsOperation()
type PoolMatchResult struct {
PoolId uint64
OrderDirection types.OrderDirection
PaidCoin sdk.Coin
ReceivedCoin sdk.Coin
MatchedAmount sdk.Int
}
poolMatchResultById := map[uint64]*PoolMatchResult{}
var poolMatchResults []*PoolMatchResult
for _, order := range orders {
if !order.IsMatched() {
continue
}
matchedAmt := order.GetAmount().Sub(order.GetOpenAmount())
switch order := order.(type) {
case *types.UserOrder:
paidCoin := sdk.NewCoin(order.OfferCoinDenom, order.PaidOfferCoinAmount)
receivedCoin := sdk.NewCoin(order.DemandCoinDenom, order.ReceivedDemandCoinAmount)
o, _ := k.GetOrder(ctx, pair.Id, order.OrderId)
o.OpenAmount = o.OpenAmount.Sub(matchedAmt)
o.RemainingOfferCoin = o.RemainingOfferCoin.Sub(paidCoin)
o.ReceivedCoin = o.ReceivedCoin.Add(receivedCoin)
if o.OpenAmount.IsZero() {
if err := k.FinishOrder(ctx, o, types.OrderStatusCompleted); err != nil {
return err
}
} else {
o.SetStatus(types.OrderStatusPartiallyMatched)
k.SetOrder(ctx, o)
}
bulkOp.QueueSendCoins(pair.GetEscrowAddress(), order.Orderer, sdk.NewCoins(receivedCoin))
ctx.EventManager().EmitEvents(sdk.Events{
sdk.NewEvent(
types.EventTypeUserOrderMatched,
sdk.NewAttribute(types.AttributeKeyOrderDirection, types.OrderDirectionFromAMM(order.Direction).String()),
sdk.NewAttribute(types.AttributeKeyOrderer, order.Orderer.String()),
sdk.NewAttribute(types.AttributeKeyPairId, strconv.FormatUint(pair.Id, 10)),
sdk.NewAttribute(types.AttributeKeyOrderId, strconv.FormatUint(order.OrderId, 10)),
sdk.NewAttribute(types.AttributeKeyMatchedAmount, matchedAmt.String()),
sdk.NewAttribute(types.AttributeKeyPaidCoin, paidCoin.String()),
sdk.NewAttribute(types.AttributeKeyReceivedCoin, receivedCoin.String()),
),
})
case *types.PoolOrder:
paidCoin := sdk.NewCoin(order.OfferCoinDenom, order.PaidOfferCoinAmount)
receivedCoin := sdk.NewCoin(order.DemandCoinDenom, order.ReceivedDemandCoinAmount)
bulkOp.QueueSendCoins(pair.GetEscrowAddress(), order.ReserveAddress, sdk.NewCoins(receivedCoin))
r, ok := poolMatchResultById[order.PoolId]
if !ok {
r = &PoolMatchResult{
PoolId: order.PoolId,
OrderDirection: types.OrderDirectionFromAMM(order.Direction),
PaidCoin: sdk.NewCoin(paidCoin.Denom, sdk.ZeroInt()),
ReceivedCoin: sdk.NewCoin(receivedCoin.Denom, sdk.ZeroInt()),
MatchedAmount: sdk.ZeroInt(),
}
poolMatchResultById[order.PoolId] = r
poolMatchResults = append(poolMatchResults, r)
}
dir := types.OrderDirectionFromAMM(order.Direction)
if r.OrderDirection != dir {
panic(fmt.Errorf("wrong order direction: %s != %s", dir, r.OrderDirection))
}
r.PaidCoin = r.PaidCoin.Add(paidCoin)
r.ReceivedCoin = r.ReceivedCoin.Add(receivedCoin)
r.MatchedAmount = r.MatchedAmount.Add(matchedAmt)
default:
panic(fmt.Errorf("invalid order type: %T", order))
}
}
bulkOp.QueueSendCoins(pair.GetEscrowAddress(), k.GetDustCollector(ctx), sdk.NewCoins(sdk.NewCoin(pair.QuoteCoinDenom, quoteCoinDiff)))
if err := bulkOp.Run(ctx, k.bankKeeper); err != nil {
return err
}
for _, r := range poolMatchResults {
ctx.EventManager().EmitEvents(sdk.Events{
sdk.NewEvent(
types.EventTypePoolOrderMatched,
sdk.NewAttribute(types.AttributeKeyOrderDirection, r.OrderDirection.String()),
sdk.NewAttribute(types.AttributeKeyPairId, strconv.FormatUint(pair.Id, 10)),
sdk.NewAttribute(types.AttributeKeyPoolId, strconv.FormatUint(r.PoolId, 10)),
sdk.NewAttribute(types.AttributeKeyMatchedAmount, r.MatchedAmount.String()),
sdk.NewAttribute(types.AttributeKeyPaidCoin, r.PaidCoin.String()),
sdk.NewAttribute(types.AttributeKeyReceivedCoin, r.ReceivedCoin.String()),
),
})
}
return nil
}
func (k Keeper) FinishOrder(ctx sdk.Context, order types.Order, status types.OrderStatus) error {
if order.Status == types.OrderStatusCompleted || order.Status.IsCanceledOrExpired() { // sanity check
return nil
}
if order.RemainingOfferCoin.IsPositive() {
pair, _ := k.GetPair(ctx, order.PairId)
if err := k.bankKeeper.SendCoins(ctx, pair.GetEscrowAddress(), order.GetOrderer(), sdk.NewCoins(order.RemainingOfferCoin)); err != nil {
return err
}
}
order.SetStatus(status)
k.SetOrder(ctx, order)
ctx.EventManager().EmitEvents(sdk.Events{
sdk.NewEvent(
types.EventTypeOrderResult,
sdk.NewAttribute(types.AttributeKeyOrderDirection, order.Direction.String()),
sdk.NewAttribute(types.AttributeKeyOrderer, order.Orderer),
sdk.NewAttribute(types.AttributeKeyPairId, strconv.FormatUint(order.PairId, 10)),
sdk.NewAttribute(types.AttributeKeyOrderId, strconv.FormatUint(order.Id, 10)),
sdk.NewAttribute(types.AttributeKeyAmount, order.Amount.String()),
sdk.NewAttribute(types.AttributeKeyOpenAmount, order.OpenAmount.String()),
sdk.NewAttribute(types.AttributeKeyOfferCoin, order.OfferCoin.String()),
sdk.NewAttribute(types.AttributeKeyRemainingOfferCoin, order.RemainingOfferCoin.String()),
sdk.NewAttribute(types.AttributeKeyReceivedCoin, order.ReceivedCoin.String()),
sdk.NewAttribute(types.AttributeKeyStatus, order.Status.String()),
),
})
return nil
}