-
Notifications
You must be signed in to change notification settings - Fork 99
/
message_proposed_operations.go
373 lines (332 loc) · 12 KB
/
message_proposed_operations.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
package types
import (
fmt "fmt"
"math/big"
errorsmod "cosmossdk.io/errors"
sdk "github.com/cosmos/cosmos-sdk/types"
)
const TypeMsgProposedOperations = "proposed_operations"
var _ sdk.Msg = &MsgProposedOperations{}
func (msg *MsgProposedOperations) GetSigners() []sdk.AccAddress {
// Return empty slice because app-injected msg is not expected to be signed.
return []sdk.AccAddress{}
}
// Stateless validation for MsgProposedOperations is located in ValidateAndTransformRawOperations.
func (msg *MsgProposedOperations) ValidateBasic() error {
// Go through the operations one by one to validate them, updating state as necessary.
for _, rawOperation := range msg.GetOperationsQueue() {
switch operation := rawOperation.Operation.(type) {
case
*OperationRaw_Match,
*OperationRaw_ShortTermOrderPlacement:
// no-op, stateless validation is done in ValidateAndTransformRawOperations
case *OperationRaw_OrderRemoval:
orderId := operation.OrderRemoval.GetOrderId()
if orderId.IsShortTermOrder() {
return errorsmod.Wrapf(
ErrInvalidMsgProposedOperations,
"order removal is not allowed for short-term orders: %v",
orderId,
)
}
switch operation.OrderRemoval.RemovalReason {
case OrderRemoval_REMOVAL_REASON_UNSPECIFIED:
return errorsmod.Wrapf(
ErrInvalidMsgProposedOperations,
"order removal reason must be specified: %v",
orderId,
)
case OrderRemoval_REMOVAL_REASON_INVALID_REDUCE_ONLY:
// TODO: remove this case when reduce-only orders are enabled.
return errorsmod.Wrapf(
ErrInvalidMsgProposedOperations,
"order removals for invalid reduce-only orders are not allowed. Reduce-only orders"+
" are not currently supported.",
)
}
default:
return errorsmod.Wrapf(
ErrInvalidMsgProposedOperations,
"operation queue type not implemented yet for raw operation %v",
rawOperation,
)
}
}
return nil
}
// ValidateAndTransformRawOperations performs stateless validation on the proposed operation queue
// and transforms the input []OperationRaw into []InternalOperation.
// Validations differ based on operation types. We are able to supply a TxDecoder and AnteHandler
// to this function. These are needed to decode OperationRaw tx bytes and to validate that
// the operations' transactions were signed correctly.
func ValidateAndTransformRawOperations(
ctx sdk.Context,
rawOperations []OperationRaw,
decoder sdk.TxDecoder,
anteHandler sdk.AnteHandler,
) ([]InternalOperation, error) {
operations := make([]InternalOperation, 0, len(rawOperations))
validator := operationsQueueValidator{
ordersPlacedInBlock: make(map[OrderId]Order, 0),
}
// Go through the operations one by one to validate them, updating state as necessary.
for _, rawOperation := range rawOperations {
var err error
operation := &InternalOperation{}
switch rawOperation.Operation.(type) {
case *OperationRaw_Match:
match := rawOperation.GetMatch()
if err = validator.validateMatchOperation(match); err != nil {
return nil, err
}
operation.Operation = &InternalOperation_Match{
Match: match,
}
case *OperationRaw_ShortTermOrderPlacement:
operation, err = decodeOperationRawShortTermOrderPlacementBytes(
ctx,
rawOperation.GetShortTermOrderPlacement(),
decoder,
anteHandler,
)
if err != nil {
return nil, err
}
if err = validator.validateShortTermOrderPlacementOperation(
operation.GetShortTermOrderPlacement(),
); err != nil {
return nil, err
}
case *OperationRaw_OrderRemoval:
orderRemoval := rawOperation.GetOrderRemoval()
if err := orderRemoval.OrderId.Validate(); err != nil {
return nil, err
}
if orderRemoval.RemovalReason == OrderRemoval_REMOVAL_REASON_UNSPECIFIED {
return nil, errorsmod.Wrapf(
ErrInvalidOrderRemoval,
"Invalid order removal reason: %+v",
orderRemoval.RemovalReason,
)
}
operation.Operation = &InternalOperation_OrderRemoval{
OrderRemoval: rawOperation.GetOrderRemoval(),
}
default:
return nil, fmt.Errorf("operation queue type not implemented yet for raw operation %v", rawOperation)
}
operations = append(operations, *operation)
}
return operations, nil
}
// operationsQueueValidator encapsulates all the previous context we need to validate sequential
// operations in the operations queue since the order of operations matters.
type operationsQueueValidator struct {
// All the previous orders placed in this block (short and long term).
// This field is used when ensuring short term OrderIds references an order in the last block.
// ordersPlacedInBlock stores the most recently placed order.
// It tracks orders placed via `OrderPlacement` operations.
ordersPlacedInBlock map[OrderId]Order
}
// validateMatchOperation unwraps the match message and performs validation for each match type.
func (validator *operationsQueueValidator) validateMatchOperation(match *ClobMatch) error {
switch match.Match.(type) {
case *ClobMatch_MatchOrders:
matchOrders := match.GetMatchOrders()
if err := validator.validateMatchOrdersOperation(matchOrders); err != nil {
return err
}
case *ClobMatch_MatchPerpetualLiquidation:
matchPerpetualLiquidation := match.GetMatchPerpetualLiquidation()
if err := validator.validateMatchPerpetualLiquidationOperation(matchPerpetualLiquidation); err != nil {
return err
}
case *ClobMatch_MatchPerpetualDeleveraging:
matchPerpetualDeleveraging := match.GetMatchPerpetualDeleveraging()
if err := matchPerpetualDeleveraging.Validate(); err != nil {
return errorsmod.Wrapf(
err,
"match: %+v",
matchPerpetualDeleveraging,
)
}
default:
panic("Unsupported Clob Match type")
}
return nil
}
// validateShortTermOrderPlacementOperation performs stateless validation on an order placement.
// It also populates the validator object with the order.
// This validation does not perform any state reads, or memclob reads.
//
// The following validation occurs in this method:
//
// - ValidateBasic for OrderPlacement message
// - Orders placed in the same block with same OrderId must not be the same.
func (validator *operationsQueueValidator) validateShortTermOrderPlacementOperation(
orderPlacement *MsgPlaceOrder,
) error {
// Order placement msg has to pass its own validation.
if err := orderPlacement.ValidateBasic(); err != nil {
return err
}
order := orderPlacement.GetOrder()
orderId := order.GetOrderId()
// For orders with the same orderId placed within this block, verify replacement order priority.
if prevOrder, placedPreviously := validator.ordersPlacedInBlock[orderId]; placedPreviously {
// No duplicate order placements allowed.
if prevOrder.MustCmpReplacementOrder(&order) == 0 {
return errorsmod.Wrapf(
ErrInvalidPlaceOrder,
"Duplicate Order %s",
order.GetOrderTextString(),
)
}
// Replacement Orders have a higher priority than the previously placed order that it replaces.
// All short term replacement orders should be checked here. Note that for long term orders,
// this check only takes effect if the order being replaced is in the same block.
if prevOrder.MustCmpReplacementOrder(&order) != -1 {
return errorsmod.Wrapf(
ErrInvalidReplacement,
"Replacement order is not higher priority. order: %s, prevOrder: %s",
order.GetOrderTextString(),
prevOrder.GetOrderTextString(),
)
}
}
// Record the placed order in validator.
validator.ordersPlacedInBlock[orderId] = order
return nil
}
// validateMatchOrdersOperation performs stateless validation on an match orders.
// This validation does not perform any state reads, or memclob reads.
//
// The following validation occurs in this method:
// - Match has at least one fill.
// - For all fills, The fill amount is not zero.
// - For all fills, maker order ids must be previously placed in an operation.
// - Taker order id must be previously placed in an operation.
// - There are no duplicate MakerOrderIds in fills.
func (validator *operationsQueueValidator) validateMatchOrdersOperation(
matchOrders *MatchOrders,
) error {
fills := matchOrders.GetFills()
if len(fills) == 0 {
return errorsmod.Wrapf(
ErrInvalidMatchOrder,
"Match has no fills: %+v",
matchOrders,
)
}
makerOrderIdSet := make(map[OrderId]struct{}, len(fills))
takerOrderId := matchOrders.GetTakerOrderId()
for _, fill := range fills {
// Fill amount must be greater than zero.
if fill.GetFillAmount() == 0 {
return ErrFillAmountIsZero
}
makerOrderId := fill.GetMakerOrderId()
if err := makerOrderId.Validate(); err != nil {
return err
}
// No duplicate maker order IDs in fills.
if _, exists := makerOrderIdSet[makerOrderId]; exists {
return errorsmod.Wrapf(
ErrInvalidMatchOrder,
"duplicate Maker OrderId in a MatchOrder's fills, maker: %+v, taker %+v",
makerOrderId,
takerOrderId,
)
}
// Maker order id must be previously placed in an operation.
if err := validator.verifyOrderPlacementInOperationsQueue(
makerOrderId,
); err != nil {
return err
}
makerOrderIdSet[makerOrderId] = struct{}{}
}
if err := takerOrderId.Validate(); err != nil {
return err
}
// Taker order id must be previously placed in an operation.
if err := validator.verifyOrderPlacementInOperationsQueue(takerOrderId); err != nil {
return err
}
return nil
}
// validateMatchPerpetualLiquidationOperation performs stateless validation on a liquidation match.
// This validation does not perform any state reads, or memclob reads.
//
// The following validation occurs in this method:
// - The total size of liquidation order is not zero.
// - FillAmounts is not zero.
// - Liquidation match has at least one fill.
// - For all fills, maker order ids must be previously placed in an operation.
// - The sum of all fill_amount entries in the list of fills is not greater than the total size.
func (validator *operationsQueueValidator) validateMatchPerpetualLiquidationOperation(
liquidationMatch *MatchPerpetualLiquidation,
) error {
fills := liquidationMatch.GetFills()
if len(fills) == 0 {
return errorsmod.Wrapf(
ErrInvalidMatchOrder,
"Liquidation match has no fills: %+v",
liquidationMatch,
)
}
// Make sure the total size greater than zero.
totalSize := liquidationMatch.GetTotalSize()
if totalSize == 0 {
return errorsmod.Wrapf(
ErrInvalidLiquidationOrderTotalSize,
"Liquidation match total size is zero. match: %+v",
liquidationMatch,
)
}
// Make sure the sum of all fill_amount entries in the list of fills does not exceed the total size.
// Get the total quantums filled for this liquidation order.
bigQuantumsFilled := new(big.Int)
for _, fill := range fills {
fillAmt := fill.GetFillAmount()
// Fill amount cannot be zero.
if fillAmt == 0 {
return ErrFillAmountIsZero
}
bigQuantumsFilled.Add(bigQuantumsFilled, new(big.Int).SetUint64(fill.FillAmount))
fillMakerOrderId := fill.GetMakerOrderId()
if err := fillMakerOrderId.Validate(); err != nil {
return err
}
// Maker order id must be previously placed in an operation.
if err := validator.verifyOrderPlacementInOperationsQueue(
fillMakerOrderId,
); err != nil {
return err
}
}
if err := liquidationMatch.Liquidated.Validate(); err != nil {
return err
}
if bigQuantumsFilled.Cmp(new(big.Int).SetUint64(totalSize)) == 1 {
return errorsmod.Wrapf(
ErrTotalFillAmountExceedsOrderSize,
"Total fill size: %v match total size: %v",
bigQuantumsFilled,
totalSize,
)
}
return nil
}
// verifyOrderPlacementInOperationsQueue is a pure function. For the referenced order, it checks:
// - If the order is a short-term order, that it is included in the operations queue for this block.
//
// If this condition isn't met, an `ErrOrderPlacementNotInOperationsQueue` is returned.
func (validator *operationsQueueValidator) verifyOrderPlacementInOperationsQueue(orderId OrderId) error {
if orderId.IsShortTermOrder() {
if _, prevPlaced := validator.ordersPlacedInBlock[orderId]; !prevPlaced {
return errorsmod.Wrapf(ErrOrderPlacementNotInOperationsQueue, "short term orderId: %v", orderId)
}
}
return nil
}