forked from nnlgsakib/Mindchainswap-Contracts-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MindchainswapZapV1.sol
841 lines (727 loc) · 31 KB
/
MindchainswapZapV1.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
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {IMindchainswapPair} from "./interfaces/IMindchainswapPair.sol";
import {IMindchainswapRouter02} from "./interfaces/IMindchainswapRouter02.sol";
import {IWETH} from "./interfaces/IWETH.sol";
import {Babylonian} from "./libraries/Babylonian.sol";
/*
* @author Inspiration from the work of Zapper and Beefy.
* Implemented and modified by MindchainswapSwap teams.
*/
contract MindchainswapZapV1 is Ownable, ReentrancyGuard {
using SafeERC20 for IERC20;
// Interface for Wrapped BNB (WBNB)
IWETH public WBNB;
// MindchainswapRouter interface
IMindchainswapRouter02 public MindchainswapRouter;
// Maximum integer (used for managing allowance)
uint256 public constant MAX_INT = 2**256 - 1;
// Minimum amount for a swap (derived from MindchainswapSwap)
uint256 public constant MINIMUM_AMOUNT = 1000;
// Maximum reverse zap ratio (100 --> 1%, 1000 --> 0.1%)
uint256 public maxZapReverseRatio;
// Address MindchainswapRouter
address private MindchainswapRouterAddress;
// Address Wrapped BNB (WBNB)
address private WBNBAddress;
// Owner recovers token
event AdminTokenRecovery(address indexed tokenAddress, uint256 amountTokens);
// Owner changes the maxZapReverseRatio
event NewMaxZapReverseRatio(uint256 maxZapReverseRatio);
// tokenToZap = 0x00 address if BNB
event ZapIn(
address indexed tokenToZap,
address indexed lpToken,
uint256 tokenAmountIn,
uint256 lpTokenAmountReceived,
address indexed user
);
// token0ToZap = 0x00 address if BNB
event ZapInRebalancing(
address indexed token0ToZap,
address indexed token1ToZap,
address lpToken,
uint256 token0AmountIn,
uint256 token1AmountIn,
uint256 lpTokenAmountReceived,
address indexed user
);
// tokenToReceive = 0x00 address if BNB
event ZapOut(
address indexed lpToken,
address indexed tokenToReceive,
uint256 lpTokenAmount,
uint256 tokenAmountReceived,
address indexed user
);
/*
* @notice Fallback for WBNB
*/
receive() external payable {
assert(msg.sender == WBNBAddress);
}
/*
* @notice Constructor
* @param _WBNBAddress: address of the WBNB contract
* @param _MindchainswapRouter: address of the MindchainswapRouter
* @param _maxZapReverseRatio: maximum zap ratio
*/
constructor(
address _WBNBAddress,
address _MindchainswapRouter,
uint256 _maxZapReverseRatio
) {
WBNBAddress = _WBNBAddress;
WBNB = IWETH(_WBNBAddress);
MindchainswapRouterAddress = _MindchainswapRouter;
MindchainswapRouter = IMindchainswapRouter02(_MindchainswapRouter);
maxZapReverseRatio = _maxZapReverseRatio;
}
/*
* @notice Zap BNB in a WBNB pool (e.g. WBNB/token)
* @param _lpToken: LP token address (e.g. CAKE/BNB)
* @param _tokenAmountOutMin: minimum token amount (e.g. CAKE) to receive in the intermediary swap (e.g. BNB --> CAKE)
*/
function zapInBNB(address _lpToken, uint256 _tokenAmountOutMin) external payable nonReentrant {
WBNB.deposit{value: msg.value}();
// Call zap function
uint256 lpTokenAmountTransferred = _zapIn(WBNBAddress, msg.value, _lpToken, _tokenAmountOutMin);
// Emit event
emit ZapIn(
address(0x0000000000000000000000000000000000000000),
_lpToken,
msg.value,
lpTokenAmountTransferred,
address(msg.sender)
);
}
/*
* @notice Zap a token in (e.g. token/other token)
* @param _tokenToZap: token to zap
* @param _tokenAmountIn: amount of token to swap
* @param _lpToken: LP token address (e.g. CAKE/BUSD)
* @param _tokenAmountOutMin: minimum token to receive (e.g. CAKE) in the intermediary swap (e.g. BUSD --> CAKE)
*/
function zapInToken(
address _tokenToZap,
uint256 _tokenAmountIn,
address _lpToken,
uint256 _tokenAmountOutMin
) external nonReentrant {
// Transfer tokens to this contract
IERC20(_tokenToZap).safeTransferFrom(address(msg.sender), address(this), _tokenAmountIn);
// Call zap function
uint256 lpTokenAmountTransferred = _zapIn(_tokenToZap, _tokenAmountIn, _lpToken, _tokenAmountOutMin);
// Emit event
emit ZapIn(_tokenToZap, _lpToken, _tokenAmountIn, lpTokenAmountTransferred, address(msg.sender));
}
/*
* @notice Zap two tokens in, rebalance them to 50-50, before adding them to LP
* @param _token0ToZap: address of token0 to zap
* @param _token1ToZap: address of token1 to zap
* @param _token0AmountIn: amount of token0 to zap
* @param _token1AmountIn: amount of token1 to zap
* @param _lpToken: LP token address (token0/token1)
* @param _tokenAmountInMax: maximum token amount to sell (in token to sell in the intermediary swap)
* @param _tokenAmountOutMin: minimum token to receive in the intermediary swap
* @param _isToken0Sold: whether token0 is expected to be sold (if false, sell token1)
*/
function zapInTokenRebalancing(
address _token0ToZap,
address _token1ToZap,
uint256 _token0AmountIn,
uint256 _token1AmountIn,
address _lpToken,
uint256 _tokenAmountInMax,
uint256 _tokenAmountOutMin,
bool _isToken0Sold
) external nonReentrant {
// Transfer tokens to this contract
IERC20(_token0ToZap).safeTransferFrom(address(msg.sender), address(this), _token0AmountIn);
IERC20(_token1ToZap).safeTransferFrom(address(msg.sender), address(this), _token1AmountIn);
// Call zapIn function
uint256 lpTokenAmountTransferred = _zapInRebalancing(
_token0ToZap,
_token1ToZap,
_token0AmountIn,
_token1AmountIn,
_lpToken,
_tokenAmountInMax,
_tokenAmountOutMin,
_isToken0Sold
);
// Emit event
emit ZapInRebalancing(
_token0ToZap,
_token1ToZap,
_lpToken,
_token0AmountIn,
_token1AmountIn,
lpTokenAmountTransferred,
address(msg.sender)
);
}
/*
* @notice Zap 1 token and BNB, rebalance them to 50-50, before adding them to LP
* @param _token1ToZap: address of token1 to zap
* @param _token1AmountIn: amount of token1 to zap
* @param _lpToken: LP token address
* @param _tokenAmountInMax: maximum token amount to sell (in token to sell in the intermediary swap)
* @param _tokenAmountOutMin: minimum token to receive in the intermediary swap
* @param _isToken0Sold: whether token0 is expected to be sold (if false, sell token1)
*/
function zapInBNBRebalancing(
address _token1ToZap,
uint256 _token1AmountIn,
address _lpToken,
uint256 _tokenAmountInMax,
uint256 _tokenAmountOutMin,
bool _isToken0Sold
) external payable nonReentrant {
WBNB.deposit{value: msg.value}();
IERC20(_token1ToZap).safeTransferFrom(address(msg.sender), address(this), _token1AmountIn);
// Call zapIn function
uint256 lpTokenAmountTransferred = _zapInRebalancing(
WBNBAddress,
_token1ToZap,
msg.value,
_token1AmountIn,
_lpToken,
_tokenAmountInMax,
_tokenAmountOutMin,
_isToken0Sold
);
// Emit event
emit ZapInRebalancing(
address(0x0000000000000000000000000000000000000000),
_token1ToZap,
_lpToken,
msg.value,
_token1AmountIn,
lpTokenAmountTransferred,
address(msg.sender)
);
}
/*
* @notice Zap a LP token out to receive BNB
* @param _lpToken: LP token address (e.g. CAKE/WBNB)
* @param _lpTokenAmount: amount of LP tokens to zap out
* @param _tokenAmountOutMin: minimum amount to receive (in BNB/WBNB) in the intermediary swap (e.g. CAKE --> BNB)
*/
function zapOutBNB(
address _lpToken,
uint256 _lpTokenAmount,
uint256 _tokenAmountOutMin
) external nonReentrant {
// Transfer LP token to this address
IERC20(_lpToken).safeTransferFrom(address(msg.sender), address(_lpToken), _lpTokenAmount);
// Call zapOut
uint256 tokenAmountToTransfer = _zapOut(_lpToken, WBNBAddress, _tokenAmountOutMin);
// Unwrap BNB
WBNB.withdraw(tokenAmountToTransfer);
// Transfer BNB to the msg.sender
(bool success, ) = msg.sender.call{value: tokenAmountToTransfer}(new bytes(0));
require(success, "BNB: transfer fail");
// Emit event
emit ZapOut(
_lpToken,
address(0x0000000000000000000000000000000000000000),
_lpTokenAmount,
tokenAmountToTransfer,
address(msg.sender)
);
}
/*
* @notice Zap a LP token out (to receive a token)
* @param _lpToken: LP token address (e.g. CAKE/BUSD)
* @param _tokenToReceive: one of the 2 tokens from the LP (e.g. CAKE or BUSD)
* @param _lpTokenAmount: amount of LP tokens to zap out
* @param _tokenAmountOutMin: minimum token to receive (e.g. CAKE) in the intermediary swap (e.g. BUSD --> CAKE)
*/
function zapOutToken(
address _lpToken,
address _tokenToReceive,
uint256 _lpTokenAmount,
uint256 _tokenAmountOutMin
) external nonReentrant {
// Transfer LP token to this address
IERC20(_lpToken).safeTransferFrom(address(msg.sender), address(_lpToken), _lpTokenAmount);
uint256 tokenAmountToTransfer = _zapOut(_lpToken, _tokenToReceive, _tokenAmountOutMin);
IERC20(_tokenToReceive).safeTransfer(address(msg.sender), tokenAmountToTransfer);
emit ZapOut(_lpToken, _tokenToReceive, _lpTokenAmount, tokenAmountToTransfer, msg.sender);
}
/**
* @notice It allows the owner to change the risk parameter for quantities
* @param _maxZapInverseRatio: new inverse ratio
* @dev This function is only callable by owner.
*/
function updateMaxZapInverseRatio(uint256 _maxZapInverseRatio) external onlyOwner {
maxZapReverseRatio = _maxZapInverseRatio;
emit NewMaxZapReverseRatio(_maxZapInverseRatio);
}
/**
* @notice It allows the owner to recover wrong tokens sent to the contract
* @param _tokenAddress: the address of the token to withdraw (18 decimals)
* @param _tokenAmount: the number of token amount to withdraw
* @dev This function is only callable by owner.
*/
function recoverWrongTokens(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
IERC20(_tokenAddress).safeTransfer(address(msg.sender), _tokenAmount);
emit AdminTokenRecovery(_tokenAddress, _tokenAmount);
}
/*
* @notice View the details for single zap
* @dev Use WBNB for _tokenToZap (if BNB is the input)
* @param _tokenToZap: address of the token to zap
* @param _tokenAmountIn: amount of token to zap inputed
* @param _lpToken: address of the LP token
* @return swapAmountIn: amount that is expected to get swapped in intermediary swap
* @return swapAmountOut: amount that is expected to get received in intermediary swap
* @return swapTokenOut: token address of the token that is used in the intermediary swap
*/
function estimateZapInSwap(
address _tokenToZap,
uint256 _tokenAmountIn,
address _lpToken
)
external
view
returns (
uint256 swapAmountIn,
uint256 swapAmountOut,
address swapTokenOut
)
{
address token0 = IMindchainswapPair(_lpToken).token0();
address token1 = IMindchainswapPair(_lpToken).token1();
require(_tokenToZap == token0 || _tokenToZap == token1, "Zap: Wrong tokens");
// Convert to uint256 (from uint112)
(uint256 reserveA, uint256 reserveB, ) = IMindchainswapPair(_lpToken).getReserves();
if (token0 == _tokenToZap) {
swapTokenOut = token1;
swapAmountIn = _calculateAmountToSwap(_tokenAmountIn, reserveA, reserveB);
swapAmountOut = MindchainswapRouter.getAmountOut(swapAmountIn, reserveA, reserveB);
} else {
swapTokenOut = token0;
swapAmountIn = _calculateAmountToSwap(_tokenAmountIn, reserveB, reserveA);
swapAmountOut = MindchainswapRouter.getAmountOut(swapAmountIn, reserveB, reserveA);
}
return (swapAmountIn, swapAmountOut, swapTokenOut);
}
/*
* @notice View the details for a rebalancing zap
* @dev Use WBNB for _token0ToZap (if BNB is the input)
* @param _token0ToZap: address of the token0 to zap
* @param _token1ToZap: address of the token0 to zap
* @param _token0AmountIn: amount for token0 to zap
* @param _token1AmountIn: amount for token1 to zap
* @param _lpToken: address of the LP token
* @return swapAmountIn: amount that is expected to get swapped in intermediary swap
* @return swapAmountOut: amount that is expected to get received in intermediary swap
* @return isToken0Sold: whether the token0 is sold (false --> token1 is sold in the intermediary swap)
*/
function estimateZapInRebalancingSwap(
address _token0ToZap,
address _token1ToZap,
uint256 _token0AmountIn,
uint256 _token1AmountIn,
address _lpToken
)
external
view
returns (
uint256 swapAmountIn,
uint256 swapAmountOut,
bool sellToken0
)
{
require(
_token0ToZap == IMindchainswapPair(_lpToken).token0() || _token0ToZap == IMindchainswapPair(_lpToken).token1(),
"Zap: Wrong token0"
);
require(
_token1ToZap == IMindchainswapPair(_lpToken).token0() || _token1ToZap == IMindchainswapPair(_lpToken).token1(),
"Zap: Wrong token1"
);
require(_token0ToZap != _token1ToZap, "Zap: Same tokens");
// Convert to uint256 (from uint112)
(uint256 reserveA, uint256 reserveB, ) = IMindchainswapPair(_lpToken).getReserves();
if (_token0ToZap == IMindchainswapPair(_lpToken).token0()) {
sellToken0 = (_token0AmountIn * reserveB > _token1AmountIn * reserveA) ? true : false;
// Calculate the amount that is expected to be swapped
swapAmountIn = _calculateAmountToSwapForRebalancing(
_token0AmountIn,
_token1AmountIn,
reserveA,
reserveB,
sellToken0
);
// Calculate the amount expected to be received in the intermediary swap
if (sellToken0) {
swapAmountOut = MindchainswapRouter.getAmountOut(swapAmountIn, reserveA, reserveB);
} else {
swapAmountOut = MindchainswapRouter.getAmountOut(swapAmountIn, reserveB, reserveA);
}
} else {
sellToken0 = (_token0AmountIn * reserveA > _token1AmountIn * reserveB) ? true : false;
// Calculate the amount that is expected to be swapped
swapAmountIn = _calculateAmountToSwapForRebalancing(
_token0AmountIn,
_token1AmountIn,
reserveB,
reserveA,
sellToken0
);
// Calculate the amount expected to be received in the intermediary swap
if (sellToken0) {
swapAmountOut = MindchainswapRouter.getAmountOut(swapAmountIn, reserveB, reserveA);
} else {
swapAmountOut = MindchainswapRouter.getAmountOut(swapAmountIn, reserveA, reserveB);
}
}
return (swapAmountIn, swapAmountOut, sellToken0);
}
/*
* @notice View the details for single zap
* @dev Use WBNB for _tokenToReceive (if BNB is the asset to be received)
* @param _lpToken: address of the LP token to zap out
* @param _lpTokenAmount: amount of LP token to zap out
* @param _tokenToReceive: token address to receive
* @return swapAmountIn: amount that is expected to get swapped for intermediary swap
* @return swapAmountOut: amount that is expected to get received for intermediary swap
* @return swapTokenOut: address of the token that is sold in the intermediary swap
*/
function estimateZapOutSwap(
address _lpToken,
uint256 _lpTokenAmount,
address _tokenToReceive
)
external
view
returns (
uint256 swapAmountIn,
uint256 swapAmountOut,
address swapTokenOut
)
{
address token0 = IMindchainswapPair(_lpToken).token0();
address token1 = IMindchainswapPair(_lpToken).token1();
require(_tokenToReceive == token0 || _tokenToReceive == token1, "Zap: Token not in LP");
// Convert to uint256 (from uint112)
(uint256 reserveA, uint256 reserveB, ) = IMindchainswapPair(_lpToken).getReserves();
if (token1 == _tokenToReceive) {
// sell token0
uint256 tokenAmountIn = (_lpTokenAmount * reserveA) / IMindchainswapPair(_lpToken).totalSupply();
swapAmountIn = _calculateAmountToSwap(tokenAmountIn, reserveA, reserveB);
swapAmountOut = MindchainswapRouter.getAmountOut(swapAmountIn, reserveA, reserveB);
swapTokenOut = token0;
} else {
// sell token1
uint256 tokenAmountIn = (_lpTokenAmount * reserveB) / IMindchainswapPair(_lpToken).totalSupply();
swapAmountIn = _calculateAmountToSwap(tokenAmountIn, reserveB, reserveA);
swapAmountOut = MindchainswapRouter.getAmountOut(swapAmountIn, reserveB, reserveA);
swapTokenOut = token1;
}
return (swapAmountIn, swapAmountOut, swapTokenOut);
}
/*
* @notice Zap a token in (e.g. token/other token)
* @param _tokenToZap: token to zap
* @param _tokenAmountIn: amount of token to swap
* @param _lpToken: LP token address
* @param _tokenAmountOutMin: minimum token to receive in the intermediary swap
*/
function _zapIn(
address _tokenToZap,
uint256 _tokenAmountIn,
address _lpToken,
uint256 _tokenAmountOutMin
) internal returns (uint256 lpTokenReceived) {
require(_tokenAmountIn >= MINIMUM_AMOUNT, "Zap: Amount too low");
address token0 = IMindchainswapPair(_lpToken).token0();
address token1 = IMindchainswapPair(_lpToken).token1();
require(_tokenToZap == token0 || _tokenToZap == token1, "Zap: Wrong tokens");
// Retrieve the path
address[] memory path = new address[](2);
path[0] = _tokenToZap;
// Initiates an estimation to swap
uint256 swapAmountIn;
{
// Convert to uint256 (from uint112)
(uint256 reserveA, uint256 reserveB, ) = IMindchainswapPair(_lpToken).getReserves();
require((reserveA >= MINIMUM_AMOUNT) && (reserveB >= MINIMUM_AMOUNT), "Zap: Reserves too low");
if (token0 == _tokenToZap) {
swapAmountIn = _calculateAmountToSwap(_tokenAmountIn, reserveA, reserveB);
path[1] = token1;
require(reserveA / swapAmountIn >= maxZapReverseRatio, "Zap: Quantity higher than limit");
} else {
swapAmountIn = _calculateAmountToSwap(_tokenAmountIn, reserveB, reserveA);
path[1] = token0;
require(reserveB / swapAmountIn >= maxZapReverseRatio, "Zap: Quantity higher than limit");
}
}
// Approve token to zap if necessary
_approveTokenIfNeeded(_tokenToZap);
uint256[] memory swapedAmounts = MindchainswapRouter.swapExactTokensForTokens(
swapAmountIn,
_tokenAmountOutMin,
path,
address(this),
block.timestamp
);
// Approve other token if necessary
if (token0 == _tokenToZap) {
_approveTokenIfNeeded(token1);
} else {
_approveTokenIfNeeded(token0);
}
// Add liquidity and retrieve the amount of LP received by the sender
(, , lpTokenReceived) = MindchainswapRouter.addLiquidity(
path[0],
path[1],
_tokenAmountIn - swapedAmounts[0],
swapedAmounts[1],
1,
1,
address(msg.sender),
block.timestamp
);
return lpTokenReceived;
}
/*
* @notice Zap two tokens in, rebalance them to 50-50, before adding them to LP
* @param _token0ToZap: address of token0 to zap
* @param _token1ToZap: address of token1 to zap
* @param _token0AmountIn: amount of token0 to zap
* @param _token1AmountIn: amount of token1 to zap
* @param _lpToken: LP token address
* @param _tokenAmountInMax: maximum token amount to sell (in token to sell in the intermediary swap)
* @param _tokenAmountOutMin: minimum token to receive in the intermediary swap
* @param _isToken0Sold: whether token0 is expected to be sold (if false, sell token1)
*/
function _zapInRebalancing(
address _token0ToZap,
address _token1ToZap,
uint256 _token0AmountIn,
uint256 _token1AmountIn,
address _lpToken,
uint256 _tokenAmountInMax,
uint256 _tokenAmountOutMin,
bool _isToken0Sold
) internal returns (uint256 lpTokenReceived) {
require(
_token0ToZap == IMindchainswapPair(_lpToken).token0() || _token0ToZap == IMindchainswapPair(_lpToken).token1(),
"Zap: Wrong token0"
);
require(
_token1ToZap == IMindchainswapPair(_lpToken).token0() || _token1ToZap == IMindchainswapPair(_lpToken).token1(),
"Zap: Wrong token1"
);
require(_token0ToZap != _token1ToZap, "Zap: Same tokens");
// Initiates an estimation to swap
uint256 swapAmountIn;
{
// Convert to uint256 (from uint112)
(uint256 reserveA, uint256 reserveB, ) = IMindchainswapPair(_lpToken).getReserves();
require((reserveA >= MINIMUM_AMOUNT) && (reserveB >= MINIMUM_AMOUNT), "Zap: Reserves too low");
if (_token0ToZap == IMindchainswapPair(_lpToken).token0()) {
swapAmountIn = _calculateAmountToSwapForRebalancing(
_token0AmountIn,
_token1AmountIn,
reserveA,
reserveB,
_isToken0Sold
);
require(reserveA / swapAmountIn >= maxZapReverseRatio, "Zap: Quantity higher than limit");
} else {
swapAmountIn = _calculateAmountToSwapForRebalancing(
_token0AmountIn,
_token1AmountIn,
reserveB,
reserveA,
_isToken0Sold
);
require(reserveB / swapAmountIn >= maxZapReverseRatio, "Zap: Quantity higher than limit");
}
}
require(swapAmountIn <= _tokenAmountInMax, "Zap: Amount to swap too high");
address[] memory path = new address[](2);
// Define path for swapping and check whether to approve token to sell in intermediary swap
if (_isToken0Sold) {
path[0] = _token0ToZap;
path[1] = _token1ToZap;
_approveTokenIfNeeded(_token0ToZap);
} else {
path[0] = _token1ToZap;
path[1] = _token0ToZap;
_approveTokenIfNeeded(_token1ToZap);
}
// Execute the swap and retrieve quantity received
uint256[] memory swapedAmounts = MindchainswapRouter.swapExactTokensForTokens(
swapAmountIn,
_tokenAmountOutMin,
path,
address(this),
block.timestamp
);
// Check whether to approve other token and add liquidity to LP
if (_isToken0Sold) {
_approveTokenIfNeeded(_token1ToZap);
(, , lpTokenReceived) = MindchainswapRouter.addLiquidity(
path[0],
path[1],
(_token0AmountIn - swapedAmounts[0]),
(_token1AmountIn + swapedAmounts[1]),
1,
1,
address(msg.sender),
block.timestamp
);
} else {
_approveTokenIfNeeded(_token0ToZap);
(, , lpTokenReceived) = MindchainswapRouter.addLiquidity(
path[0],
path[1],
(_token1AmountIn - swapedAmounts[0]),
(_token0AmountIn + swapedAmounts[1]),
1,
1,
address(msg.sender),
block.timestamp
);
}
return lpTokenReceived;
}
/*
* @notice Zap a LP token out to a token (e.g. token/other token)
* @param _lpToken: LP token address
* @param _tokenToReceive: token address
* @param _tokenAmountOutMin: minimum token to receive in the intermediary swap
*/
function _zapOut(
address _lpToken,
address _tokenToReceive,
uint256 _tokenAmountOutMin
) internal returns (uint256) {
address token0 = IMindchainswapPair(_lpToken).token0();
address token1 = IMindchainswapPair(_lpToken).token1();
require(_tokenToReceive == token0 || _tokenToReceive == token1, "Zap: Token not in LP");
// Burn all LP tokens to receive the two tokens to this address
(uint256 amount0, uint256 amount1) = IMindchainswapPair(_lpToken).burn(address(this));
require(amount0 >= MINIMUM_AMOUNT, "MindchainswapRouter: INSUFFICIENT_A_AMOUNT");
require(amount1 >= MINIMUM_AMOUNT, "MindchainswapRouter: INSUFFICIENT_B_AMOUNT");
address[] memory path = new address[](2);
path[1] = _tokenToReceive;
uint256 swapAmountIn;
if (token0 == _tokenToReceive) {
path[0] = token1;
swapAmountIn = IERC20(token1).balanceOf(address(this));
// Approve token to sell if necessary
_approveTokenIfNeeded(token1);
} else {
path[0] = token0;
swapAmountIn = IERC20(token0).balanceOf(address(this));
// Approve token to sell if necessary
_approveTokenIfNeeded(token0);
}
// Swap tokens
MindchainswapRouter.swapExactTokensForTokens(swapAmountIn, _tokenAmountOutMin, path, address(this), block.timestamp);
// Return full balance for the token to receive by the sender
return IERC20(_tokenToReceive).balanceOf(address(this));
}
/*
* @notice Allows to zap a token in (e.g. token/other token)
* @param _token: token address
*/
function _approveTokenIfNeeded(address _token) private {
if (IERC20(_token).allowance(address(this), MindchainswapRouterAddress) < 1e24) {
// Re-approve
IERC20(_token).safeApprove(MindchainswapRouterAddress, MAX_INT);
}
}
/*
* @notice Calculate the swap amount to get the price at 50/50 split
* @param _token0AmountIn: amount of token 0
* @param _reserve0: amount in reserve for token0
* @param _reserve1: amount in reserve for token1
* @return amountToSwap: swapped amount (in token0)
*/
function _calculateAmountToSwap(
uint256 _token0AmountIn,
uint256 _reserve0,
uint256 _reserve1
) private view returns (uint256 amountToSwap) {
uint256 halfToken0Amount = _token0AmountIn / 2;
uint256 nominator = MindchainswapRouter.getAmountOut(halfToken0Amount, _reserve0, _reserve1);
uint256 denominator = MindchainswapRouter.quote(
halfToken0Amount,
_reserve0 + halfToken0Amount,
_reserve1 - nominator
);
// Adjustment for price impact
amountToSwap =
_token0AmountIn -
Babylonian.sqrt((halfToken0Amount * halfToken0Amount * nominator) / denominator);
return amountToSwap;
}
/*
* @notice Calculate the amount to swap to get the tokens at a 50/50 split
* @param _token0AmountIn: amount of token 0
* @param _token1AmountIn: amount of token 1
* @param _reserve0: amount in reserve for token0
* @param _reserve1: amount in reserve for token1
* @param _isToken0Sold: whether token0 is expected to be sold (if false, sell token1)
* @return amountToSwap: swapped amount in token0 (if _isToken0Sold is true) or token1 (if _isToken0Sold is false)
*/
function _calculateAmountToSwapForRebalancing(
uint256 _token0AmountIn,
uint256 _token1AmountIn,
uint256 _reserve0,
uint256 _reserve1,
bool _isToken0Sold
) private view returns (uint256 amountToSwap) {
bool sellToken0 = (_token0AmountIn * _reserve1 > _token1AmountIn * _reserve0) ? true : false;
require(sellToken0 == _isToken0Sold, "Zap: Wrong trade direction");
if (sellToken0) {
uint256 token0AmountToSell = (_token0AmountIn - (_token1AmountIn * _reserve0) / _reserve1) / 2;
uint256 nominator = MindchainswapRouter.getAmountOut(token0AmountToSell, _reserve0, _reserve1);
uint256 denominator = MindchainswapRouter.quote(
token0AmountToSell,
_reserve0 + token0AmountToSell,
_reserve1 - nominator
);
// Calculate the amount to sell (in token0)
token0AmountToSell =
(_token0AmountIn - (_token1AmountIn * (_reserve0 + token0AmountToSell)) / (_reserve1 - nominator)) /
2;
// Adjustment for price impact
amountToSwap =
2 *
token0AmountToSell -
Babylonian.sqrt((token0AmountToSell * token0AmountToSell * nominator) / denominator);
} else {
uint256 token1AmountToSell = (_token1AmountIn - (_token0AmountIn * _reserve1) / _reserve0) / 2;
uint256 nominator = MindchainswapRouter.getAmountOut(token1AmountToSell, _reserve1, _reserve0);
uint256 denominator =
MindchainswapRouter.quote(
token1AmountToSell,
_reserve1 + token1AmountToSell,
_reserve0 - nominator
);
// Calculate the amount to sell (in token1)
token1AmountToSell =
(_token1AmountIn - ((_token0AmountIn * (_reserve1 + token1AmountToSell)) / (_reserve0 - nominator))) /
2;
// Adjustment for price impact
amountToSwap =
2 *
token1AmountToSell -
Babylonian.sqrt((token1AmountToSell * token1AmountToSell * nominator) / denominator);
}
return amountToSwap;
}
}