-
Notifications
You must be signed in to change notification settings - Fork 51
/
LBRouter.sol
1149 lines (990 loc) Β· 44.7 KB
/
LBRouter.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.20;
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {BinHelper} from "./libraries/BinHelper.sol";
import {Constants} from "./libraries/Constants.sol";
import {Encoded} from "./libraries/math/Encoded.sol";
import {FeeHelper} from "./libraries/FeeHelper.sol";
import {JoeLibrary} from "./libraries/JoeLibrary.sol";
import {LiquidityConfigurations} from "./libraries/math/LiquidityConfigurations.sol";
import {PackedUint128Math} from "./libraries/math/PackedUint128Math.sol";
import {TokenHelper, IERC20} from "./libraries/TokenHelper.sol";
import {Uint256x256Math} from "./libraries/math/Uint256x256Math.sol";
import {IJoePair} from "./interfaces/IJoePair.sol";
import {ILBPair} from "./interfaces/ILBPair.sol";
import {ILBLegacyPair} from "./interfaces/ILBLegacyPair.sol";
import {ILBToken} from "./interfaces/ILBToken.sol";
import {ILBRouter} from "./interfaces/ILBRouter.sol";
import {ILBLegacyRouter} from "./interfaces/ILBLegacyRouter.sol";
import {IJoeFactory} from "./interfaces/IJoeFactory.sol";
import {ILBLegacyFactory} from "./interfaces/ILBLegacyFactory.sol";
import {ILBFactory} from "./interfaces/ILBFactory.sol";
import {IWNATIVE} from "./interfaces/IWNATIVE.sol";
/**
* @title Liquidity Book Router
* @author Trader Joe
* @notice Main contract to interact with to swap and manage liquidity on Joe V2 exchange.
*/
contract LBRouter is ILBRouter {
using TokenHelper for IERC20;
using JoeLibrary for uint256;
using PackedUint128Math for bytes32;
ILBFactory private immutable _factory2_2;
ILBFactory private immutable _factory2_1;
IJoeFactory private immutable _factoryV1;
ILBLegacyFactory private immutable _legacyFactory;
ILBLegacyRouter private immutable _legacyRouter;
IWNATIVE private immutable _wnative;
modifier onlyFactoryOwner() {
if (msg.sender != Ownable(address(_factory2_2)).owner()) revert LBRouter__NotFactoryOwner();
_;
}
modifier ensure(uint256 deadline) {
if (block.timestamp > deadline) revert LBRouter__DeadlineExceeded(deadline, block.timestamp);
_;
}
modifier verifyPathValidity(Path memory path) {
if (
path.pairBinSteps.length == 0 || path.versions.length != path.pairBinSteps.length
|| path.pairBinSteps.length + 1 != path.tokenPath.length
) revert LBRouter__LengthsMismatch();
_;
}
/**
* @notice Constructor
* @param factory2_2 Address of Joe V2.2 factory
* @param factory2_1 Address of Joe V2.1 factory
* @param factoryV1 Address of Joe V1 factory
* @param legacyFactory Address of Joe V2 factory
* @param legacyRouter Address of Joe V2 router
* @param wnative Address of WNATIVE
*/
constructor(
ILBFactory factory2_2,
IJoeFactory factoryV1,
ILBLegacyFactory legacyFactory,
ILBLegacyRouter legacyRouter,
ILBFactory factory2_1,
IWNATIVE wnative
) {
_factory2_2 = factory2_2;
_factory2_1 = factory2_1;
_factoryV1 = factoryV1;
_legacyFactory = legacyFactory;
_legacyRouter = legacyRouter;
_wnative = wnative;
}
/**
* @dev Receive function that only accept NATIVE from the WNATIVE contract
*/
receive() external payable {
if (msg.sender != address(_wnative)) revert LBRouter__SenderIsNotWNATIVE();
}
/**
* View function to get the factory V2.1 address
* @return lbFactory The address of the factory V2.1
*/
function getFactory() external view override returns (ILBFactory lbFactory) {
return _factory2_2;
}
/**
* View function to get the factory V2.1 address
* @return lbFactory The address of the factory V2.1
*/
function getFactoryV2_1() external view override returns (ILBFactory lbFactory) {
return _factory2_1;
}
/**
* View function to get the factory V2 address
* @return legacyLBfactory The address of the factory V2
*/
function getLegacyFactory() external view override returns (ILBLegacyFactory legacyLBfactory) {
return _legacyFactory;
}
/**
* View function to get the factory V1 address
* @return factoryV1 The address of the factory V1
*/
function getV1Factory() external view override returns (IJoeFactory factoryV1) {
return _factoryV1;
}
/**
* View function to get the router V2 address
* @return legacyRouter The address of the router V2
*/
function getLegacyRouter() external view override returns (ILBLegacyRouter legacyRouter) {
return _legacyRouter;
}
/**
* View function to get the WNATIVE address
* @return wnative The address of WNATIVE
*/
function getWNATIVE() external view override returns (IWNATIVE wnative) {
return _wnative;
}
/**
* @notice Returns the approximate id corresponding to the inputted price.
* Warning, the returned id may be inaccurate close to the start price of a bin
* @param pair The address of the LBPair
* @param price The price of y per x (multiplied by 1e36)
* @return The id corresponding to this price
*/
function getIdFromPrice(ILBPair pair, uint256 price) external view override returns (uint24) {
return pair.getIdFromPrice(price);
}
/**
* @notice Returns the price corresponding to the inputted id
* @param pair The address of the LBPair
* @param id The id
* @return The price corresponding to this id
*/
function getPriceFromId(ILBPair pair, uint24 id) external view override returns (uint256) {
return pair.getPriceFromId(id);
}
/**
* @notice Simulate a swap in
* @param pair The address of the LBPair
* @param amountOut The amount of token to receive
* @param swapForY Whether you swap X for Y (true), or Y for X (false)
* @return amountIn The amount of token to send in order to receive amountOut token
* @return amountOutLeft The amount of token Out that can't be returned due to a lack of liquidity
* @return fee The amount of fees paid in token sent
*/
function getSwapIn(ILBPair pair, uint128 amountOut, bool swapForY)
public
view
override
returns (uint128 amountIn, uint128 amountOutLeft, uint128 fee)
{
(amountIn, amountOutLeft, fee) = pair.getSwapIn(amountOut, swapForY);
}
/**
* @notice Simulate a swap out
* @param pair The address of the LBPair
* @param amountIn The amount of token sent
* @param swapForY Whether you swap X for Y (true), or Y for X (false)
* @return amountInLeft The amount of token In that can't be swapped due to a lack of liquidity
* @return amountOut The amount of token received if amountIn tokenX are sent
* @return fee The amount of fees paid in token sent
*/
function getSwapOut(ILBPair pair, uint128 amountIn, bool swapForY)
external
view
override
returns (uint128 amountInLeft, uint128 amountOut, uint128 fee)
{
(amountInLeft, amountOut, fee) = pair.getSwapOut(amountIn, swapForY);
}
/**
* @notice Create a liquidity bin LBPair for tokenX and tokenY using the factory
* @param tokenX The address of the first token
* @param tokenY The address of the second token
* @param activeId The active id of the pair
* @param binStep The bin step in basis point, used to calculate log(1 + binStep)
* @return pair The address of the newly created LBPair
*/
function createLBPair(IERC20 tokenX, IERC20 tokenY, uint24 activeId, uint16 binStep)
external
override
returns (ILBPair pair)
{
pair = _factory2_2.createLBPair(tokenX, tokenY, activeId, binStep);
}
/**
* @notice Add liquidity while performing safety checks
* @dev This function is compliant with fee on transfer tokens
* @param liquidityParameters The liquidity parameters
* @return amountXAdded The amount of token X added
* @return amountYAdded The amount of token Y added
* @return amountXLeft The amount of token X left (sent back to liquidityParameters.refundTo)
* @return amountYLeft The amount of token Y left (sent back to liquidityParameters.refundTo)
* @return depositIds The ids of the deposits
* @return liquidityMinted The amount of liquidity minted
*/
function addLiquidity(LiquidityParameters calldata liquidityParameters)
external
override
returns (
uint256 amountXAdded,
uint256 amountYAdded,
uint256 amountXLeft,
uint256 amountYLeft,
uint256[] memory depositIds,
uint256[] memory liquidityMinted
)
{
ILBPair lbPair = ILBPair(
_getLBPairInformation(
liquidityParameters.tokenX, liquidityParameters.tokenY, liquidityParameters.binStep, Version.V2_2
)
);
if (liquidityParameters.tokenX != lbPair.getTokenX()) revert LBRouter__WrongTokenOrder();
_safeTransferFrom(liquidityParameters.tokenX, msg.sender, address(lbPair), liquidityParameters.amountX);
_safeTransferFrom(liquidityParameters.tokenY, msg.sender, address(lbPair), liquidityParameters.amountY);
(amountXAdded, amountYAdded, amountXLeft, amountYLeft, depositIds, liquidityMinted) =
_addLiquidity(liquidityParameters, lbPair);
}
/**
* @notice Add liquidity with NATIVE while performing safety checks
* @dev This function is compliant with fee on transfer tokens
* @param liquidityParameters The liquidity parameters
* @return amountXAdded The amount of token X added
* @return amountYAdded The amount of token Y added
* @return amountXLeft The amount of token X left (sent back to liquidityParameters.refundTo)
* @return amountYLeft The amount of token Y left (sent back to liquidityParameters.refundTo)
* @return depositIds The ids of the deposits
* @return liquidityMinted The amount of liquidity minted
*/
function addLiquidityNATIVE(LiquidityParameters calldata liquidityParameters)
external
payable
override
returns (
uint256 amountXAdded,
uint256 amountYAdded,
uint256 amountXLeft,
uint256 amountYLeft,
uint256[] memory depositIds,
uint256[] memory liquidityMinted
)
{
ILBPair _LBPair = ILBPair(
_getLBPairInformation(
liquidityParameters.tokenX, liquidityParameters.tokenY, liquidityParameters.binStep, Version.V2_2
)
);
if (liquidityParameters.tokenX != _LBPair.getTokenX()) revert LBRouter__WrongTokenOrder();
if (liquidityParameters.tokenX == _wnative && liquidityParameters.amountX == msg.value) {
_safeTransferFrom(liquidityParameters.tokenY, msg.sender, address(_LBPair), liquidityParameters.amountY);
_wNativeDepositAndTransfer(address(_LBPair), msg.value);
} else if (liquidityParameters.tokenY == _wnative && liquidityParameters.amountY == msg.value) {
_safeTransferFrom(liquidityParameters.tokenX, msg.sender, address(_LBPair), liquidityParameters.amountX);
_wNativeDepositAndTransfer(address(_LBPair), msg.value);
} else {
revert LBRouter__WrongNativeLiquidityParameters(
address(liquidityParameters.tokenX),
address(liquidityParameters.tokenY),
liquidityParameters.amountX,
liquidityParameters.amountY,
msg.value
);
}
(amountXAdded, amountYAdded, amountXLeft, amountYLeft, depositIds, liquidityMinted) =
_addLiquidity(liquidityParameters, _LBPair);
}
/**
* @notice Remove liquidity while performing safety checks
* @dev This function is compliant with fee on transfer tokens
* @param tokenX The address of token X
* @param tokenY The address of token Y
* @param binStep The bin step of the LBPair
* @param amountXMin The min amount to receive of token X
* @param amountYMin The min amount to receive of token Y
* @param ids The list of ids to burn
* @param amounts The list of amounts to burn of each id in `_ids`
* @param to The address of the recipient
* @param deadline The deadline of the tx
* @return amountX Amount of token X returned
* @return amountY Amount of token Y returned
*/
function removeLiquidity(
IERC20 tokenX,
IERC20 tokenY,
uint16 binStep,
uint256 amountXMin,
uint256 amountYMin,
uint256[] memory ids,
uint256[] memory amounts,
address to,
uint256 deadline
) external override ensure(deadline) returns (uint256 amountX, uint256 amountY) {
ILBPair _LBPair = ILBPair(_getLBPairInformation(tokenX, tokenY, binStep, Version.V2_2));
bool isWrongOrder = tokenX != _LBPair.getTokenX();
if (isWrongOrder) (amountXMin, amountYMin) = (amountYMin, amountXMin);
(amountX, amountY) = _removeLiquidity(_LBPair, amountXMin, amountYMin, ids, amounts, to);
if (isWrongOrder) (amountX, amountY) = (amountY, amountX);
}
/**
* @notice Remove NATIVE liquidity while performing safety checks
* @dev This function is **NOT** compliant with fee on transfer tokens.
* This is wanted as it would make users pays the fee on transfer twice,
* use the `removeLiquidity` function to remove liquidity with fee on transfer tokens.
* @param token The address of token
* @param binStep The bin step of the LBPair
* @param amountTokenMin The min amount to receive of token
* @param amountNATIVEMin The min amount to receive of NATIVE
* @param ids The list of ids to burn
* @param amounts The list of amounts to burn of each id in `_ids`
* @param to The address of the recipient
* @param deadline The deadline of the tx
* @return amountToken Amount of token returned
* @return amountNATIVE Amount of NATIVE returned
*/
function removeLiquidityNATIVE(
IERC20 token,
uint16 binStep,
uint256 amountTokenMin,
uint256 amountNATIVEMin,
uint256[] memory ids,
uint256[] memory amounts,
address payable to,
uint256 deadline
) external override ensure(deadline) returns (uint256 amountToken, uint256 amountNATIVE) {
ILBPair lbPair = ILBPair(_getLBPairInformation(token, IERC20(_wnative), binStep, Version.V2_2));
{
bool isNATIVETokenY = IERC20(_wnative) == lbPair.getTokenY();
if (!isNATIVETokenY) {
(amountTokenMin, amountNATIVEMin) = (amountNATIVEMin, amountTokenMin);
}
(uint256 amountX, uint256 amountY) =
_removeLiquidity(lbPair, amountTokenMin, amountNATIVEMin, ids, amounts, address(this));
(amountToken, amountNATIVE) = isNATIVETokenY ? (amountX, amountY) : (amountY, amountX);
}
_safeTransfer(token, to, amountToken);
_wNativeWithdrawAndTransfer(to, amountNATIVE);
}
/**
* @notice Swaps exact tokens for tokens while performing safety checks
* @param amountIn The amount of token to send
* @param amountOutMin The min amount of token to receive
* @param path The path of the swap
* @param to The address of the recipient
* @param deadline The deadline of the tx
* @return amountOut Output amount of the swap
*/
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
Path memory path,
address to,
uint256 deadline
) external override ensure(deadline) verifyPathValidity(path) returns (uint256 amountOut) {
address[] memory pairs = _getPairs(path.pairBinSteps, path.versions, path.tokenPath);
_safeTransferFrom(path.tokenPath[0], msg.sender, pairs[0], amountIn);
amountOut = _swapExactTokensForTokens(amountIn, pairs, path.versions, path.tokenPath, to);
if (amountOutMin > amountOut) revert LBRouter__InsufficientAmountOut(amountOutMin, amountOut);
}
/**
* @notice Swaps exact tokens for NATIVE while performing safety checks
* @param amountIn The amount of token to send
* @param amountOutMinNATIVE The min amount of NATIVE to receive
* @param path The path of the swap
* @param to The address of the recipient
* @param deadline The deadline of the tx
* @return amountOut Output amount of the swap
*/
function swapExactTokensForNATIVE(
uint256 amountIn,
uint256 amountOutMinNATIVE,
Path memory path,
address payable to,
uint256 deadline
) external override ensure(deadline) verifyPathValidity(path) returns (uint256 amountOut) {
if (path.tokenPath[path.pairBinSteps.length] != IERC20(_wnative)) {
revert LBRouter__InvalidTokenPath(address(path.tokenPath[path.pairBinSteps.length]));
}
address[] memory pairs = _getPairs(path.pairBinSteps, path.versions, path.tokenPath);
_safeTransferFrom(path.tokenPath[0], msg.sender, pairs[0], amountIn);
amountOut = _swapExactTokensForTokens(amountIn, pairs, path.versions, path.tokenPath, address(this));
if (amountOutMinNATIVE > amountOut) revert LBRouter__InsufficientAmountOut(amountOutMinNATIVE, amountOut);
_wNativeWithdrawAndTransfer(to, amountOut);
}
/**
* @notice Swaps exact NATIVE for tokens while performing safety checks
* @param amountOutMin The min amount of token to receive
* @param path The path of the swap
* @param to The address of the recipient
* @param deadline The deadline of the tx
* @return amountOut Output amount of the swap
*/
function swapExactNATIVEForTokens(uint256 amountOutMin, Path memory path, address to, uint256 deadline)
external
payable
override
ensure(deadline)
verifyPathValidity(path)
returns (uint256 amountOut)
{
if (path.tokenPath[0] != IERC20(_wnative)) revert LBRouter__InvalidTokenPath(address(path.tokenPath[0]));
address[] memory pairs = _getPairs(path.pairBinSteps, path.versions, path.tokenPath);
_wNativeDepositAndTransfer(pairs[0], msg.value);
amountOut = _swapExactTokensForTokens(msg.value, pairs, path.versions, path.tokenPath, to);
if (amountOutMin > amountOut) revert LBRouter__InsufficientAmountOut(amountOutMin, amountOut);
}
/**
* @notice Swaps tokens for exact tokens while performing safety checks
* @param amountOut The amount of token to receive
* @param amountInMax The max amount of token to send
* @param path The path of the swap
* @param to The address of the recipient
* @param deadline The deadline of the tx
* @return amountsIn Input amounts of the swap
*/
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
Path memory path,
address to,
uint256 deadline
) external override ensure(deadline) verifyPathValidity(path) returns (uint256[] memory amountsIn) {
address[] memory pairs = _getPairs(path.pairBinSteps, path.versions, path.tokenPath);
{
amountsIn = _getAmountsIn(path.versions, pairs, path.tokenPath, amountOut);
if (amountsIn[0] > amountInMax) revert LBRouter__MaxAmountInExceeded(amountInMax, amountsIn[0]);
_safeTransferFrom(path.tokenPath[0], msg.sender, pairs[0], amountsIn[0]);
uint256 _amountOutReal = _swapTokensForExactTokens(pairs, path.versions, path.tokenPath, amountsIn, to);
if (_amountOutReal < amountOut) revert LBRouter__InsufficientAmountOut(amountOut, _amountOutReal);
}
}
/**
* @notice Swaps tokens for exact NATIVE while performing safety checks
* @param amountNATIVEOut The amount of NATIVE to receive
* @param amountInMax The max amount of token to send
* @param path The path of the swap
* @param to The address of the recipient
* @param deadline The deadline of the tx
* @return amountsIn path amounts for every step of the swap
*/
function swapTokensForExactNATIVE(
uint256 amountNATIVEOut,
uint256 amountInMax,
Path memory path,
address payable to,
uint256 deadline
) external override ensure(deadline) verifyPathValidity(path) returns (uint256[] memory amountsIn) {
if (path.tokenPath[path.pairBinSteps.length] != IERC20(_wnative)) {
revert LBRouter__InvalidTokenPath(address(path.tokenPath[path.pairBinSteps.length]));
}
address[] memory pairs = _getPairs(path.pairBinSteps, path.versions, path.tokenPath);
amountsIn = _getAmountsIn(path.versions, pairs, path.tokenPath, amountNATIVEOut);
if (amountsIn[0] > amountInMax) revert LBRouter__MaxAmountInExceeded(amountInMax, amountsIn[0]);
_safeTransferFrom(path.tokenPath[0], msg.sender, pairs[0], amountsIn[0]);
uint256 _amountOutReal =
_swapTokensForExactTokens(pairs, path.versions, path.tokenPath, amountsIn, address(this));
if (_amountOutReal < amountNATIVEOut) revert LBRouter__InsufficientAmountOut(amountNATIVEOut, _amountOutReal);
_wNativeWithdrawAndTransfer(to, _amountOutReal);
}
/**
* @notice Swaps NATIVE for exact tokens while performing safety checks
* @dev Will refund any NATIVE amount sent in excess to `msg.sender`
* @param amountOut The amount of tokens to receive
* @param path The path of the swap
* @param to The address of the recipient
* @param deadline The deadline of the tx
* @return amountsIn path amounts for every step of the swap
*/
function swapNATIVEForExactTokens(uint256 amountOut, Path memory path, address to, uint256 deadline)
external
payable
override
ensure(deadline)
verifyPathValidity(path)
returns (uint256[] memory amountsIn)
{
if (path.tokenPath[0] != IERC20(_wnative)) revert LBRouter__InvalidTokenPath(address(path.tokenPath[0]));
address[] memory pairs = _getPairs(path.pairBinSteps, path.versions, path.tokenPath);
amountsIn = _getAmountsIn(path.versions, pairs, path.tokenPath, amountOut);
if (amountsIn[0] > msg.value) revert LBRouter__MaxAmountInExceeded(msg.value, amountsIn[0]);
_wNativeDepositAndTransfer(pairs[0], amountsIn[0]);
uint256 amountOutReal = _swapTokensForExactTokens(pairs, path.versions, path.tokenPath, amountsIn, to);
if (amountOutReal < amountOut) revert LBRouter__InsufficientAmountOut(amountOut, amountOutReal);
if (msg.value > amountsIn[0]) _safeTransferNative(msg.sender, msg.value - amountsIn[0]);
}
/**
* @notice Swaps exact tokens for tokens while performing safety checks supporting for fee on transfer tokens
* @param amountIn The amount of token to send
* @param amountOutMin The min amount of token to receive
* @param path The path of the swap
* @param to The address of the recipient
* @param deadline The deadline of the tx
* @return amountOut Output amount of the swap
*/
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
Path memory path,
address to,
uint256 deadline
) external override ensure(deadline) verifyPathValidity(path) returns (uint256 amountOut) {
address[] memory pairs = _getPairs(path.pairBinSteps, path.versions, path.tokenPath);
IERC20 targetToken = path.tokenPath[pairs.length];
uint256 balanceBefore = targetToken.balanceOf(to);
_safeTransferFrom(path.tokenPath[0], msg.sender, pairs[0], amountIn);
_swapSupportingFeeOnTransferTokens(pairs, path.versions, path.tokenPath, to);
amountOut = targetToken.balanceOf(to) - balanceBefore;
if (amountOutMin > amountOut) revert LBRouter__InsufficientAmountOut(amountOutMin, amountOut);
}
/**
* @notice Swaps exact tokens for NATIVE while performing safety checks supporting for fee on transfer tokens
* @param amountIn The amount of token to send
* @param amountOutMinNATIVE The min amount of NATIVE to receive
* @param path The path of the swap
* @param to The address of the recipient
* @param deadline The deadline of the tx
* @return amountOut Output amount of the swap
*/
function swapExactTokensForNATIVESupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMinNATIVE,
Path memory path,
address payable to,
uint256 deadline
) external override ensure(deadline) verifyPathValidity(path) returns (uint256 amountOut) {
if (path.tokenPath[path.pairBinSteps.length] != IERC20(_wnative)) {
revert LBRouter__InvalidTokenPath(address(path.tokenPath[path.pairBinSteps.length]));
}
address[] memory pairs = _getPairs(path.pairBinSteps, path.versions, path.tokenPath);
uint256 balanceBefore = _wnative.balanceOf(address(this));
_safeTransferFrom(path.tokenPath[0], msg.sender, pairs[0], amountIn);
_swapSupportingFeeOnTransferTokens(pairs, path.versions, path.tokenPath, address(this));
amountOut = _wnative.balanceOf(address(this)) - balanceBefore;
if (amountOutMinNATIVE > amountOut) revert LBRouter__InsufficientAmountOut(amountOutMinNATIVE, amountOut);
_wNativeWithdrawAndTransfer(to, amountOut);
}
/**
* @notice Swaps exact NATIVE for tokens while performing safety checks supporting for fee on transfer tokens
* @param amountOutMin The min amount of token to receive
* @param path The path of the swap
* @param to The address of the recipient
* @param deadline The deadline of the tx
* @return amountOut Output amount of the swap
*/
function swapExactNATIVEForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
Path memory path,
address to,
uint256 deadline
) external payable override ensure(deadline) verifyPathValidity(path) returns (uint256 amountOut) {
if (path.tokenPath[0] != IERC20(_wnative)) revert LBRouter__InvalidTokenPath(address(path.tokenPath[0]));
address[] memory pairs = _getPairs(path.pairBinSteps, path.versions, path.tokenPath);
IERC20 targetToken = path.tokenPath[pairs.length];
uint256 balanceBefore = targetToken.balanceOf(to);
_wNativeDepositAndTransfer(pairs[0], msg.value);
_swapSupportingFeeOnTransferTokens(pairs, path.versions, path.tokenPath, to);
amountOut = targetToken.balanceOf(to) - balanceBefore;
if (amountOutMin > amountOut) revert LBRouter__InsufficientAmountOut(amountOutMin, amountOut);
}
/**
* @notice Unstuck tokens that are sent to this contract by mistake
* @dev Only callable by the factory owner
* @param token The address of the token
* @param to The address of the user to send back the tokens
* @param amount The amount to send
*/
function sweep(IERC20 token, address to, uint256 amount) external override onlyFactoryOwner {
if (address(token) == address(0)) {
amount = amount == type(uint256).max ? address(this).balance : amount;
_safeTransferNative(to, amount);
} else {
amount = amount == type(uint256).max ? token.balanceOf(address(this)) : amount;
token.safeTransfer(to, amount);
}
}
/**
* @notice Unstuck LBTokens that are sent to this contract by mistake
* @dev Only callable by the factory owner
* @param lbToken The address of the LBToken
* @param to The address of the user to send back the tokens
* @param ids The list of token ids
* @param amounts The list of amounts to send
*/
function sweepLBToken(ILBToken lbToken, address to, uint256[] calldata ids, uint256[] calldata amounts)
external
override
onlyFactoryOwner
{
lbToken.batchTransferFrom(address(this), to, ids, amounts);
}
/**
* @notice Helper function to add liquidity
* @param liq The liquidity parameter
* @param pair LBPair where liquidity is deposited
* @return amountXAdded Amount of token X added
* @return amountYAdded Amount of token Y added
* @return amountXLeft Amount of token X left
* @return amountYLeft Amount of token Y left
* @return depositIds The list of deposit ids
* @return liquidityMinted The list of liquidity minted
*/
function _addLiquidity(LiquidityParameters calldata liq, ILBPair pair)
private
ensure(liq.deadline)
returns (
uint256 amountXAdded,
uint256 amountYAdded,
uint256 amountXLeft,
uint256 amountYLeft,
uint256[] memory depositIds,
uint256[] memory liquidityMinted
)
{
unchecked {
if (liq.deltaIds.length != liq.distributionX.length || liq.deltaIds.length != liq.distributionY.length) {
revert LBRouter__LengthsMismatch();
}
if (liq.activeIdDesired > type(uint24).max || liq.idSlippage > type(uint24).max) {
revert LBRouter__IdDesiredOverflows(liq.activeIdDesired, liq.idSlippage);
}
bytes32[] memory liquidityConfigs = new bytes32[](liq.deltaIds.length);
depositIds = new uint256[](liq.deltaIds.length);
{
uint256 _activeId = pair.getActiveId();
if (
liq.activeIdDesired + liq.idSlippage < _activeId || _activeId + liq.idSlippage < liq.activeIdDesired
) {
revert LBRouter__IdSlippageCaught(liq.activeIdDesired, liq.idSlippage, _activeId);
}
for (uint256 i; i < liquidityConfigs.length; ++i) {
int256 _id = int256(_activeId) + liq.deltaIds[i];
if (_id < 0 || uint256(_id) > type(uint24).max) revert LBRouter__IdOverflows(_id);
depositIds[i] = uint256(_id);
liquidityConfigs[i] = LiquidityConfigurations.encodeParams(
uint64(liq.distributionX[i]), uint64(liq.distributionY[i]), uint24(uint256(_id))
);
}
}
bytes32 amountsReceived;
bytes32 amountsLeft;
(amountsReceived, amountsLeft, liquidityMinted) = pair.mint(liq.to, liquidityConfigs, liq.refundTo);
bytes32 amountsAdded = amountsReceived.sub(amountsLeft);
amountXAdded = amountsAdded.decodeX();
amountYAdded = amountsAdded.decodeY();
if (amountXAdded < liq.amountXMin || amountYAdded < liq.amountYMin) {
revert LBRouter__AmountSlippageCaught(liq.amountXMin, amountXAdded, liq.amountYMin, amountYAdded);
}
amountXLeft = amountsLeft.decodeX();
amountYLeft = amountsLeft.decodeY();
}
}
/**
* @notice Helper function to return the amounts in
* @param versions The list of versions (V1, V2, V2_1 or V2_2)
* @param pairs The list of pairs
* @param tokenPath The swap path
* @param amountOut The amount out
* @return amountsIn The list of amounts in
*/
function _getAmountsIn(
Version[] memory versions,
address[] memory pairs,
IERC20[] memory tokenPath,
uint256 amountOut
) private view returns (uint256[] memory amountsIn) {
amountsIn = new uint256[](tokenPath.length);
// Avoid doing -1, as `pairs.length == pairBinSteps.length-1`
amountsIn[pairs.length] = amountOut;
for (uint256 i = pairs.length; i != 0; i--) {
IERC20 token = tokenPath[i - 1];
Version version = versions[i - 1];
address pair = pairs[i - 1];
if (version == Version.V1) {
(uint256 reserveIn, uint256 reserveOut,) = IJoePair(pair).getReserves();
if (token > tokenPath[i]) {
(reserveIn, reserveOut) = (reserveOut, reserveIn);
}
uint256 amountOut_ = amountsIn[i];
amountsIn[i - 1] = uint128(amountOut_.getAmountIn(reserveIn, reserveOut));
} else if (version == Version.V2) {
(amountsIn[i - 1],) = _legacyRouter.getSwapIn(
ILBLegacyPair(pair), uint128(amountsIn[i]), ILBLegacyPair(pair).tokenX() == token
);
} else {
(amountsIn[i - 1],,) =
getSwapIn(ILBPair(pair), uint128(amountsIn[i]), ILBPair(pair).getTokenX() == token);
}
}
}
/**
* @notice Helper function to remove liquidity
* @param pair The address of the LBPair
* @param amountXMin The min amount to receive of token X
* @param amountYMin The min amount to receive of token Y
* @param ids The list of ids to burn
* @param amounts The list of amounts to burn of each id in `_ids`
* @param to The address of the recipient
* @return amountX The amount of token X sent by the pair
* @return amountY The amount of token Y sent by the pair
*/
function _removeLiquidity(
ILBPair pair,
uint256 amountXMin,
uint256 amountYMin,
uint256[] memory ids,
uint256[] memory amounts,
address to
) private returns (uint256 amountX, uint256 amountY) {
(bytes32[] memory amountsBurned) = pair.burn(msg.sender, to, ids, amounts);
for (uint256 i; i < amountsBurned.length; ++i) {
amountX += amountsBurned[i].decodeX();
amountY += amountsBurned[i].decodeY();
}
if (amountX < amountXMin || amountY < amountYMin) {
revert LBRouter__AmountSlippageCaught(amountXMin, amountX, amountYMin, amountY);
}
}
/**
* @notice Helper function to swap exact tokens for tokens
* @param amountIn The amount of token sent
* @param pairs The list of pairs
* @param versions The list of versions (V1, V2, V2_1 or V2_2)
* @param tokenPath The swap path using the binSteps following `pairBinSteps`
* @param to The address of the recipient
* @return amountOut The amount of token sent to `to`
*/
function _swapExactTokensForTokens(
uint256 amountIn,
address[] memory pairs,
Version[] memory versions,
IERC20[] memory tokenPath,
address to
) private returns (uint256 amountOut) {
IERC20 token;
Version version;
address recipient;
address pair;
IERC20 tokenNext = tokenPath[0];
amountOut = amountIn;
unchecked {
for (uint256 i; i < pairs.length; ++i) {
pair = pairs[i];
version = versions[i];
token = tokenNext;
tokenNext = tokenPath[i + 1];
recipient = i + 1 == pairs.length ? to : pairs[i + 1];
if (version == Version.V1) {
(uint256 reserve0, uint256 reserve1,) = IJoePair(pair).getReserves();
if (token < tokenNext) {
amountOut = amountOut.getAmountOut(reserve0, reserve1);
IJoePair(pair).swap(0, amountOut, recipient, "");
} else {
amountOut = amountOut.getAmountOut(reserve1, reserve0);
IJoePair(pair).swap(amountOut, 0, recipient, "");
}
} else if (version == Version.V2) {
bool swapForY = tokenNext == ILBLegacyPair(pair).tokenY();
(uint256 amountXOut, uint256 amountYOut) = ILBLegacyPair(pair).swap(swapForY, recipient);
if (swapForY) amountOut = amountYOut;
else amountOut = amountXOut;
} else {
bool swapForY = tokenNext == ILBPair(pair).getTokenY();
(uint256 amountXOut, uint256 amountYOut) = ILBPair(pair).swap(swapForY, recipient).decode();
if (swapForY) amountOut = amountYOut;
else amountOut = amountXOut;
}
}
}
}
/**
* @notice Helper function to swap tokens for exact tokens
* @param pairs The array of pairs
* @param versions The list of versions (V1, V2, V2_1 or V2_2)
* @param tokenPath The swap path using the binSteps following `pairBinSteps`
* @param amountsIn The list of amounts in
* @param to The address of the recipient
* @return amountOut The amount of token sent to `to`
*/
function _swapTokensForExactTokens(
address[] memory pairs,
Version[] memory versions,
IERC20[] memory tokenPath,
uint256[] memory amountsIn,
address to
) private returns (uint256 amountOut) {
IERC20 token;
address recipient;
address pair;
Version version;
IERC20 tokenNext = tokenPath[0];
unchecked {
for (uint256 i; i < pairs.length; ++i) {
pair = pairs[i];
version = versions[i];
token = tokenNext;
tokenNext = tokenPath[i + 1];
recipient = i + 1 == pairs.length ? to : pairs[i + 1];
if (version == Version.V1) {
amountOut = amountsIn[i + 1];
if (token < tokenNext) {
IJoePair(pair).swap(0, amountOut, recipient, "");
} else {
IJoePair(pair).swap(amountOut, 0, recipient, "");
}
} else if (version == Version.V2) {
bool swapForY = tokenNext == ILBLegacyPair(pair).tokenY();
(uint256 amountXOut, uint256 amountYOut) = ILBLegacyPair(pair).swap(swapForY, recipient);
if (swapForY) amountOut = amountYOut;
else amountOut = amountXOut;
} else {
bool swapForY = tokenNext == ILBPair(pair).getTokenY();
(uint256 amountXOut, uint256 amountYOut) = ILBPair(pair).swap(swapForY, recipient).decode();
if (swapForY) amountOut = amountYOut;
else amountOut = amountXOut;
}
}
}
}
/**
* @notice Helper function to swap exact tokens supporting for fee on transfer tokens
* @param pairs The list of pairs
* @param versions The list of versions (V1, V2, V2_1 or V2_2)
* @param tokenPath The swap path using the binSteps following `pairBinSteps`
* @param to The address of the recipient
*/
function _swapSupportingFeeOnTransferTokens(
address[] memory pairs,
Version[] memory versions,
IERC20[] memory tokenPath,
address to
) private {
IERC20 token;
Version version;
address recipient;
address pair;
IERC20 tokenNext = tokenPath[0];
unchecked {
for (uint256 i; i < pairs.length; ++i) {
pair = pairs[i];
version = versions[i];
token = tokenNext;
tokenNext = tokenPath[i + 1];
recipient = i + 1 == pairs.length ? to : pairs[i + 1];
if (version == Version.V1) {
(uint256 _reserve0, uint256 _reserve1,) = IJoePair(pair).getReserves();
if (token < tokenNext) {
uint256 amountIn = token.balanceOf(pair) - _reserve0;
uint256 amountOut = amountIn.getAmountOut(_reserve0, _reserve1);
IJoePair(pair).swap(0, amountOut, recipient, "");
} else {
uint256 amountIn = token.balanceOf(pair) - _reserve1;