-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLimitOrderManager.sol
1251 lines (1056 loc) · 51.5 KB
/
LimitOrderManager.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
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
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import {IERC20} from "openzeppelin/token/ERC20/IERC20.sol";
import {SafeERC20} from "openzeppelin/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "openzeppelin/security/ReentrancyGuard.sol";
import {ILBPair} from "joe-v2/interfaces/ILBPair.sol";
import {ILBFactory} from "joe-v2/interfaces/ILBFactory.sol";
import {LiquidityConfigurations} from "joe-v2/libraries/math/LiquidityConfigurations.sol";
import {Constants} from "joe-v2/libraries/Constants.sol";
import {PackedUint128Math} from "joe-v2/libraries/math/PackedUint128Math.sol";
import {Uint256x256Math} from "joe-v2/libraries/math/Uint256x256Math.sol";
import {SafeCast} from "joe-v2/libraries/math/SafeCast.sol";
import {IWNATIVE} from "joe-v2/interfaces/IWNATIVE.sol";
import {ILimitOrderManager} from "./interfaces/ILimitOrderManager.sol";
/**
* @title Limit Order Manager
* @author Trader Joe
* @notice This contracts allows users to place limit orders using the Liquidity Book protocol.
* It allows to create orders for any Liquidity Book pair V2.1.
*
* The flow of the Limit Order Manager is the following:
* - Users create orders for a specific pair, type (bid or ask), price (bin id) and amount
* (in token Y for bid orders and token X for ask orders) which will be added to the liquidity book pair.
* - Users can cancel orders, which will remove the liquidity from the liquidity book pair according to the order amount
* and send the token amounts back to the user (the amounts depend on the bin composition).
* - Users can execute orders, which will remove the liquidity from the order and send the token to the
* Limit Order Manager contract.
* - Users can claim their executed orders, which will send a portion of the token received from the execution
* to the user (the share depends on the total executed amount of the orders).
*
* Users can place orders using the `placeOrder` function by specifying the following parameters:
* - `tokenX`: the token X of the liquidity book pair
* - `tokenY`: the token Y of the liquidity book pair
* - `binStep`: the bin step of the liquidity book pair
* - `orderType`: the order type (bid or ask)
* - `binId`: the bin id of the order, which is the price of the order
* - `amount`: the amount of token to be used for the order, in token Y for bid orders and token X for ask orders
* Orders can't be placed in the active bin id. Bid orders need to be placed in a bin id lower than the active id,
* while ask orders need to be placed in a bin id greater than the active bin id.
*
* Users can cancel orders using the `cancelOrder` function by specifying the same parameters as for `placeOrder` but
* without the `amount` parameter.
* If the order is already executed, it can't be cancelled, and user will need to claim the filled amount.
* If the user is trying to cancel an order that is inside the active bin id, he may receive a partially filled order,
* according to the active bin composition.
*
* Users can claim orders using the `claimOrder` function by specifying the same parameters as for `placeOrder` but
* without the `amount` parameter.
* If the order is not already executed, but that it can be executed, it will be executed first and then claimed.
* If the order isn't executable, it can't be claimed and the transaction will revert.
* If the order is already executed, the user will receive the filled amount.
*
* Users can execute orders using the `executeOrder` function by specifying the same parameters as for `placeOrder` but
* without the `amount` parameter.
* If the order can't be executed or if it is already executed, the transaction will not revert but will return false.
*/
contract LimitOrderManager is ReentrancyGuard, ILimitOrderManager {
using SafeERC20 for IERC20;
using PackedUint128Math for bytes32;
using Uint256x256Math for uint256;
using SafeCast for uint256;
ILBFactory private immutable _factory;
IWNATIVE private immutable _wNative;
/**
* @dev Mapping of order key (pair, order type, bin id) to positions.
*/
mapping(bytes32 => Positions) private _positions;
/**
* @dev Mapping of user address to mapping of order key (pair, order type, bin id) to order.
*/
mapping(address => mapping(bytes32 => Order)) private _orders;
uint256 private _executorFeeShare;
/**
* @notice Constructor of the Limit Order Manager.
* @param factory The address of the Liquidity Book factory.
* @param wNative The address of the WNative token.
*/
constructor(ILBFactory factory, IWNATIVE wNative) {
if (address(factory) == address(0) || address(wNative) == address(0)) revert LimitOrderManager__ZeroAddress();
_factory = factory;
_wNative = wNative;
_setExecutorFeeShare(Constants.BASIS_POINT_MAX);
}
/**
* @notice Returns the name of the Limit Order Manager.
* @return The name of the Limit Order Manager.
*/
function name() external pure override returns (string memory) {
return "Joe Limit Order Manager";
}
/**
* @notice Returns the address of the Liquidity Book factory.
* @return The address of the Liquidity Book factory.
*/
function getFactory() external view override returns (ILBFactory) {
return _factory;
}
/**
* @notice Returns the address of the WNative token.
* @return The address of the WNative token.
*/
function getWNative() external view override returns (IERC20) {
return _wNative;
}
/**
* @notice Returns the executor fee share.
* @return The executor fee share.
*/
function getExecutorFeeShare() external view override returns (uint256) {
return _executorFeeShare;
}
/**
* @notice Returns the order of the user for the given parameters.
* @param tokenX The token X of the liquidity book pair.
* @param tokenY The token Y of the liquidity book pair.
* @param binStep The bin step of the liquidity book pair.
* @param orderType The order type (bid or ask).
* @param binId The bin id of the order, which is the price of the order.
* @param user The user address.
* @return The order of the user for the given parameters.
*/
function getOrder(IERC20 tokenX, IERC20 tokenY, uint16 binStep, OrderType orderType, uint24 binId, address user)
external
view
override
returns (Order memory)
{
ILBPair lbPair = _getLBPair(tokenX, tokenY, binStep);
return _orders[user][_getOrderKey(lbPair, orderType, binId)];
}
/**
* @notice Returns the last position id for the given parameters.
* @param tokenX The token X of the liquidity book pair.
* @param tokenY The token Y of the liquidity book pair.
* @param binStep The bin step of the liquidity book pair.
* @param orderType The order type (bid or ask).
* @param binId The bin id of the order, which is the price of the order.
* @return The last position id for the given parameters.
*/
function getLastPositionId(IERC20 tokenX, IERC20 tokenY, uint16 binStep, OrderType orderType, uint24 binId)
external
view
override
returns (uint256)
{
ILBPair lbPair = _getLBPair(tokenX, tokenY, binStep);
return _positions[_getOrderKey(lbPair, orderType, binId)].lastId;
}
/**
* @notice Returns the position for the given parameters.
* @param tokenX The token X of the liquidity book pair.
* @param tokenY The token Y of the liquidity book pair.
* @param binStep The bin step of the liquidity book pair.
* @param orderType The order type (bid or ask).
* @param binId The bin id of the order, which is the price of the order.
* @param positionId The position id.
* @return The position for the given parameters.
*/
function getPosition(
IERC20 tokenX,
IERC20 tokenY,
uint16 binStep,
OrderType orderType,
uint24 binId,
uint256 positionId
) external view override returns (Position memory) {
ILBPair lbPair = _getLBPair(tokenX, tokenY, binStep);
return _positions[_getOrderKey(lbPair, orderType, binId)].at[positionId];
}
/**
* @notice Return whether the order is executable or not.
* Will return false if the order is already executed or if it is not executable.
* @param tokenX The token X of the liquidity book pair.
* @param tokenY The token Y of the liquidity book pair.
* @param binStep The bin step of the liquidity book pair.
* @param orderType The order type (bid or ask).
* @param binId The bin id of the order, which is the price of the order.
* @return Whether the order is executable or not.
*/
function isOrderExecutable(IERC20 tokenX, IERC20 tokenY, uint16 binStep, OrderType orderType, uint24 binId)
external
view
override
returns (bool)
{
ILBPair lbPair = _getLBPair(tokenX, tokenY, binStep);
// Get the order key
bytes32 orderKey = _getOrderKey(lbPair, orderType, binId);
// Get the positions for the order key to get the last position id
Positions storage positions = _positions[orderKey];
uint256 positionId = positions.lastId;
// Get the position at the last position id
Position storage position = positions.at[positionId];
// Return whether the position is executable or not, that is, if the position id is greater than 0,
// the position is not already withdrawn and the order is executable
return (positionId > 0 && !position.withdrawn && _isOrderExecutable(lbPair, orderType, binId));
}
/**
* @notice Returns the current amounts of the order for the given parameters.
* Depending on the current bin id, the amounts might fluctuate.
* The amount returned will be the value that the user will receive if the order is cancelled.
* If it's fully converted to the other token, then it's the amount that the user will receive after the order
* is claimed.
* If the order was already claimed, it will return 0.
* @param tokenX The token X of the liquidity book pair.
* @param tokenY The token Y of the liquidity book pair.
* @param binStep The bin step of the liquidity book pair.
* @param orderType The order type (bid or ask).
* @param binId The bin id of the order, which is the price of the order.
* @param user The user address.
* @return amountX The amount of token X.
* @return amountY The amount of token Y.
* @return executionFeeX The execution fee of token X, if the order is executed. If the order is cancelled or was
* already executed, it will be 0.
* @return executionFeeY The execution fee of token Y, if the order is executed. If the order is cancelled or was
* already executed, it will be 0.
*/
function getCurrentAmounts(
IERC20 tokenX,
IERC20 tokenY,
uint16 binStep,
OrderType orderType,
uint24 binId,
address user
) external view override returns (uint256 amountX, uint256 amountY, uint256 executionFeeX, uint256 executionFeeY) {
ILBPair lbPair = _getLBPair(tokenX, tokenY, binStep);
bytes32 orderKey = _getOrderKey(lbPair, orderType, binId);
Order storage order = _orders[user][orderKey];
Position storage position = _positions[orderKey].at[order.positionId];
uint256 orderLiquidity = order.liquidity;
if (position.withdrawn) {
uint256 amount = orderLiquidity.mulDivRoundDown(position.amount, position.liquidity);
(amountX, amountY) = orderType == OrderType.BID ? (amount, uint256(0)) : (uint256(0), amount);
} else {
uint256 totalLiquidity = lbPair.totalSupply(binId);
if (totalLiquidity == 0) return (0, 0, 0, 0);
(uint256 binReserveX, uint256 binReserveY) = lbPair.getBin(binId);
amountX = orderLiquidity.mulDivRoundDown(binReserveX, totalLiquidity);
amountY = orderLiquidity.mulDivRoundDown(binReserveY, totalLiquidity);
(executionFeeX, executionFeeY) = _getExecutionFee(lbPair, amountX, amountY);
}
}
/**
* @notice Preview the execution fee sent to the executor if the order is executed.
* @dev This is the base fee minus the protocol fee of the liquidity book pair.
* @param tokenX The token X of the liquidity book pair.
* @param tokenY The token Y of the liquidity book pair.
* @param binStep The bin step of the liquidity book pair.
* @return fee The executor fee, in 1e18 precision.
*/
function getExecutionFee(IERC20 tokenX, IERC20 tokenY, uint16 binStep)
external
view
override
returns (uint256 fee)
{
ILBPair lbPair = _getLBPair(tokenX, tokenY, binStep);
(fee,) = _getExecutionFee(lbPair, 1e18, 1e18);
}
/**
* @notice Place an order.
* @param tokenX The token X of the liquidity book pair.
* @param tokenY The token Y of the liquidity book pair.
* @param binStep The bin step of the liquidity book pair.
* @param orderType The order type (bid or ask).
* @param binId The bin id of the order, which is the price of the order.
* @param amount The amount of the order.
* @return orderPlaced True if the order was placed, false otherwise.
* @return orderPositionId The position id of the order.
*/
function placeOrder(IERC20 tokenX, IERC20 tokenY, uint16 binStep, OrderType orderType, uint24 binId, uint256 amount)
external
payable
override
nonReentrant
returns (bool orderPlaced, uint256 orderPositionId)
{
(IERC20 tokenIn, IERC20 tokenOut) = orderType == OrderType.BID ? (tokenY, tokenX) : (tokenX, tokenY);
if (
(address(tokenIn) != address(0) && msg.value != 0) || (address(tokenIn) == address(0) && amount > msg.value)
) {
revert LimitOrderManager__InvalidNativeAmount();
}
ILBPair lbPair = _getLBPair(tokenX, tokenY, binStep);
(orderPlaced, orderPositionId) = _placeOrder(lbPair, tokenIn, tokenOut, amount, orderType, binId);
if (!orderPlaced) amount = 0;
if (msg.value > amount) _transferNativeToken(msg.sender, msg.value - amount);
}
/**
* @notice Cancel an order.
* @param tokenX The token X of the liquidity book pair.
* @param tokenY The token Y of the liquidity book pair.
* @param binStep The bin step of the liquidity book pair.
* @param orderType The order type (bid or ask).
* @param binId The bin id of the order, which is the price of the order.
* @param minAmountX The minimum amount of token X to receive.
* @param minAmountY The minimum amount of token Y to receive.
* @return orderPositionId The position id of the order.
*/
function cancelOrder(
IERC20 tokenX,
IERC20 tokenY,
uint16 binStep,
OrderType orderType,
uint24 binId,
uint256 minAmountX,
uint256 minAmountY
) external override nonReentrant returns (uint256 orderPositionId) {
ILBPair lbPair = _getLBPair(tokenX, tokenY, binStep);
return _cancelOrder(lbPair, tokenX, tokenY, orderType, binId, minAmountX, minAmountY);
}
/**
* @notice Claim an order.
* @param tokenX The token X of the liquidity book pair.
* @param tokenY The token Y of the liquidity book pair.
* @param binStep The bin step of the liquidity book pair.
* @param orderType The order type (bid or ask).
* @param binId The bin id of the order, which is the price of the order.
* @return orderPositionId The position id of the order.
*/
function claimOrder(IERC20 tokenX, IERC20 tokenY, uint16 binStep, OrderType orderType, uint24 binId)
external
override
nonReentrant
returns (uint256 orderPositionId)
{
ILBPair lbPair = _getLBPair(tokenX, tokenY, binStep);
return _claimOrder(lbPair, tokenX, tokenY, orderType, binId);
}
/**
* @notice Execute an order.
* @param tokenX The token X of the liquidity book pair.
* @param tokenY The token Y of the liquidity book pair.
* @param binStep The bin step of the liquidity book pair.
* @param orderType The order type (bid or ask).
* @param binId The bin id of the order, which is the price of the order.
* @return executed True if the order was executed, false otherwise.
* @return positionId The position id.
*/
function executeOrders(IERC20 tokenX, IERC20 tokenY, uint16 binStep, OrderType orderType, uint24 binId)
external
override
nonReentrant
returns (bool executed, uint256 positionId)
{
ILBPair lbPair = _getLBPair(tokenX, tokenY, binStep);
return _executeOrders(lbPair, tokenX, tokenY, orderType, binId);
}
/**
* @notice Place multiple orders.
* @param orders The orders to place.
* @return orderPlaced True if the order was placed, false otherwise.
* @return orderPositionIds The position ids of the orders.
*/
function batchPlaceOrders(PlaceOrderParams[] calldata orders)
external
payable
override
nonReentrant
returns (bool[] memory orderPlaced, uint256[] memory orderPositionIds)
{
if (orders.length == 0) revert LimitOrderManager__InvalidBatchLength();
uint256 nativeAmount;
orderPositionIds = new uint256[](orders.length);
orderPlaced = new bool[](orders.length);
for (uint256 i; i < orders.length;) {
PlaceOrderParams calldata order = orders[i];
(IERC20 tokenIn, IERC20 tokenOut) =
order.orderType == OrderType.BID ? (order.tokenY, order.tokenX) : (order.tokenX, order.tokenY);
if (address(tokenIn) == address(0) && (nativeAmount += order.amount) > msg.value) {
revert LimitOrderManager__InvalidNativeAmount();
}
ILBPair lbPair = _getLBPair(order.tokenX, order.tokenY, order.binStep);
(bool placed, uint256 positionId) =
_placeOrder(lbPair, tokenIn, tokenOut, order.amount, order.orderType, order.binId);
orderPlaced[i] = placed;
orderPositionIds[i] = positionId;
if (address(tokenIn) == address(0) && !placed) nativeAmount -= order.amount;
unchecked {
++i;
}
}
if (msg.value > nativeAmount) _transferNativeToken(msg.sender, msg.value - nativeAmount);
}
/**
* @notice Cancel multiple orders.
* @param orders The orders to cancel.
* @return orderPositionIds The position ids of the orders.
*/
function batchCancelOrders(CancelOrderParams[] calldata orders)
external
override
nonReentrant
returns (uint256[] memory orderPositionIds)
{
if (orders.length == 0) revert LimitOrderManager__InvalidBatchLength();
orderPositionIds = new uint256[](orders.length);
for (uint256 i; i < orders.length;) {
CancelOrderParams calldata order = orders[i];
ILBPair lbPair = _getLBPair(order.tokenX, order.tokenY, order.binStep);
orderPositionIds[i] = _cancelOrder(
lbPair, order.tokenX, order.tokenY, order.orderType, order.binId, order.minAmountX, order.minAmountY
);
unchecked {
++i;
}
}
}
/**
* @notice Claim multiple orders.
* @param orders The orders to claim.
* @return orderPositionIds The position ids of the orders.
*/
function batchClaimOrders(OrderParams[] calldata orders)
external
override
nonReentrant
returns (uint256[] memory orderPositionIds)
{
if (orders.length == 0) revert LimitOrderManager__InvalidBatchLength();
orderPositionIds = new uint256[](orders.length);
for (uint256 i; i < orders.length;) {
OrderParams calldata order = orders[i];
ILBPair lbPair = _getLBPair(order.tokenX, order.tokenY, order.binStep);
orderPositionIds[i] = _claimOrder(lbPair, order.tokenX, order.tokenY, order.orderType, order.binId);
unchecked {
++i;
}
}
}
/**
* @notice Execute multiple orders.
* @param orders The orders to execute.
* @return orderExecuted True if the order was executed, false otherwise.
* @return orderPositionIds The position ids of the orders.
*/
function batchExecuteOrders(OrderParams[] calldata orders)
external
override
nonReentrant
returns (bool[] memory orderExecuted, uint256[] memory orderPositionIds)
{
if (orders.length == 0) revert LimitOrderManager__InvalidBatchLength();
orderPositionIds = new uint256[](orders.length);
orderExecuted = new bool[](orders.length);
for (uint256 i; i < orders.length;) {
OrderParams calldata order = orders[i];
ILBPair lbPair = _getLBPair(order.tokenX, order.tokenY, order.binStep);
(orderExecuted[i], orderPositionIds[i]) =
_executeOrders(lbPair, order.tokenX, order.tokenY, order.orderType, order.binId);
unchecked {
++i;
}
}
}
/**
* @notice Place multiple orders for the same pair.
* @dev This function saves a bit of gas, as it avoids calling multiple time the _getLBPair function.
* @param tokenX The token X of the liquidity book pair.
* @param tokenY The token Y of the liquidity book pair.
* @param binStep The bin step of the liquidity book pair.
* @param orders The orders to place.
* @return orderPlaced True if the order was placed, false otherwise.
* @return orderPositionIds The position ids of the orders.
*/
function batchPlaceOrdersSamePair(
IERC20 tokenX,
IERC20 tokenY,
uint16 binStep,
PlaceOrderParamsSamePair[] calldata orders
) external payable override nonReentrant returns (bool[] memory orderPlaced, uint256[] memory orderPositionIds) {
if (orders.length == 0) revert LimitOrderManager__InvalidBatchLength();
orderPositionIds = new uint256[](orders.length);
orderPlaced = new bool[](orders.length);
uint256 nativeAmount;
ILBPair lbPair = _getLBPair(tokenX, tokenY, binStep);
for (uint256 i; i < orders.length;) {
PlaceOrderParamsSamePair calldata order = orders[i];
(IERC20 tokenIn, IERC20 tokenOut) = order.orderType == OrderType.BID ? (tokenY, tokenX) : (tokenX, tokenY);
if (address(tokenIn) == address(0) && (nativeAmount += order.amount) > msg.value) {
revert LimitOrderManager__InvalidNativeAmount();
}
(bool placed, uint256 positionId) =
_placeOrder(lbPair, tokenIn, tokenOut, order.amount, order.orderType, order.binId);
orderPlaced[i] = placed;
orderPositionIds[i] = positionId;
if (address(tokenIn) == address(0) && !placed) nativeAmount -= order.amount;
unchecked {
++i;
}
}
if (msg.value > nativeAmount) _transferNativeToken(msg.sender, msg.value - nativeAmount);
}
/**
* @notice Cancel multiple orders for the same pair.
* @dev This function saves a bit of gas, as it avoids calling multiple time the _getLBPair function.
* @param tokenX The token X of the liquidity book pair.
* @param tokenY The token Y of the liquidity book pair.
* @param binStep The bin step of the liquidity book pair.
* @param orders The orders to cancel.
* @return orderPositionIds The position ids of the orders.
*/
function batchCancelOrdersSamePair(
IERC20 tokenX,
IERC20 tokenY,
uint16 binStep,
CancelOrderParamsSamePair[] calldata orders
) external override nonReentrant returns (uint256[] memory orderPositionIds) {
if (orders.length == 0) revert LimitOrderManager__InvalidBatchLength();
orderPositionIds = new uint256[](orders.length);
ILBPair lbPair = _getLBPair(tokenX, tokenY, binStep);
for (uint256 i; i < orders.length;) {
CancelOrderParamsSamePair calldata order = orders[i];
orderPositionIds[i] =
_cancelOrder(lbPair, tokenX, tokenY, order.orderType, order.binId, order.minAmountX, order.minAmountY);
unchecked {
++i;
}
}
}
/**
* @notice Claim multiple orders for the same pair.
* @dev This function saves a bit of gas, as it avoids calling multiple time the _getLBPair function.
* @param tokenX The token X of the liquidity book pair.
* @param tokenY The token Y of the liquidity book pair.
* @param binStep The bin step of the liquidity book pair.
* @param orders The orders to claim.
* @return orderPositionIds The position ids of the orders.
*/
function batchClaimOrdersSamePair(
IERC20 tokenX,
IERC20 tokenY,
uint16 binStep,
OrderParamsSamePair[] calldata orders
) external override nonReentrant returns (uint256[] memory orderPositionIds) {
if (orders.length == 0) revert LimitOrderManager__InvalidBatchLength();
orderPositionIds = new uint256[](orders.length);
ILBPair lbPair = _getLBPair(tokenX, tokenY, binStep);
for (uint256 i; i < orders.length;) {
OrderParamsSamePair calldata order = orders[i];
orderPositionIds[i] = _claimOrder(lbPair, tokenX, tokenY, order.orderType, order.binId);
unchecked {
++i;
}
}
}
/**
* @notice Execute multiple orders for the same pair.
* @dev This function saves a bit of gas, as it avoids calling multiple time the _getLBPair function.
* @param tokenX The token X of the liquidity book pair.
* @param tokenY The token Y of the liquidity book pair.
* @param binStep The bin step of the liquidity book pair.
* @param orders The orders to execute.
* @return orderExecuted Whether the orders have been executed.
* @return orderPositionIds The position ids of the orders.
*/
function batchExecuteOrdersSamePair(
IERC20 tokenX,
IERC20 tokenY,
uint16 binStep,
OrderParamsSamePair[] calldata orders
) external override nonReentrant returns (bool[] memory orderExecuted, uint256[] memory orderPositionIds) {
if (orders.length == 0) revert LimitOrderManager__InvalidBatchLength();
orderPositionIds = new uint256[](orders.length);
orderExecuted = new bool[](orders.length);
ILBPair lbPair = _getLBPair(tokenX, tokenY, binStep);
for (uint256 i; i < orders.length;) {
OrderParamsSamePair calldata order = orders[i];
(orderExecuted[i], orderPositionIds[i]) =
_executeOrders(lbPair, tokenX, tokenY, order.orderType, order.binId);
unchecked {
++i;
}
}
}
/**
* @notice Sets the executor fee share.
* @dev Only the factory owner can call this function. The remaining share is sent to the users.
* @param executorFeeShare The executor fee share, in basis points.
*/
function setExecutorFeeShare(uint256 executorFeeShare) external override {
if (msg.sender != _factory.owner()) revert LimitOrderManager__OnlyFactoryOwner();
_setExecutorFeeShare(executorFeeShare);
}
/**
* @notice Allow the contract to receive native token, only if they come from the wrapped native token contract.
*/
receive() external payable {
if (msg.sender != address(_wNative)) revert LimitOrderManager__OnlyWNative();
}
/**
* @dev Get the liquidity book pair address from the factory.
* @param tokenX The token X of the liquidity book pair.
* @param tokenY The token Y of the liquidity book pair.
* @param binStep The bin step of the liquidity book pair.
* @return lbPair The liquidity book pair.
*/
function _getLBPair(IERC20 tokenX, IERC20 tokenY, uint16 binStep) private view returns (ILBPair lbPair) {
tokenX = address(tokenX) == address(0) ? IERC20(address(_wNative)) : tokenX;
tokenY = address(tokenY) == address(0) ? IERC20(address(_wNative)) : tokenY;
lbPair = _factory.getLBPairInformation(tokenX, tokenY, binStep).LBPair;
// Check if the liquidity book pair is valid, that is, if the lbPair address is not 0.
if (address(lbPair) == address(0)) revert LimitOrderManager__InvalidPair();
// Check if the token X of the liquidity book pair is the same as the token X of the order.
// We revert here because if the tokens are in the wrong order, then the price of the order will be wrong.
if (lbPair.getTokenX() != tokenX) revert LimitOrderManager__InvalidTokenOrder();
}
/**
* @dev Return whether the order is valid or not.
* An order is valid if the order type is bid and the bin id is lower than the active id,
* or if the order type is ask and the bin id is greater than the active id. This is to prevent adding
* orders to the active bin and to add liquidity to a bin that can't receive the token sent.
* @param lbPair The liquidity book pair.
* @param orderType The order type (bid or ask).
* @param binId The bin id of the order, which is the price of the order.
* @return valid Whether the order is valid or not.
*/
function _isOrderValid(ILBPair lbPair, OrderType orderType, uint24 binId) private view returns (bool) {
uint24 activeId = lbPair.getActiveId();
return ((orderType == OrderType.BID && binId < activeId) || (orderType == OrderType.ASK && binId > activeId));
}
/**
* @dev Return whether the order is executable or not.
* An order is executable if the bin was crossed, if the order type is bid and the bin id is now lower than
* to the active id, or if the order type is ask and the bin id is now greater than the active id.
* This is to only allow executing orders that are fully filled.
* @param lbPair The liquidity book pair.
* @param orderType The order type (bid or ask).
* @param binId The bin id of the order, which is the price of the order.
* @return executable Whether the order is executable or not.
*/
function _isOrderExecutable(ILBPair lbPair, OrderType orderType, uint24 binId) private view returns (bool) {
uint24 activeId = lbPair.getActiveId();
return ((orderType == OrderType.BID && binId > activeId) || (orderType == OrderType.ASK && binId < activeId));
}
/**
* @dev Transfer the amount of token to the recipient. If the token is the zero address, then transfer the amount
* of native token to the recipient.
* @param token The token to transfer.
* @param to The recipient of the transfer.
* @param amount The amount to transfer.
*/
function _transfer(IERC20 token, address to, uint256 amount) private {
if (address(token) == address(0)) {
_wNative.withdraw(amount);
_transferNativeToken(to, amount);
} else {
token.safeTransfer(to, amount);
}
}
/**
* @dev Transfer native token to the recipient.
* @param to The recipient of the transfer.
* @param amount The amount to transfer.
*/
function _transferNativeToken(address to, uint256 amount) private {
(bool success,) = to.call{value: amount}("");
if (!success) revert LimitOrderManager__TransferFailed();
}
/**
* @dev Transfer the amount of token from the sender to the recipient. If the token is the zero address, then
* first deposit the amount of native token from the sender to the contract, then transfer the amount of native
* token from the contract to the recipient.
* @param token The token to transfer.
* @param to The recipient of the transfer.
* @param amount The amount to transfer.
*/
function _transferFromSender(IERC20 token, address to, uint256 amount) private {
if (address(token) == address(0)) {
_wNative.deposit{value: amount}();
IERC20(_wNative).safeTransfer(to, amount);
} else {
token.safeTransferFrom(msg.sender, to, amount);
}
}
/**
* @dev Place an order.
* If the user already have an order with the same parameters and that it's not executed yet, instead of creating a
* new order, the amount of the previous order is increased by the amount of the new order.
* If the user already have an order with the same parameters and that it's executed, the order is claimed if
* it was not claimed yet and a new order is created overwriting the previous one.
* @param lbPair The liquidity book pair.
* @param tokenIn The token in of the order.
* @param tokenOut The token out of the order.
* @param amount The amount of the order.
* @param orderType The order type (bid or ask).
* @param binId The bin id of the order, which is the price of the order.
* @return orderPlaced True if the order was placed, false otherwise.
* @return orderPositionId The position id of the order.
*/
function _placeOrder(
ILBPair lbPair,
IERC20 tokenIn,
IERC20 tokenOut,
uint256 amount,
OrderType orderType,
uint24 binId
) private returns (bool orderPlaced, uint256 orderPositionId) {
// Check if the order is valid.
if (!_isOrderValid(lbPair, orderType, binId)) return (false, 0);
// Deposit the amount sent by the user to the liquidity book pair.
(bytes32 amounts, uint256 liquidity) = _depositToLBPair(lbPair, tokenIn, orderType, binId, amount);
// Get the order key.
bytes32 orderKey = _getOrderKey(lbPair, orderType, binId);
// Get the position of the order.
Positions storage positions = _positions[orderKey];
// Get the last position id and the last position.
uint256 positionId = positions.lastId;
Position storage position = positions.at[positionId];
// If the last position id is 0 or the last position is withdrawn, create a new position.
if (positionId == 0 || position.withdrawn) {
++positionId;
positions.lastId = positionId;
position = positions.at[positionId];
}
// Update the liquidity of the position.
position.liquidity += liquidity;
// Get the current user order.
Order storage order = _orders[msg.sender][orderKey];
// Get the position id of the current user order.
orderPositionId = order.positionId;
// If the position id of the order is smaller than the current position id, the order needs to be claimed,
// unless the position id of the order is 0.
if (orderPositionId < positionId) {
// If the position id of the order is not 0, claim the order from the position.
if (orderPositionId != 0) {
_claimOrderFromPosition(positions.at[orderPositionId], order, tokenOut, orderPositionId, orderKey);
}
// Set the position id of the order to the current position id.
orderPositionId = positionId;
order.positionId = orderPositionId;
}
// Update the order liquidity.
order.liquidity += liquidity;
emit OrderPlaced(
msg.sender, lbPair, binId, orderType, orderPositionId, liquidity, amounts.decodeX(), amounts.decodeY()
);
return (true, orderPositionId);
}
/**
* @dev Claim an order.
* If the order is not claimable, the function reverts.
* If the order is not claimable but executable, the order is first executed and then claimed.
* If the order is claimable, the order is claimed and the user receives the tokens.
* @param lbPair The liquidity book pair.
* @param orderType The order type (bid or ask).
* @param binId The bin id of the order, which is the price of the order.
* @return orderPositionId The position id of the order.
*/
function _claimOrder(ILBPair lbPair, IERC20 tokenX, IERC20 tokenY, OrderType orderType, uint24 binId)
private
returns (uint256 orderPositionId)
{
// Get the order key.
bytes32 orderKey = _getOrderKey(lbPair, orderType, binId);
// Get the current user order.
Order storage order = _orders[msg.sender][orderKey];
// Get the position id of the current user order.
orderPositionId = order.positionId;
// If the position id of the order is 0, the order is not claimable, therefore revert.
if (orderPositionId == 0) revert LimitOrderManager__OrderNotClaimable();
// Get the position of the order.
Position storage position = _positions[orderKey].at[orderPositionId];
// If the position is not withdrawn, try to execute the order.
if (!position.withdrawn) {
(bool orderExecuted,) = _executeOrders(lbPair, tokenX, tokenY, orderType, binId);
if (!orderExecuted) revert LimitOrderManager__OrderNotExecutable();
}
// Claim the order from the position, which will transfer the amount of the filled order to the user.
_claimOrderFromPosition(
position, order, orderType == OrderType.BID ? tokenX : tokenY, orderPositionId, orderKey
);
}
/**
* @dev Claim an order from a position.
* This function does not check if the order is claimable or not, therefore it needs to be called by a function
* that does the necessary checks.
* @param position The position of the order.
* @param order The order.
* @param token The token of the order.
* @param orderPositionId The position id of the order.
* @param orderKey The order key.
*/
function _claimOrderFromPosition(
Position storage position,
Order storage order,
IERC20 token,
uint256 orderPositionId,
bytes32 orderKey
) private {
// Get the order liquidity.
uint256 orderLiquidity = order.liquidity;
// Set the order liquidity and position id to 0.
order.positionId = 0;
order.liquidity = 0;
// Calculate the amount of the order.
uint256 amount = orderLiquidity.mulDivRoundDown(position.amount, position.liquidity);
// Update the liquidity and the amount of the position from the amounts withdrawn.
position.amount -= uint128(amount);
position.liquidity -= orderLiquidity;
// Transfer the amount of the order to the user.
_transfer(token, msg.sender, amount);
// Get the order key components (liquidity book pair, order type, bin id) from the order key to emit the event.
(ILBPair lbPair, OrderType orderType, uint24 binId) = _getOrderKeyComponents(orderKey);
(uint256 amountX, uint256 amountY) = orderType == OrderType.BID ? (amount, uint256(0)) : (uint256(0), amount);
emit OrderClaimed(msg.sender, lbPair, binId, orderType, orderPositionId, orderLiquidity, amountX, amountY);
}
/**
* @dev Cancel an order.
* If the order is not placed, the function reverts.
* If the order is already executed, the function reverts.
* If the order is placed, the order is cancelled and the liquidity is withdrawn from the liquidity book pair.
* The liquidity is then transferred back to the user (the amounts depend on the bin composition).
* @param lbPair The liquidity book pair.
* @param tokenX The token X of the liquidity book pair.
* @param tokenY The token Y of the liquidity book pair.
* @param orderType The order type (bid or ask).
* @param binId The bin id of the order, which is the price of the order.
* @param minAmountX The minimum amount of token X to receive on withdrawal from the liquidity book pair.
* @param minAmountY The minimum amount of token Y to receive on withdrawal from the liquidity book pair.
* @return orderPositionId The position id of the order.
*/
function _cancelOrder(
ILBPair lbPair,
IERC20 tokenX,
IERC20 tokenY,
OrderType orderType,
uint24 binId,
uint256 minAmountX,
uint256 minAmountY
) private returns (uint256 orderPositionId) {
// Get the order key.
bytes32 orderKey = _getOrderKey(lbPair, orderType, binId);
// Get the current user order.
Order storage order = _orders[msg.sender][orderKey];
// Get the position id of the current user order.
orderPositionId = order.positionId;
// If the position id of the order is 0, the order is not placed, therefore revert.
if (orderPositionId == 0) revert LimitOrderManager__OrderNotPlaced();
// Get the position of the order.
Position storage position = _positions[orderKey].at[orderPositionId];
// If the position is withdrawn, the order is already executed, therefore revert.
if (position.withdrawn) revert LimitOrderManager__OrderAlreadyExecuted();
// Get the order liquidity.
uint256 orderLiquidity = order.liquidity;
// Set the order liquidity and position id to 0.
order.positionId = 0;
order.liquidity = 0;