-
Notifications
You must be signed in to change notification settings - Fork 117
/
MetaSwapUtils.sol
1182 lines (1072 loc) · 41 KB
/
MetaSwapUtils.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.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../LPToken.sol";
import "../interfaces/ISwap.sol";
import "../MathUtils.sol";
import "../SwapUtils.sol";
/**
* @title MetaSwapUtils library
* @notice A library to be used within MetaSwap.sol. Contains functions responsible for custody and AMM functionalities.
*
* MetaSwap is a modified version of Swap that allows Swap's LP token to be utilized in pooling with other tokens.
* As an example, if there is a Swap pool consisting of [DAI, USDC, USDT]. Then a MetaSwap pool can be created
* with [sUSD, BaseSwapLPToken] to allow trades between either the LP token or the underlying tokens and sUSD.
*
* @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library
* for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins.
* Admin functions should be protected within contracts using this library.
*/
library MetaSwapUtils {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using MathUtils for uint256;
using AmplificationUtils for SwapUtils.Swap;
/*** EVENTS ***/
event TokenSwap(
address indexed buyer,
uint256 tokensSold,
uint256 tokensBought,
uint128 soldId,
uint128 boughtId
);
event TokenSwapUnderlying(
address indexed buyer,
uint256 tokensSold,
uint256 tokensBought,
uint128 soldId,
uint128 boughtId
);
event AddLiquidity(
address indexed provider,
uint256[] tokenAmounts,
uint256[] fees,
uint256 invariant,
uint256 lpTokenSupply
);
event RemoveLiquidityOne(
address indexed provider,
uint256 lpTokenAmount,
uint256 lpTokenSupply,
uint256 boughtId,
uint256 tokensBought
);
event RemoveLiquidityImbalance(
address indexed provider,
uint256[] tokenAmounts,
uint256[] fees,
uint256 invariant,
uint256 lpTokenSupply
);
event NewAdminFee(uint256 newAdminFee);
event NewSwapFee(uint256 newSwapFee);
event NewWithdrawFee(uint256 newWithdrawFee);
struct MetaSwap {
// Meta-Swap related parameters
ISwap baseSwap;
uint256 baseVirtualPrice;
uint256 baseCacheLastUpdated;
IERC20[] baseTokens;
}
// Struct storing variables used in calculations in the
// calculateWithdrawOneTokenDY function to avoid stack too deep errors
struct CalculateWithdrawOneTokenDYInfo {
uint256 d0;
uint256 d1;
uint256 newY;
uint256 feePerToken;
uint256 preciseA;
uint256 xpi;
}
// Struct storing variables used in calculation in removeLiquidityImbalance function
// to avoid stack too deep error
struct ManageLiquidityInfo {
uint256 d0;
uint256 d1;
uint256 d2;
LPToken lpToken;
uint256 totalSupply;
uint256 preciseA;
uint256 baseVirtualPrice;
uint256[] tokenPrecisionMultipliers;
uint256[] newBalances;
}
struct SwapUnderlyingInfo {
uint256 x;
uint256 dx;
uint256 dy;
uint256[] tokenPrecisionMultipliers;
uint256[] oldBalances;
IERC20[] baseTokens;
IERC20 tokenFrom;
uint8 metaIndexFrom;
IERC20 tokenTo;
uint8 metaIndexTo;
uint256 baseVirtualPrice;
}
struct CalculateSwapUnderlyingInfo {
uint256 baseVirtualPrice;
ISwap baseSwap;
uint8 baseLPTokenIndex;
uint8 baseTokensLength;
uint8 metaIndexTo;
uint256 x;
uint256 dy;
}
// the denominator used to calculate admin and LP fees. For example, an
// LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR)
uint256 private constant FEE_DENOMINATOR = 10**10;
// Cache expire time for the stored value of base Swap's virtual price
uint256 public constant BASE_CACHE_EXPIRE_TIME = 10 minutes;
uint256 public constant BASE_VIRTUAL_PRICE_PRECISION = 10**18;
/*** VIEW & PURE FUNCTIONS ***/
/**
* @notice Return the stored value of base Swap's virtual price. If
* value was updated past BASE_CACHE_EXPIRE_TIME, then read it directly
* from the base Swap contract.
* @param metaSwapStorage MetaSwap struct to read from
* @return base Swap's virtual price
*/
function _getBaseVirtualPrice(MetaSwap storage metaSwapStorage)
internal
view
returns (uint256)
{
if (
block.timestamp >
metaSwapStorage.baseCacheLastUpdated + BASE_CACHE_EXPIRE_TIME
) {
return metaSwapStorage.baseSwap.getVirtualPrice();
}
return metaSwapStorage.baseVirtualPrice;
}
/**
* @notice Calculate how much the user would receive when withdrawing via single token
* @param self Swap struct to read from
* @param metaSwapStorage MetaSwap struct to read from
* @param tokenAmount the amount to withdraw in the pool's precision
* @param tokenIndex which token will be withdrawn
* @return dy the amount of token user will receive
*/
function calculateWithdrawOneToken(
SwapUtils.Swap storage self,
MetaSwap storage metaSwapStorage,
uint256 tokenAmount,
uint8 tokenIndex
) external view returns (uint256 dy) {
(dy, ) = _calculateWithdrawOneToken(
self,
tokenAmount,
tokenIndex,
_getBaseVirtualPrice(metaSwapStorage),
self.lpToken.totalSupply()
);
}
function _calculateWithdrawOneToken(
SwapUtils.Swap storage self,
uint256 tokenAmount,
uint8 tokenIndex,
uint256 baseVirtualPrice,
uint256 totalSupply
) internal view returns (uint256, uint256) {
uint256 dy;
uint256 dySwapFee;
{
uint256 currentY;
uint256 newY;
// Calculate how much to withdraw
(dy, newY, currentY) = _calculateWithdrawOneTokenDY(
self,
tokenIndex,
tokenAmount,
baseVirtualPrice,
totalSupply
);
// Calculate the associated swap fee
dySwapFee = currentY
.sub(newY)
.div(self.tokenPrecisionMultipliers[tokenIndex])
.sub(dy);
}
return (dy, dySwapFee);
}
/**
* @notice Calculate the dy of withdrawing in one token
* @param self Swap struct to read from
* @param tokenIndex which token will be withdrawn
* @param tokenAmount the amount to withdraw in the pools precision
* @param baseVirtualPrice the virtual price of the base swap's LP token
* @return the dy excluding swap fee, the new y after withdrawing one token, and current y
*/
function _calculateWithdrawOneTokenDY(
SwapUtils.Swap storage self,
uint8 tokenIndex,
uint256 tokenAmount,
uint256 baseVirtualPrice,
uint256 totalSupply
)
internal
view
returns (
uint256,
uint256,
uint256
)
{
// Get the current D, then solve the stableswap invariant
// y_i for D - tokenAmount
uint256[] memory xp = _xp(self, baseVirtualPrice);
require(tokenIndex < xp.length, "Token index out of range");
CalculateWithdrawOneTokenDYInfo memory v =
CalculateWithdrawOneTokenDYInfo(0, 0, 0, 0, self._getAPrecise(), 0);
v.d0 = SwapUtils.getD(xp, v.preciseA);
v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(totalSupply));
require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available");
v.newY = SwapUtils.getYD(v.preciseA, tokenIndex, xp, v.d1);
uint256[] memory xpReduced = new uint256[](xp.length);
v.feePerToken = SwapUtils._feePerToken(self.swapFee, xp.length);
for (uint256 i = 0; i < xp.length; i++) {
v.xpi = xp[i];
// if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY
// else dxExpected = xp[i] - (xp[i] * d1 / d0)
// xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR
xpReduced[i] = v.xpi.sub(
(
(i == tokenIndex)
? v.xpi.mul(v.d1).div(v.d0).sub(v.newY)
: v.xpi.sub(v.xpi.mul(v.d1).div(v.d0))
)
.mul(v.feePerToken)
.div(FEE_DENOMINATOR)
);
}
uint256 dy =
xpReduced[tokenIndex].sub(
SwapUtils.getYD(v.preciseA, tokenIndex, xpReduced, v.d1)
);
if (tokenIndex == xp.length.sub(1)) {
dy = dy.mul(BASE_VIRTUAL_PRICE_PRECISION).div(baseVirtualPrice);
}
dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]);
return (dy, v.newY, xp[tokenIndex]);
}
/**
* @notice Given a set of balances and precision multipliers, return the
* precision-adjusted balances. The last element will also get scaled up by
* the given baseVirtualPrice.
*
* @param balances an array of token balances, in their native precisions.
* These should generally correspond with pooled tokens.
*
* @param precisionMultipliers an array of multipliers, corresponding to
* the amounts in the balances array. When multiplied together they
* should yield amounts at the pool's precision.
*
* @param baseVirtualPrice the base virtual price to scale the balance of the
* base Swap's LP token.
*
* @return an array of amounts "scaled" to the pool's precision
*/
function _xp(
uint256[] memory balances,
uint256[] memory precisionMultipliers,
uint256 baseVirtualPrice
) internal pure returns (uint256[] memory) {
uint256[] memory xp = SwapUtils._xp(balances, precisionMultipliers);
uint256 baseLPTokenIndex = balances.length.sub(1);
xp[baseLPTokenIndex] = xp[baseLPTokenIndex].mul(baseVirtualPrice).div(
BASE_VIRTUAL_PRICE_PRECISION
);
return xp;
}
/**
* @notice Return the precision-adjusted balances of all tokens in the pool
* @param self Swap struct to read from
* @return the pool balances "scaled" to the pool's precision, allowing
* them to be more easily compared.
*/
function _xp(SwapUtils.Swap storage self, uint256 baseVirtualPrice)
internal
view
returns (uint256[] memory)
{
return
_xp(
self.balances,
self.tokenPrecisionMultipliers,
baseVirtualPrice
);
}
/**
* @notice Get the virtual price, to help calculate profit
* @param self Swap struct to read from
* @param metaSwapStorage MetaSwap struct to read from
* @return the virtual price, scaled to precision of BASE_VIRTUAL_PRICE_PRECISION
*/
function getVirtualPrice(
SwapUtils.Swap storage self,
MetaSwap storage metaSwapStorage
) external view returns (uint256) {
uint256 d =
SwapUtils.getD(
_xp(
self.balances,
self.tokenPrecisionMultipliers,
_getBaseVirtualPrice(metaSwapStorage)
),
self._getAPrecise()
);
uint256 supply = self.lpToken.totalSupply();
if (supply != 0) {
return d.mul(BASE_VIRTUAL_PRICE_PRECISION).div(supply);
}
return 0;
}
/**
* @notice Externally calculates a swap between two tokens. The SwapUtils.Swap storage and
* MetaSwap storage should be from the same MetaSwap contract.
* @param self Swap struct to read from
* @param metaSwapStorage MetaSwap struct from the same contract
* @param tokenIndexFrom the token to sell
* @param tokenIndexTo the token to buy
* @param dx the number of tokens to sell. If the token charges a fee on transfers,
* use the amount that gets transferred after the fee.
* @return dy the number of tokens the user will get
*/
function calculateSwap(
SwapUtils.Swap storage self,
MetaSwap storage metaSwapStorage,
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx
) external view returns (uint256 dy) {
(dy, ) = _calculateSwap(
self,
tokenIndexFrom,
tokenIndexTo,
dx,
_getBaseVirtualPrice(metaSwapStorage)
);
}
/**
* @notice Internally calculates a swap between two tokens.
*
* @dev The caller is expected to transfer the actual amounts (dx and dy)
* using the token contracts.
*
* @param self Swap struct to read from
* @param tokenIndexFrom the token to sell
* @param tokenIndexTo the token to buy
* @param dx the number of tokens to sell. If the token charges a fee on transfers,
* use the amount that gets transferred after the fee.
* @param baseVirtualPrice the virtual price of the base LP token
* @return dy the number of tokens the user will get and dyFee the associated fee
*/
function _calculateSwap(
SwapUtils.Swap storage self,
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx,
uint256 baseVirtualPrice
) internal view returns (uint256 dy, uint256 dyFee) {
uint256[] memory xp = _xp(self, baseVirtualPrice);
require(
tokenIndexFrom < xp.length && tokenIndexTo < xp.length,
"Token index out of range"
);
uint256 x =
dx.mul(self.tokenPrecisionMultipliers[tokenIndexFrom]).add(
xp[tokenIndexFrom]
);
uint256 y =
SwapUtils.getY(
self._getAPrecise(),
tokenIndexFrom,
tokenIndexTo,
x,
xp
);
dy = xp[tokenIndexTo].sub(y).sub(1);
dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR);
dy = dy.sub(dyFee).div(self.tokenPrecisionMultipliers[tokenIndexTo]);
}
/**
* @notice Calculates the expected return amount from swapping between
* the pooled tokens and the underlying tokens of the base Swap pool.
*
* @param self Swap struct to read from
* @param metaSwapStorage MetaSwap struct from the same contract
* @param tokenIndexFrom the token to sell
* @param tokenIndexTo the token to buy
* @param dx the number of tokens to sell. If the token charges a fee on transfers,
* use the amount that gets transferred after the fee.
* @return dy the number of tokens the user will get
*/
function calculateSwapUnderlying(
SwapUtils.Swap storage self,
MetaSwap storage metaSwapStorage,
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx
) external view returns (uint256) {
CalculateSwapUnderlyingInfo memory v =
CalculateSwapUnderlyingInfo(
_getBaseVirtualPrice(metaSwapStorage),
metaSwapStorage.baseSwap,
0,
uint8(metaSwapStorage.baseTokens.length),
0,
0,
0
);
uint256[] memory xp = _xp(self, v.baseVirtualPrice);
v.baseLPTokenIndex = uint8(xp.length.sub(1));
{
uint8 maxRange = v.baseLPTokenIndex + v.baseTokensLength;
require(
tokenIndexFrom < maxRange && tokenIndexTo < maxRange,
"Token index out of range"
);
}
if (tokenIndexFrom < v.baseLPTokenIndex) {
// tokenFrom is from this pool
v.x = xp[tokenIndexFrom].add(
dx.mul(self.tokenPrecisionMultipliers[tokenIndexFrom])
);
} else {
// tokenFrom is from the base pool
tokenIndexFrom = tokenIndexFrom - v.baseLPTokenIndex;
if (tokenIndexTo < v.baseLPTokenIndex) {
uint256[] memory baseInputs = new uint256[](v.baseTokensLength);
baseInputs[tokenIndexFrom] = dx;
v.x = v
.baseSwap
.calculateTokenAmount(baseInputs, true)
.mul(v.baseVirtualPrice)
.div(BASE_VIRTUAL_PRICE_PRECISION)
.add(xp[v.baseLPTokenIndex]);
} else {
// both from and to are from the base pool
return
v.baseSwap.calculateSwap(
tokenIndexFrom,
tokenIndexTo - v.baseLPTokenIndex,
dx
);
}
tokenIndexFrom = v.baseLPTokenIndex;
}
v.metaIndexTo = v.baseLPTokenIndex;
if (tokenIndexTo < v.baseLPTokenIndex) {
v.metaIndexTo = tokenIndexTo;
}
{
uint256 y =
SwapUtils.getY(
self._getAPrecise(),
tokenIndexFrom,
v.metaIndexTo,
v.x,
xp
);
v.dy = xp[v.metaIndexTo].sub(y).sub(1);
uint256 dyFee = v.dy.mul(self.swapFee).div(FEE_DENOMINATOR);
v.dy = v.dy.sub(dyFee);
}
if (tokenIndexTo < v.baseLPTokenIndex) {
// tokenTo is from this pool
v.dy = v.dy.div(self.tokenPrecisionMultipliers[v.metaIndexTo]);
} else {
// tokenTo is from the base pool
v.dy = v.baseSwap.calculateRemoveLiquidityOneToken(
v.dy.mul(BASE_VIRTUAL_PRICE_PRECISION).div(v.baseVirtualPrice),
tokenIndexTo - v.baseLPTokenIndex
);
}
return v.dy;
}
/**
* @notice A simple method to calculate prices from deposits or
* withdrawals, excluding fees but including slippage. This is
* helpful as an input into the various "min" parameters on calls
* to fight front-running
*
* @dev This shouldn't be used outside frontends for user estimates.
*
* @param self Swap struct to read from
* @param metaSwapStorage MetaSwap struct to read from
* @param amounts an array of token amounts to deposit or withdrawal,
* corresponding to pooledTokens. The amount should be in each
* pooled token's native precision. If a token charges a fee on transfers,
* use the amount that gets transferred after the fee.
* @param deposit whether this is a deposit or a withdrawal
* @return if deposit was true, total amount of lp token that will be minted and if
* deposit was false, total amount of lp token that will be burned
*/
function calculateTokenAmount(
SwapUtils.Swap storage self,
MetaSwap storage metaSwapStorage,
uint256[] calldata amounts,
bool deposit
) external view returns (uint256) {
uint256 a = self._getAPrecise();
uint256 d0;
uint256 d1;
{
uint256 baseVirtualPrice = _getBaseVirtualPrice(metaSwapStorage);
uint256[] memory balances1 = self.balances;
uint256[] memory tokenPrecisionMultipliers =
self.tokenPrecisionMultipliers;
uint256 numTokens = balances1.length;
d0 = SwapUtils.getD(
_xp(balances1, tokenPrecisionMultipliers, baseVirtualPrice),
a
);
for (uint256 i = 0; i < numTokens; i++) {
if (deposit) {
balances1[i] = balances1[i].add(amounts[i]);
} else {
balances1[i] = balances1[i].sub(
amounts[i],
"Cannot withdraw more than available"
);
}
}
d1 = SwapUtils.getD(
_xp(balances1, tokenPrecisionMultipliers, baseVirtualPrice),
a
);
}
uint256 totalSupply = self.lpToken.totalSupply();
if (deposit) {
return d1.sub(d0).mul(totalSupply).div(d0);
} else {
return d0.sub(d1).mul(totalSupply).div(d0);
}
}
/*** STATE MODIFYING FUNCTIONS ***/
/**
* @notice swap two tokens in the pool
* @param self Swap struct to read from and write to
* @param metaSwapStorage MetaSwap struct to read from and write to
* @param tokenIndexFrom the token the user wants to sell
* @param tokenIndexTo the token the user wants to buy
* @param dx the amount of tokens the user wants to sell
* @param minDy the min amount the user would like to receive, or revert.
* @return amount of token user received on swap
*/
function swap(
SwapUtils.Swap storage self,
MetaSwap storage metaSwapStorage,
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx,
uint256 minDy
) external returns (uint256) {
{
uint256 pooledTokensLength = self.pooledTokens.length;
require(
tokenIndexFrom < pooledTokensLength &&
tokenIndexTo < pooledTokensLength,
"Token index is out of range"
);
}
uint256 transferredDx;
{
IERC20 tokenFrom = self.pooledTokens[tokenIndexFrom];
require(
dx <= tokenFrom.balanceOf(msg.sender),
"Cannot swap more than you own"
);
{
// Transfer tokens first to see if a fee was charged on transfer
uint256 beforeBalance = tokenFrom.balanceOf(address(this));
tokenFrom.safeTransferFrom(msg.sender, address(this), dx);
// Use the actual transferred amount for AMM math
transferredDx = tokenFrom.balanceOf(address(this)).sub(
beforeBalance
);
}
}
(uint256 dy, uint256 dyFee) =
_calculateSwap(
self,
tokenIndexFrom,
tokenIndexTo,
transferredDx,
_updateBaseVirtualPrice(metaSwapStorage)
);
require(dy >= minDy, "Swap didn't result in min tokens");
uint256 dyAdminFee =
dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div(
self.tokenPrecisionMultipliers[tokenIndexTo]
);
self.balances[tokenIndexFrom] = self.balances[tokenIndexFrom].add(
transferredDx
);
self.balances[tokenIndexTo] = self.balances[tokenIndexTo].sub(dy).sub(
dyAdminFee
);
self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy);
emit TokenSwap(
msg.sender,
transferredDx,
dy,
tokenIndexFrom,
tokenIndexTo
);
return dy;
}
/**
* @notice Swaps with the underlying tokens of the base Swap pool. For this function,
* the token indices are flattened out so that underlying tokens are represented
* in the indices.
* @dev Since this calls multiple external functions during the execution,
* it is recommended to protect any function that depends on this with reentrancy guards.
* @param self Swap struct to read from and write to
* @param metaSwapStorage MetaSwap struct to read from and write to
* @param tokenIndexFrom the token the user wants to sell
* @param tokenIndexTo the token the user wants to buy
* @param dx the amount of tokens the user wants to sell
* @param minDy the min amount the user would like to receive, or revert.
* @return amount of token user received on swap
*/
function swapUnderlying(
SwapUtils.Swap storage self,
MetaSwap storage metaSwapStorage,
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx,
uint256 minDy
) external returns (uint256) {
SwapUnderlyingInfo memory v =
SwapUnderlyingInfo(
0,
0,
0,
self.tokenPrecisionMultipliers,
self.balances,
metaSwapStorage.baseTokens,
IERC20(address(0)),
0,
IERC20(address(0)),
0,
_updateBaseVirtualPrice(metaSwapStorage)
);
uint8 baseLPTokenIndex = uint8(v.oldBalances.length.sub(1));
{
uint8 maxRange = uint8(baseLPTokenIndex + v.baseTokens.length);
require(
tokenIndexFrom < maxRange && tokenIndexTo < maxRange,
"Token index out of range"
);
}
ISwap baseSwap = metaSwapStorage.baseSwap;
// Find the address of the token swapping from and the index in MetaSwap's token list
if (tokenIndexFrom < baseLPTokenIndex) {
v.tokenFrom = self.pooledTokens[tokenIndexFrom];
v.metaIndexFrom = tokenIndexFrom;
} else {
v.tokenFrom = v.baseTokens[tokenIndexFrom - baseLPTokenIndex];
v.metaIndexFrom = baseLPTokenIndex;
}
// Find the address of the token swapping to and the index in MetaSwap's token list
if (tokenIndexTo < baseLPTokenIndex) {
v.tokenTo = self.pooledTokens[tokenIndexTo];
v.metaIndexTo = tokenIndexTo;
} else {
v.tokenTo = v.baseTokens[tokenIndexTo - baseLPTokenIndex];
v.metaIndexTo = baseLPTokenIndex;
}
// Check for possible fee on transfer
v.dx = v.tokenFrom.balanceOf(address(this));
v.tokenFrom.safeTransferFrom(msg.sender, address(this), dx);
v.dx = v.tokenFrom.balanceOf(address(this)).sub(v.dx); // update dx in case of fee on transfer
if (
tokenIndexFrom < baseLPTokenIndex || tokenIndexTo < baseLPTokenIndex
) {
// Either one of the tokens belongs to the MetaSwap tokens list
uint256[] memory xp =
_xp(
v.oldBalances,
v.tokenPrecisionMultipliers,
v.baseVirtualPrice
);
if (tokenIndexFrom < baseLPTokenIndex) {
// Swapping from a MetaSwap token
v.x = xp[tokenIndexFrom].add(
dx.mul(v.tokenPrecisionMultipliers[tokenIndexFrom])
);
} else {
// Swapping from a base Swap token
// This case requires adding the underlying token to the base Swap, then
// using the base LP token to swap to the desired token
uint256[] memory baseAmounts =
new uint256[](v.baseTokens.length);
baseAmounts[tokenIndexFrom - baseLPTokenIndex] = v.dx;
// Add liquidity to the underlying Swap contract and receive base LP token
v.dx = baseSwap.addLiquidity(baseAmounts, 0, block.timestamp);
// Calculate the value of total amount of baseLPToken we end up with
v.x = v
.dx
.mul(v.baseVirtualPrice)
.div(BASE_VIRTUAL_PRICE_PRECISION)
.add(xp[baseLPTokenIndex]);
}
// Calculate how much to withdraw in MetaSwap level and the the associated swap fee
uint256 dyFee;
{
uint256 y =
SwapUtils.getY(
self._getAPrecise(),
v.metaIndexFrom,
v.metaIndexTo,
v.x,
xp
);
v.dy = xp[v.metaIndexTo].sub(y).sub(1);
dyFee = v.dy.mul(self.swapFee).div(FEE_DENOMINATOR);
v.dy = v.dy.sub(dyFee).div(
v.tokenPrecisionMultipliers[v.metaIndexTo]
);
}
if (tokenIndexTo >= baseLPTokenIndex) {
// When swapping to a base Swap token, scale down dy by its virtual price
v.dy = v.dy.mul(BASE_VIRTUAL_PRICE_PRECISION).div(
v.baseVirtualPrice
);
}
// Update the balances array according to the calculated input and output amount
{
uint256 dyAdminFee =
dyFee.mul(self.adminFee).div(FEE_DENOMINATOR);
dyAdminFee = dyAdminFee.div(
v.tokenPrecisionMultipliers[v.metaIndexTo]
);
self.balances[v.metaIndexFrom] = v.oldBalances[v.metaIndexFrom]
.add(v.dx);
self.balances[v.metaIndexTo] = v.oldBalances[v.metaIndexTo]
.sub(v.dy)
.sub(dyAdminFee);
}
if (tokenIndexTo >= baseLPTokenIndex) {
// When swapping to a token that belongs to the base Swap, burn the LP token
// and withdraw the desired token from the base pool
uint256 oldBalance = v.tokenTo.balanceOf(address(this));
baseSwap.removeLiquidityOneToken(
v.dy,
tokenIndexTo - baseLPTokenIndex,
0,
block.timestamp
);
v.dy = v.tokenTo.balanceOf(address(this)) - oldBalance;
}
// Check the amount of token to send meets minDy
require(v.dy >= minDy, "Swap didn't result in min tokens");
} else {
// Both tokens are from the base Swap pool
// Do a swap through the base Swap
v.dy = v.tokenTo.balanceOf(address(this));
baseSwap.swap(
tokenIndexFrom - baseLPTokenIndex,
tokenIndexTo - baseLPTokenIndex,
v.dx,
minDy,
block.timestamp
);
v.dy = v.tokenTo.balanceOf(address(this)).sub(v.dy);
}
// Send the desired token to the caller
v.tokenTo.safeTransfer(msg.sender, v.dy);
emit TokenSwapUnderlying(
msg.sender,
dx,
v.dy,
tokenIndexFrom,
tokenIndexTo
);
return v.dy;
}
/**
* @notice Add liquidity to the pool
* @param self Swap struct to read from and write to
* @param metaSwapStorage MetaSwap struct to read from and write to
* @param amounts the amounts of each token to add, in their native precision
* @param minToMint the minimum LP tokens adding this amount of liquidity
* should mint, otherwise revert. Handy for front-running mitigation
* allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored.
* @return amount of LP token user received
*/
function addLiquidity(
SwapUtils.Swap storage self,
MetaSwap storage metaSwapStorage,
uint256[] memory amounts,
uint256 minToMint
) external returns (uint256) {
IERC20[] memory pooledTokens = self.pooledTokens;
require(
amounts.length == pooledTokens.length,
"Amounts must match pooled tokens"
);
uint256[] memory fees = new uint256[](pooledTokens.length);
// current state
ManageLiquidityInfo memory v =
ManageLiquidityInfo(
0,
0,
0,
self.lpToken,
0,
self._getAPrecise(),
_updateBaseVirtualPrice(metaSwapStorage),
self.tokenPrecisionMultipliers,
self.balances
);
v.totalSupply = v.lpToken.totalSupply();
if (v.totalSupply != 0) {
v.d0 = SwapUtils.getD(
_xp(
v.newBalances,
v.tokenPrecisionMultipliers,
v.baseVirtualPrice
),
v.preciseA
);
}
for (uint256 i = 0; i < pooledTokens.length; i++) {
require(
v.totalSupply != 0 || amounts[i] > 0,
"Must supply all tokens in pool"
);
// Transfer tokens first to see if a fee was charged on transfer
if (amounts[i] != 0) {
uint256 beforeBalance =
pooledTokens[i].balanceOf(address(this));
pooledTokens[i].safeTransferFrom(
msg.sender,
address(this),
amounts[i]
);
// Update the amounts[] with actual transfer amount
amounts[i] = pooledTokens[i].balanceOf(address(this)).sub(
beforeBalance
);
}
v.newBalances[i] = v.newBalances[i].add(amounts[i]);
}
// invariant after change
v.d1 = SwapUtils.getD(
_xp(v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice),
v.preciseA
);
require(v.d1 > v.d0, "D should increase");
// updated to reflect fees and calculate the user's LP tokens
v.d2 = v.d1;
uint256 toMint;
if (v.totalSupply != 0) {
uint256 feePerToken =
SwapUtils._feePerToken(self.swapFee, pooledTokens.length);
for (uint256 i = 0; i < pooledTokens.length; i++) {
uint256 idealBalance = v.d1.mul(self.balances[i]).div(v.d0);
fees[i] = feePerToken
.mul(idealBalance.difference(v.newBalances[i]))
.div(FEE_DENOMINATOR);
self.balances[i] = v.newBalances[i].sub(
fees[i].mul(self.adminFee).div(FEE_DENOMINATOR)
);
v.newBalances[i] = v.newBalances[i].sub(fees[i]);
}
v.d2 = SwapUtils.getD(
_xp(
v.newBalances,
v.tokenPrecisionMultipliers,
v.baseVirtualPrice
),
v.preciseA
);
toMint = v.d2.sub(v.d0).mul(v.totalSupply).div(v.d0);
} else {
// the initial depositor doesn't pay fees
self.balances = v.newBalances;
toMint = v.d1;
}
require(toMint >= minToMint, "Couldn't mint min requested");
// mint the user's LP tokens
self.lpToken.mint(msg.sender, toMint);
emit AddLiquidity(
msg.sender,
amounts,
fees,
v.d1,
v.totalSupply.add(toMint)
);
return toMint;
}
/**
* @notice Remove liquidity from the pool all in one token.
* @param self Swap struct to read from and write to
* @param metaSwapStorage MetaSwap struct to read from and write to
* @param tokenAmount the amount of the lp tokens to burn
* @param tokenIndex the index of the token you want to receive