-
Notifications
You must be signed in to change notification settings - Fork 389
/
Copy pathBasePool.sol
787 lines (677 loc) · 34.7 KB
/
BasePool.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
// 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-interfaces/contracts/pool-utils/IControlledPool.sol";
import "@balancer-labs/v2-interfaces/contracts/vault/IVault.sol";
import "@balancer-labs/v2-interfaces/contracts/vault/IBasePool.sol";
import "@balancer-labs/v2-solidity-utils/contracts/helpers/InputHelpers.sol";
import "@balancer-labs/v2-solidity-utils/contracts/helpers/WordCodec.sol";
import "@balancer-labs/v2-solidity-utils/contracts/helpers/ScalingHelpers.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-solidity-utils/contracts/math/FixedPoint.sol";
import "@balancer-labs/v2-solidity-utils/contracts/math/Math.sol";
import "./lib/PoolRegistrationLib.sol";
import "./BalancerPoolToken.sol";
import "./BasePoolAuthorization.sol";
import "./RecoveryMode.sol";
// solhint-disable max-states-count
/**
* @notice Reference implementation for the base layer of a Pool contract.
* @dev Reference implementation for the base layer of a Pool contract that manages a single Pool with optional
* Asset Managers, an admin-controlled swap fee percentage, and an emergency pause mechanism.
*
* This Pool pays protocol fees by minting BPT directly to the ProtocolFeeCollector instead of using the
* `dueProtocolFees` return value. This results in the underlying tokens continuing to provide liquidity
* for traders, while still keeping gas usage to a minimum since only a single token (the BPT) is transferred.
*
* Note that neither swap fees nor the pause mechanism are used by this contract. They are passed through so that
* derived contracts can use them via the `_addSwapFeeAmount` and `_subtractSwapFeeAmount` functions, and the
* `whenNotPaused` modifier.
*
* No admin permissions are checked here: instead, this contract delegates that to the Vault's own Authorizer.
*
* Because this contract doesn't implement the swap hooks, derived contracts should generally inherit from
* BaseGeneralPool or BaseMinimalSwapInfoPool. Otherwise, subclasses must inherit from the corresponding interfaces
* and implement the swap callbacks themselves.
*/
abstract contract BasePool is
IBasePool,
IControlledPool,
BasePoolAuthorization,
BalancerPoolToken,
TemporarilyPausable,
RecoveryMode
{
using WordCodec for bytes32;
using FixedPoint for uint256;
using BasePoolUserData for bytes;
uint256 private constant _MIN_TOKENS = 2;
uint256 private constant _DEFAULT_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% - this fits in 64 bits
// `_miscData` is a storage slot that can be used to store unrelated pieces of information. All pools store the
// recovery mode flag and swap fee percentage, but `miscData` can be extended to store more pieces of information.
// The most signficant bit is reserved for the recovery mode flag, and the swap fee percentage is stored in
// the next most significant 63 bits, leaving the remaining 192 bits free to store any other information derived
// pools might need.
//
// This slot is preferred for gas-sensitive operations as it is read in all joins, swaps and exits,
// and therefore warm.
// [ recovery | swap fee | available ]
// [ 1 bit | 63 bits | 192 bits ]
// [ MSB LSB ]
bytes32 private _miscData;
uint256 private constant _SWAP_FEE_PERCENTAGE_OFFSET = 192;
uint256 private constant _RECOVERY_MODE_BIT_OFFSET = 255;
// A fee can never be larger than FixedPoint.ONE, which fits in 60 bits, so 63 is more than enough.
uint256 private constant _SWAP_FEE_PERCENTAGE_BIT_LENGTH = 63;
bytes32 private immutable _poolId;
// Note that this value is immutable in the Vault, so we can make it immutable here and save gas
IProtocolFeesCollector private immutable _protocolFeesCollector;
event SwapFeePercentageChanged(uint256 swapFeePercentage);
constructor(
IVault vault,
IVault.PoolSpecialization specialization,
string memory name,
string memory symbol,
IERC20[] memory tokens,
address[] memory assetManagers,
uint256 swapFeePercentage,
uint256 pauseWindowDuration,
uint256 bufferPeriodDuration,
address owner
)
// 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(name, symbol, vault)
BasePoolAuthorization(owner)
TemporarilyPausable(pauseWindowDuration, bufferPeriodDuration)
RecoveryMode(vault)
{
_require(tokens.length >= _MIN_TOKENS, Errors.MIN_TOKENS);
_require(tokens.length <= _getMaxTokens(), Errors.MAX_TOKENS);
_setSwapFeePercentage(swapFeePercentage);
bytes32 poolId = PoolRegistrationLib.registerPoolWithAssetManagers(
vault,
specialization,
tokens,
assetManagers
);
// Set immutable state variables - these cannot be read from during construction
_poolId = poolId;
_protocolFeesCollector = vault.getProtocolFeesCollector();
}
// Getters / Setters
/**
* @notice Return the pool id.
*/
function getPoolId() public view override returns (bytes32) {
return _poolId;
}
function _getTotalTokens() internal view virtual returns (uint256);
function _getMaxTokens() internal pure virtual returns (uint256);
/**
* @dev Returns the minimum BPT supply. This amount is minted to the zero address during initialization, effectively
* locking it.
*
* This is useful to make sure Pool initialization happens only once, but derived Pools can change this value (even
* to zero) by overriding this function.
*/
function _getMinimumBpt() internal pure virtual returns (uint256) {
return _DEFAULT_MINIMUM_BPT;
}
/**
* @notice Return the current value of the swap fee percentage.
* @dev This is stored in `_miscData`.
*/
function getSwapFeePercentage() public view virtual override returns (uint256) {
return _miscData.decodeUint(_SWAP_FEE_PERCENTAGE_OFFSET, _SWAP_FEE_PERCENTAGE_BIT_LENGTH);
}
/**
* @notice Return the ProtocolFeesCollector contract.
* @dev This is immutable, and retrieved from the Vault on construction. (It is also immutable in the Vault.)
*/
function getProtocolFeesCollector() public view returns (IProtocolFeesCollector) {
return _protocolFeesCollector;
}
/**
* @notice Set the swap fee percentage.
* @dev This is a permissioned function, and disabled if the pool is paused. The swap fee must be within the
* bounds set by MIN_SWAP_FEE_PERCENTAGE/MAX_SWAP_FEE_PERCENTAGE. Emits the SwapFeePercentageChanged event.
*/
function setSwapFeePercentage(uint256 swapFeePercentage) public virtual override authenticate whenNotPaused {
_setSwapFeePercentage(swapFeePercentage);
}
function _setSwapFeePercentage(uint256 swapFeePercentage) internal virtual {
_require(swapFeePercentage >= _getMinSwapFeePercentage(), Errors.MIN_SWAP_FEE_PERCENTAGE);
_require(swapFeePercentage <= _getMaxSwapFeePercentage(), Errors.MAX_SWAP_FEE_PERCENTAGE);
_miscData = _miscData.insertUint(
swapFeePercentage,
_SWAP_FEE_PERCENTAGE_OFFSET,
_SWAP_FEE_PERCENTAGE_BIT_LENGTH
);
emit SwapFeePercentageChanged(swapFeePercentage);
}
function _getMinSwapFeePercentage() internal pure virtual returns (uint256) {
return _MIN_SWAP_FEE_PERCENTAGE;
}
function _getMaxSwapFeePercentage() internal pure virtual returns (uint256) {
return _MAX_SWAP_FEE_PERCENTAGE;
}
/**
* @notice Returns whether the pool is in Recovery Mode.
*/
function inRecoveryMode() public view override returns (bool) {
return _miscData.decodeBool(_RECOVERY_MODE_BIT_OFFSET);
}
/**
* @dev Sets the recoveryMode state, and emits the corresponding event.
*/
function _setRecoveryMode(bool enabled) internal virtual override {
_miscData = _miscData.insertBool(enabled, _RECOVERY_MODE_BIT_OFFSET);
emit RecoveryModeStateChanged(enabled);
// Some pools need to update their state when leaving recovery mode to ensure proper functioning of the Pool.
// We do not allow an `_onEnableRecoveryMode()` hook as this may jeopardize the ability to enable Recovery mode.
if (!enabled) _onDisableRecoveryMode();
}
/**
* @dev Performs any necessary actions on the disabling of Recovery Mode.
* This is usually to reset any fee collection mechanisms to ensure that they operate correctly going forward.
*/
function _onDisableRecoveryMode() internal virtual {
// solhint-disable-previous-line no-empty-blocks
}
/**
* @notice Pause the pool: an emergency action which disables all pool functions.
* @dev This is a permissioned function that will only work during the Pause Window set during pool factory
* deployment (see `TemporarilyPausable`).
*/
function pause() external authenticate {
_setPaused(true);
}
/**
* @notice Reverse a `pause` operation, and restore a pool to normal functionality.
* @dev This is a permissioned function that will only work on a paused pool within the Buffer Period set during
* pool factory deployment (see `TemporarilyPausable`). Note that any paused pools will automatically unpause
* after the Buffer Period expires.
*/
function unpause() external authenticate {
_setPaused(false);
}
function _isOwnerOnlyAction(bytes32 actionId) internal view virtual override returns (bool) {
return (actionId == getActionId(this.setSwapFeePercentage.selector)) || super._isOwnerOnlyAction(actionId);
}
function _getMiscData() internal view returns (bytes32) {
return _miscData;
}
/**
* @dev Inserts data into the least-significant 192 bits of the misc data storage slot.
* Note that the remaining 64 bits are used for the swap fee percentage and cannot be overloaded.
*/
function _setMiscData(bytes32 newData) internal {
_miscData = _miscData.insertBits192(newData, 0);
}
// Join / Exit Hooks
modifier onlyVault(bytes32 poolId) {
_require(msg.sender == address(getVault()), Errors.CALLER_NOT_VAULT);
_require(poolId == getPoolId(), Errors.INVALID_POOL_ID);
_;
}
/**
* @notice Vault hook for adding liquidity to a pool (including the first time, "initializing" the pool).
* @dev This function can only be called from the Vault, from `joinPool`.
*/
function onJoinPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external override onlyVault(poolId) returns (uint256[] memory, uint256[] memory) {
_beforeSwapJoinExit();
uint256[] memory scalingFactors = _scalingFactors();
if (totalSupply() == 0) {
(uint256 bptAmountOut, uint256[] memory amountsIn) = _onInitializePool(
poolId,
sender,
recipient,
scalingFactors,
userData
);
// On initialization, we lock _getMinimumBpt() 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 >= _getMinimumBpt(), Errors.MINIMUM_BPT);
_mintPoolTokens(address(0), _getMinimumBpt());
_mintPoolTokens(recipient, bptAmountOut - _getMinimumBpt());
// amountsIn are amounts entering the Pool, so we round up.
_downscaleUpArray(amountsIn, scalingFactors);
return (amountsIn, new uint256[](balances.length));
} else {
_upscaleArray(balances, scalingFactors);
(uint256 bptAmountOut, uint256[] memory amountsIn) = _onJoinPool(
poolId,
sender,
recipient,
balances,
lastChangeBlock,
inRecoveryMode() ? 0 : protocolSwapFeePercentage, // Protocol fees are disabled while in recovery mode
scalingFactors,
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, scalingFactors);
// This Pool ignores the `dueProtocolFees` return value, so we simply return a zeroed-out array.
return (amountsIn, new uint256[](balances.length));
}
}
/**
* @notice Vault hook for removing liquidity from a pool.
* @dev This function can only be called from the Vault, from `exitPool`.
*/
function onExitPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external override onlyVault(poolId) returns (uint256[] memory, uint256[] memory) {
uint256[] memory amountsOut;
uint256 bptAmountIn;
// When a user calls `exitPool`, this is the first point of entry from the Vault.
// We first check whether this is a Recovery Mode exit - if so, we proceed using this special lightweight exit
// mechanism which avoids computing any complex values, interacting with external contracts, etc., and generally
// should always work, even if the Pool's mathematics or a dependency break down.
if (userData.isRecoveryModeExitKind()) {
// This exit kind is only available in Recovery Mode.
_ensureInRecoveryMode();
// Note that we don't upscale balances nor downscale amountsOut - we don't care about scaling factors during
// a recovery mode exit.
(bptAmountIn, amountsOut) = _doRecoveryModeExit(balances, totalSupply(), userData);
} else {
// Note that we only call this if we're not in a recovery mode exit.
_beforeSwapJoinExit();
uint256[] memory scalingFactors = _scalingFactors();
_upscaleArray(balances, scalingFactors);
(bptAmountIn, amountsOut) = _onExitPool(
poolId,
sender,
recipient,
balances,
lastChangeBlock,
inRecoveryMode() ? 0 : protocolSwapFeePercentage, // Protocol fees are disabled while in recovery mode
scalingFactors,
userData
);
// amountsOut are amounts exiting the Pool, so we round down.
_downscaleDownArray(amountsOut, scalingFactors);
}
// Note we no longer use `balances` after calling `_onExitPool`, which may mutate it.
_burnPoolTokens(sender, bptAmountIn);
// This Pool ignores the `dueProtocolFees` return value, so we simply return a zeroed-out array.
return (amountsOut, new uint256[](balances.length));
}
// Query functions
/**
* @notice "Dry run" `onJoinPool`.
* @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 override returns (uint256 bptOut, uint256[] memory amountsIn) {
InputHelpers.ensureInputLengthMatch(balances.length, _getTotalTokens());
_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);
}
/**
* @notice "Dry run" `onExitPool`.
* @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 override returns (uint256 bptIn, uint256[] memory amountsOut) {
InputHelpers.ensureInputLengthMatch(balances.length, _getTotalTokens());
_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);
}
// Internal hooks to be overridden by derived contracts - all token amounts (except BPT) in these interfaces are
// upscaled.
/**
* @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 _getMinimumBpt(), 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 poolId,
address sender,
address recipient,
uint256[] memory scalingFactors,
bytes memory userData
) internal virtual returns (uint256 bptAmountOut, uint256[] memory 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 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
uint256[] memory scalingFactors,
bytes memory userData
) internal virtual returns (uint256 bptAmountOut, uint256[] memory amountsIn);
/**
* @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 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
uint256[] memory scalingFactors,
bytes memory userData
) internal virtual returns (uint256 bptAmountIn, uint256[] memory amountsOut);
/**
* @dev Called at the very beginning of swaps, joins and exits, even before the scaling factors are read. Derived
* contracts can extend this implementation to perform any state-changing operations they might need (including e.g.
* updating the scaling factors),
*
* The only scenario in which this function is not called is during a recovery mode exit. This makes it safe to
* perform non-trivial computations or interact with external dependencies here, as recovery mode will not be
* affected.
*
* Since this contract does not implement swaps, derived contracts must also make sure this function is called on
* swap handlers.
*/
function _beforeSwapJoinExit() internal virtual {
// All joins, exits and swaps are disabled (except recovery mode exits).
_ensureNotPaused();
}
// Internal functions
/**
* @dev Pays protocol fees by minting `bptAmount` to the Protocol Fee Collector.
*/
function _payProtocolFees(uint256 bptAmount) internal {
if (bptAmount > 0) {
_mintPoolTokens(address(getProtocolFeesCollector()), bptAmount);
}
}
/**
* @dev Adds swap fee amount to `amount`, returning a higher value.
*/
function _addSwapFeeAmount(uint256 amount) internal view returns (uint256) {
// This returns amount + fee amount, so we round up (favoring a higher fee amount).
return amount.divUp(getSwapFeePercentage().complement());
}
/**
* @dev Subtracts swap fee amount from `amount`, returning a lower value.
*/
function _subtractSwapFeeAmount(uint256 amount) internal view returns (uint256) {
// This returns amount - fee amount, so we round up (favoring a higher fee amount).
uint256 feeAmount = amount.mulUp(getSwapFeePercentage());
return amount.sub(feeAmount);
}
// 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) internal view returns (uint256) {
if (address(token) == address(this)) {
return FixedPoint.ONE;
}
// Tokens that don't implement the `decimals` method are not supported.
uint256 tokenDecimals = ERC20(address(token)).decimals();
// Tokens with more than 18 decimals are not supported.
uint256 decimalsDifference = Math.sub(18, tokenDecimals);
return FixedPoint.ONE * 10**decimalsDifference;
}
/**
* @dev Returns the scaling factor for one of the Pool's tokens. Reverts if `token` is not a token registered by the
* Pool.
*
* All scaling factors are fixed-point values with 18 decimals, to allow for this function to be overridden by
* derived contracts that need to apply further scaling, making these factors potentially non-integer.
*
* The largest 'base' scaling factor (i.e. in tokens with less than 18 decimals) is 10**18, which in fixed-point is
* 10**36. This value can be multiplied with a 112 bit Vault balance with no overflow by a factor of ~1e7, making
* even relatively 'large' factors safe to use.
*
* The 1e7 figure is the result of 2**256 / (1e18 * 1e18 * 2**112).
*/
function _scalingFactor(IERC20 token) internal view virtual returns (uint256);
/**
* @dev Same as `_scalingFactor()`, except for all registered tokens (in the same order as registered). The Vault
* will always pass balances in this order when calling any of the Pool hooks.
*/
function _scalingFactors() internal view virtual returns (uint256[] memory);
function getScalingFactors() external view override returns (uint256[] memory) {
return _scalingFactors();
}
function _getAuthorizer() internal view override returns (IAuthorizer) {
// Access control management is delegated to the Vault's Authorizer. This lets Balancer Governance manage which
// accounts can call permissioned functions: for example, to perform emergency pauses.
// If the owner is delegated, then *all* permissioned functions, including `setSwapFeePercentage`, will be under
// Governance control.
return getVault().getAuthorizer();
}
function _queryAction(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData,
function(bytes32, address, address, uint256[] memory, uint256, uint256, uint256[] memory, bytes memory)
internal
returns (uint256, uint256[] memory) _action,
function(uint256[] memory, uint256[] memory) internal view _downscaleArray
) private {
// This uses the same technique used by the Vault in queryBatchSwap. Refer to that function for a detailed
// explanation.
if (msg.sender != address(this)) {
// We perform an external call to ourselves, forwarding the same calldata. In this call, the else clause of
// the preceding if statement will be executed instead.
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = address(this).call(msg.data);
// solhint-disable-next-line no-inline-assembly
assembly {
// This call should always revert to decode the bpt and token amounts from the revert reason
switch success
case 0 {
// Note we are manually writing the memory slot 0. We can safely overwrite whatever is
// stored there as we take full control of the execution and then immediately return.
// We copy the first 4 bytes to check if it matches with the expected signature, otherwise
// there was another revert reason and we should forward it.
returndatacopy(0, 0, 0x04)
let error := and(mload(0), 0xffffffff00000000000000000000000000000000000000000000000000000000)
// If the first 4 bytes don't match with the expected signature, we forward the revert reason.
if eq(eq(error, 0x43adbafb00000000000000000000000000000000000000000000000000000000), 0) {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
// The returndata contains the signature, followed by the raw memory representation of the
// `bptAmount` and `tokenAmounts` (array: length + data). We need to return an ABI-encoded
// representation of these.
// An ABI-encoded response will include one additional field to indicate the starting offset of
// the `tokenAmounts` array. The `bptAmount` will be laid out in the first word of the
// returndata.
//
// In returndata:
// [ signature ][ bptAmount ][ tokenAmounts length ][ tokenAmounts values ]
// [ 4 bytes ][ 32 bytes ][ 32 bytes ][ (32 * length) bytes ]
//
// We now need to return (ABI-encoded values):
// [ bptAmount ][ tokeAmounts offset ][ tokenAmounts length ][ tokenAmounts values ]
// [ 32 bytes ][ 32 bytes ][ 32 bytes ][ (32 * length) bytes ]
// We copy 32 bytes for the `bptAmount` from returndata into memory.
// Note that we skip the first 4 bytes for the error signature
returndatacopy(0, 0x04, 32)
// The offsets are 32-bytes long, so the array of `tokenAmounts` will start after
// the initial 64 bytes.
mstore(0x20, 64)
// We now copy the raw memory array for the `tokenAmounts` from returndata into memory.
// Since bpt amount and offset take up 64 bytes, we start copying at address 0x40. We also
// skip the first 36 bytes from returndata, which correspond to the signature plus bpt amount.
returndatacopy(0x40, 0x24, sub(returndatasize(), 36))
// We finally return the ABI-encoded uint256 and the array, which has a total length equal to
// the size of returndata, plus the 32 bytes of the offset but without the 4 bytes of the
// error signature.
return(0, add(returndatasize(), 28))
}
default {
// This call should always revert, but we fail nonetheless if that didn't happen
invalid()
}
}
} else {
// This imitates the relevant parts of the bodies of onJoin and onExit. Since they're not virtual, we know
// that their implementations will match this regardless of what derived contracts might do.
_beforeSwapJoinExit();
uint256[] memory scalingFactors = _scalingFactors();
_upscaleArray(balances, scalingFactors);
(uint256 bptAmount, uint256[] memory tokenAmounts) = _action(
poolId,
sender,
recipient,
balances,
lastChangeBlock,
protocolSwapFeePercentage,
scalingFactors,
userData
);
_downscaleArray(tokenAmounts, scalingFactors);
// solhint-disable-next-line no-inline-assembly
assembly {
// We will return a raw representation of `bptAmount` and `tokenAmounts` in memory, which is composed of
// a 32-byte uint256, followed by a 32-byte for the array length, and finally the 32-byte uint256 values
// Because revert expects a size in bytes, we multiply the array length (stored at `tokenAmounts`) by 32
let size := mul(mload(tokenAmounts), 32)
// We store the `bptAmount` in the previous slot to the `tokenAmounts` array. We can make sure there
// will be at least one available slot due to how the memory scratch space works.
// We can safely overwrite whatever is stored in this slot as we will revert immediately after that.
let start := sub(tokenAmounts, 0x20)
mstore(start, bptAmount)
// We send one extra value for the error signature "QueryError(uint256,uint256[])" which is 0x43adbafb
// We use the previous slot to `bptAmount`.
mstore(sub(start, 0x20), 0x0000000000000000000000000000000000000000000000000000000043adbafb)
start := sub(start, 0x04)
// When copying from `tokenAmounts` into returndata, we copy the additional 68 bytes to also return
// the `bptAmount`, the array 's length, and the error signature.
revert(start, add(size, 68))
}
}
}
}