-
Notifications
You must be signed in to change notification settings - Fork 120
/
Exchange.sol
904 lines (831 loc) · 22.7 KB
/
Exchange.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
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
/*
Copyright 2017 Loopring Project Ltd (Loopring Foundation).
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.10;
import "../lib/Claimable.sol";
import "../lib/NoDefaultFunc.sol";
import "../lib/ReentrancyGuard.sol";
import "../iface/IExchange.sol";
import "./libexchange/ExchangeAccounts.sol";
import "./libexchange/ExchangeAdmins.sol";
import "./libexchange/ExchangeBalances.sol";
import "./libexchange/ExchangeBlocks.sol";
import "./libexchange/ExchangeData.sol";
import "./libexchange/ExchangeDeposits.sol";
import "./libexchange/ExchangeGenesis.sol";
import "./libexchange/ExchangeMode.sol";
import "./libexchange/ExchangeTokens.sol";
import "./libexchange/ExchangeWithdrawals.sol";
/// @title An Implementation of IExchange.
/// @author Brecht Devos - <brecht@loopring.org>
/// @author Daniel Wang - <daniel@loopring.org>
contract Exchange is IExchange, Claimable, NoDefaultFunc, ReentrancyGuard
{
using ExchangeAdmins for ExchangeData.State;
using ExchangeAccounts for ExchangeData.State;
using ExchangeBalances for ExchangeData.State;
using ExchangeBlocks for ExchangeData.State;
using ExchangeDeposits for ExchangeData.State;
using ExchangeGenesis for ExchangeData.State;
using ExchangeMode for ExchangeData.State;
using ExchangeTokens for ExchangeData.State;
using ExchangeWithdrawals for ExchangeData.State;
ExchangeData.State private state;
// -- Constructor --
constructor(
uint _id,
address payable _loopringAddress,
address _owner,
address payable _operator,
bool _onchainDataAvailability
)
public
{
require(address(0) != _owner, "ZERO_ADDRESS");
owner = _owner;
state.initializeGenesisBlock(
_id,
_loopringAddress,
_operator,
_onchainDataAvailability
);
}
modifier onlyOperator()
{
require(msg.sender == state.operator, "UNAUTHORIZED");
_;
}
// -- Settings --
function getGlobalSettings()
public
pure
returns (
uint32 MAX_PROOF_GENERATION_TIME_IN_SECONDS,
uint16 MAX_OPEN_DEPOSIT_REQUESTS,
uint16 MAX_OPEN_WITHDRAWAL_REQUESTS,
uint32 MAX_AGE_UNFINALIZED_BLOCK_UNTIL_WITHDRAW_MODE,
uint32 MAX_AGE_REQUEST_UNTIL_FORCED,
uint32 MAX_AGE_REQUEST_UNTIL_WITHDRAW_MODE,
uint32 MAX_TIME_TO_DISTRIBUTE_WITHDRAWALS,
uint32 MAX_TIME_IN_SHUTDOWN_BASE,
uint32 MAX_TIME_IN_SHUTDOWN_DELTA,
uint32 TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS,
uint32 FEE_BLOCK_FINE_START_TIME,
uint32 FEE_BLOCK_FINE_MAX_DURATION,
uint MAX_NUM_TOKENS,
uint MAX_NUM_ACCOUNTS
)
{
return (
ExchangeData.MAX_PROOF_GENERATION_TIME_IN_SECONDS(),
ExchangeData.MAX_OPEN_DEPOSIT_REQUESTS(),
ExchangeData.MAX_OPEN_WITHDRAWAL_REQUESTS(),
ExchangeData.MAX_AGE_UNFINALIZED_BLOCK_UNTIL_WITHDRAW_MODE(),
ExchangeData.MAX_AGE_REQUEST_UNTIL_FORCED(),
ExchangeData.MAX_AGE_REQUEST_UNTIL_WITHDRAW_MODE(),
ExchangeData.MAX_TIME_TO_DISTRIBUTE_WITHDRAWALS(),
ExchangeData.MAX_TIME_IN_SHUTDOWN_BASE(),
ExchangeData.MAX_TIME_IN_SHUTDOWN_DELTA(),
ExchangeData.TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS(),
ExchangeData.FEE_BLOCK_FINE_START_TIME(),
ExchangeData.FEE_BLOCK_FINE_MAX_DURATION(),
ExchangeData.MAX_NUM_TOKENS(),
ExchangeData.MAX_NUM_ACCOUNTS()
);
}
// -- Mode --
function isInWithdrawalMode()
external
view
returns (bool result)
{
result = state.isInWithdrawalMode();
}
function isShutdown()
external
view
returns (bool result)
{
result = state.isShutdown();
}
function isInMaintenance()
external
view
returns (bool result)
{
result = state.isInMaintenance();
}
// -- Accounts --
function getNumAccounts()
external
view
returns (uint)
{
return state.accounts.length;
}
function getAccount(
address owner
)
external
view
returns (
uint24 accountID,
uint pubKeyX,
uint pubKeyY
)
{
(accountID, pubKeyX, pubKeyY) = state.getAccount(owner);
}
function createOrUpdateAccount(
uint pubKeyX,
uint pubKeyY,
bytes calldata permission
)
external
payable
nonReentrant
returns (
uint24 accountID,
bool isAccountNew,
bool isAccountUpdated
)
{
return updateAccountAndDepositInternal(
pubKeyX,
pubKeyY,
address(0),
0,
permission
);
}
// -- Balances --
function isAccountBalanceCorrect(
uint merkleRoot,
uint24 accountID,
uint16 tokenID,
uint pubKeyX,
uint pubKeyY,
uint32 nonce,
uint96 balance,
uint tradeHistoryRoot,
uint[30] calldata accountPath,
uint[12] calldata balancePath
)
external
pure
returns (bool)
{
return ExchangeBalances.isAccountBalanceCorrect(
merkleRoot,
accountID,
tokenID,
pubKeyX,
pubKeyY,
nonce,
balance,
tradeHistoryRoot,
accountPath,
balancePath
);
}
// -- Tokens --
function getLRCFeeForRegisteringOneMoreToken()
external
view
returns (uint feeLRC)
{
feeLRC = state.getLRCFeeForRegisteringOneMoreToken();
}
function registerToken(
address tokenAddress
)
external
nonReentrant
onlyOwner
returns (uint16 tokenID)
{
tokenID = state.registerToken(tokenAddress);
}
function getTokenID(
address tokenAddress
)
external
view
returns (uint16 tokenID)
{
tokenID = state.getTokenID(tokenAddress);
}
function getTokenAddress(
uint16 tokenID
)
external
view
returns (address tokenAddress)
{
tokenAddress = state.getTokenAddress(tokenID);
}
function disableTokenDeposit(
address tokenAddress
)
external
nonReentrant
onlyOwner
{
state.disableTokenDeposit(tokenAddress);
}
function enableTokenDeposit(
address tokenAddress
)
external
nonReentrant
onlyOwner
{
state.enableTokenDeposit(tokenAddress);
}
// -- Stakes --
function getExchangeStake()
external
view
returns (uint)
{
return state.loopring.getExchangeStake(state.id);
}
function withdrawExchangeStake(
address recipient
)
external
nonReentrant
onlyOwner
returns (uint)
{
return state.withdrawExchangeStake(recipient);
}
function withdrawTokenNotOwnedByUsers(
address tokenAddress,
address payable recipient
)
external
nonReentrant
onlyOwner
returns(uint)
{
return state.withdrawTokenNotOwnedByUsers(tokenAddress, recipient);
}
function withdrawProtocolFeeStake(
address recipient,
uint amount
)
external
nonReentrant
onlyOwner
{
state.loopring.withdrawProtocolFeeStake(state.id, recipient, amount);
}
function burnExchangeStake()
external
nonReentrant
{
// Allow burning the complete exchange stake when the exchange gets into withdrawal mode
if(state.isInWithdrawalMode()) {
// Burn the complete stake of the exchange
uint stake = state.loopring.getExchangeStake(state.id);
state.loopring.burnExchangeStake(state.id, stake);
}
}
// -- Blocks --
function getBlockHeight()
external
view
returns (uint)
{
return state.blocks.length - 1;
}
function getNumBlocksFinalized()
external
view
returns (uint)
{
return state.numBlocksFinalized - 1;
}
function getBlock(
uint blockIdx
)
external
view
returns (
bytes32 merkleRoot,
bytes32 publicDataHash,
uint8 blockState,
uint8 blockType,
uint16 blockSize,
uint32 timestamp,
uint32 numDepositRequestsCommitted,
uint32 numWithdrawalRequestsCommitted,
bool blockFeeWithdrawn,
uint16 numWithdrawalsDistributed
)
{
require(blockIdx < state.blocks.length, "INVALID_BLOCK_IDX");
ExchangeData.Block storage specifiedBlock = state.blocks[blockIdx];
merkleRoot = specifiedBlock.merkleRoot;
publicDataHash = specifiedBlock.publicDataHash;
blockState = uint8(specifiedBlock.state);
blockType = uint8(specifiedBlock.blockType);
blockSize = specifiedBlock.blockSize;
timestamp = specifiedBlock.timestamp;
numDepositRequestsCommitted = specifiedBlock.numDepositRequestsCommitted;
numWithdrawalRequestsCommitted = specifiedBlock.numWithdrawalRequestsCommitted;
blockFeeWithdrawn = specifiedBlock.blockFeeWithdrawn;
numWithdrawalsDistributed = specifiedBlock.numWithdrawalsDistributed;
}
function commitBlock(
uint8 blockType,
uint16 blockSize,
uint8 blockVersion,
bytes calldata /*data*/,
bytes calldata offchainData
)
external
nonReentrant
onlyOperator
{
// Decompress the data here so we can extract the data directly from calldata
bytes4 selector = IDecompressor(0x0).decompress.selector;
bytes memory decompressed;
assembly {
// Calldata layout:
// 0: selector
// 4: blockType
// 36: blockSize
// 68: blockVersion
// 100: offset data
// 132: offset offchainData
let dataOffset := add(calldataload(100), 4)
let mode := and(calldataload(add(dataOffset, 1)), 0xFF)
switch mode
case 0 {
// No compression
let length := sub(calldataload(dataOffset), 1)
let data := mload(0x40)
calldatacopy(add(data, 32), add(dataOffset, 33), length)
mstore(data, length)
decompressed := data
mstore(0x40, add(add(decompressed, length), 32))
}
case 1 {
// External contract
let contractAddress := and(calldataload(add(dataOffset, 21)), 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
let length := sub(calldataload(dataOffset), 21)
let data := mload(0x40)
mstore(data, selector)
mstore(add(data, 4), 32)
mstore(add(data, 36), length)
calldatacopy(add(data, 68), add(dataOffset, 53), length)
let success := call(gas, contractAddress, 0, data, add(68, length), 0x0, 0)
if eq(success, 0) {
revert(0, 0)
}
returndatacopy(data, 32, sub(returndatasize(), 32))
decompressed := data
mstore(0x40, add(add(decompressed, mload(decompressed)), 32))
}
default {
revert(0, 0)
}
}
state.commitBlock(blockType, blockSize, blockVersion, decompressed, offchainData);
}
function verifyBlocks(
uint[] calldata blockIndices,
uint[] calldata proofs
)
external
nonReentrant
onlyOperator
{
state.verifyBlocks(blockIndices, proofs);
}
function revertBlock(
uint blockIdx
)
external
nonReentrant
onlyOperator
{
state.revertBlock(blockIdx);
}
// -- Deposits --
function getNumDepositRequestsProcessed()
external
view
returns (uint)
{
return state.getNumDepositRequestsProcessed();
}
function getNumAvailableDepositSlots()
external
view
returns (uint)
{
return state.getNumAvailableDepositSlots();
}
function getDepositRequest(
uint index
)
external
view
returns (
bytes32 accumulatedHash,
uint accumulatedFee,
uint32 timestamp
)
{
(accumulatedHash, accumulatedFee, timestamp) = state.getDepositRequest(index);
}
function updateAccountAndDeposit(
uint pubKeyX,
uint pubKeyY,
address token,
uint96 amount,
bytes calldata permission
)
external
payable
nonReentrant
returns (
uint24 accountID,
bool isAccountNew,
bool isAccountUpdated
)
{
return updateAccountAndDepositInternal(
pubKeyX,
pubKeyY,
token,
amount,
permission
);
}
function deposit(
address token,
uint96 amount
)
external
payable
nonReentrant
{
state.depositTo(
msg.sender,
token,
amount,
0
);
}
function depositTo(
address recipient,
address tokenAddress,
uint96 amount
)
external
payable
nonReentrant
{
state.depositTo(
recipient,
tokenAddress,
amount,
0
);
}
// -- Withdrawals --
function getNumWithdrawalRequestsProcessed()
external
view
returns (uint)
{
return state.getNumWithdrawalRequestsProcessed();
}
function getNumAvailableWithdrawalSlots(
)
external
view
returns (uint)
{
return state.getNumAvailableWithdrawalSlots();
}
function getWithdrawRequest(
uint index
)
external
view
returns (
bytes32 accumulatedHash,
uint accumulatedFee,
uint32 timestamp
)
{
(accumulatedHash, accumulatedFee, timestamp) = state.getWithdrawRequest(index);
}
function withdraw(
address token,
uint96 amount
)
external
payable
nonReentrant
{
uint24 accountID = state.getAccountID(msg.sender);
state.withdraw(accountID, token, amount);
}
function withdrawProtocolFees(
address token
)
external
payable
nonReentrant
{
// Always request the maximum amount so the complete balance is withdrawn
state.withdraw(0, token, ~uint96(0));
}
function withdrawFromMerkleTree(
address token,
uint pubKeyX,
uint pubKeyY,
uint32 nonce,
uint96 balance,
uint tradeHistoryRoot,
uint[30] calldata accountPath,
uint[12] calldata balancePath
)
external
nonReentrant
{
state.withdrawFromMerkleTreeFor(
msg.sender,
token,
pubKeyX,
pubKeyY,
nonce,
balance,
tradeHistoryRoot,
accountPath,
balancePath
);
}
// We still alow anyone to withdraw these funds for the account owner
function withdrawFromMerkleTreeFor(
address owner,
address token,
uint pubKeyX,
uint pubKeyY,
uint32 nonce,
uint96 balance,
uint tradeHistoryRoot,
uint[30] calldata accountPath,
uint[12] calldata balancePath
)
external
nonReentrant
{
state.withdrawFromMerkleTreeFor(
owner,
token,
pubKeyX,
pubKeyY,
nonce,
balance,
tradeHistoryRoot,
accountPath,
balancePath
);
}
function withdrawFromDepositRequest(
uint depositIdx
)
external
nonReentrant
{
state.withdrawFromDepositRequest(depositIdx);
}
function withdrawFromApprovedWithdrawal(
uint blockIdx,
uint slotIdx
)
external
nonReentrant
{
require(blockIdx < state.blocks.length, "INVALID_BLOCK_IDX");
ExchangeData.Block storage withdrawBlock = state.blocks[blockIdx];
state.withdrawFromApprovedWithdrawal(
blockIdx,
withdrawBlock,
slotIdx,
false
);
}
function withdrawBlockFee(
uint blockIdx,
address payable feeRecipient
)
external
nonReentrant
onlyOperator
returns (uint feeAmount)
{
feeAmount = state.withdrawBlockFee(blockIdx, feeRecipient);
}
function distributeWithdrawals(
uint blockIdx,
uint maxNumWithdrawals
)
external
nonReentrant
{
state.distributeWithdrawals(blockIdx, maxNumWithdrawals);
}
// -- Admins --
function setOperator(
address payable _operator
)
external
nonReentrant
onlyOwner
returns (address payable)
{
return state.setOperator(_operator);
}
function setAddressWhitelist(
address _addressWhitelist
)
external
nonReentrant
onlyOwner
returns (address)
{
return state.setAddressWhitelist(_addressWhitelist);
}
function setFees(
uint _accountCreationFeeETH,
uint _accountUpdateFeeETH,
uint _depositFeeETH,
uint _withdrawalFeeETH
)
external
nonReentrant
onlyOwner
{
state.setFees(
_accountCreationFeeETH,
_accountUpdateFeeETH,
_depositFeeETH,
_withdrawalFeeETH
);
}
function getFees()
external
view
returns (
uint _accountCreationFeeETH,
uint _accountUpdateFeeETH,
uint _depositFeeETH,
uint _withdrawalFeeETH
)
{
_accountCreationFeeETH = state.accountCreationFeeETH;
_accountUpdateFeeETH = state.accountUpdateFeeETH;
_depositFeeETH = state.depositFeeETH;
_withdrawalFeeETH = state.withdrawalFeeETH;
}
function startOrContinueMaintenanceMode(
uint durationMinutes
)
external
nonReentrant
onlyOwner
{
state.startOrContinueMaintenanceMode(durationMinutes);
}
function stopMaintenanceMode()
external
nonReentrant
onlyOwner
{
state.stopMaintenanceMode();
}
function getRemainingDowntime()
external
view
returns (uint durationMinutes)
{
durationMinutes = state.getRemainingDowntime();
}
function getDowntimeCostLRC(
uint durationMinutes
)
external
nonReentrant
returns (uint costLRC)
{
costLRC = state.getDowntimeCostLRC(durationMinutes);
}
function getTotalTimeInMaintenanceSeconds()
external
view
returns (uint timeSeconds)
{
timeSeconds = state.getTotalTimeInMaintenanceSeconds();
}
function getExchangeCreationTimestamp()
external
view
returns (uint timestamp)
{
timestamp = state.exchangeCreationTimestamp;
}
function shutdown()
external
nonReentrant
onlyOwner
returns (bool success)
{
require(!state.isInWithdrawalMode(), "INVALID_MODE");
require(!state.isShutdown(), "ALREADY_SHUTDOWN");
state.shutdownStartTime = now;
emit Shutdown(state.shutdownStartTime);
return true;
}
function getRequestStats()
external
view
returns(
uint numDepositRequestsProcessed,
uint numAvailableDepositSlots,
uint numWithdrawalRequestsProcessed,
uint numAvailableWithdrawalSlots
)
{
numDepositRequestsProcessed = state.getNumDepositRequestsProcessed();
numAvailableDepositSlots = state.getNumAvailableDepositSlots();
numWithdrawalRequestsProcessed = state.getNumWithdrawalRequestsProcessed();
numAvailableWithdrawalSlots = state.getNumAvailableWithdrawalSlots();
}
function getProtocolFeeValues()
external
view
returns (
uint32 timestamp,
uint8 takerFeeBips,
uint8 makerFeeBips,
uint8 previousTakerFeeBips,
uint8 previousMakerFeeBips
)
{
timestamp = state.protocolFeeData.timestamp;
takerFeeBips = state.protocolFeeData.takerFeeBips;
makerFeeBips = state.protocolFeeData.makerFeeBips;
previousTakerFeeBips = state.protocolFeeData.previousTakerFeeBips;
previousMakerFeeBips = state.protocolFeeData.previousMakerFeeBips;
}
// == Internal Functions ==
function updateAccountAndDepositInternal(
uint pubKeyX,
uint pubKeyY,
address token,
uint96 amount,
bytes memory permission
)
internal
returns (
uint24 accountID,
bool isAccountNew,
bool isAccountUpdated
)
{
(accountID, isAccountNew, isAccountUpdated) = state.createOrUpdateAccount(
pubKeyX,
pubKeyY,
permission
);
uint additionalFeeETH = 0;
if (isAccountNew) {
additionalFeeETH = state.accountCreationFeeETH;
} else if (isAccountUpdated) {
additionalFeeETH = state.accountUpdateFeeETH;
}
state.depositTo(
msg.sender,
token,
amount,
additionalFeeETH
);
}
}