-
Notifications
You must be signed in to change notification settings - Fork 0
/
orders.go
1342 lines (1211 loc) · 47.9 KB
/
orders.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
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package keeper
import (
"fmt"
"math"
"math/big"
"time"
errorsmod "cosmossdk.io/errors"
gometrics "github.com/armon/go-metrics"
"github.com/cometbft/cometbft/crypto/tmhash"
"github.com/jinxprotocol/v4-chain/protocol/indexer/msgsender"
"github.com/jinxprotocol/v4-chain/protocol/indexer/off_chain_updates"
indexershared "github.com/jinxprotocol/v4-chain/protocol/indexer/shared"
"github.com/jinxprotocol/v4-chain/protocol/lib"
"github.com/jinxprotocol/v4-chain/protocol/lib/metrics"
"github.com/jinxprotocol/v4-chain/protocol/x/clob/types"
satypes "github.com/jinxprotocol/v4-chain/protocol/x/subaccounts/types"
"github.com/cosmos/cosmos-sdk/telemetry"
sdk "github.com/cosmos/cosmos-sdk/types"
)
func (k Keeper) GetOperations(ctx sdk.Context) *types.MsgProposedOperations {
operationsQueueRaw := k.MemClob.GetOperationsRaw(ctx)
msgProposedOperations := &types.MsgProposedOperations{
OperationsQueue: operationsQueueRaw,
}
if err := msgProposedOperations.ValidateBasic(); err != nil {
operations, _ := k.MemClob.GetOperationsToReplay(ctx)
panic(fmt.Sprintf("MsgProposedOperations failed validation: %s. Operations to replay: %+v", err, operations))
}
if _, err := types.ValidateAndTransformRawOperations(
ctx,
operationsQueueRaw,
k.txDecoder,
k.antehandler,
); err != nil {
operations, _ := k.MemClob.GetOperationsToReplay(ctx)
panic(fmt.Sprintf("MsgProposedOperations failed stateful validation: %s. Operations to replay: %+v", err, operations))
}
return msgProposedOperations
}
// CancelShortTermOrder removes a Short-Term order by `OrderId` (if it exists) from all order-related data structures
// in the memclob. As well, CancelShortTermOrder adds (or updates) a cancel to the desired `goodTilBlock` in the
// memclob.
// If a cancel already exists for this order with a lower `goodTilBlock`, the cancel is updated to the
// new `goodTilBlock`. This method is meant to be used in the CheckTx flow. It uses the next block height.
//
// An error will be returned if any of the following conditions are true:
// - The cancel's `GoodTilblock` is less than or equal to the next block height.
// - The cancel's `GoodTilblock` is greater than the sum of the next block height and `ShortBlockWindow`.
// - The memclob itself returns an error.
//
// This method assumes the provided MsgCancelOrder has already passed ValidateBasic in CheckTx.
func (k Keeper) CancelShortTermOrder(
ctx sdk.Context,
msgCancelOrder *types.MsgCancelOrder,
) error {
lib.AssertCheckTxMode(ctx)
// Note that we add `+1` here to account for the fact that `ctx.BlockHeight()` is technically the
// previously mined block, not the next block that will be proposed. This is due to the fact that
// this function is only ever called during `CheckTx`.
nextBlockHeight := lib.MustConvertIntegerToUint32(ctx.BlockHeight() + 1)
defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), metrics.CancelShortTermOrder, metrics.Latency)
telemetry.IncrCounter(1, types.ModuleName, metrics.CancelShortTermOrder, metrics.Count)
// Perform all stateful validation on the short term order.
if err := k.PerformOrderCancellationStatefulValidation(ctx, msgCancelOrder, nextBlockHeight); err != nil {
return err
}
// Update in-memory orderbook to remove short term order.
offchainUpdates, err := k.MemClob.CancelOrder(ctx, msgCancelOrder)
if err != nil {
return err
}
k.sendOffchainMessagesWithTxHash(
offchainUpdates,
tmhash.Sum(ctx.TxBytes()),
metrics.SendCancelOrderOffchainUpdates,
)
return nil
}
// PlaceShortTermOrder places an order on the corresponding orderbook, and performs matching if placing the
// order causes an overlap. This function will return the result of calling `PlaceOrder` on the
// keeper's memclob. This method is meant to be used in the CheckTx flow. It uses the next block height.
//
// An error will be returned if any of the following conditions are true:
// - Standard stateful validation fails.
// - The subaccount's equity tier limit is exceeded.
// - Placing the short term order on the memclob returns an error.
//
// This method will panic if the provided order is not a Short-Term order.
func (k Keeper) PlaceShortTermOrder(
ctx sdk.Context,
msg *types.MsgPlaceOrder,
) (
orderSizeOptimisticallyFilledFromMatchingQuantums satypes.BaseQuantums,
orderStatus types.OrderStatus,
err error,
) {
lib.AssertCheckTxMode(ctx)
nextBlockHeight := lib.MustConvertIntegerToUint32(ctx.BlockHeight() + 1)
order := msg.GetOrder()
order.OrderId.MustBeShortTermOrder()
orderLabels := order.GetOrderLabels()
defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), metrics.PlaceOrder, metrics.Latency)
defer func() {
telemetry.IncrCounterWithLabels(
[]string{types.ModuleName, metrics.PlaceOrder, metrics.Count},
1,
orderLabels,
)
if err != nil {
telemetry.IncrCounterWithLabels(
[]string{types.ModuleName, metrics.PlaceOrder, metrics.Rejected},
1,
orderLabels,
)
}
}()
// Perform stateful validation.
err = k.PerformStatefulOrderValidation(ctx, &order, nextBlockHeight, true)
if err != nil {
return 0, 0, err
}
// Validate that adding the order wouldn't exceed subaccount equity tier limits.
err = k.ValidateSubaccountEquityTierLimitForNewOrder(ctx, order)
if err != nil {
return 0, 0, err
}
// Place the order on the memclob and return the result.
orderSizeOptimisticallyFilledFromMatchingQuantums, orderStatus, offchainUpdates, err := k.MemClob.PlaceOrder(
ctx,
msg.Order,
)
// Send off-chain updates generated from placing the order. `SendOffchainData` enqueues the
// the messages to be sent in a channel and should be non-blocking.
// Off-chain update messages should be only be returned if the `IndexerMessageSender`
// is enabled (`msgSender.Enabled()` returns true).
k.sendOffchainMessagesWithTxHash(
offchainUpdates,
tmhash.Sum(ctx.TxBytes()),
metrics.SendPlaceOrderOffchainUpdates,
)
if orderSizeOptimisticallyFilledFromMatchingQuantums > 0 {
telemetry.IncrCounterWithLabels(
[]string{types.ModuleName, metrics.PlaceOrder, metrics.Matched},
1,
orderLabels,
)
}
return orderSizeOptimisticallyFilledFromMatchingQuantums, orderStatus, err
}
// CancelStatefulOrder performs stateful order cancellation validation and removes the stateful order
// from state and the memstore.
//
// The following conditions must be true otherwise an error will be returned:
// - Stateful Order Cancellation cancels an existing stateful order.
// - Stateful Order Cancellation GTBT is greater than or equal to than stateful order GTBT.
// - Stateful Order Cancellation GTBT is greater than the block time of previous block.
// - Stateful Order Cancellation GTBT is less than or equal to `StatefulOrderTimeWindow` away from block time of
// previous block.
//
// Note that this method conditionally updates state depending on the context. This is needed
// to separate updating committed state during DeliverTx (the stateful order and the ToBeCommitted stateful order
// count) from uncommitted state that is modified during CheckTx.
func (k Keeper) CancelStatefulOrder(
ctx sdk.Context,
msg *types.MsgCancelOrder,
) (err error) {
defer func() {
if err != nil {
telemetry.IncrCounterWithLabels(
[]string{types.ModuleName, metrics.CancelStatefulOrder, metrics.Error, metrics.Count},
1,
[]gometrics.Label{
metrics.GetLabelForStringValue(metrics.Callback, metrics.GetCallbackMetricFromCtx(ctx)),
},
)
} else {
telemetry.IncrCounterWithLabels(
[]string{types.ModuleName, metrics.CancelStatefulOrder, metrics.Success, metrics.Count},
1,
[]gometrics.Label{
metrics.GetLabelForStringValue(metrics.Callback, metrics.GetCallbackMetricFromCtx(ctx)),
},
)
}
}()
// 1. If this is a Short-Term order, panic.
msg.OrderId.MustBeStatefulOrder()
// 2. Perform stateful validation on the order cancellation.
if err := k.PerformOrderCancellationStatefulValidation(
ctx,
msg,
// Note that the blockHeight is not used during stateful order cancellation validation.
0,
); err != nil {
return err
}
// 3. Update uncommitted or committed state depending on whether we are in `checkTx` or `deliverTx`.
if lib.IsDeliverTxMode(ctx) {
// Remove the stateful order from state. Note that if the stateful order did not
// exist in state, then it would have failed validation in the previous step.
k.MustRemoveStatefulOrder(ctx, msg.OrderId)
} else {
// Write the stateful order cancellation to uncommitted state. PerformOrderCancellationStatefulValidation will
// return an error if the order cancellation already exists which will prevent
// MustAddUncommittedStatefulOrderCancellation from panicking.
k.MustAddUncommittedStatefulOrderCancellation(ctx, msg)
// TODO(DEC-1238): Support stateful order replacements by removing the uncommitted order placement.
// This should allow a cycle of place + cancel + place + cancel + ... which we currently disallow during
// `DeliverTx`.
}
return nil
}
// PlaceStatefulOrder performs order validation, equity tier limit check, a collateralization check and writes the
// order to state and the memstore. The order will not be placed on the orderbook.
//
// An error will be returned if any of the following conditions are true:
// - Standard stateful validation fails.
// - Equity tier limit exceeded.
// - Collateralization check fails.
//
// Note that this method conditionally updates state depending on the context. This is needed
// to separate updating committed state during DeliverTx from uncommitted state that is modified during
// CheckTx.
//
// This method will panic if the provided order is not a Stateful order.
func (k Keeper) PlaceStatefulOrder(
ctx sdk.Context,
msg *types.MsgPlaceOrder,
) (err error) {
defer func() {
if err != nil {
telemetry.IncrCounterWithLabels(
[]string{types.ModuleName, metrics.PlaceStatefulOrder, metrics.Error, metrics.Count},
1,
[]gometrics.Label{
metrics.GetLabelForStringValue(metrics.Callback, metrics.GetCallbackMetricFromCtx(ctx)),
},
)
} else {
telemetry.IncrCounterWithLabels(
[]string{types.ModuleName, metrics.PlaceStatefulOrder, metrics.Success, metrics.Count},
1,
[]gometrics.Label{
metrics.GetLabelForStringValue(metrics.Callback, metrics.GetCallbackMetricFromCtx(ctx)),
},
)
}
}()
// 1. Ensure the order is not a Short-Term order.
order := msg.Order
order.OrderId.MustBeStatefulOrder()
// 2. Perform stateful validation on the order.
if err := k.PerformStatefulOrderValidation(
ctx,
&order,
// Note that the blockHeight is not used during stateful order validation.
0,
false,
); err != nil {
return err
}
// 3. Check that adding the order would not exceed the equity tier for the account.
if err := k.ValidateSubaccountEquityTierLimitForNewOrder(ctx, order); err != nil {
return err
}
// 4. Perform a collateralization check for the full size of the order to mitigate spam.
// TODO(CLOB-725): Consider using a pessimistic collateralization check.
_, successPerSubaccountUpdate := k.AddOrderToOrderbookCollatCheck(
ctx,
order.GetClobPairId(),
map[satypes.SubaccountId][]types.PendingOpenOrder{
order.OrderId.SubaccountId: {
{
RemainingQuantums: order.GetBaseQuantums(),
IsBuy: order.IsBuy(),
Subticks: order.GetOrderSubticks(),
ClobPairId: order.GetClobPairId(),
},
},
},
)
if !successPerSubaccountUpdate[order.OrderId.SubaccountId].IsSuccess() {
return errorsmod.Wrapf(
types.ErrStatefulOrderCollateralizationCheckFailed,
"PlaceStatefulOrder: order (%+v), result (%s)",
order,
successPerSubaccountUpdate[order.OrderId.SubaccountId].String(),
)
}
// 5. If we are in `deliverTx` then we write the order to committed state otherwise add the order to uncommitted
// state.
if lib.IsDeliverTxMode(ctx) {
// Write the stateful order to state and the memstore.
k.SetLongTermOrderPlacement(ctx, order, lib.MustConvertIntegerToUint32(ctx.BlockHeight()))
k.MustAddOrderToStatefulOrdersTimeSlice(
ctx,
order.MustGetUnixGoodTilBlockTime(),
order.GetOrderId(),
)
} else {
// Write the stateful order to a transient store. PerformStatefulOrderValidation will ensure that the order does
// not exist which will prevent MustAddUncommittedStatefulOrderPlacement from panicking.
k.MustAddUncommittedStatefulOrderPlacement(ctx, msg)
// TODO(DEC-1238): Support stateful order replacements by removing the uncommitted order cancellation.
// This should allow a cycle of place + cancel + place + cancel + ... which we currently disallow during
// `DeliverTx`.
}
return nil
}
// ReplayPlaceOrder returns the result of calling `PlaceOrder` on the memclob.
// This method does not forward events directly to indexer, but instead returns
// them in the form of `OffchainUpdates`. This method is meant to be used in the
// `ReplayOperations` flow, where we replay Short-Term and newly-played stateful
// orders back onto the memclob.
//
// An error will be returned if any of the following conditions are true:
// - Standard stateful validation fails.
// - The memclob itself returns an error.
func (k Keeper) ReplayPlaceOrder(
ctx sdk.Context,
msg *types.MsgPlaceOrder,
) (
orderSizeOptimisticallyFilledFromMatchingQuantums satypes.BaseQuantums,
orderStatus types.OrderStatus,
offchainUpdates *types.OffchainUpdates,
err error,
) {
order := msg.GetOrder()
// Use the height of the next block. Check if this order would be valid if it were included
// in the next block height, not in the block that was already committed.
nextBlockHeight := lib.MustConvertIntegerToUint32(ctx.BlockHeight() + 1)
// Perform stateful validation.
err = k.PerformStatefulOrderValidation(ctx, &order, nextBlockHeight, true)
if err != nil {
return 0, 0, nil, err
}
// Place the order on the memclob and return the result.
orderSizeOptimisticallyFilledFromMatchingQuantums, orderStatus, offchainUpdates, err = k.MemClob.PlaceOrder(
ctx,
msg.Order,
)
return orderSizeOptimisticallyFilledFromMatchingQuantums, orderStatus, offchainUpdates, err
}
// AddPreexistingStatefulOrder performs stateful validation on an order and adds it to the specified memclob.
// This function does not add the order into state, since it is assumed to be preexisting. Function panics
// if the specified order is not stateful.
func (k Keeper) AddPreexistingStatefulOrder(
ctx sdk.Context,
order *types.Order,
memclob types.MemClob,
) (
orderSizeOptimisticallyFilledFromMatchingQuantums satypes.BaseQuantums,
orderStatus types.OrderStatus,
offchainUpdates *types.OffchainUpdates,
err error,
) {
order.MustBeStatefulOrder()
// Perform stateful validation without checking existing order in state.
// Block height is not used when validating stateful orders, so always pass in zero.
err = k.PerformStatefulOrderValidation(ctx, order, 0, true)
if err != nil {
return 0, 0, nil, err
}
// Place the order on the memclob and return the result. Note that we shouldn't perform
// the add-to-orderbook collateralization check here for long-term orders since it was performed in a prior block,
// but for triggered conditional orders we have not yet performed the collaterlization check.
return memclob.PlaceOrder(
ctx,
*order,
)
}
// PlaceStatefulOrdersFromLastBlock validates and places stateful orders from the last block onto the memclob.
// Note that stateful orders could fail to be placed due to various reasons such as collateralization
// check failures, self-trade errors, etc. In these cases the `checkState` will not be written to.
// This function is used in:
// 1. `PrepareCheckState` to place newly placed long term orders from the last
// block from ProcessProposerMatchesEvents.PlacedStatefulOrderIds. This is step 3 in PrepareCheckState.
// 2. `PlaceConditionalOrdersTriggeredInLastBlock` to place conditional orders triggered in the last block
// from ProcessProposerMatchesEvents.ConditionalOrderIdsTriggeredInLastBlock. This is step 4 in PrepareCheckState.
func (k Keeper) PlaceStatefulOrdersFromLastBlock(
ctx sdk.Context,
placedStatefulOrderIds []types.OrderId,
existingOffchainUpdates *types.OffchainUpdates,
) (
offchainUpdates *types.OffchainUpdates,
) {
lib.AssertCheckTxMode(ctx)
for _, orderId := range placedStatefulOrderIds {
orderId.MustBeStatefulOrder()
orderPlacement, exists := k.GetLongTermOrderPlacement(ctx, orderId)
if !exists {
// Error log if this is a conditional orders and it doesn't exist in triggered state, since it
// can't have been canceled.
if orderId.IsConditionalOrder() {
k.Logger(ctx).Error(
fmt.Sprintf(
"PlaceStatefulOrdersFromLastBlock: Triggered conditional Order ID %+v doesn't exist in state",
orderId,
),
)
}
// Order does not exist in state and therefore should not be placed. This likely
// indicates that the order was cancelled.
continue
}
order := orderPlacement.GetOrder()
// Validate and place order.
_, orderStatus, placeOrderOffchainUpdates, err := k.AddPreexistingStatefulOrder(
ctx,
&order,
k.MemClob,
)
if err != nil {
k.Logger(ctx).Debug(
fmt.Sprintf(
"MustPlaceStatefulOrdersFromLastBlock: PlaceOrder() returned an error %+v for order %+v",
err,
order,
),
)
// Note: Currently, the error returned from placing the order determines whether an order
// removal message is sent to the Indexer. This may change later on to be a check on whether
// the order has an existing nonce.
if k.indexerEventManager.Enabled() && off_chain_updates.ShouldSendOrderRemovalOnReplay(err) {
// If the stateful order is dropped while adding it to the book, return an off-chain order remove
// message for the order. It's possible that this validator already knows about this order, in which
// case an `ErrInvalidReplacement` error would be returned here.
// It's possible that this is a new stateful order that this validator has never learned about,
// but the validator failed to place on it on the book, even though it does exist in state.
// In this case, Indexer could be learning of this order for the first
// time with this removal.
if message, success := off_chain_updates.CreateOrderRemoveMessageWithDefaultReason(
k.Logger(ctx),
order.OrderId,
orderStatus,
err,
off_chain_updates.OrderRemoveV1_ORDER_REMOVAL_STATUS_BEST_EFFORT_CANCELED,
indexershared.OrderRemovalReason_ORDER_REMOVAL_REASON_INTERNAL_ERROR,
); success {
existingOffchainUpdates.AddRemoveMessage(order.OrderId, message)
}
}
} else if k.indexerEventManager.Enabled() {
existingOffchainUpdates.Append(placeOrderOffchainUpdates)
}
}
// Clear place messages as BEST_EFFORT_OPEN messages should not be
// sent for stateful order placements.
existingOffchainUpdates.CondenseMessagesForReplay()
return existingOffchainUpdates
}
// PlaceConditionalOrdersTriggeredInLastBlock takes in a list of conditional order ids that were triggered
// in the last block, verifies they are conditional orders, verifies they are in triggered state, and places
// the orders on the memclob.
func (k Keeper) PlaceConditionalOrdersTriggeredInLastBlock(
ctx sdk.Context,
conditionalOrderIdsTriggeredInLastBlock []types.OrderId,
existingOffchainUpdates *types.OffchainUpdates,
) (
offchainUpdates *types.OffchainUpdates,
) {
defer telemetry.MeasureSince(
time.Now(),
types.ModuleName,
metrics.PlaceConditionalOrdersFromLastBlock,
metrics.Latency,
)
telemetry.SetGauge(
float32(len(conditionalOrderIdsTriggeredInLastBlock)),
types.ModuleName,
metrics.PlaceConditionalOrdersFromLastBlock,
metrics.Count,
)
for _, orderId := range conditionalOrderIdsTriggeredInLastBlock {
// Panic if the order is not in triggered state.
if !k.IsConditionalOrderTriggered(ctx, orderId) {
panic(
fmt.Sprintf(
"PlaceConditionalOrdersTriggeredInLastBlock: Order with OrderId %+v is not in triggered state",
orderId,
),
)
}
}
return k.PlaceStatefulOrdersFromLastBlock(ctx, conditionalOrderIdsTriggeredInLastBlock, existingOffchainUpdates)
}
// PerformOrderCancellationStatefulValidation performs stateful validation on an order cancellation.
// The order cancellation can be either stateful or short term. This validation performs state reads.
//
// This validation ensures:
// - Stateful Order Cancellation for the order does not already exist in uncommitted state.
// - Stateful Order Cancellation cancels an uncommitted or existing stateful order.
// - Stateful Order Cancellation GTBT is greater than or equal to than stateful order GTBT.
// - Stateful Order Cancellation GTBT is greater than the block time of previous block.
// - Stateful Order Cancellation GTBT is less than or equal to `StatefulOrderTimeWindow` away from block time of
// previous block.
// - Short term Order Cancellation GTB must be greater than or equal to blockHeight
// - Short term Order Cancellation GTB is less than or equal to ShortBlockWindow block hight in the future.
func (k Keeper) PerformOrderCancellationStatefulValidation(
ctx sdk.Context,
msgCancelOrder *types.MsgCancelOrder,
blockHeight uint32,
) error {
orderIdToCancel := msgCancelOrder.GetOrderId()
if orderIdToCancel.IsStatefulOrder() {
previousBlockInfo := k.blockTimeKeeper.GetPreviousBlockInfo(ctx)
prevBlockHeight := previousBlockInfo.Height
currBlockHeight := uint32(ctx.BlockHeight())
if lib.IsDeliverTxMode(ctx) && prevBlockHeight != currBlockHeight-1 {
k.Logger(ctx).Error(
"PerformOrderCancellationStatefulValidation: prev block height is not one below"+
"current block height in DeliverTx",
"previousBlockHeight", prevBlockHeight,
"currentBlockHeight", currBlockHeight,
"msgCancelOrder", msgCancelOrder,
)
}
// CheckTx or ReCheckTx
if !lib.IsDeliverTxMode(ctx) && currBlockHeight > 1 && prevBlockHeight != currBlockHeight {
k.Logger(ctx).Error(
"PerformOrderCancellationStatefulValidation: prev block height is not equal to current block height"+
metrics.Callback, metrics.GetCallbackMetricFromCtx(ctx),
"previousBlockHeight", prevBlockHeight,
"currentBlockHeight", currBlockHeight,
"msgCancelOrder", msgCancelOrder,
)
}
cancelGoodTilBlockTime := msgCancelOrder.GetGoodTilBlockTime()
// Return an error if `goodTilBlockTime` is less than previous block's blockTime
if cancelGoodTilBlockTime <= lib.MustConvertIntegerToUint32(previousBlockInfo.Timestamp.Unix()) {
return types.ErrTimeExceedsGoodTilBlockTime
}
// Return an error if `goodTilBlockTime` is further into the future
// than the previous block time plus `StatefulOrderTimeWindow`.
endTime := previousBlockInfo.Timestamp.Add(types.StatefulOrderTimeWindow)
if cancelGoodTilBlockTime > lib.MustConvertIntegerToUint32(endTime.Unix()) {
return errorsmod.Wrapf(
types.ErrGoodTilBlockTimeExceedsStatefulOrderTimeWindow,
"GoodTilBlockTime %v exceeds the previous blockTime plus StatefulOrderTimeWindow %v. MsgCancelOrder: %+v",
cancelGoodTilBlockTime,
endTime,
msgCancelOrder,
)
}
// Return an error if we are attempting to submit another cancellation when the mempool already has an
// existing uncommitted cancellation for this order ID.
existingCancellation, uncommittedCancelExists := k.GetUncommittedStatefulOrderCancellation(ctx, orderIdToCancel)
if uncommittedCancelExists {
return errorsmod.Wrapf(
types.ErrStatefulOrderCancellationAlreadyExists,
"An uncommitted stateful order cancellation with this OrderId already exists and stateful "+
"order cancellation replacement is not supported. Existing order cancellation GoodTilBlockTime "+
"(%v), New order cancellation GoodTilBlockTime (%v). Existing order cancellation: (%+v). New "+
"order cancellation: (%+v).",
existingCancellation.GetGoodTilBlockTime(),
cancelGoodTilBlockTime,
existingCancellation,
msgCancelOrder,
)
}
// Fetch the highest priority order we are trying to cancel from state.
statefulOrderPlacement, orderToCancelExists := k.GetLongTermOrderPlacement(ctx, orderIdToCancel)
// The order we are cancelling must exist in uncommitted or committed state.
if !orderToCancelExists {
statefulOrderPlacement, orderToCancelExists = k.GetUncommittedStatefulOrderPlacement(ctx, orderIdToCancel)
if !orderToCancelExists {
return errorsmod.Wrapf(
types.ErrStatefulOrderDoesNotExist,
"Order Id to cancel does not exist. OrderId : %+v",
orderIdToCancel,
)
}
}
// Highest priority stateful matching order to cancel.
existingStatefulOrder := statefulOrderPlacement.Order
// Return an error if cancellation's GTBT is less than stateful order's GTBT.
if cancelGoodTilBlockTime < existingStatefulOrder.GetGoodTilBlockTime() {
return errorsmod.Wrapf(
types.ErrInvalidStatefulOrderCancellation,
"cancellation goodTilBlockTime less than stateful order goodTilBlockTime."+
" cancellation %+v, order %+v",
msgCancelOrder,
statefulOrderPlacement,
)
}
} else {
if err := k.validateGoodTilBlock(msgCancelOrder.GetGoodTilBlock(), blockHeight); err != nil {
return err
}
}
return nil
}
// validateGoodTilBlock validates that the good til block (GTB) is within valid bounds, specifically
// blockHeight <= GTB <= blockHeight + ShortBlockWindow.
func (k Keeper) validateGoodTilBlock(goodTilBlock uint32, blockHeight uint32) error {
// Return an error if `goodTilBlock` is in the past.
if goodTilBlock < blockHeight {
return errorsmod.Wrapf(
types.ErrHeightExceedsGoodTilBlock,
"GoodTilBlock %v is less than the current blockHeight %v",
goodTilBlock,
blockHeight,
)
}
// Return an error if `goodTilBlock` is further into the future than `ShortBlockWindow`.
if goodTilBlock > types.ShortBlockWindow+blockHeight {
return errorsmod.Wrapf(
types.ErrGoodTilBlockExceedsShortBlockWindow,
"The GoodTilBlock %v exceeds the current blockHeight %v plus ShortBlockWindow %v",
goodTilBlock,
blockHeight,
types.ShortBlockWindow,
)
}
return nil
}
// PerformStatefulOrderValidation performs stateful validation on an order. This validation performs
// state reads.
//
// This validation ensures:
// - The `ClobPairId` on the order is for a valid CLOB.
// - The `Subticks` of the order is a multiple of the ClobPair's `SubticksPerTick`.
// - The `Quantums` of the order is a multiple of the ClobPair's `StepBaseQuantums`.
//
// This validation also ensures that the order is valid for the ClobPair's status.
//
// For short term orders it also ensures:
// - The `GoodTilBlock` of the order is greater than the provided `blockHeight`.
// - The `GoodTilBlock` of the order does not exceed the provided `blockHeight + ShortBlockWindow`.
//
// For stateful orders it also ensures:
// - GTBT is greater than the block time of previous block.
// - GTBT is less than or equal to `StatefulOrderTimeWindow` away from block time of
// previous block.
// - That there isn't an order cancellation in uncommitted state.
// - That the order does not already exist in uncommitted state unless `isPreexistingStatefulOrder` is true.
// - That the order does not already exist in committed state unless `isPreexistingStatefulOrder` is true.
func (k Keeper) PerformStatefulOrderValidation(
ctx sdk.Context,
order *types.Order,
blockHeight uint32,
isPreexistingStatefulOrder bool,
) error {
defer telemetry.ModuleMeasureSince(
types.ModuleName,
time.Now(),
metrics.PlaceOrder,
metrics.ValidateOrder,
metrics.Latency,
)
clobPair, found := k.GetClobPair(ctx, order.GetClobPairId())
if !found {
return errorsmod.Wrapf(
types.ErrInvalidClob,
"Clob %v is not a valid clob",
order.GetClobPairId(),
)
}
if order.Subticks%uint64(clobPair.SubticksPerTick) != 0 {
return errorsmod.Wrapf(
types.ErrInvalidPlaceOrder,
"Order subticks %v must be a multiple of the ClobPair's SubticksPerTick %v",
order.Subticks,
clobPair.SubticksPerTick,
)
}
if order.Quantums%clobPair.StepBaseQuantums != 0 {
return errorsmod.Wrapf(
types.ErrInvalidPlaceOrder,
"Order Quantums %v must be a multiple of the ClobPair's StepBaseQuantums %v",
order.Quantums,
clobPair.StepBaseQuantums,
)
}
// Validates the order against the ClobPair's status.
if err := k.validateOrderAgainstClobPairStatus(ctx, order.MustGetOrder(), clobPair); err != nil {
telemetry.IncrCounterWithLabels(
[]string{types.ModuleName, metrics.ValidateOrder, metrics.OrderConflictsWithClobPairStatus, metrics.Count},
1,
append(
order.GetOrderLabels(),
metrics.GetLabelForBoolValue(metrics.CheckTx, ctx.IsCheckTx()),
metrics.GetLabelForBoolValue(metrics.DeliverTx, lib.IsDeliverTxMode(ctx)),
),
)
return err
}
if order.OrderId.IsShortTermOrder() {
if err := k.validateGoodTilBlock(order.GetGoodTilBlock(), blockHeight); err != nil {
return err
}
} else {
goodTilBlockTimeUnix := order.GetGoodTilBlockTime()
previousBlockTime := k.blockTimeKeeper.GetPreviousBlockInfo(ctx).Timestamp
previousBlockTimeUnix := lib.MustConvertIntegerToUint32(previousBlockTime.Unix())
// Return an error if `goodTilBlockTime` is less than or equal to the
// block time of the previous block.
if goodTilBlockTimeUnix <= previousBlockTimeUnix {
return errorsmod.Wrapf(
types.ErrTimeExceedsGoodTilBlockTime,
"GoodTilBlockTime %v is less than the previous blockTime %v",
goodTilBlockTimeUnix,
previousBlockTimeUnix,
)
}
// Return an error if `goodTilBlockTime` is further into the future
// than the previous block time plus `StatefulOrderTimeWindow`.
endTimeUnix := lib.MustConvertIntegerToUint32(
previousBlockTime.Add(types.StatefulOrderTimeWindow).Unix(),
)
if goodTilBlockTimeUnix > endTimeUnix {
return errorsmod.Wrapf(
types.ErrGoodTilBlockTimeExceedsStatefulOrderTimeWindow,
"GoodTilBlockTime %v exceeds the previous blockTime plus StatefulOrderTimeWindow %v",
goodTilBlockTimeUnix,
endTimeUnix,
)
}
// Check to see if we are aware of a cancellation that is part of the mempool and has yet to be included
// in a block for the order in state.
// TODO(DEC-1238): Support stateful order replacements.
if uncommittedCancel, uncommittedCancelExists := k.GetUncommittedStatefulOrderCancellation(
ctx, order.OrderId); uncommittedCancelExists {
return errorsmod.Wrapf(
types.ErrStatefulOrderPreviouslyCancelled,
"An uncommitted stateful order cancellation with this OrderId already exists. "+
"Existing order cancellation: (%+v). New order: (%+v).",
uncommittedCancel,
order,
)
}
// If this is not pre-existing stateful order, then we expect it does not exist in uncommitted state.
// TODO(DEC-1238): Support stateful order replacements.
statefulOrderPlacement, found := k.GetUncommittedStatefulOrderPlacement(ctx, order.OrderId)
if !isPreexistingStatefulOrder && found {
existingOrder := statefulOrderPlacement.GetOrder()
return errorsmod.Wrapf(
types.ErrStatefulOrderAlreadyExists,
"An uncommitted stateful order with this OrderId already exists and stateful order replacement is not supported. "+
"Existing order GoodTilBlockTime (%v), New order GoodTilBlockTime (%v). "+
"Existing order: (%+v). New order: (%+v).",
existingOrder.GetGoodTilBlockTime(),
goodTilBlockTimeUnix,
existingOrder,
order,
)
}
// If the stateful order already exists in state, validate
// that the new stateful order has a higher priority than the existing order.
statefulOrderPlacement, found = k.GetLongTermOrderPlacement(ctx, order.OrderId)
// If this is a pre-existing stateful order, then we expect it to exist in state.
// Panic if the order is not in state, as this indicates an application error.
if isPreexistingStatefulOrder && !found {
panic(
fmt.Sprintf(
"PerformStatefulOrderValidation: Expected pre-existing stateful order to exist in state "+
"order: (%+v).",
order,
),
)
}
// If this is not pre-existing stateful order, then we expect it does not exist in state.
// TODO(DEC-1238): Support stateful order replacements.
if !isPreexistingStatefulOrder && found {
existingOrder := statefulOrderPlacement.GetOrder()
return errorsmod.Wrapf(
types.ErrStatefulOrderAlreadyExists,
"A stateful order with this OrderId already exists and stateful order replacement is not supported. "+
"Existing order GoodTilBlockTime (%v), New order GoodTilBlockTime (%v). "+
"Existing order: (%+v). New order: (%+v).",
existingOrder.GetGoodTilBlockTime(),
goodTilBlockTimeUnix,
existingOrder,
order,
)
}
if order.IsConditionalOrder() {
if order.ConditionalOrderTriggerSubticks%uint64(clobPair.SubticksPerTick) != 0 {
return errorsmod.Wrapf(
types.ErrInvalidPlaceOrder,
"Conditional order trigger subticks %v must be a multiple of the ClobPair's SubticksPerTick %v",
order.ConditionalOrderTriggerSubticks,
clobPair.StepBaseQuantums,
)
}
}
}
return nil
}
// MustValidateReduceOnlyOrder makes sure the given reduce-only
// order is valid with respect to the current position size.
// Specifically, this function validates:
// - The reduce-only order is on the opposite side of the existing position.
// - The reduce-only order does not change the subaccount's position side.
func (k Keeper) MustValidateReduceOnlyOrder(
ctx sdk.Context,
order types.MatchableOrder,
matchedAmount uint64,
) error {
if !order.IsReduceOnly() {
panic("Order is not reduce-only.")
}
// Get the current position size from state.
currentPositionSize := k.GetStatePosition(
ctx,
order.GetSubaccountId(),
order.GetClobPairId(),
)
// Validate that the reduce-only order is on the opposite side of the existing position.
if order.IsBuy() {
if currentPositionSize.Sign() != -1 {
return errorsmod.Wrapf(
types.ErrReduceOnlyWouldIncreasePositionSize,
"Reduce-only order failed validation while matching. Order: (%+v), position-size: (%+v)",
order,
currentPositionSize,
)
}
} else {
if currentPositionSize.Sign() != 1 {
return errorsmod.Wrapf(
types.ErrReduceOnlyWouldIncreasePositionSize,
"Reduce-only order failed validation while matching. Order: (%+v), position-size: (%+v)",
order,
currentPositionSize,
)
}
}
// Validate that the reduce-only order does not change the subaccount's position side.
bigMatchedAmount := new(big.Int).SetUint64(matchedAmount)
if bigMatchedAmount.CmpAbs(currentPositionSize) == 1 {
return errorsmod.Wrapf(
types.ErrReduceOnlyWouldChangePositionSide,
"Current position size: %v, reduce-only order fill amount: %v",
currentPositionSize,
bigMatchedAmount,
)
}
return nil
}
// AddOrderToOrderbookCollatCheck performs collateralization checks for orders to determine whether or not they may
// be added to the orderbook.
func (k Keeper) AddOrderToOrderbookCollatCheck(
ctx sdk.Context,
clobPairId types.ClobPairId,
// TODO(DEC-1713): Convert this to 2 parameters: SubaccountId and a slice of PendingOpenOrders.
subaccountOpenOrders map[satypes.SubaccountId][]types.PendingOpenOrder,
) (
success bool,
successPerUpdate map[satypes.SubaccountId]satypes.UpdateResult,
) {
defer telemetry.ModuleMeasureSince(
types.ModuleName,
time.Now(),
metrics.CollateralizationCheck,
metrics.Latency,
)
telemetry.SetGauge(
float32(len(subaccountOpenOrders)),
types.ModuleName,
metrics.CollateralizationCheckSubaccounts,
metrics.Count,
)
clobPair, found := k.GetClobPair(ctx, clobPairId)
if !found {
panic(types.ErrInvalidClob)
}
pendingUpdates := types.NewPendingUpdates()
// Retrieve the associated `PerpetualId` for the `ClobPair`.
oraclePriceSubticksRat := k.GetOraclePriceSubticksRat(ctx, clobPair)
perpetualId := clobPair.MustGetPerpetualId()
// TODO(DEC-1713): Complete as many calculations from getPessimisticCollateralCheckPrice as possible here
// so we aren't recalculating the same thing within the loop.
iterateOverOpenOrdersStart := time.Now()
for subaccountId, openOrders := range subaccountOpenOrders {
telemetry.SetGauge(
float32(len(openOrders)),
types.ModuleName,
metrics.SubaccountPendingMatches,
metrics.Count,
)
makerFeePpm := k.feeTiersKeeper.GetPerpetualFeePpm(ctx, subaccountId.Owner, false)
// For each subaccount ID, create the update from all of its existing open orders for the clob and side.
for _, openOrder := range openOrders {
if openOrder.ClobPairId != clobPairId {
panic(fmt.Sprintf("Order `ClobPairId` must equal `clobPairId` for order %+v", openOrder))
}
// We don't want to allow users to place orders to improve their collateralization, so we choose between the
// order price (user-input) or the oracle price (sane default) and select the price that results in the
// most pessimistic collateral-check outcome.
collatCheckPriceSubticks, err := getPessimisticCollateralCheckPrice(
oraclePriceSubticksRat,
openOrder.Subticks,
openOrder.IsBuy,
)
if satypes.ErrIntegerOverflow.Is(err) {
// TODO(DEC-1701): Determine best action to take if the oracle price overflows max uint64
k.Logger(ctx).Error(
fmt.Sprintf(
"Integer overflow: oracle price (subticks) exceeded uint64 max. "+
"perpetual ID = (%d), oracle price = (%+v), is buy = (%t)",
perpetualId,