-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathIPool.sol
1418 lines (1263 loc) · 42.3 KB
/
IPool.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: GPL-3.0
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./BToken.sol";
import "./BMath.sol";
import "../interfaces/IFlashLoanRecipient.sol";
/************************************************************************************************
Originally from https://github.com/balancer-labs/balancer-core/blob/master/contracts/BPool.sol
This source code has been modified from the original, which was copied from the github repository
at commit hash f4ed5d65362a8d6cec21662fb6eae233b0babc1f.
Subject to the GPL-3.0 license
*************************************************************************************************/
contract IPool is BToken, BMath {
/**
* @dev Token record data structure
* @param bound is token bound to pool
* @param ready has token been initialized
* @param lastDenormUpdate timestamp of last denorm change
* @param denorm denormalized weight
* @param desiredDenorm desired denormalized weight (used for incremental changes)
* @param index index of address in tokens array
* @param balance token balance
*/
struct Record {
bool bound;
bool ready;
uint40 lastDenormUpdate;
uint96 denorm;
uint96 desiredDenorm;
uint8 index;
uint256 balance;
}
/* --- EVENTS --- */
/** @dev Emitted when tokens are swapped. */
event LOG_SWAP(
address indexed caller,
address indexed tokenIn,
address indexed tokenOut,
uint256 tokenAmountIn,
uint256 tokenAmountOut
);
/** @dev Emitted when underlying tokens are deposited for pool tokens. */
event LOG_JOIN(
address indexed caller,
address indexed tokenIn,
uint256 tokenAmountIn
);
/** @dev Emitted when pool tokens are burned for underlying. */
event LOG_EXIT(
address indexed caller,
address indexed tokenOut,
uint256 tokenAmountOut
);
/** @dev Emitted when a token's weight updates. */
event LOG_DENORM_UPDATED(address indexed token, uint256 newDenorm);
/** @dev Emitted when a token's desired weight is set. */
event LOG_DESIRED_DENORM_SET(address indexed token, uint256 desiredDenorm);
/** @dev Emitted when a token is unbound from the pool. */
event LOG_TOKEN_REMOVED(address token);
/** @dev Emitted when a token is unbound from the pool. */
event LOG_TOKEN_ADDED(
address indexed token,
uint256 desiredDenorm,
uint256 minimumBalance
);
/** @dev Emitted when a token's minimum balance is updated. */
event LOG_MINIMUM_BALANCE_UPDATED(address token, uint256 minimumBalance);
/** @dev Emitted when a token reaches its minimum balance. */
event LOG_TOKEN_READY(address indexed token);
/** @dev Emitted when public trades are enabled or disabled. */
event LOG_PUBLIC_SWAP_TOGGLED(bool publicSwap);
/** @dev Emitted when the maximum tokens value is updated. */
event LOG_MAX_TOKENS_UPDATED(uint256 maxPoolTokens);
/** @dev Emitted when the swap fee is updated. */
event LOG_SWAP_FEE_UPDATED(uint256 swapFee);
/* --- Modifiers --- */
modifier _lock_ {
require(!_mutex, "ERR_REENTRY");
_mutex = true;
_;
_mutex = false;
}
modifier _control_ {
require(msg.sender == _controller, "ERR_NOT_CONTROLLER");
_;
}
modifier _public_ {
require(_publicSwap, "ERR_NOT_PUBLIC");
_;
}
/* --- Storage --- */
bool internal _mutex;
// Account with CONTROL role. Able to modify the swap fee,
// adjust token weights, bind and unbind tokens and lock
// public swaps & joins.
address internal _controller;
// Contract that handles unbound tokens.
TokenUnbindHandler internal _unbindHandler;
// True if PUBLIC can call SWAP & JOIN functions
bool internal _publicSwap;
// `setSwapFee` requires CONTROL
uint256 internal _swapFee;
// Array of underlying tokens in the pool.
address[] internal _tokens;
// Internal records of the pool's underlying tokens
mapping(address => Record) internal _records;
// Total denormalized weight of the pool.
uint256 internal _totalWeight;
// Minimum balances for tokens which have been added without the
// requisite initial balance.
mapping(address => uint256) internal _minimumBalances;
// Maximum LP tokens that can be bound.
// Used in alpha to restrict the economic impact of a catastrophic
// failure. It can be gradually increased as the pool continues to
// not be exploited.
uint256 internal _maxPoolTokens;
/* --- Controls --- */
/**
* @dev Sets the controller address and the token name & symbol.
*
* Note: This saves on storage costs for multi-step pool deployment.
*
* @param controller Controller of the pool
* @param name Name of the pool token
* @param symbol Symbol of the pool token
*/
function configure(
address controller,
string calldata name,
string calldata symbol
) external {
require(_controller == address(0), "ERR_CONFIGURED");
require(controller != address(0), "ERR_NULL_ADDRESS");
_controller = controller;
// default fee is 2.5%
_swapFee = BONE / 40;
_initializeToken(name, symbol);
}
/**
* @dev Sets up the initial assets for the pool.
*
* Note: `tokenProvider` must have approved the pool to transfer the
* corresponding `balances` of `tokens`.
*
* @param tokens Underlying tokens to initialize the pool with
* @param balances Initial balances to transfer
* @param denorms Initial denormalized weights for the tokens
* @param tokenProvider Address to transfer the balances from
*/
function initialize(
address[] calldata tokens,
uint256[] calldata balances,
uint96[] calldata denorms,
address tokenProvider,
address unbindHandler
)
external
_control_
{
require(_tokens.length == 0, "ERR_INITIALIZED");
uint256 len = tokens.length;
require(len >= MIN_BOUND_TOKENS, "ERR_MIN_TOKENS");
require(len <= MAX_BOUND_TOKENS, "ERR_MAX_TOKENS");
require(balances.length == len && denorms.length == len, "ERR_ARR_LEN");
uint256 totalWeight = 0;
for (uint256 i = 0; i < len; i++) {
// _bind(tokens[i], balances[i], denorms[i]);
address token = tokens[i];
uint96 denorm = denorms[i];
uint256 balance = balances[i];
require(denorm >= MIN_WEIGHT, "ERR_MIN_WEIGHT");
require(denorm <= MAX_WEIGHT, "ERR_MAX_WEIGHT");
require(balance >= MIN_BALANCE, "ERR_MIN_BALANCE");
_records[token] = Record({
bound: true,
ready: true,
lastDenormUpdate: uint40(now),
denorm: denorm,
desiredDenorm: denorm,
index: uint8(i),
balance: balance
});
_tokens.push(token);
totalWeight = badd(totalWeight, denorm);
_pullUnderlying(token, tokenProvider, balance);
}
require(totalWeight <= MAX_TOTAL_WEIGHT, "ERR_MAX_TOTAL_WEIGHT");
_totalWeight = totalWeight;
_publicSwap = true;
emit LOG_PUBLIC_SWAP_TOGGLED(true);
_mintPoolShare(INIT_POOL_SUPPLY);
_pushPoolShare(tokenProvider, INIT_POOL_SUPPLY);
_unbindHandler = TokenUnbindHandler(unbindHandler);
}
/**
* @dev Sets the maximum number of pool tokens that can be minted.
*
* This value will be used in the alpha to limit the maximum damage
* that can be caused by a catastrophic error. It can be gradually
* increased as the pool continues to not be exploited.
*
* If it is set to 0, the limit will be removed.
*/
function setMaxPoolTokens(uint256 maxPoolTokens) external _control_ {
_maxPoolTokens = maxPoolTokens;
emit LOG_MAX_TOKENS_UPDATED(maxPoolTokens);
}
/* --- Configuration Actions --- */
/**
* @dev Set the swap fee.
* Note: Swap fee must be between 0.0001% and 10%
*/
function setSwapFee(uint256 swapFee) external _control_ {
require(swapFee >= MIN_FEE, "ERR_MIN_FEE");
require(swapFee <= MAX_FEE, "ERR_MAX_FEE");
_swapFee = swapFee;
emit LOG_SWAP_FEE_UPDATED(swapFee);
}
/* --- Token Management Actions --- */
/**
* @dev Sets the desired weights for the pool tokens, which
* will be adjusted over time as they are swapped.
*
* Note: This does not check for duplicate tokens or that the total
* of the desired weights is equal to the target total weight (25).
* Those assumptions should be met in the controller. Further, the
* provided tokens should only include the tokens which are not set
* for removal.
*/
function reweighTokens(
address[] calldata tokens,
uint96[] calldata desiredDenorms
)
external
_lock_
_control_
{
uint256 len = tokens.length;
require(desiredDenorms.length == len, "ERR_ARR_LEN");
for (uint256 i = 0; i < len; i++)
_setDesiredDenorm(tokens[i], desiredDenorms[i]);
}
/**
* @dev Update the underlying assets held by the pool and their associated
* weights. Tokens which are not currently bound will be gradually added
* as they are swapped in to reach the provided minimum balances, which must
* be an amount of tokens worth the minimum weight of the total pool value.
* If a currently bound token is not received in this call, the token's
* desired weight will be set to 0.
*/
function reindexTokens(
address[] calldata tokens,
uint96[] calldata desiredDenorms,
uint256[] calldata minimumBalances
)
external
_lock_
_control_
{
uint256 len = tokens.length;
require(
desiredDenorms.length == len && minimumBalances.length == len,
"ERR_ARR_LEN"
);
// This size may not be the same as the input size, as it is possible
// to temporarily exceed the index size while tokens are being phased in
// or out.
uint256 tLen = _tokens.length;
bool[] memory receivedIndices = new bool[](tLen);
// We need to read token records in two separate loops, so
// write them to memory to avoid duplicate storage reads.
Record[] memory records = new Record[](len);
// Read all the records from storage and mark which of the existing tokens
// were represented in the reindex call.
for (uint256 i = 0; i < len; i++) {
Record memory record = _records[tokens[i]];
if (record.bound) receivedIndices[record.index] = true;
records[i] = record;
}
// If any bound tokens were not sent in this call, set their desired weights to 0.
for (uint256 i = 0; i < tLen; i++) {
if (!receivedIndices[i]) {
_setDesiredDenorm(_tokens[i], 0);
}
}
for (uint256 i = 0; i < len; i++) {
address token = tokens[i];
// If an input weight is less than the minimum weight, use that instead.
uint96 denorm = desiredDenorms[i];
if (denorm < MIN_WEIGHT) denorm = uint96(MIN_WEIGHT);
if (!records[i].bound) {
// If the token is not bound, bind it.
_bind(token, minimumBalances[i], denorm);
} else {
_setDesiredDenorm(token, denorm);
}
}
}
/**
* @dev Updates the minimum balance for an uninitialized token.
* This becomes useful if a token's external price significantly
* rises after being bound, since the pool can not send a token
* out until it reaches the minimum balance.
*/
function setMinimumBalance(
address token,
uint256 minimumBalance
)
external
_control_
{
Record memory record = _records[token];
require(record.bound, "ERR_NOT_BOUND");
require(!record.ready, "ERR_READY");
_minimumBalances[token] = minimumBalance;
emit LOG_MINIMUM_BALANCE_UPDATED(token, minimumBalance);
}
/* --- Liquidity Provider Actions --- */
/**
* @dev Mint new pool tokens by providing the proportional amount of each
* underlying token's balance relative to the proportion of pool tokens minted.
*
* For any underlying tokens which are not initialized, the caller must provide
* the proportional share of the minimum balance for the token rather than the
* actual balance.
*/
function joinPool(uint256 poolAmountOut, uint256[] calldata maxAmountsIn)
external
_lock_
_public_
{
uint256 poolTotal = totalSupply();
uint256 ratio = bdiv(poolAmountOut, poolTotal);
require(ratio != 0, "ERR_MATH_APPROX");
require(maxAmountsIn.length == _tokens.length, "ERR_ARR_LEN");
uint256 maxPoolTokens = _maxPoolTokens;
if (maxPoolTokens > 0) {
require(
badd(poolTotal, poolAmountOut) <= _maxPoolTokens,
"ERR_MAX_POOL_TOKENS"
);
}
for (uint256 i = 0; i < maxAmountsIn.length; i++) {
address t = _tokens[i];
(Record memory record, uint256 realBalance) = _getInputToken(t);
uint256 tokenAmountIn = bmul(ratio, record.balance);
require(tokenAmountIn != 0, "ERR_MATH_APPROX");
require(tokenAmountIn <= maxAmountsIn[i], "ERR_LIMIT_IN");
_updateInputToken(t, record, badd(realBalance, tokenAmountIn));
emit LOG_JOIN(msg.sender, t, tokenAmountIn);
_pullUnderlying(t, msg.sender, tokenAmountIn);
}
_mintPoolShare(poolAmountOut);
_pushPoolShare(msg.sender, poolAmountOut);
}
/**
* @dev Pay `tokenAmountIn` of `tokenIn` to mint at least `minPoolAmountOut`
* pool tokens.
*
* The pool implicitly swaps `(1- weightTokenIn) * tokenAmountIn` to the other
* underlying tokens. Thus a swap fee is charged against the input tokens.
*/
function joinswapExternAmountIn(
address tokenIn,
uint256 tokenAmountIn,
uint256 minPoolAmountOut
)
external
_lock_
_public_
returns (uint256 poolAmountOut)
{
(Record memory inRecord, uint256 realInBalance) = _getInputToken(tokenIn);
require(tokenAmountIn != 0, "ERR_ZERO_IN");
require(
tokenAmountIn <= bmul(inRecord.balance, MAX_IN_RATIO),
"ERR_MAX_IN_RATIO"
);
poolAmountOut = calcPoolOutGivenSingleIn(
inRecord.balance,
inRecord.denorm,
_totalSupply,
_totalWeight,
tokenAmountIn,
_swapFee
);
uint256 maxPoolTokens = _maxPoolTokens;
if (maxPoolTokens > 0) {
require(
badd(_totalSupply, poolAmountOut) <= _maxPoolTokens,
"ERR_MAX_POOL_TOKENS"
);
}
require(poolAmountOut >= minPoolAmountOut, "ERR_LIMIT_OUT");
_updateInputToken(tokenIn, inRecord, badd(realInBalance, tokenAmountIn));
emit LOG_JOIN(msg.sender, tokenIn, tokenAmountIn);
_mintPoolShare(poolAmountOut);
_pushPoolShare(msg.sender, poolAmountOut);
_pullUnderlying(tokenIn, msg.sender, tokenAmountIn);
return poolAmountOut;
}
/**
* @dev Pay up to `maxAmountIn` of `tokenIn` to mint exactly `poolAmountOut`.
*
* The pool implicitly swaps `(1- weightTokenIn) * tokenAmountIn` to the other
* underlying tokens. Thus a swap fee is charged against the input tokens.
*/
function joinswapPoolAmountOut(
address tokenIn,
uint256 poolAmountOut,
uint256 maxAmountIn
)
external
_lock_
_public_
returns (uint256 tokenAmountIn)
{
uint256 maxPoolTokens = _maxPoolTokens;
if (maxPoolTokens > 0) {
require(
badd(_totalSupply, poolAmountOut) <= _maxPoolTokens,
"ERR_MAX_POOL_TOKENS"
);
}
(Record memory inRecord, uint256 realInBalance) = _getInputToken(tokenIn);
tokenAmountIn = calcSingleInGivenPoolOut(
inRecord.balance,
inRecord.denorm,
_totalSupply,
_totalWeight,
poolAmountOut,
_swapFee
);
require(tokenAmountIn != 0, "ERR_MATH_APPROX");
require(tokenAmountIn <= maxAmountIn, "ERR_LIMIT_IN");
require(
tokenAmountIn <= bmul(inRecord.balance, MAX_IN_RATIO),
"ERR_MAX_IN_RATIO"
);
_updateInputToken(tokenIn, inRecord, badd(realInBalance, tokenAmountIn));
emit LOG_JOIN(msg.sender, tokenIn, tokenAmountIn);
_mintPoolShare(poolAmountOut);
_pushPoolShare(msg.sender, poolAmountOut);
_pullUnderlying(tokenIn, msg.sender, tokenAmountIn);
return tokenAmountIn;
}
/**
* @dev Burns `poolAmountIn` pool tokens in exchange for the amounts of each
* underlying token's balance proportional to the ratio of tokens burned to
* total pool supply. The amount of each token transferred to the caller must
* be greater than or equal to the associated minimum output amount from the
* `minAmountsOut` array.
*/
function exitPool(uint256 poolAmountIn, uint256[] calldata minAmountsOut)
external
_lock_
{
uint256 poolTotal = totalSupply();
uint256 exitFee = bmul(poolAmountIn, EXIT_FEE);
uint256 pAiAfterExitFee = bsub(poolAmountIn, exitFee);
uint256 ratio = bdiv(pAiAfterExitFee, poolTotal);
require(ratio != 0, "ERR_MATH_APPROX");
_pullPoolShare(msg.sender, poolAmountIn);
_pushPoolShare(_controller, exitFee);
_burnPoolShare(pAiAfterExitFee);
require(minAmountsOut.length == _tokens.length, "ERR_ARR_LEN");
for (uint256 i = 0; i < minAmountsOut.length; i++) {
address t = _tokens[i];
Record memory record = _records[t];
if (record.ready) {
uint256 tokenAmountOut = bmul(ratio, record.balance);
require(tokenAmountOut != 0, "ERR_MATH_APPROX");
require(tokenAmountOut >= minAmountsOut[i], "ERR_LIMIT_OUT");
_records[t].balance = bsub(record.balance, tokenAmountOut);
emit LOG_EXIT(msg.sender, t, tokenAmountOut);
_pushUnderlying(t, msg.sender, tokenAmountOut);
} else {
// If the token is not initialized, it can not exit the pool.
require(minAmountsOut[i] == 0, "ERR_OUT_NOT_READY");
}
}
}
/**
* @dev Burns `poolAmountIn` pool tokens in exchange for at least `minAmountOut`
* of `tokenOut`. Returns the number of tokens sent to the caller.
*
* The pool implicitly burns the tokens for all underlying tokens and swaps them
* to the desired output token. A swap fee is charged against the output tokens.
*/
function exitswapPoolAmountIn(
address tokenOut,
uint256 poolAmountIn,
uint256 minAmountOut
)
external
_lock_
returns (uint256 tokenAmountOut)
{
Record memory outRecord = _getOutputToken(tokenOut);
tokenAmountOut = calcSingleOutGivenPoolIn(
outRecord.balance,
outRecord.denorm,
_totalSupply,
_totalWeight,
poolAmountIn,
_swapFee
);
require(tokenAmountOut >= minAmountOut, "ERR_LIMIT_OUT");
require(
tokenAmountOut <= bmul(outRecord.balance, MAX_OUT_RATIO),
"ERR_MAX_OUT_RATIO"
);
_pushUnderlying(tokenOut, msg.sender, tokenAmountOut);
_records[tokenOut].balance = bsub(outRecord.balance, tokenAmountOut);
_decreaseDenorm(outRecord, tokenOut);
uint256 exitFee = bmul(poolAmountIn, EXIT_FEE);
emit LOG_EXIT(msg.sender, tokenOut, tokenAmountOut);
_pullPoolShare(msg.sender, poolAmountIn);
_burnPoolShare(bsub(poolAmountIn, exitFee));
_pushPoolShare(_controller, exitFee);
return tokenAmountOut;
}
/**
* @dev Burn up to `maxPoolAmountIn` for exactly `tokenAmountOut` of `tokenOut`.
* Returns the number of pool tokens burned.
*
* The pool implicitly burns the tokens for all underlying tokens and swaps them
* to the desired output token. A swap fee is charged against the output tokens.
*/
function exitswapExternAmountOut(
address tokenOut,
uint256 tokenAmountOut,
uint256 maxPoolAmountIn
)
external
_lock_
returns (uint256 poolAmountIn)
{
Record memory outRecord = _getOutputToken(tokenOut);
require(
tokenAmountOut <= bmul(outRecord.balance, MAX_OUT_RATIO),
"ERR_MAX_OUT_RATIO"
);
poolAmountIn = calcPoolInGivenSingleOut(
outRecord.balance,
outRecord.denorm,
_totalSupply,
_totalWeight,
tokenAmountOut,
_swapFee
);
require(poolAmountIn != 0, "ERR_MATH_APPROX");
require(poolAmountIn <= maxPoolAmountIn, "ERR_LIMIT_IN");
_pushUnderlying(tokenOut, msg.sender, tokenAmountOut);
_records[tokenOut].balance = bsub(outRecord.balance, tokenAmountOut);
_decreaseDenorm(outRecord, tokenOut);
uint256 exitFee = bmul(poolAmountIn, EXIT_FEE);
emit LOG_EXIT(msg.sender, tokenOut, tokenAmountOut);
_pullPoolShare(msg.sender, poolAmountIn);
_burnPoolShare(bsub(poolAmountIn, exitFee));
_pushPoolShare(_controller, exitFee);
return poolAmountIn;
}
/* --- Other --- */
/**
* @dev Absorb any tokens that have been sent to the pool.
* If the token is not bound, it will be sent to the unbound
* token handler.
*/
function gulp(address token) external _lock_ {
Record memory record = _records[token];
uint256 balance = IERC20(token).balanceOf(address(this));
if (record.bound) {
if (!record.ready) {
record.denorm = uint96(MIN_WEIGHT);
_updateInputToken(token, record, balance);
}
} else {
_pushUnderlying(token, address(_unbindHandler), balance);
_unbindHandler.handleUnbindToken(token, balance);
}
}
/* --- Flash Loan --- */
/**
* @dev Execute a flash loan, transferring `amount` of `token` to `recipient`.
* `amount` must be repaid with `swapFee` interest by the end of the transaction.
*
* @param recipient Must implement the IFlashLoanRecipient interface
* @param token Token to borrow
* @param amount Amount to borrow
* @param data Data to send to the recipient in `receiveFlashLoan` call
*/
function flashBorrow(
IFlashLoanRecipient recipient,
address token,
uint256 amount,
bytes calldata data
)
external
_lock_
{
Record memory record = _records[token];
require(record.bound, "ERR_NOT_BOUND");
uint256 balStart = IERC20(token).balanceOf(address(this));
require(balStart >= amount, "ERR_INSUFFICIENT_BAL");
_pushUnderlying(token, address(recipient), amount);
recipient.receiveFlashLoan(data);
uint256 balEnd = IERC20(token).balanceOf(address(this));
uint256 gained = bsub(balEnd, balStart);
uint256 fee = bmul(balStart, _swapFee);
require(
balEnd > balStart && fee >= gained,
"ERR_INSUFFICIENT_PAYMENT"
);
_records[token].balance = balEnd;
// If the payment brings the token above its minimum balance,
// clear the minimum and mark the token as ready.
if (!record.ready) {
uint256 minimumBalance = _minimumBalances[token];
if (balEnd >= minimumBalance) {
_minimumBalances[token] = 0;
_records[token].ready = true;
_records[token].denorm = uint96(MIN_WEIGHT);
_totalWeight = badd(_totalWeight, MIN_WEIGHT);
}
}
}
/* --- Token Swaps --- */
/**
* @dev Execute a token swap with a specified amount of input
* tokens and a minimum amount of output tokens.
* Note: Will throw if `tokenOut` is uninitialized.
*/
function swapExactAmountIn(
address tokenIn,
uint256 tokenAmountIn,
address tokenOut,
uint256 minAmountOut,
uint256 maxPrice
)
external
_lock_
_public_
returns (uint256 tokenAmountOut, uint256 spotPriceAfter)
{
(Record memory inRecord, uint256 realInBalance) = _getInputToken(tokenIn);
Record memory outRecord = _getOutputToken(tokenOut);
require(
tokenAmountIn <= bmul(inRecord.balance, MAX_IN_RATIO),
"ERR_MAX_IN_RATIO"
);
uint256 spotPriceBefore = calcSpotPrice(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
_swapFee
);
require(spotPriceBefore <= maxPrice, "ERR_BAD_LIMIT_PRICE");
tokenAmountOut = calcOutGivenIn(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
tokenAmountIn,
_swapFee
);
require(tokenAmountOut >= minAmountOut, "ERR_LIMIT_OUT");
_pullUnderlying(tokenIn, msg.sender, tokenAmountIn);
_pushUnderlying(tokenOut, msg.sender, tokenAmountOut);
realInBalance = badd(realInBalance, tokenAmountIn);
_updateInputToken(tokenIn, inRecord, realInBalance);
if (inRecord.ready) {
inRecord.balance = realInBalance;
}
// Update the in-memory record for the spotPriceAfter calculation,
// then update the storage record with the local balance.
outRecord.balance = bsub(outRecord.balance, tokenAmountOut);
_records[tokenOut].balance = outRecord.balance;
// If needed, update the output token's weight.
_decreaseDenorm(outRecord, tokenOut);
spotPriceAfter = calcSpotPrice(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
_swapFee
);
require(spotPriceAfter >= spotPriceBefore, "ERR_MATH_APPROX_2");
require(spotPriceAfter <= maxPrice, "ERR_LIMIT_PRICE");
require(
spotPriceBefore <= bdiv(tokenAmountIn, tokenAmountOut),
"ERR_MATH_APPROX"
);
emit LOG_SWAP(msg.sender, tokenIn, tokenOut, tokenAmountIn, tokenAmountOut);
return (tokenAmountOut, spotPriceAfter);
}
/**
* @dev Trades at most `maxAmountIn` of `tokenIn` for exactly `tokenAmountOut`
* of `tokenOut`.
* Returns the actual input amount and the new spot price after the swap,
* which can not exceed `maxPrice`.
*/
function swapExactAmountOut(
address tokenIn,
uint256 maxAmountIn,
address tokenOut,
uint256 tokenAmountOut,
uint256 maxPrice
)
external
_lock_
_public_
returns (uint256 tokenAmountIn, uint256 spotPriceAfter)
{
(Record memory inRecord, uint256 realInBalance) = _getInputToken(tokenIn);
Record memory outRecord = _getOutputToken(tokenOut);
require(
tokenAmountOut <= bmul(outRecord.balance, MAX_OUT_RATIO),
"ERR_MAX_OUT_RATIO"
);
uint256 spotPriceBefore = calcSpotPrice(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
_swapFee
);
require(spotPriceBefore <= maxPrice, "ERR_BAD_LIMIT_PRICE");
tokenAmountIn = calcInGivenOut(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
tokenAmountOut,
_swapFee
);
require(tokenAmountIn <= maxAmountIn, "ERR_LIMIT_IN");
_pullUnderlying(tokenIn, msg.sender, tokenAmountIn);
_pushUnderlying(tokenOut, msg.sender, tokenAmountOut);
// Update the balance and (if necessary) weight of the input token.
realInBalance = badd(realInBalance, tokenAmountIn);
_updateInputToken(tokenIn, inRecord, realInBalance);
if (inRecord.ready) {
inRecord.balance = realInBalance;
}
// Update the in-memory record for the spotPriceAfter calculation,
// then update the storage record with the local balance.
outRecord.balance = bsub(outRecord.balance, tokenAmountOut);
_records[tokenOut].balance = outRecord.balance;
// If needed, update the output token's weight.
_decreaseDenorm(outRecord, tokenOut);
spotPriceAfter = calcSpotPrice(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
_swapFee
);
require(spotPriceAfter >= spotPriceBefore, "ERR_MATH_APPROX");
require(spotPriceAfter <= maxPrice, "ERR_LIMIT_PRICE");
require(
spotPriceBefore <= bdiv(tokenAmountIn, tokenAmountOut),
"ERR_MATH_APPROX"
);
emit LOG_SWAP(msg.sender, tokenIn, tokenOut, tokenAmountIn, tokenAmountOut);
return (tokenAmountIn, spotPriceAfter);
}
/* --- Config Queries --- */
/**
* @dev Check if swapping tokens and joining the pool is allowed.
*/
function isPublicSwap() external view returns (bool isPublic) {
isPublic = _publicSwap;
}
function getSwapFee() external view returns (uint256 swapFee) {
swapFee = _swapFee;
}
/**
* @dev Returns the controller address.
*/
function getController()
external
view
returns (address controller)
{
controller = _controller;
}
/* --- Token Queries --- */
function getMaxPoolTokens() external view returns (uint256) {
return _maxPoolTokens;
}
/**
* @dev Check if a token is bound to the pool.
*/
function isBound(address t) external view returns (bool) {
return _records[t].bound;
}
/**
* @dev Get the number of tokens bound to the pool.
*/
function getNumTokens() external
view
returns (uint256 num)
{
num = _tokens.length;
}
/**
* @dev Get all bound tokens.
*/
function getCurrentTokens()
external
view
returns (address[] memory tokens)
{
return _tokens;
}
/**
* @dev Returns the list of tokens which have a desired weight above 0.
* Tokens with a desired weight of 0 are set to be phased out of the pool.
*/
function getCurrentDesiredTokens()
external
view
returns (address[] memory tokens)
{
address[] memory tempTokens = _tokens;
tokens = new address[](tempTokens.length);
uint256 usedIndex = 0;
for (uint256 i = 0; i < tokens.length; i++) {
address token = tempTokens[i];
Record memory record = _records[token];
if (record.desiredDenorm > 0) {
tokens[usedIndex++] = token;
}
}
assembly { mstore(tokens, usedIndex) }
}
/**
* @dev Get the denormalized weight of a bound token.
*/
function getDenormalizedWeight(address token)
external
view
returns (uint256 denorm)
{
require(_records[token].bound, "ERR_NOT_BOUND");
denorm = _records[token].denorm;
}
/**
* @dev Get the record for a token bound to the pool.
*/
function getTokenRecord(address token)
external
view
returns (Record memory record)
{
record = _records[token];
require(record.bound, "ERR_NOT_BOUND");
}
/**
* @dev Finds the first token which is initialized and
* returns the address of that token and the extrapolated
* value of the pool in that token.
*
* The value is extrapolated by multiplying the token's
* balance by the reciprocal of its normalized weight.
*/
function extrapolatePoolValueFromToken()
external
view
returns (address token, uint256 extrapolatedValue)
{
uint256 len = _tokens.length;