-
Notifications
You must be signed in to change notification settings - Fork 0
/
WeightedPool2Tokens.sol
1193 lines (1013 loc) · 49.4 KB
/
WeightedPool2Tokens.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-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "@balancer-labs/v2-solidity-utils/contracts/math/FixedPoint.sol";
import "@balancer-labs/v2-solidity-utils/contracts/helpers/InputHelpers.sol";
import "@balancer-labs/v2-solidity-utils/contracts/helpers/LogCompression.sol";
import "@balancer-labs/v2-solidity-utils/contracts/helpers/TemporarilyPausable.sol";
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ERC20.sol";
import "@balancer-labs/v2-vault/contracts/interfaces/IMinimalSwapInfoPool.sol";
import "@balancer-labs/v2-pool-utils/contracts/BasePoolAuthorization.sol";
import "@balancer-labs/v2-pool-utils/contracts/BalancerPoolToken.sol";
import "@balancer-labs/v2-pool-utils/contracts/oracle/PoolPriceOracle.sol";
import "@balancer-labs/v2-pool-utils/contracts/oracle/Buffer.sol";
import "./WeightedMath.sol";
import "./WeightedOracleMath.sol";
import "./WeightedPoolUserData.sol";
import "./WeightedPool2TokensMiscData.sol";
contract WeightedPool2Tokens is
IMinimalSwapInfoPool,
BasePoolAuthorization,
BalancerPoolToken,
TemporarilyPausable,
PoolPriceOracle,
WeightedOracleMath
{
using FixedPoint for uint256;
using WeightedPoolUserData for bytes;
using WeightedPool2TokensMiscData for bytes32;
uint256 private constant _MINIMUM_BPT = 1e6;
// 1e18 corresponds to 1.0, or a 100% fee
uint256 private constant _MIN_SWAP_FEE_PERCENTAGE = 1e12; // 0.0001%
uint256 private constant _MAX_SWAP_FEE_PERCENTAGE = 1e17; // 10%
// The swap fee is internally stored using 64 bits, which is enough to represent _MAX_SWAP_FEE_PERCENTAGE.
bytes32 internal _miscData;
uint256 private _lastInvariant;
bytes32 private immutable _poolId;
IERC20 internal immutable _token0;
IERC20 internal immutable _token1;
uint256 private immutable _normalizedWeight0;
uint256 private immutable _normalizedWeight1;
// The protocol fees will always be charged using the token associated with the max weight in the pool.
// Since these Pools will register tokens only once, we can assume this index will be constant.
uint256 private immutable _maxWeightTokenIndex;
// All token balances are normalized to behave as if the token had 18 decimals. We assume a token's decimals will
// not change throughout its lifetime, and store the corresponding scaling factor for each at construction time.
// These factors are always greater than or equal to one: tokens with more than 18 decimals are not supported.
uint256 internal immutable _scalingFactor0;
uint256 internal immutable _scalingFactor1;
event OracleEnabledChanged(bool enabled);
event SwapFeePercentageChanged(uint256 swapFeePercentage);
modifier onlyVault(bytes32 poolId) {
_require(msg.sender == address(getVault()), Errors.CALLER_NOT_VAULT);
_require(poolId == getPoolId(), Errors.INVALID_POOL_ID);
_;
}
struct NewPoolParams {
IVault vault;
string name;
string symbol;
IERC20 token0;
IERC20 token1;
uint256 normalizedWeight0;
uint256 normalizedWeight1;
uint256 swapFeePercentage;
uint256 pauseWindowDuration;
uint256 bufferPeriodDuration;
bool oracleEnabled;
address owner;
}
constructor(NewPoolParams memory params)
// Base Pools are expected to be deployed using factories. By using the factory address as the action
// disambiguator, we make all Pools deployed by the same factory share action identifiers. This allows for
// simpler management of permissions (such as being able to manage granting the 'set fee percentage' action in
// any Pool created by the same factory), while still making action identifiers unique among different factories
// if the selectors match, preventing accidental errors.
Authentication(bytes32(uint256(msg.sender)))
BalancerPoolToken(params.name, params.symbol, params.vault)
BasePoolAuthorization(params.owner)
TemporarilyPausable(params.pauseWindowDuration, params.bufferPeriodDuration)
{
_setOracleEnabled(params.oracleEnabled);
_setSwapFeePercentage(params.swapFeePercentage);
bytes32 poolId = params.vault.registerPool(IVault.PoolSpecialization.TWO_TOKEN);
// Pass in zero addresses for Asset Managers
IERC20[] memory tokens = new IERC20[](2);
tokens[0] = params.token0;
tokens[1] = params.token1;
params.vault.registerTokens(poolId, tokens, new address[](2));
// Set immutable state variables - these cannot be read from during construction
_poolId = poolId;
_token0 = params.token0;
_token1 = params.token1;
_scalingFactor0 = _computeScalingFactor(params.token0);
_scalingFactor1 = _computeScalingFactor(params.token1);
// Ensure each normalized weight is above them minimum and find the token index of the maximum weight
_require(params.normalizedWeight0 >= WeightedMath._MIN_WEIGHT, Errors.MIN_WEIGHT);
_require(params.normalizedWeight1 >= WeightedMath._MIN_WEIGHT, Errors.MIN_WEIGHT);
// Ensure that the normalized weights sum to ONE
uint256 normalizedSum = params.normalizedWeight0.add(params.normalizedWeight1);
_require(normalizedSum == FixedPoint.ONE, Errors.NORMALIZED_WEIGHT_INVARIANT);
_normalizedWeight0 = params.normalizedWeight0;
_normalizedWeight1 = params.normalizedWeight1;
_maxWeightTokenIndex = params.normalizedWeight0 >= params.normalizedWeight1 ? 0 : 1;
}
// Getters / Setters
function getPoolId() public view override returns (bytes32) {
return _poolId;
}
function getMiscData()
external
view
returns (
int256 logInvariant,
int256 logTotalSupply,
uint256 oracleSampleCreationTimestamp,
uint256 oracleIndex,
bool oracleEnabled,
uint256 swapFeePercentage
)
{
bytes32 miscData = _miscData;
logInvariant = miscData.logInvariant();
logTotalSupply = miscData.logTotalSupply();
oracleSampleCreationTimestamp = miscData.oracleSampleCreationTimestamp();
oracleIndex = miscData.oracleIndex();
oracleEnabled = miscData.oracleEnabled();
swapFeePercentage = miscData.swapFeePercentage();
}
function getSwapFeePercentage() public view returns (uint256) {
return _miscData.swapFeePercentage();
}
// Caller must be approved by the Vault's Authorizer
function setSwapFeePercentage(uint256 swapFeePercentage) public virtual authenticate whenNotPaused {
_setSwapFeePercentage(swapFeePercentage);
}
function _setSwapFeePercentage(uint256 swapFeePercentage) private {
_require(swapFeePercentage >= _MIN_SWAP_FEE_PERCENTAGE, Errors.MIN_SWAP_FEE_PERCENTAGE);
_require(swapFeePercentage <= _MAX_SWAP_FEE_PERCENTAGE, Errors.MAX_SWAP_FEE_PERCENTAGE);
_miscData = _miscData.setSwapFeePercentage(swapFeePercentage);
emit SwapFeePercentageChanged(swapFeePercentage);
}
function _isOwnerOnlyAction(bytes32 actionId) internal view virtual override returns (bool) {
return
(actionId == getActionId(BasePool.setSwapFeePercentage.selector)) ||
(actionId == getActionId(BasePool.setAssetManagerPoolConfig.selector));
}
/**
* @dev Balancer Governance can always enable the Oracle, even if it was originally not enabled. This allows for
* Pools that unexpectedly drive much more volume and liquidity than expected to serve as Price Oracles.
*
* Note that the Oracle can only be enabled - it can never be disabled.
*/
function enableOracle() external whenNotPaused authenticate {
_setOracleEnabled(true);
// Cache log invariant and supply only if the pool was initialized
if (totalSupply() > 0) {
_cacheInvariantAndSupply();
}
}
function _setOracleEnabled(bool enabled) internal {
_miscData = _miscData.setOracleEnabled(enabled);
emit OracleEnabledChanged(enabled);
}
// Caller must be approved by the Vault's Authorizer
function setPaused(bool paused) external authenticate {
_setPaused(paused);
}
function getNormalizedWeights() external view returns (uint256[] memory) {
return _normalizedWeights();
}
function _normalizedWeights() internal view virtual returns (uint256[] memory) {
uint256[] memory normalizedWeights = new uint256[](2);
normalizedWeights[0] = _normalizedWeights(true);
normalizedWeights[1] = _normalizedWeights(false);
return normalizedWeights;
}
function _normalizedWeights(bool token0) internal view virtual returns (uint256) {
return token0 ? _normalizedWeight0 : _normalizedWeight1;
}
function getLastInvariant() external view returns (uint256) {
return _lastInvariant;
}
/**
* @dev Returns the current value of the invariant.
*/
function getInvariant() public view returns (uint256) {
(, uint256[] memory balances, ) = getVault().getPoolTokens(getPoolId());
// Since the Pool hooks always work with upscaled balances, we manually
// upscale here for consistency
_upscaleArray(balances);
uint256[] memory normalizedWeights = _normalizedWeights();
return WeightedMath._calculateInvariant(normalizedWeights, balances);
}
// Swap Hooks
function onSwap(
SwapRequest memory request,
uint256 balanceTokenIn,
uint256 balanceTokenOut
) public virtual override whenNotPaused onlyVault(request.poolId) returns (uint256) {
bool tokenInIsToken0 = request.tokenIn == _token0;
uint256 scalingFactorTokenIn = _scalingFactor(tokenInIsToken0);
uint256 scalingFactorTokenOut = _scalingFactor(!tokenInIsToken0);
uint256 normalizedWeightIn = _normalizedWeights(tokenInIsToken0);
uint256 normalizedWeightOut = _normalizedWeights(!tokenInIsToken0);
// All token amounts are upscaled.
balanceTokenIn = _upscale(balanceTokenIn, scalingFactorTokenIn);
balanceTokenOut = _upscale(balanceTokenOut, scalingFactorTokenOut);
// Update price oracle with the pre-swap balances
_updateOracle(
request.lastChangeBlock,
tokenInIsToken0 ? balanceTokenIn : balanceTokenOut,
tokenInIsToken0 ? balanceTokenOut : balanceTokenIn
);
if (request.kind == IVault.SwapKind.GIVEN_IN) {
// Fees are subtracted before scaling, to reduce the complexity of the rounding direction analysis.
// This is amount - fee amount, so we round up (favoring a higher fee amount).
uint256 feeAmount = request.amount.mulUp(getSwapFeePercentage());
request.amount = _upscale(request.amount.sub(feeAmount), scalingFactorTokenIn);
uint256 amountOut = _onSwapGivenIn(
request,
balanceTokenIn,
balanceTokenOut,
normalizedWeightIn,
normalizedWeightOut
);
// amountOut tokens are exiting the Pool, so we round down.
return _downscaleDown(amountOut, scalingFactorTokenOut);
} else {
request.amount = _upscale(request.amount, scalingFactorTokenOut);
uint256 amountIn = _onSwapGivenOut(
request,
balanceTokenIn,
balanceTokenOut,
normalizedWeightIn,
normalizedWeightOut
);
// amountIn tokens are entering the Pool, so we round up.
amountIn = _downscaleUp(amountIn, scalingFactorTokenIn);
// Fees are added after scaling happens, to reduce the complexity of the rounding direction analysis.
// This is amount + fee amount, so we round up (favoring a higher fee amount).
return amountIn.divUp(getSwapFeePercentage().complement());
}
}
function _onSwapGivenIn(
SwapRequest memory swapRequest,
uint256 currentBalanceTokenIn,
uint256 currentBalanceTokenOut,
uint256 normalizedWeightIn,
uint256 normalizedWeightOut
) private pure returns (uint256) {
// Swaps are disabled while the contract is paused.
return
WeightedMath._calcOutGivenIn(
currentBalanceTokenIn,
normalizedWeightIn,
currentBalanceTokenOut,
normalizedWeightOut,
swapRequest.amount
);
}
function _onSwapGivenOut(
SwapRequest memory swapRequest,
uint256 currentBalanceTokenIn,
uint256 currentBalanceTokenOut,
uint256 normalizedWeightIn,
uint256 normalizedWeightOut
) private pure returns (uint256) {
// Swaps are disabled while the contract is paused.
return
WeightedMath._calcInGivenOut(
currentBalanceTokenIn,
normalizedWeightIn,
currentBalanceTokenOut,
normalizedWeightOut,
swapRequest.amount
);
}
// Join Hook
function onJoinPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
)
public
virtual
override
onlyVault(poolId)
whenNotPaused
returns (uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts)
{
// All joins, including initializations, are disabled while the contract is paused.
uint256 bptAmountOut;
if (totalSupply() == 0) {
(bptAmountOut, amountsIn) = _onInitializePool(poolId, sender, recipient, userData);
// On initialization, we lock _MINIMUM_BPT by minting it for the zero address. This BPT acts as a minimum
// as it will never be burned, which reduces potential issues with rounding, and also prevents the Pool from
// ever being fully drained.
_require(bptAmountOut >= _MINIMUM_BPT, Errors.MINIMUM_BPT);
_mintPoolTokens(address(0), _MINIMUM_BPT);
_mintPoolTokens(recipient, bptAmountOut - _MINIMUM_BPT);
// amountsIn are amounts entering the Pool, so we round up.
_downscaleUpArray(amountsIn);
// There are no due protocol fee amounts during initialization
dueProtocolFeeAmounts = new uint256[](2);
} else {
_upscaleArray(balances);
// Update price oracle with the pre-join balances
_updateOracle(lastChangeBlock, balances[0], balances[1]);
(bptAmountOut, amountsIn, dueProtocolFeeAmounts) = _onJoinPool(
poolId,
sender,
recipient,
balances,
lastChangeBlock,
protocolSwapFeePercentage,
userData
);
// Note we no longer use `balances` after calling `_onJoinPool`, which may mutate it.
_mintPoolTokens(recipient, bptAmountOut);
// amountsIn are amounts entering the Pool, so we round up.
_downscaleUpArray(amountsIn);
// dueProtocolFeeAmounts are amounts exiting the Pool, so we round down.
_downscaleDownArray(dueProtocolFeeAmounts);
}
// Update cached total supply and invariant using the results after the join that will be used for future
// oracle updates.
_cacheInvariantAndSupply();
}
/**
* @dev Called when the Pool is joined for the first time; that is, when the BPT total supply is zero.
*
* Returns the amount of BPT to mint, and the token amounts the Pool will receive in return.
*
* Minted BPT will be sent to `recipient`, except for _MINIMUM_BPT, which will be deducted from this amount and sent
* to the zero address instead. This will cause that BPT to remain forever locked there, preventing total BTP from
* ever dropping below that value, and ensuring `_onInitializePool` can only be called once in the entire Pool's
* lifetime.
*
* The tokens granted to the Pool will be transferred from `sender`. These amounts are considered upscaled and will
* be downscaled (rounding up) before being returned to the Vault.
*/
function _onInitializePool(
bytes32,
address,
address,
bytes memory userData
) private returns (uint256, uint256[] memory) {
WeightedPoolUserData.JoinKind kind = userData.joinKind();
_require(kind == WeightedPoolUserData.JoinKind.INIT, Errors.UNINITIALIZED);
uint256[] memory amountsIn = userData.initialAmountsIn();
InputHelpers.ensureInputLengthMatch(amountsIn.length, 2);
_upscaleArray(amountsIn);
uint256[] memory normalizedWeights = _normalizedWeights();
uint256 invariantAfterJoin = WeightedMath._calculateInvariant(normalizedWeights, amountsIn);
// Set the initial BPT to the value of the invariant times the number of tokens. This makes BPT supply more
// consistent in Pools with similar compositions but different number of tokens.
uint256 bptAmountOut = Math.mul(invariantAfterJoin, 2);
_lastInvariant = invariantAfterJoin;
return (bptAmountOut, amountsIn);
}
/**
* @dev Called whenever the Pool is joined after the first initialization join (see `_onInitializePool`).
*
* Returns the amount of BPT to mint, the token amounts that the Pool will receive in return, and the number of
* tokens to pay in protocol swap fees.
*
* Implementations of this function might choose to mutate the `balances` array to save gas (e.g. when
* performing intermediate calculations, such as subtraction of due protocol fees). This can be done safely.
*
* Minted BPT will be sent to `recipient`.
*
* The tokens granted to the Pool will be transferred from `sender`. These amounts are considered upscaled and will
* be downscaled (rounding up) before being returned to the Vault.
*
* Due protocol swap fees will be taken from the Pool's balance in the Vault (see `IBasePool.onJoinPool`). These
* amounts are considered upscaled and will be downscaled (rounding down) before being returned to the Vault.
*/
function _onJoinPool(
bytes32,
address,
address,
uint256[] memory balances,
uint256,
uint256 protocolSwapFeePercentage,
bytes memory userData
)
private
returns (
uint256,
uint256[] memory,
uint256[] memory
)
{
uint256[] memory normalizedWeights = _normalizedWeights();
// Due protocol swap fee amounts are computed by measuring the growth of the invariant between the previous join
// or exit event and now - the invariant's growth is due exclusively to swap fees. This avoids spending gas
// computing them on each individual swap
uint256 invariantBeforeJoin = WeightedMath._calculateInvariant(normalizedWeights, balances);
uint256[] memory dueProtocolFeeAmounts = _getDueProtocolFeeAmounts(
balances,
normalizedWeights,
_lastInvariant,
invariantBeforeJoin,
protocolSwapFeePercentage
);
// Update current balances by subtracting the protocol fee amounts
_mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub);
(uint256 bptAmountOut, uint256[] memory amountsIn) = _doJoin(balances, normalizedWeights, userData);
// Update the invariant with the balances the Pool will have after the join, in order to compute the
// protocol swap fee amounts due in future joins and exits.
_mutateAmounts(balances, amountsIn, FixedPoint.add);
_lastInvariant = WeightedMath._calculateInvariant(normalizedWeights, balances);
return (bptAmountOut, amountsIn, dueProtocolFeeAmounts);
}
function _doJoin(
uint256[] memory balances,
uint256[] memory normalizedWeights,
bytes memory userData
) private view returns (uint256, uint256[] memory) {
WeightedPoolUserData.JoinKind kind = userData.joinKind();
if (kind == WeightedPoolUserData.JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT) {
return _joinExactTokensInForBPTOut(balances, normalizedWeights, userData);
} else if (kind == WeightedPoolUserData.JoinKind.TOKEN_IN_FOR_EXACT_BPT_OUT) {
return _joinTokenInForExactBPTOut(balances, normalizedWeights, userData);
} else if (kind == WeightedPoolUserData.JoinKind.ALL_TOKENS_IN_FOR_EXACT_BPT_OUT) {
return _joinAllTokensInForExactBPTOut(balances, userData);
} else {
_revert(Errors.UNHANDLED_JOIN_KIND);
}
}
function _joinExactTokensInForBPTOut(
uint256[] memory balances,
uint256[] memory normalizedWeights,
bytes memory userData
) private view returns (uint256, uint256[] memory) {
(uint256[] memory amountsIn, uint256 minBPTAmountOut) = userData.exactTokensInForBptOut();
InputHelpers.ensureInputLengthMatch(amountsIn.length, 2);
_upscaleArray(amountsIn);
(uint256 bptAmountOut, ) = WeightedMath._calcBptOutGivenExactTokensIn(
balances,
normalizedWeights,
amountsIn,
totalSupply(),
getSwapFeePercentage()
);
_require(bptAmountOut >= minBPTAmountOut, Errors.BPT_OUT_MIN_AMOUNT);
return (bptAmountOut, amountsIn);
}
function _joinTokenInForExactBPTOut(
uint256[] memory balances,
uint256[] memory normalizedWeights,
bytes memory userData
) private view returns (uint256, uint256[] memory) {
(uint256 bptAmountOut, uint256 tokenIndex) = userData.tokenInForExactBptOut();
// Note that there is no maximum amountIn parameter: this is handled by `IVault.joinPool`.
_require(tokenIndex < 2, Errors.OUT_OF_BOUNDS);
uint256[] memory amountsIn = new uint256[](2);
(amountsIn[tokenIndex], ) = WeightedMath._calcTokenInGivenExactBptOut(
balances[tokenIndex],
normalizedWeights[tokenIndex],
bptAmountOut,
totalSupply(),
getSwapFeePercentage()
);
return (bptAmountOut, amountsIn);
}
function _joinAllTokensInForExactBPTOut(uint256[] memory balances, bytes memory userData)
private
view
returns (uint256, uint256[] memory)
{
uint256 bptAmountOut = userData.allTokensInForExactBptOut();
// Note that there is no maximum amountsIn parameter: this is handled by `IVault.joinPool`.
uint256[] memory amountsIn = WeightedMath._calcAllTokensInGivenExactBptOut(
balances,
bptAmountOut,
totalSupply()
);
return (bptAmountOut, amountsIn);
}
// Exit Hook
function onExitPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) public virtual override onlyVault(poolId) returns (uint256[] memory, uint256[] memory) {
_upscaleArray(balances);
(uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts) = _onExitPool(
poolId,
sender,
recipient,
balances,
lastChangeBlock,
protocolSwapFeePercentage,
userData
);
// Note we no longer use `balances` after calling `_onExitPool`, which may mutate it.
_burnPoolTokens(sender, bptAmountIn);
// Both amountsOut and dueProtocolFeeAmounts are amounts exiting the Pool, so we round down.
_downscaleDownArray(amountsOut);
_downscaleDownArray(dueProtocolFeeAmounts);
// Update cached total supply and invariant using the results after the exit that will be used for future
// oracle updates, only if the pool was not paused (to minimize code paths taken while paused).
if (_isNotPaused()) {
_cacheInvariantAndSupply();
}
return (amountsOut, dueProtocolFeeAmounts);
}
/**
* @dev Called whenever the Pool is exited.
*
* Returns the amount of BPT to burn, the token amounts for each Pool token that the Pool will grant in return, and
* the number of tokens to pay in protocol swap fees.
*
* Implementations of this function might choose to mutate the `balances` array to save gas (e.g. when
* performing intermediate calculations, such as subtraction of due protocol fees). This can be done safely.
*
* BPT will be burnt from `sender`.
*
* The Pool will grant tokens to `recipient`. These amounts are considered upscaled and will be downscaled
* (rounding down) before being returned to the Vault.
*
* Due protocol swap fees will be taken from the Pool's balance in the Vault (see `IBasePool.onExitPool`). These
* amounts are considered upscaled and will be downscaled (rounding down) before being returned to the Vault.
*/
function _onExitPool(
bytes32,
address,
address,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
)
private
returns (
uint256 bptAmountIn,
uint256[] memory amountsOut,
uint256[] memory dueProtocolFeeAmounts
)
{
// Exits are not completely disabled while the contract is paused: proportional exits (exact BPT in for tokens
// out) remain functional.
uint256[] memory normalizedWeights = _normalizedWeights();
if (_isNotPaused()) {
// Update price oracle with the pre-exit balances
_updateOracle(lastChangeBlock, balances[0], balances[1]);
// Due protocol swap fee amounts are computed by measuring the growth of the invariant between the previous
// join or exit event and now - the invariant's growth is due exclusively to swap fees. This avoids
// spending gas calculating the fees on each individual swap.
uint256 invariantBeforeExit = WeightedMath._calculateInvariant(normalizedWeights, balances);
dueProtocolFeeAmounts = _getDueProtocolFeeAmounts(
balances,
normalizedWeights,
_lastInvariant,
invariantBeforeExit,
protocolSwapFeePercentage
);
// Update current balances by subtracting the protocol fee amounts
_mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub);
} else {
// If the contract is paused, swap protocol fee amounts are not charged and the oracle is not updated
// to avoid extra calculations and reduce the potential for errors.
dueProtocolFeeAmounts = new uint256[](2);
}
(bptAmountIn, amountsOut) = _doExit(balances, normalizedWeights, userData);
// Update the invariant with the balances the Pool will have after the exit, in order to compute the
// protocol swap fees due in future joins and exits.
_mutateAmounts(balances, amountsOut, FixedPoint.sub);
_lastInvariant = WeightedMath._calculateInvariant(normalizedWeights, balances);
return (bptAmountIn, amountsOut, dueProtocolFeeAmounts);
}
function _doExit(
uint256[] memory balances,
uint256[] memory normalizedWeights,
bytes memory userData
) private view returns (uint256, uint256[] memory) {
WeightedPoolUserData.ExitKind kind = userData.exitKind();
if (kind == WeightedPoolUserData.ExitKind.EXACT_BPT_IN_FOR_ONE_TOKEN_OUT) {
return _exitExactBPTInForTokenOut(balances, normalizedWeights, userData);
} else if (kind == WeightedPoolUserData.ExitKind.EXACT_BPT_IN_FOR_TOKENS_OUT) {
return _exitExactBPTInForTokensOut(balances, userData);
} else if (kind == WeightedPoolUserData.ExitKind.BPT_IN_FOR_EXACT_TOKENS_OUT) {
return _exitBPTInForExactTokensOut(balances, normalizedWeights, userData);
} else {
_revert(Errors.UNHANDLED_EXIT_KIND);
}
}
function _exitExactBPTInForTokenOut(
uint256[] memory balances,
uint256[] memory normalizedWeights,
bytes memory userData
) private view whenNotPaused returns (uint256, uint256[] memory) {
// This exit function is disabled if the contract is paused.
(uint256 bptAmountIn, uint256 tokenIndex) = userData.exactBptInForTokenOut();
// Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`.
_require(tokenIndex < 2, Errors.OUT_OF_BOUNDS);
// We exit in a single token, so we initialize amountsOut with zeros
uint256[] memory amountsOut = new uint256[](2);
// And then assign the result to the selected token
(amountsOut[tokenIndex], ) = WeightedMath._calcTokenOutGivenExactBptIn(
balances[tokenIndex],
normalizedWeights[tokenIndex],
bptAmountIn,
totalSupply(),
getSwapFeePercentage()
);
return (bptAmountIn, amountsOut);
}
function _exitExactBPTInForTokensOut(uint256[] memory balances, bytes memory userData)
private
view
returns (uint256, uint256[] memory)
{
// This exit function is the only one that is not disabled if the contract is paused: it remains unrestricted
// in an attempt to provide users with a mechanism to retrieve their tokens in case of an emergency.
// This particular exit function is the only one that remains available because it is the simplest one, and
// therefore the one with the lowest likelihood of errors.
uint256 bptAmountIn = userData.exactBptInForTokensOut();
// Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`.
uint256[] memory amountsOut = WeightedMath._calcTokensOutGivenExactBptIn(balances, bptAmountIn, totalSupply());
return (bptAmountIn, amountsOut);
}
function _exitBPTInForExactTokensOut(
uint256[] memory balances,
uint256[] memory normalizedWeights,
bytes memory userData
) private view whenNotPaused returns (uint256, uint256[] memory) {
// This exit function is disabled if the contract is paused.
(uint256[] memory amountsOut, uint256 maxBPTAmountIn) = userData.bptInForExactTokensOut();
InputHelpers.ensureInputLengthMatch(amountsOut.length, 2);
_upscaleArray(amountsOut);
(uint256 bptAmountIn, ) = WeightedMath._calcBptInGivenExactTokensOut(
balances,
normalizedWeights,
amountsOut,
totalSupply(),
getSwapFeePercentage()
);
_require(bptAmountIn <= maxBPTAmountIn, Errors.BPT_IN_MAX_AMOUNT);
return (bptAmountIn, amountsOut);
}
// Oracle functions
/**
* @dev Updates the Price Oracle based on the Pool's current state (balances, BPT supply and invariant). Must be
* called on *all* state-changing functions with the balances *before* the state change happens, and with
* `lastChangeBlock` as the number of the block in which any of the balances last changed.
*/
function _updateOracle(
uint256 lastChangeBlock,
uint256 balanceToken0,
uint256 balanceToken1
) internal {
bytes32 miscData = _miscData;
if (miscData.oracleEnabled() && block.number > lastChangeBlock) {
int256 logSpotPrice = WeightedOracleMath._calcLogSpotPrice(
_normalizedWeight0,
balanceToken0,
_normalizedWeight1,
balanceToken1
);
int256 logBPTPrice = WeightedOracleMath._calcLogBPTPrice(
_normalizedWeight0,
balanceToken0,
miscData.logTotalSupply()
);
uint256 oracleCurrentIndex = miscData.oracleIndex();
uint256 oracleCurrentSampleInitialTimestamp = miscData.oracleSampleCreationTimestamp();
uint256 oracleUpdatedIndex = _processPriceData(
oracleCurrentSampleInitialTimestamp,
oracleCurrentIndex,
logSpotPrice,
logBPTPrice,
miscData.logInvariant()
);
if (oracleCurrentIndex != oracleUpdatedIndex) {
// solhint-disable not-rely-on-time
miscData = miscData.setOracleIndex(oracleUpdatedIndex);
miscData = miscData.setOracleSampleCreationTimestamp(block.timestamp);
_miscData = miscData;
}
}
}
/**
* @dev Stores the logarithm of the invariant and BPT total supply, to be later used in each oracle update. Because
* it is stored in miscData, which is read in all operations (including swaps), this saves gas by not requiring to
* compute or read these values when updating the oracle.
*
* This function must be called by all actions that update the invariant and BPT supply (joins and exits). Swaps
* also alter the invariant due to collected swap fees, but this growth is considered negligible and not accounted
* for.
*/
function _cacheInvariantAndSupply() internal {
bytes32 miscData = _miscData;
if (miscData.oracleEnabled()) {
miscData = miscData.setLogInvariant(LogCompression.toLowResLog(_lastInvariant));
miscData = miscData.setLogTotalSupply(LogCompression.toLowResLog(totalSupply()));
_miscData = miscData;
}
}
function _getOracleIndex() internal view override returns (uint256) {
return _miscData.oracleIndex();
}
// Query functions
/**
* @dev Returns the amount of BPT that would be granted to `recipient` if the `onJoinPool` hook were called by the
* Vault with the same arguments, along with the number of tokens `sender` would have to supply.
*
* This function is not meant to be called directly, but rather from a helper contract that fetches current Vault
* data, such as the protocol swap fee percentage and Pool balances.
*
* Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must
* explicitly use eth_call instead of eth_sendTransaction.
*/
function queryJoin(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external returns (uint256 bptOut, uint256[] memory amountsIn) {
InputHelpers.ensureInputLengthMatch(balances.length, 2);
_queryAction(
poolId,
sender,
recipient,
balances,
lastChangeBlock,
protocolSwapFeePercentage,
userData,
_onJoinPool,
_downscaleUpArray
);
// The `return` opcode is executed directly inside `_queryAction`, so execution never reaches this statement,
// and we don't need to return anything here - it just silences compiler warnings.
return (bptOut, amountsIn);
}
/**
* @dev Returns the amount of BPT that would be burned from `sender` if the `onExitPool` hook were called by the
* Vault with the same arguments, along with the number of tokens `recipient` would receive.
*
* This function is not meant to be called directly, but rather from a helper contract that fetches current Vault
* data, such as the protocol swap fee percentage and Pool balances.
*
* Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must
* explicitly use eth_call instead of eth_sendTransaction.
*/
function queryExit(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external returns (uint256 bptIn, uint256[] memory amountsOut) {
InputHelpers.ensureInputLengthMatch(balances.length, 2);
_queryAction(
poolId,
sender,
recipient,
balances,
lastChangeBlock,
protocolSwapFeePercentage,
userData,
_onExitPool,
_downscaleDownArray
);
// The `return` opcode is executed directly inside `_queryAction`, so execution never reaches this statement,
// and we don't need to return anything here - it just silences compiler warnings.
return (bptIn, amountsOut);
}
// Helpers
function _getDueProtocolFeeAmounts(
uint256[] memory balances,
uint256[] memory normalizedWeights,
uint256 previousInvariant,
uint256 currentInvariant,
uint256 protocolSwapFeePercentage
) private view returns (uint256[] memory) {
// Initialize with zeros
uint256[] memory dueProtocolFeeAmounts = new uint256[](2);
// Early return if the protocol swap fee percentage is zero, saving gas.
if (protocolSwapFeePercentage == 0) {
return dueProtocolFeeAmounts;
}
// The protocol swap fees are always paid using the token with the largest weight in the Pool. As this is the
// token that is expected to have the largest balance, using it to pay fees should not unbalance the Pool.
dueProtocolFeeAmounts[_maxWeightTokenIndex] = WeightedMath._calcDueTokenProtocolSwapFeeAmount(
balances[_maxWeightTokenIndex],
normalizedWeights[_maxWeightTokenIndex],
previousInvariant,
currentInvariant,
protocolSwapFeePercentage
);
return dueProtocolFeeAmounts;
}
/**
* @dev Mutates `amounts` by applying `mutation` with each entry in `arguments`.
*
* Equivalent to `amounts = amounts.map(mutation)`.
*/
function _mutateAmounts(
uint256[] memory toMutate,
uint256[] memory arguments,
function(uint256, uint256) pure returns (uint256) mutation
) private pure {
toMutate[0] = mutation(toMutate[0], arguments[0]);
toMutate[1] = mutation(toMutate[1], arguments[1]);
}
/**
* @dev This function returns the appreciation of one BPT relative to the
* underlying tokens. This starts at 1 when the pool is created and grows over time
*/
function getRate() public view returns (uint256) {
// The initial BPT supply is equal to the invariant times the number of tokens.
return Math.mul(getInvariant(), 2).divDown(totalSupply());
}
// Scaling
/**
* @dev Returns a scaling factor that, when multiplied to a token amount for `token`, normalizes its balance as if
* it had 18 decimals.
*/
function _computeScalingFactor(IERC20 token) private view returns (uint256) {
// Tokens that don't implement the `decimals` method are not supported.
uint256 tokenDecimals = ERC20(address(token)).decimals();