forked from dydxprotocol/solo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LimitOrders.sol
682 lines (596 loc) · 19 KB
/
LimitOrders.sol
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
/*
Copyright 2019 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.7;
pragma experimental ABIEncoderV2;
import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol";
import { Ownable } from "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import { IAutoTrader } from "../../protocol/interfaces/IAutoTrader.sol";
import { ICallee } from "../../protocol/interfaces/ICallee.sol";
import { Account } from "../../protocol/lib/Account.sol";
import { Math } from "../../protocol/lib/Math.sol";
import { Require } from "../../protocol/lib/Require.sol";
import { Types } from "../../protocol/lib/Types.sol";
import { OnlySolo } from "../helpers/OnlySolo.sol";
import { TypedSignature } from "../lib/TypedSignature.sol";
/**
* @title LimitOrders
* @author dYdX
*
* Allows for Limit Orders to be used with dYdX
*/
contract LimitOrders is
Ownable,
OnlySolo,
IAutoTrader,
ICallee
{
using Math for uint256;
using SafeMath for uint256;
using Types for Types.Par;
using Types for Types.Wei;
// ============ Constants ============
bytes32 constant private FILE = "LimitOrders";
// EIP191 header for EIP712 prefix
bytes2 constant private EIP191_HEADER = 0x1901;
// EIP712 Domain Name value
string constant private EIP712_DOMAIN_NAME = "LimitOrders";
// EIP712 Domain Version value
string constant private EIP712_DOMAIN_VERSION = "1.1";
// Hash of the EIP712 Domain Separator Schema
/* solium-disable-next-line indentation */
bytes32 constant private EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = keccak256(abi.encodePacked(
"EIP712Domain(",
"string name,",
"string version,",
"uint256 chainId,",
"address verifyingContract",
")"
));
// Hash of the EIP712 LimitOrder struct
/* solium-disable-next-line indentation */
bytes32 constant private EIP712_LIMIT_ORDER_STRUCT_SCHEMA_HASH = keccak256(abi.encodePacked(
"LimitOrder(",
"uint256 makerMarket,",
"uint256 takerMarket,",
"uint256 makerAmount,",
"uint256 takerAmount,",
"address makerAccountOwner,",
"uint256 makerAccountNumber,",
"address takerAccountOwner,",
"uint256 takerAccountNumber,",
"uint256 expiration,",
"uint256 salt",
")"
));
// Number of bytes in an Order struct
uint256 constant private NUM_ORDER_BYTES = 320;
// Number of bytes in a typed signature
uint256 constant private NUM_SIGNATURE_BYTES = 66;
// Number of bytes in a CallFunctionData struct
uint256 constant private NUM_CALLFUNCTIONDATA_BYTES = 32 + NUM_ORDER_BYTES;
// ============ Enums ============
enum OrderStatus {
Null,
Approved,
Canceled
}
enum CallFunctionType {
Approve,
Cancel
}
// ============ Structs ============
struct Order {
uint256 makerMarket;
uint256 takerMarket;
uint256 makerAmount;
uint256 takerAmount;
address makerAccountOwner;
uint256 makerAccountNumber;
address takerAccountOwner;
uint256 takerAccountNumber;
uint256 expiration;
uint256 salt;
}
struct OrderInfo {
Order order;
bytes32 orderHash;
}
struct CallFunctionData {
CallFunctionType callType;
Order order;
}
struct OrderQueryOutput {
OrderStatus orderStatus;
uint256 orderMakerFilledAmount;
}
// ============ Events ============
event ContractStatusSet(
bool operational
);
event LogLimitOrderCanceled(
bytes32 indexed orderHash,
address indexed canceler,
uint256 makerMarket,
uint256 takerMarket
);
event LogLimitOrderApproved(
bytes32 indexed orderHash,
address indexed approver,
uint256 makerMarket,
uint256 takerMarket
);
event LogLimitOrderFilled(
bytes32 indexed orderHash,
address indexed orderMaker,
uint256 makerFillAmount,
uint256 totalMakerFilledAmount
);
// ============ Immutable Storage ============
// Hash of the EIP712 Domain Separator data
bytes32 public EIP712_DOMAIN_HASH;
// ============ Mutable Storage ============
// true if this contract can process orders
bool public g_isOperational;
// order hash => filled amount (in makerAmount)
mapping (bytes32 => uint256) public g_makerFilledAmount;
// order hash => status
mapping (bytes32 => OrderStatus) public g_status;
// ============ Constructor ============
constructor (
address soloMargin,
uint256 chainId
)
public
OnlySolo(soloMargin)
{
g_isOperational = true;
/* solium-disable-next-line indentation */
EIP712_DOMAIN_HASH = keccak256(abi.encode(
EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH,
keccak256(bytes(EIP712_DOMAIN_NAME)),
keccak256(bytes(EIP712_DOMAIN_VERSION)),
chainId,
address(this)
));
}
// ============ Admin Functions ============
/**
* The owner can shut down the exchange.
*/
function shutDown()
external
onlyOwner
{
g_isOperational = false;
emit ContractStatusSet(false);
}
/**
* The owner can start back up the exchange.
*/
function startUp()
external
onlyOwner
{
g_isOperational = true;
emit ContractStatusSet(true);
}
// ============ External Functions ============
/**
* Cancels an order. Cannot already be canceled.
*
* @param order The order to cancel
*/
function cancelOrder(
Order memory order
)
public
{
cancelOrderInternal(msg.sender, order);
}
/**
* Approves an order. Cannot already be approved or canceled.
*
* @param order The order to approve
*/
function approveOrder(
Order memory order
)
public
{
approveOrderInternal(msg.sender, order);
}
// ============ Only-Solo Functions ============
/**
* Allows traders to make trades approved by this smart contract. The active trader's account is
* the takerAccount and the passive account (for which this contract approves trades
* on-behalf-of) is the makerAccount.
*
* @param inputMarketId The market for which the trader specified the original amount
* @param outputMarketId The market for which the trader wants the resulting amount specified
* @param makerAccount The account for which this contract is making trades
* @param takerAccount The account requesting the trade
* param oldInputPar (unused)
* param newInputPar (unused)
* @param inputWei The change in token amount for the makerAccount for the inputMarketId
* @param data Arbitrary data passed in by the trader
* @return The AssetAmount for the makerAccount for the outputMarketId
*/
function getTradeCost(
uint256 inputMarketId,
uint256 outputMarketId,
Account.Info memory makerAccount,
Account.Info memory takerAccount,
Types.Par memory /* oldInputPar */,
Types.Par memory /* newInputPar */,
Types.Wei memory inputWei,
bytes memory data
)
public
onlySolo(msg.sender)
returns (Types.AssetAmount memory)
{
Require.that(
g_isOperational,
FILE,
"Contract is not operational"
);
OrderInfo memory orderInfo = getOrderAndValidateSignature(data);
verifyOrderAndAccountsAndMarkets(
orderInfo,
makerAccount,
takerAccount,
inputMarketId,
outputMarketId,
inputWei
);
return getOutputAssetAmount(
inputMarketId,
outputMarketId,
inputWei,
orderInfo
);
}
/**
* Allows users to send this contract arbitrary data.
*
* param sender (unused)
* @param accountInfo The account from which the data is being sent
* @param data Arbitrary data given by the sender
*/
function callFunction(
address /* sender */,
Account.Info memory accountInfo,
bytes memory data
)
public
onlySolo(msg.sender)
{
Require.that(
data.length == NUM_CALLFUNCTIONDATA_BYTES,
FILE,
"Cannot parse CallFunctionData"
);
CallFunctionData memory cfd = abi.decode(data, (CallFunctionData));
if (cfd.callType == CallFunctionType.Approve) {
approveOrderInternal(accountInfo.owner, cfd.order);
} else {
assert(cfd.callType == CallFunctionType.Cancel);
cancelOrderInternal(accountInfo.owner, cfd.order);
}
}
// ============ Getters ============
/**
* Returns the status and the filled amount (in makerAmount) of several orders.
*/
function getOrderStates(
bytes32[] memory orderHashes
)
public
view
returns(OrderQueryOutput[] memory)
{
uint256 numOrders = orderHashes.length;
OrderQueryOutput[] memory output = new OrderQueryOutput[](numOrders);
// for each order
for (uint256 i = 0; i < numOrders; i++) {
bytes32 orderHash = orderHashes[i];
output[i] = OrderQueryOutput({
orderStatus: g_status[orderHash],
orderMakerFilledAmount: g_makerFilledAmount[orderHash]
});
}
return output;
}
// ============ Private Storage Functions ============
/**
* Cancels an order as long as it is not already canceled.
*/
function cancelOrderInternal(
address canceler,
Order memory order
)
private
{
Require.that(
canceler == order.makerAccountOwner,
FILE,
"Canceler must be maker"
);
bytes32 orderHash = getOrderHash(order);
g_status[orderHash] = OrderStatus.Canceled;
emit LogLimitOrderCanceled(
orderHash,
canceler,
order.makerMarket,
order.takerMarket
);
}
/**
* Approves an order as long as it is not already approved or canceled.
*/
function approveOrderInternal(
address approver,
Order memory order
)
private
{
Require.that(
approver == order.makerAccountOwner,
FILE,
"Approver must be maker"
);
bytes32 orderHash = getOrderHash(order);
Require.that(
g_status[orderHash] != OrderStatus.Canceled,
FILE,
"Cannot approve canceled order",
orderHash
);
g_status[orderHash] = OrderStatus.Approved;
emit LogLimitOrderApproved(
orderHash,
approver,
order.makerMarket,
order.takerMarket
);
}
// ============ Private Helper Functions ============
/**
* Verifies that the order is still fillable for the particular accounts and markets specified.
*/
function verifyOrderAndAccountsAndMarkets(
OrderInfo memory orderInfo,
Account.Info memory makerAccount,
Account.Info memory takerAccount,
uint256 inputMarketId,
uint256 outputMarketId,
Types.Wei memory inputWei
)
private
view
{
// verify expriy
Require.that(
orderInfo.order.expiration == 0 || orderInfo.order.expiration >= block.timestamp,
FILE,
"Order expired",
orderInfo.orderHash
);
// verify maker
Require.that(
makerAccount.owner == orderInfo.order.makerAccountOwner &&
makerAccount.number == orderInfo.order.makerAccountNumber,
FILE,
"Order maker account mismatch",
orderInfo.orderHash
);
// verify taker
Require.that(
(
orderInfo.order.takerAccountOwner == address(0) &&
orderInfo.order.takerAccountNumber == 0
) || (
orderInfo.order.takerAccountOwner == takerAccount.owner &&
orderInfo.order.takerAccountNumber == takerAccount.number
),
FILE,
"Order taker account mismatch",
orderInfo.orderHash
);
// verify markets
Require.that(
(
orderInfo.order.makerMarket == outputMarketId &&
orderInfo.order.takerMarket == inputMarketId
) || (
orderInfo.order.takerMarket == outputMarketId &&
orderInfo.order.makerMarket == inputMarketId
),
FILE,
"Market mismatch",
orderInfo.orderHash
);
// verify inputWei
Require.that(
!inputWei.isZero(),
FILE,
"InputWei is zero",
orderInfo.orderHash
);
Require.that(
inputWei.sign == (orderInfo.order.takerMarket == inputMarketId),
FILE,
"InputWei sign mismatch",
orderInfo.orderHash
);
}
/**
* Returns the AssetAmount for the outputMarketId given the order and the inputs. Updates the
* filled amount of the order in storage.
*/
function getOutputAssetAmount(
uint256 inputMarketId,
uint256 outputMarketId,
Types.Wei memory inputWei,
OrderInfo memory orderInfo
)
private
returns (Types.AssetAmount memory)
{
uint256 outputAmount;
uint256 makerFillAmount;
if (orderInfo.order.takerMarket == inputMarketId) {
outputAmount = inputWei.value.getPartial(
orderInfo.order.makerAmount,
orderInfo.order.takerAmount
);
makerFillAmount = outputAmount;
} else {
assert(orderInfo.order.takerMarket == outputMarketId);
outputAmount = inputWei.value.getPartialRoundUp(
orderInfo.order.takerAmount,
orderInfo.order.makerAmount
);
makerFillAmount = inputWei.value;
}
updateMakerFilledAmount(orderInfo, makerFillAmount);
return Types.AssetAmount({
sign: orderInfo.order.takerMarket == outputMarketId,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: outputAmount
});
}
/**
* Increases the stored filled amount (in makerAmount) of the order by makerFillAmount.
* Returns the new total filled amount (in makerAmount).
*/
function updateMakerFilledAmount(
OrderInfo memory orderInfo,
uint256 makerFillAmount
)
private
{
uint256 oldMakerFilledAmount = g_makerFilledAmount[orderInfo.orderHash];
uint256 totalMakerFilledAmount = oldMakerFilledAmount.add(makerFillAmount);
Require.that(
totalMakerFilledAmount <= orderInfo.order.makerAmount,
FILE,
"Cannot overfill order",
orderInfo.orderHash,
oldMakerFilledAmount,
makerFillAmount
);
g_makerFilledAmount[orderInfo.orderHash] = totalMakerFilledAmount;
emit LogLimitOrderFilled(
orderInfo.orderHash,
orderInfo.order.makerAccountOwner,
makerFillAmount,
totalMakerFilledAmount
);
}
/**
* Parses the order, verifies that it is not expired or canceled, and verifies the signature.
*/
function getOrderAndValidateSignature(
bytes memory data
)
private
view
returns (OrderInfo memory)
{
Require.that(
(
data.length == NUM_ORDER_BYTES ||
data.length == NUM_ORDER_BYTES + NUM_SIGNATURE_BYTES
),
FILE,
"Cannot parse order from data"
);
OrderInfo memory orderInfo;
orderInfo.order = abi.decode(data, (Order));
orderInfo.orderHash = getOrderHash(orderInfo.order);
OrderStatus orderStatus = g_status[orderInfo.orderHash];
// verify valid signature or is pre-approved
if (orderStatus == OrderStatus.Null) {
bytes memory signature = parseSignature(data);
address signer = TypedSignature.recover(orderInfo.orderHash, signature);
Require.that(
orderInfo.order.makerAccountOwner == signer,
FILE,
"Order invalid signature",
orderInfo.orderHash
);
} else {
Require.that(
orderStatus != OrderStatus.Canceled,
FILE,
"Order canceled",
orderInfo.orderHash
);
assert(orderStatus == OrderStatus.Approved);
}
return orderInfo;
}
// ============ Private Parsing Functions ============
/**
* Returns the EIP712 hash of an order.
*/
function getOrderHash(
Order memory order
)
private
view
returns (bytes32)
{
// compute the overall signed struct hash
/* solium-disable-next-line indentation */
bytes32 structHash = keccak256(abi.encode(
EIP712_LIMIT_ORDER_STRUCT_SCHEMA_HASH,
order
));
// compute eip712 compliant hash
/* solium-disable-next-line indentation */
return keccak256(abi.encodePacked(
EIP191_HEADER,
EIP712_DOMAIN_HASH,
structHash
));
}
/**
* Parses out a signature from call data.
*/
function parseSignature(
bytes memory data
)
private
pure
returns (bytes memory)
{
Require.that(
data.length == NUM_ORDER_BYTES + NUM_SIGNATURE_BYTES,
FILE,
"Cannot parse signature from data"
);
bytes memory signature = new bytes(NUM_SIGNATURE_BYTES);
uint256 sigOffset = NUM_ORDER_BYTES;
/* solium-disable-next-line security/no-inline-assembly */
assembly {
let sigStart := add(data, sigOffset)
mstore(add(signature, 0x020), mload(add(sigStart, 0x20)))
mstore(add(signature, 0x040), mload(add(sigStart, 0x40)))
mstore(add(signature, 0x042), mload(add(sigStart, 0x42)))
}
return signature;
}
}