-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSwapper.sol
682 lines (595 loc) · 23.4 KB
/
Swapper.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
//SPDX-License-Identifier: MIT
pragma solidity 0.8.17;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "../Utils/EIP712HashGenerator.sol";
import "hardhat/console.sol";
/// @title A trustless off-chain orderbook-based DEX
/// @author nobidex team
/// @notice Only a group of preApproved addresses(brokers) are allowed to Swap assets directly from the contract
/*
* @dev The Swap is the main function that executes token swaps and fee transactions
* @dev The Swap function operates with the help of some internal functions:
* _validateTransaction, _getMessageHash, _isValidSignatureHash.
*/
contract Swapper is Pausable, ReentrancyGuard, EIP712HashGenerator {
using SafeERC20 for IERC20;
using Strings for uint8;
// State Variables
/*
* @dev Moderator is the only address that can call the following functions:
* updateFeeRatio, unpause, proposeToUpdateModerator.
*/
address public Moderator;
address public candidateModerator;
uint32 public FeeRatioDenominator;
uint16 public maxFeeRatio;
uint8 public version;
bytes32 constant ORDER_TYPEHASH =
keccak256(
"Order(uint16 maxFeeRatio,uint64 clientOrderId,uint64 validUntil,uint256 chainId,uint256 ratioSellArgument,uint256 ratioBuyArgument,address sellTokenAddress,address buyTokenAddress)"
);
// status codes
// Low Balance Or Allowance ERROR 402 (Payment Required)
// Cancelled order ERROR 410 (Gone)
// ValidUntil ERROR 408 (Request Timeout)
// Fairness ERROR 417 (Precondition Failed)
// Signature Validation ERROR 401 (Unauthorized)
// SUCCESSFUL SWAP 200 (OK)
// https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
uint16[5] errorCodes;
uint16 private constant SUCCESSFUL_SWAP_CODE = 200;
/// @dev brokersAddresses are the only addresses that are allowed to call the Swap function
mapping(address => bool) public brokersAddresses;
/// @dev orderRevokedStatus mapps the address of the user to one of it's clientOrderIds to the orders status
/// @notice when the order status is true the order is considered cancelled
mapping(address => mapping(uint64 => bool)) public orderRevokedStatus;
// Structs
struct MatchedOrders {
uint16 makerFeeRatio;
uint16 takerFeeRatio;
uint64 makerOrderID;
uint64 takerOrderID;
uint64 makerValidUntil;
uint64 takerValidUntil;
uint256 matchID;
uint256 makerRatioSellArg;
uint256 makerRatioBuyArg;
uint256 takerRatioSellArg;
uint256 takerRatioBuyArg;
uint256 makerTotalSellAmount;
uint256 takerTotalSellAmount;
address makerSellTokenAddress;
address takerSellTokenAddress;
address makerUserAddress;
address takerUserAddress;
bytes makerSignature;
bytes takerSignature;
}
struct SwapStatus {
uint256 matchID;
uint16 statusCode;
}
struct Order {
uint16 maxFeeRatio;
uint64 clientOrderId;
uint64 validUntil;
uint256 chainId;
uint256 ratioSellArgument;
uint256 ratioBuyArgument;
address sellTokenAddress;
address buyTokenAddress;
}
// Events
/// @dev Emitted when the Swap is called
event SwapExecuted(SwapStatus[]);
/// @dev Emitted when the revokeOrder function is called
event orderCancelled(address, uint64);
// Modifiers
modifier isBroker() {
require(brokersAddresses[msg.sender], "ERROR: unauthorized caller");
_;
}
modifier isModerator() {
require(msg.sender == Moderator, "ERROR: unauthorized caller");
_;
}
/// @dev isDaoMember, checks to see if the caller is one the listed Moderator
/// @dev daoMembers are the only addresses that are allowed to call the following functions: registerBrokers, unregisterBrokers, pause
modifier isDaoMember() {
require(
_isModerator() || _isOwner(msg.sender),
"ERROR: unauthorized caller"
);
_;
}
// Constructor and Functions
/**
*
*@dev Sets the values for {MaxFeeRatio} and {Moderator} and {brokersAddresses} mapping.
*
*/
constructor(
address payable _moderator,
address[] memory _brokers,
uint32 _FeeRatioDenominator,
uint16 _maxFeeRatio,
uint8 _version
) EIP712HashGenerator("nobidex", _version.toString()) {
errorCodes = [402, 410, 408, 417, 401];
maxFeeRatio = _maxFeeRatio;
Moderator = _moderator;
FeeRatioDenominator = _FeeRatioDenominator;
version = _version;
for (uint256 i = 0; i < _brokers.length; ) {
brokersAddresses[_brokers[i]] = true;
unchecked {
i++;
}
}
}
/**
*
* @notice Swap function execute the token swaps and fee transactions,
* @notice Swap function contains multiple fairness and validation checks for each Swap,
* @notice Swap function checks are for assuring our users that no broker that uses this contract
* has the ability to abuse their trust,
*
*
* @dev The matchedOrders data must match with the signed order and the signature of the user.
* @dev SwapExecuted event is emitted with the batchExecuteStatus array that declares the status of each Swap ,
* @dev batchExecuteStatus array contains the matchId of each Swap and it's statusCode.
* @dev msg.sender must be a valid Broker,
*
* @param matchedOrders is an array of the MatchedOrders struct(which contains the detail of one Swap between two addresses).
*
*/
function Swap(
MatchedOrders[] calldata matchedOrders
) external virtual whenNotPaused isBroker nonReentrant {
SwapStatus[] memory batchExecuteStatus = new SwapStatus[](
matchedOrders.length
);
for (uint256 i = 0; i < matchedOrders.length; i++) {
MatchedOrders memory matchedOrder = matchedOrders[i];
bool matchFailed = false;
(
bool isTransactionFeasible,
bool isOrderCancelled
) = _checkTransactionFeasibility(matchedOrder);
(
bool isTransactionExpired,
bool isSignatureValid
) = _checkTransactionValidity(matchedOrder);
bool isMatchFair = _checkTransactionFairness(matchedOrder);
bool[5] memory _checksFailConditions = [
!isTransactionFeasible,
isOrderCancelled,
isTransactionExpired,
!isMatchFair,
!isSignatureValid
];
for (uint256 j = 0; j < _checksFailConditions.length; j++) {
if (_checksFailConditions[j]) {
batchExecuteStatus[i] = SwapStatus(
matchedOrder.matchID,
errorCodes[j]
);
matchFailed = true;
break;
}
}
if (matchFailed) {
continue;
}
(uint256 takerFee, uint256 makerFee) = _calculateTransactionFee(
matchedOrder
);
_swapTokens(matchedOrder, takerFee, makerFee);
batchExecuteStatus[i] = SwapStatus(
matchedOrder.matchID,
SUCCESSFUL_SWAP_CODE
);
}
emit SwapExecuted(batchExecuteStatus);
}
/**
* @notice updateFeeRatio function sets a new uint256 to MaxFeeRatio variable,
*
* @dev the new feeRatio cannot be the same as the last one,
* @dev msg.sender must be the Moderator,
*
* @param _newFeeRatio uint256 is the new fee to be set to the maxFeeRatio variable.
*
*/
function updateFeeRatio(
uint16 _newFeeRatio
) external whenNotPaused isModerator {
require(_newFeeRatio != maxFeeRatio, "ERROR: invalid input");
maxFeeRatio = _newFeeRatio;
}
/**
* @notice registerBrokers function sets an address to True in brokersAddresses mapping, making it a valid caller for Swap function,
*
* @dev msg.sender must be a DAO member,
*
* @param _brokers address is the address that the DAOMember wants to turn to a broker.
*
*/
function registerBrokers(
address[] memory _brokers
) external whenNotPaused isDaoMember {
for (uint256 i = 0; i < _brokers.length; ) {
brokersAddresses[_brokers[i]] = true;
unchecked {
i++;
}
}
}
/**
* @notice unregisterBroker function sets an address to False in brokersAddresses mapping, making it an invalid caller for Swap function,
*
* @dev msg.sender must be a DAO member,
*
* @param _brokers address is the address that the DAOMember wants to remove from brokers.
*
*/
function unregisterBrokers(address[] memory _brokers) external isDaoMember {
for (uint256 i = 0; i < _brokers.length; ) {
brokersAddresses[_brokers[i]] = false;
unchecked {
i++;
}
}
}
/**
* @notice proposeToUpdateModerator function handles suggesting the update of the Moderator address,
* this suggestion will be reviewed by DAOmembers and after the appropriate approvals in the Moderator contract,
* the proposed address is assigned to the candidateModerator variables,
*
*
* @dev the new Moderator address cannot be the same as the last one,
* @dev msg.sender must be the previous Moderator contract,
*
* @param _newModerator address is the new candidate for Moderator variable.
*
*/
function proposeToUpdateModerator(
address _newModerator
) external isModerator {
require(candidateModerator != _newModerator, "ERROR: already proposed");
candidateModerator = _newModerator;
}
/**
* @notice updateModerator function handle the update of the Moderator variable,
*
* @dev msg.sender must be the new Moderator contract address,
*
*/
function updateModerator() external {
require(candidateModerator == msg.sender, "ERROR: invalid sender");
Moderator = candidateModerator;
candidateModerator = address(0);
}
/**
* @notice revokeOrder function sets the status of the msg.senders order to true in isOrderCanceled mapping,
*
* @notice revokeOrder function gives the users the ability to manage their orders on-chain in addition to managing
* them off-chain through the dex itself,
*
* @dev orderCancelled event is emitted with the msg.sender(users address) and the users clientOrderId the wish to cancel,
* @param _clientOrderId is the ID of the order the user wish to cancel.
*
*/
function revokeOrder(uint64 _clientOrderId) external whenNotPaused {
bool orderStatus = orderRevokedStatus[msg.sender][_clientOrderId];
require(!orderStatus, "ERROR: already cancelled");
orderRevokedStatus[msg.sender][_clientOrderId] = true;
emit orderCancelled(msg.sender, _clientOrderId);
}
// pause and unpause functions
/**
* @notice pause function, transfers all the given tokens balances and the Ether (if the contract have any Ether balance) to the Moderator contract and triggers the stopped state,
*
* @dev Paused event is emitted with the list of tokens,
* @dev EthTransferStatus is emitted if there is any Eth in the contract with the transfer results,
* @dev msg.sender must be the Moderator member,
*
* @param tokenAddresses is the token list to be transferred to the Moderator contract,
*
*/
function pause(
address[] memory tokenAddresses
) external whenNotPaused isDaoMember nonReentrant {
uint256 len = tokenAddresses.length;
for (uint256 i = 0; i < len; ) {
if (tokenAddresses[i] == address(0)) {
uint256 EthBalance = address(this).balance;
payable(Moderator).transfer(EthBalance);
} else {
uint256 balance = IERC20(tokenAddresses[i]).balanceOf(
address(this)
);
IERC20(tokenAddresses[i]).safeTransfer(Moderator, balance);
}
unchecked {
i++;
}
}
_pause();
}
/**
* @notice unpause function, Returns the contract to normal state after it has been paused,
*
* @dev msg.sender must be the Moderator,
*/
function unpause() external whenPaused isModerator {
_unpause();
}
//getter functions
/**
* @dev Retrieves the chain ID of the current blockchain.
* @return The chain ID as a uint256 value.
*/
function getChainID() public view returns (uint256) {
return block.chainid;
}
/**
* @dev Retrieves the current block number within the blockchain.
* @return The block number as a uint256 value.
*/
function getBlockNumber() public view returns (uint256) {
return block.number;
}
/**
* @dev _checkTransactionFeasibility function checks the Transaction Feasibility and if the Transaction cancelled returning the result as booleans.
* @dev since the function is internal, the data will later be used in the swap function to validate each swap.
* @param _matchedOrder is the data of each swap,
*
*/
function _checkTransactionFeasibility(
MatchedOrders memory _matchedOrder
) internal view returns (bool, bool) {
//Transaction Feasibility
bool isTransactionFeasible = _ValidateTransaction(
_matchedOrder.makerUserAddress,
_matchedOrder.makerSellTokenAddress,
_matchedOrder.makerTotalSellAmount
) &&
_ValidateTransaction(
_matchedOrder.takerUserAddress,
_matchedOrder.takerSellTokenAddress,
_matchedOrder.takerTotalSellAmount
);
//Transaction cancelled
bool isOrderCancelled = orderRevokedStatus[
_matchedOrder.makerUserAddress
][_matchedOrder.makerOrderID] ||
orderRevokedStatus[_matchedOrder.takerUserAddress][
_matchedOrder.takerOrderID
];
return (isTransactionFeasible, isOrderCancelled);
}
/**
* @dev _checkTransactionValidity function checks the Transactions valid until and the Transfer amount validity and the signature validity, returning the result as booleans.
* @dev since the function is internal, the data will later be used in the swap function to validate each swap.
* @param _matchedOrder is the data of each swap,
*
*/
function _checkTransactionValidity(
MatchedOrders memory _matchedOrder
) internal view returns (bool, bool) {
uint256 chainId = block.chainid;
//Transaction validity
bool isTransactionExpired = (_matchedOrder.makerValidUntil <
block.number) || (_matchedOrder.takerValidUntil < block.number);
//signature validity
bytes32 makerMsgHash = _getMessageHash(
Order(
maxFeeRatio,
_matchedOrder.makerOrderID,
_matchedOrder.makerValidUntil,
chainId,
_matchedOrder.makerRatioSellArg,
_matchedOrder.makerRatioBuyArg,
_matchedOrder.makerSellTokenAddress,
_matchedOrder.takerSellTokenAddress
)
);
bytes32 takerMsgHash = _getMessageHash(
Order(
maxFeeRatio,
_matchedOrder.takerOrderID,
_matchedOrder.takerValidUntil,
chainId,
_matchedOrder.takerRatioSellArg,
_matchedOrder.takerRatioBuyArg,
_matchedOrder.takerSellTokenAddress,
_matchedOrder.makerSellTokenAddress
)
);
bool isMakerSignatureValid = _isValidSignatureHash(
_matchedOrder.makerUserAddress,
makerMsgHash,
_matchedOrder.makerSignature
);
bool isTakerSignatureValid = _isValidSignatureHash(
_matchedOrder.takerUserAddress,
takerMsgHash,
_matchedOrder.takerSignature
);
bool isSignatureValid = (isMakerSignatureValid &&
isTakerSignatureValid);
return (isTransactionExpired, isSignatureValid);
}
/**
* @dev _checkTransactionFairness function checks the price and fee fairness and the relativity of the swap amounts toward each other as maker and taker, returning the result as boolians.
* @dev since the function is internal, the data will later be used in the swap function to validate each swap.
* @param _matchedOrder is the data of each swap,
*
*/
function _checkTransactionFairness(
MatchedOrders memory _matchedOrder
) internal view returns (bool) {
bool isPriceFair = (_matchedOrder.makerTotalSellAmount *
_matchedOrder.makerRatioBuyArg) ==
(_matchedOrder.makerRatioSellArg *
_matchedOrder.takerTotalSellAmount);
bool isPriceRelative = (_matchedOrder.makerRatioSellArg *
_matchedOrder.takerRatioSellArg) >=
(_matchedOrder.makerRatioBuyArg * _matchedOrder.takerRatioBuyArg);
bool isFeeFairness = (_matchedOrder.makerFeeRatio <= maxFeeRatio) &&
(_matchedOrder.takerFeeRatio <= maxFeeRatio);
return (isPriceFair && isPriceRelative && isFeeFairness);
}
/**
* @dev _calculateTransactionFee function calculates each users fee amount according to the fee ratio assigned to them.
* @dev since the function is internal, the data will later be used in the swap function to make the transfers.
* @param _matchedOrder is the data of each swap,
*
*/
function _calculateTransactionFee(
MatchedOrders memory _matchedOrder
) internal view whenNotPaused returns (uint256, uint256) {
uint256 takerFee = (_matchedOrder.makerTotalSellAmount *
_matchedOrder.takerFeeRatio) / FeeRatioDenominator;
uint256 makerFee = (_matchedOrder.takerTotalSellAmount *
_matchedOrder.makerFeeRatio) / FeeRatioDenominator;
return (takerFee, makerFee);
}
/**
* @dev _swapTokens function swaps the transfer amounts to each user and the fee to the Moderator.
* @dev since the function is internal, it will later be used in the swap function to make the transfers.
* @param _matchedOrder is the data of each swap,
*
*/
function _swapTokens(
MatchedOrders memory _matchedOrder,
uint256 _takerFee,
uint256 _makerFee
) internal {
IERC20(_matchedOrder.makerSellTokenAddress).safeTransferFrom(
_matchedOrder.makerUserAddress,
_matchedOrder.takerUserAddress,
_matchedOrder.makerTotalSellAmount - _takerFee
);
IERC20(_matchedOrder.takerSellTokenAddress).safeTransferFrom(
_matchedOrder.takerUserAddress,
_matchedOrder.makerUserAddress,
_matchedOrder.takerTotalSellAmount - _makerFee
);
IERC20(_matchedOrder.makerSellTokenAddress).safeTransferFrom(
_matchedOrder.makerUserAddress,
Moderator,
_takerFee
);
IERC20(_matchedOrder.takerSellTokenAddress).safeTransferFrom(
_matchedOrder.takerUserAddress,
Moderator,
_makerFee
);
}
/**
* @dev _isDao function validates the users signature is one of the owners of the Moderator contract,
* with an external call to the "Moderator" contract,
*
* @param _caller is the address of the msg.sender in the isDaoMember modifier,
*
*/
function _isOwner(address _caller) internal returns (bool) {
(bool success, bytes memory data) = Moderator.call(
abi.encodeWithSignature("isOwner(address)", _caller)
);
require(success, "ERROR: external call failed");
return abi.decode(data, (bool));
}
/**
* @dev _isValidSignatureHash function validates the users signature against the created message hash,
* with an external call to the "SignatureChecker" contract,
*
* @param _userAddress is the address of the user whose signature is being validated,
* @param _messageHash is the hash of the data user signed previously,
* @param _userSignature is the signature from when the user placed their order.
*
*/
function _isValidSignatureHash(
address _userAddress,
bytes32 _messageHash,
bytes memory _userSignature
) internal view returns (bool) {
return
SignatureChecker.isValidSignatureNow(
_userAddress,
_messageHash,
_userSignature
);
}
/**
* @notice _getMessageHashFunction hashes the data that user signed when they placed the order for further validation,
*
* @dev _getMessageHash function is used in th execute Swap to hash the given Swap data,
*
*
* @param _Order(Order struct) contains the data that a user signed while placing on order.
*
*/
function _getMessageHash(
Order memory _Order
) internal view returns (bytes32) {
bytes32 hash = keccak256(
abi.encode(
ORDER_TYPEHASH,
_Order.maxFeeRatio,
_Order.clientOrderId,
_Order.validUntil,
_Order.chainId,
_Order.ratioSellArgument,
_Order.ratioBuyArgument,
_Order.sellTokenAddress,
_Order.buyTokenAddress
)
);
return HashTypedMessage(hash);
}
/**
* @dev _ValidateTransaction function compares the users balance and allowance against the amounts required for the Swap to be executed,
* to check if the transaction is possible.
*
* @param _userAddress is the address of the user,
* @param _userSellToken is the address of the token that user is selling,
* @param _userSellAmount is total amount of token that user is selling.
*
*@return A boolean dictating if the Swap execution is possible or it is going to fail due to lack of balance or allowance.
*/
function _ValidateTransaction(
address _userAddress,
address _userSellToken,
uint256 _userSellAmount
) internal view returns (bool) {
bool isTransactionValid;
uint256 userBalance = IERC20(_userSellToken).balanceOf(_userAddress);
uint256 userAllowance = IERC20(_userSellToken).allowance(
_userAddress,
address(this)
);
if (
(userBalance >= _userSellAmount) &&
(userAllowance >= _userSellAmount)
) {
isTransactionValid = true;
} else {
isTransactionValid = false;
}
return isTransactionValid;
}
function _isModerator() internal view returns (bool) {
if (msg.sender == Moderator) {
return true;
}
return false;
}
}