-
Notifications
You must be signed in to change notification settings - Fork 20
/
Vault.sol
1564 lines (1373 loc) · 76.6 KB
/
Vault.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
pragma solidity ^0.8.24;
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import { IERC4626 } from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { Proxy } from "@openzeppelin/contracts/proxy/Proxy.sol";
import { IProtocolFeeController } from "@balancer-labs/v3-interfaces/contracts/vault/IProtocolFeeController.sol";
import { IVaultExtension } from "@balancer-labs/v3-interfaces/contracts/vault/IVaultExtension.sol";
import { IPoolLiquidity } from "@balancer-labs/v3-interfaces/contracts/vault/IPoolLiquidity.sol";
import { IAuthorizer } from "@balancer-labs/v3-interfaces/contracts/vault/IAuthorizer.sol";
import { IVaultAdmin } from "@balancer-labs/v3-interfaces/contracts/vault/IVaultAdmin.sol";
import { IVaultMain } from "@balancer-labs/v3-interfaces/contracts/vault/IVaultMain.sol";
import { IBasePool } from "@balancer-labs/v3-interfaces/contracts/vault/IBasePool.sol";
import { IHooks } from "@balancer-labs/v3-interfaces/contracts/vault/IHooks.sol";
import "@balancer-labs/v3-interfaces/contracts/vault/VaultTypes.sol";
import { StorageSlotExtension } from "@balancer-labs/v3-solidity-utils/contracts/openzeppelin/StorageSlotExtension.sol";
import { PackedTokenBalance } from "@balancer-labs/v3-solidity-utils/contracts/helpers/PackedTokenBalance.sol";
import { ScalingHelpers } from "@balancer-labs/v3-solidity-utils/contracts/helpers/ScalingHelpers.sol";
import { CastingHelpers } from "@balancer-labs/v3-solidity-utils/contracts/helpers/CastingHelpers.sol";
import { BufferHelpers } from "@balancer-labs/v3-solidity-utils/contracts/helpers/BufferHelpers.sol";
import { InputHelpers } from "@balancer-labs/v3-solidity-utils/contracts/helpers/InputHelpers.sol";
import { FixedPoint } from "@balancer-labs/v3-solidity-utils/contracts/math/FixedPoint.sol";
import {
TransientStorageHelpers
} from "@balancer-labs/v3-solidity-utils/contracts/helpers/TransientStorageHelpers.sol";
import { VaultStateLib, VaultStateBits } from "./lib/VaultStateLib.sol";
import { HooksConfigLib } from "./lib/HooksConfigLib.sol";
import { PoolConfigLib } from "./lib/PoolConfigLib.sol";
import { PoolDataLib } from "./lib/PoolDataLib.sol";
import { BasePoolMath } from "./BasePoolMath.sol";
import { VaultCommon } from "./VaultCommon.sol";
contract Vault is IVaultMain, VaultCommon, Proxy {
using PackedTokenBalance for bytes32;
using BufferHelpers for bytes32;
using InputHelpers for uint256;
using FixedPoint for *;
using Address for *;
using CastingHelpers for uint256[];
using SafeCast for *;
using SafeERC20 for IERC20;
using PoolConfigLib for PoolConfigBits;
using HooksConfigLib for PoolConfigBits;
using VaultStateLib for VaultStateBits;
using ScalingHelpers for *;
using TransientStorageHelpers for *;
using StorageSlotExtension for *;
using PoolDataLib for PoolData;
// Local reference to the Proxy pattern Vault extension contract.
IVaultExtension private immutable _vaultExtension;
constructor(IVaultExtension vaultExtension, IAuthorizer authorizer, IProtocolFeeController protocolFeeController) {
if (address(vaultExtension.vault()) != address(this)) {
revert WrongVaultExtensionDeployment();
}
if (address(protocolFeeController.vault()) != address(this)) {
revert WrongProtocolFeeControllerDeployment();
}
_vaultExtension = vaultExtension;
_protocolFeeController = protocolFeeController;
_vaultPauseWindowEndTime = IVaultAdmin(address(vaultExtension)).getPauseWindowEndTime();
_vaultBufferPeriodDuration = IVaultAdmin(address(vaultExtension)).getBufferPeriodDuration();
_vaultBufferPeriodEndTime = IVaultAdmin(address(vaultExtension)).getBufferPeriodEndTime();
_MINIMUM_TRADE_AMOUNT = IVaultAdmin(address(vaultExtension)).getMinimumTradeAmount();
_MINIMUM_WRAP_AMOUNT = IVaultAdmin(address(vaultExtension)).getMinimumWrapAmount();
_authorizer = authorizer;
}
/*******************************************************************************
Transient Accounting
*******************************************************************************/
/**
* @dev This modifier is used for functions that temporarily modify the token deltas
* of the Vault, but expect to revert or settle balances by the end of their execution.
* It works by ensuring that the balances are properly settled by the time the last
* operation is executed.
*
* This is useful for functions like `unlock`, which perform arbitrary external calls:
* we can keep track of temporary deltas changes, and make sure they are settled by the
* time the external call is complete.
*/
modifier transient() {
bool isUnlockedBefore = _isUnlocked().tload();
if (isUnlockedBefore == false) {
_isUnlocked().tstore(true);
}
// The caller does everything here and has to settle all outstanding balances.
_;
if (isUnlockedBefore == false) {
if (_nonZeroDeltaCount().tload() != 0) {
revert BalanceNotSettled();
}
_isUnlocked().tstore(false);
}
}
/// @inheritdoc IVaultMain
function unlock(bytes calldata data) external transient returns (bytes memory result) {
return (msg.sender).functionCall(data);
}
/// @inheritdoc IVaultMain
function settle(IERC20 token, uint256 amountHint) external nonReentrant onlyWhenUnlocked returns (uint256 credit) {
uint256 reservesBefore = _reservesOf[token];
uint256 currentReserves = token.balanceOf(address(this));
_reservesOf[token] = currentReserves;
credit = currentReserves - reservesBefore;
// If the given hint is equal or greater to the reserve difference, we just take the actual reserve difference
// as the paid amount; the actual balance of the tokens in the Vault is what matters here.
if (credit > amountHint) {
// If the difference in reserves is higher than the amount claimed to be paid by the caller, there was some
// leftover that had been sent to the Vault beforehand, which was not incorporated into the reserves.
// In that case, we simply discard the leftover by considering the given hint as the amount paid.
// In turn, this gives the caller credit for the given amount hint, which is what the caller is expecting.
credit = amountHint;
}
_supplyCredit(token, credit);
}
/// @inheritdoc IVaultMain
function sendTo(IERC20 token, address to, uint256 amount) external nonReentrant onlyWhenUnlocked {
_takeDebt(token, amount);
_reservesOf[token] -= amount;
token.safeTransfer(to, amount);
}
/*******************************************************************************
Pool Operations
*******************************************************************************/
// The Vault performs all upscaling and downscaling (due to token decimals, rates, etc.), so that the pools
// don't have to. However, scaling inevitably leads to rounding errors, so we take great care to ensure that
// any rounding errors favor the Vault. An important invariant of the system is that there is no repeatable
// path where tokensOut > tokensIn.
//
// In general, this means rounding up any values entering the Vault, and rounding down any values leaving
// the Vault, so that external users either pay a little extra or receive a little less in the case of a
// rounding error.
//
// However, it's not always straightforward to determine the correct rounding direction, given the presence
// and complexity of intermediate steps. An "amountIn" sounds like it should be rounded up: but only if that
// is the amount actually being transferred. If instead it is an amount sent to the pool math, where rounding
// up would result in a *higher* calculated amount out, that would favor the user instead of the Vault. So in
// that case, amountIn should be rounded down.
//
// See comments justifying the rounding direction in each case.
//
// This reasoning applies to Weighted Pool math, and is likely to apply to others as well, but of course
// it's possible a new pool type might not conform. Duplicate the tests for new pool types (e.g., Stable Math).
// Also, the final code should ensure that we are not relying entirely on the rounding directions here,
// but have enough additional layers (e.g., minimum amounts, buffer wei on all transfers) to guarantee safety,
// even if it turns out these directions are incorrect for a new pool type.
/*******************************************************************************
Swaps
*******************************************************************************/
/// @inheritdoc IVaultMain
function swap(
VaultSwapParams memory vaultSwapParams
)
external
onlyWhenUnlocked
withInitializedPool(vaultSwapParams.pool)
returns (uint256 amountCalculated, uint256 amountIn, uint256 amountOut)
{
_ensureUnpaused(vaultSwapParams.pool);
if (vaultSwapParams.amountGivenRaw == 0) {
revert AmountGivenZero();
}
if (vaultSwapParams.tokenIn == vaultSwapParams.tokenOut) {
revert CannotSwapSameToken();
}
// `_loadPoolDataUpdatingBalancesAndYieldFees` is non-reentrant, as it updates storage as well
// as filling in poolData in memory. Since the swap hooks are reentrant and could do anything, including
// change these balances, we cannot defer settlement until `_swap`.
//
// Sets all fields in `poolData`. Side effects: updates `_poolTokenBalances`, `_aggregateFeeAmounts`
// in storage.
PoolData memory poolData = _loadPoolDataUpdatingBalancesAndYieldFees(vaultSwapParams.pool, Rounding.ROUND_DOWN);
SwapState memory swapState = _loadSwapState(vaultSwapParams, poolData);
PoolSwapParams memory poolSwapParams = _buildPoolSwapParams(vaultSwapParams, swapState, poolData);
if (poolData.poolConfigBits.shouldCallBeforeSwap()) {
HooksConfigLib.callBeforeSwapHook(
poolSwapParams,
vaultSwapParams.pool,
_hooksContracts[vaultSwapParams.pool]
);
// The call to `onBeforeSwap` could potentially update token rates and balances.
// We update `poolData.tokenRates`, `poolData.rawBalances` and `poolData.balancesLiveScaled18`
// to ensure the `onSwap` and `onComputeDynamicSwapFeePercentage` are called with the current values.
poolData.reloadBalancesAndRates(_poolTokenBalances[vaultSwapParams.pool], Rounding.ROUND_DOWN);
// Also update amountGivenScaled18, as it will now be used in the swap, and the rates might have changed.
swapState.amountGivenScaled18 = _computeAmountGivenScaled18(vaultSwapParams, poolData, swapState);
poolSwapParams = _buildPoolSwapParams(vaultSwapParams, swapState, poolData);
}
// Note that this must be called *after* the before hook, to guarantee that the swap params are the same
// as those passed to the main operation.
//
// At this point, the static swap fee percentage is loaded in the `swapState` as the default, to be used
// unless the pool has a dynamic swap fee. It is also passed into the hook, to support common cases
// where the dynamic fee computation logic uses it.
if (poolData.poolConfigBits.shouldCallComputeDynamicSwapFee()) {
swapState.swapFeePercentage = HooksConfigLib.callComputeDynamicSwapFeeHook(
poolSwapParams,
vaultSwapParams.pool,
swapState.swapFeePercentage,
_hooksContracts[vaultSwapParams.pool]
);
}
// Non-reentrant call that updates accounting.
// The following side-effects are important to note:
// PoolData balancesRaw and balancesLiveScaled18 are adjusted for swap amounts and fees inside of _swap.
uint256 amountCalculatedScaled18;
(amountCalculated, amountCalculatedScaled18, amountIn, amountOut) = _swap(
vaultSwapParams,
swapState,
poolData,
poolSwapParams
);
// The new amount calculated is 'amountCalculated + delta'. If the underlying hook fails, or limits are
// violated, `onAfterSwap` will revert. Uses msg.sender as the Router (the contract that called the Vault).
if (poolData.poolConfigBits.shouldCallAfterSwap()) {
// `hooksContract` needed to fix stack too deep.
IHooks hooksContract = _hooksContracts[vaultSwapParams.pool];
amountCalculated = poolData.poolConfigBits.callAfterSwapHook(
amountCalculatedScaled18,
amountCalculated,
msg.sender,
vaultSwapParams,
swapState,
poolData,
hooksContract
);
}
if (vaultSwapParams.kind == SwapKind.EXACT_IN) {
amountOut = amountCalculated;
} else {
amountIn = amountCalculated;
}
}
function _loadSwapState(
VaultSwapParams memory vaultSwapParams,
PoolData memory poolData
) private pure returns (SwapState memory swapState) {
swapState.indexIn = _findTokenIndex(poolData.tokens, vaultSwapParams.tokenIn);
swapState.indexOut = _findTokenIndex(poolData.tokens, vaultSwapParams.tokenOut);
swapState.amountGivenScaled18 = _computeAmountGivenScaled18(vaultSwapParams, poolData, swapState);
swapState.swapFeePercentage = poolData.poolConfigBits.getStaticSwapFeePercentage();
}
function _buildPoolSwapParams(
VaultSwapParams memory vaultSwapParams,
SwapState memory swapState,
PoolData memory poolData
) internal view returns (PoolSwapParams memory) {
// Uses msg.sender as the Router (the contract that called the Vault).
return
PoolSwapParams({
kind: vaultSwapParams.kind,
amountGivenScaled18: swapState.amountGivenScaled18,
balancesScaled18: poolData.balancesLiveScaled18,
indexIn: swapState.indexIn,
indexOut: swapState.indexOut,
router: msg.sender,
userData: vaultSwapParams.userData
});
}
/**
* @dev Preconditions: decimalScalingFactors and tokenRates in `poolData` must be current.
* Uses amountGivenRaw and kind from `vaultSwapParams`.
*/
function _computeAmountGivenScaled18(
VaultSwapParams memory vaultSwapParams,
PoolData memory poolData,
SwapState memory swapState
) private pure returns (uint256) {
// If the amountGiven is entering the pool math (ExactIn), round down, since a lower apparent amountIn leads
// to a lower calculated amountOut, favoring the pool.
return
vaultSwapParams.kind == SwapKind.EXACT_IN
? vaultSwapParams.amountGivenRaw.toScaled18ApplyRateRoundDown(
poolData.decimalScalingFactors[swapState.indexIn],
poolData.tokenRates[swapState.indexIn]
)
: vaultSwapParams.amountGivenRaw.toScaled18ApplyRateRoundUp(
poolData.decimalScalingFactors[swapState.indexOut],
// If the swap is ExactOut, the amountGiven is the amount of tokenOut. So, we want to use the rate
// rounded up to calculate the amountGivenScaled18, because if this value is bigger, the
// amountCalculatedRaw will be bigger, implying that the user will pay for any rounding
// inconsistency, and not the Vault.
poolData.tokenRates[swapState.indexOut].computeRateRoundUp()
);
}
/**
* @dev Auxiliary struct to prevent stack-too-deep issues inside `_swap` function.
* Total swap fees include LP (pool) fees and aggregate (protocol + pool creator) fees.
*/
struct SwapInternalLocals {
uint256 totalSwapFeeAmountScaled18;
uint256 totalSwapFeeAmountRaw;
uint256 aggregateFeeAmountRaw;
}
/**
* @dev Main non-reentrant portion of the swap, which calls the pool hook and updates accounting. `vaultSwapParams`
* are passed to the pool's `onSwap` hook.
*
* Preconditions: complete `SwapParams`, `SwapState`, and `PoolData`.
* Side effects: mutates balancesRaw and balancesLiveScaled18 in `poolData`.
* Updates `_aggregateFeeAmounts`, and `_poolTokenBalances` in storage.
* Emits Swap event.
*/
function _swap(
VaultSwapParams memory vaultSwapParams,
SwapState memory swapState,
PoolData memory poolData,
PoolSwapParams memory poolSwapParams
)
internal
nonReentrant
returns (
uint256 amountCalculatedRaw,
uint256 amountCalculatedScaled18,
uint256 amountInRaw,
uint256 amountOutRaw
)
{
SwapInternalLocals memory locals;
if (vaultSwapParams.kind == SwapKind.EXACT_IN) {
// Round up to avoid losses during precision loss.
locals.totalSwapFeeAmountScaled18 = poolSwapParams.amountGivenScaled18.mulUp(swapState.swapFeePercentage);
poolSwapParams.amountGivenScaled18 -= locals.totalSwapFeeAmountScaled18;
}
_ensureValidSwapAmount(poolSwapParams.amountGivenScaled18);
// Perform the swap request hook and compute the new balances for 'token in' and 'token out' after the swap.
amountCalculatedScaled18 = IBasePool(vaultSwapParams.pool).onSwap(poolSwapParams);
_ensureValidSwapAmount(amountCalculatedScaled18);
// Note that balances are kept in memory, and are not fully computed until the `setPoolBalances` below.
// Intervening code cannot read balances from storage, as they are temporarily out-of-sync here. This function
// is nonReentrant, to guard against read-only reentrancy issues.
// (1) and (2): get raw amounts and check limits.
if (vaultSwapParams.kind == SwapKind.EXACT_IN) {
// Restore the original input value; this function should not mutate memory inputs.
// At this point swap fee amounts have already been computed for EXACT_IN.
poolSwapParams.amountGivenScaled18 = swapState.amountGivenScaled18;
// For `ExactIn` the amount calculated is leaving the Vault, so we round down.
amountCalculatedRaw = amountCalculatedScaled18.toRawUndoRateRoundDown(
poolData.decimalScalingFactors[swapState.indexOut],
// If the swap is ExactIn, the amountCalculated is the amount of tokenOut. So, we want to use the rate
// rounded up to calculate the amountCalculatedRaw, because scale down (undo rate) is a division, the
// larger the rate, the smaller the amountCalculatedRaw. So, any rounding imprecision will stay in the
// Vault and not be drained by the user.
poolData.tokenRates[swapState.indexOut].computeRateRoundUp()
);
(amountInRaw, amountOutRaw) = (vaultSwapParams.amountGivenRaw, amountCalculatedRaw);
if (amountOutRaw < vaultSwapParams.limitRaw) {
revert SwapLimit(amountOutRaw, vaultSwapParams.limitRaw);
}
} else {
// To ensure symmetry with EXACT_IN, the swap fee used by ExactOut is
// `amountCalculated * fee% / (100% - fee%)`. Add it to the calculated amountIn. Round up to avoid losses
// during precision loss.
locals.totalSwapFeeAmountScaled18 = amountCalculatedScaled18.mulDivUp(
swapState.swapFeePercentage,
swapState.swapFeePercentage.complement()
);
amountCalculatedScaled18 += locals.totalSwapFeeAmountScaled18;
// For `ExactOut` the amount calculated is entering the Vault, so we round up.
amountCalculatedRaw = amountCalculatedScaled18.toRawUndoRateRoundUp(
poolData.decimalScalingFactors[swapState.indexIn],
poolData.tokenRates[swapState.indexIn]
);
(amountInRaw, amountOutRaw) = (amountCalculatedRaw, vaultSwapParams.amountGivenRaw);
if (amountInRaw > vaultSwapParams.limitRaw) {
revert SwapLimit(amountInRaw, vaultSwapParams.limitRaw);
}
}
// 3) Deltas: debit for token in, credit for token out.
_takeDebt(vaultSwapParams.tokenIn, amountInRaw);
_supplyCredit(vaultSwapParams.tokenOut, amountOutRaw);
// 4) Compute and charge protocol and creator fees.
// Note that protocol fee storage is updated before balance storage, as the final raw balances need to take
// the fees into account.
(locals.totalSwapFeeAmountRaw, locals.aggregateFeeAmountRaw) = _computeAndChargeAggregateSwapFees(
poolData,
locals.totalSwapFeeAmountScaled18,
vaultSwapParams.pool,
vaultSwapParams.tokenIn,
swapState.indexIn
);
// 5) Pool balances: raw and live.
poolData.updateRawAndLiveBalance(
swapState.indexIn,
poolData.balancesRaw[swapState.indexIn] + amountInRaw - locals.aggregateFeeAmountRaw,
Rounding.ROUND_DOWN
);
poolData.updateRawAndLiveBalance(
swapState.indexOut,
poolData.balancesRaw[swapState.indexOut] - amountOutRaw,
Rounding.ROUND_DOWN
);
// 6) Store pool balances, raw and live (only index in and out).
mapping(uint256 tokenIndex => bytes32 packedTokenBalance) storage poolBalances = _poolTokenBalances[
vaultSwapParams.pool
];
poolBalances[swapState.indexIn] = PackedTokenBalance.toPackedBalance(
poolData.balancesRaw[swapState.indexIn],
poolData.balancesLiveScaled18[swapState.indexIn]
);
poolBalances[swapState.indexOut] = PackedTokenBalance.toPackedBalance(
poolData.balancesRaw[swapState.indexOut],
poolData.balancesLiveScaled18[swapState.indexOut]
);
// 7) Off-chain events.
emit Swap(
vaultSwapParams.pool,
vaultSwapParams.tokenIn,
vaultSwapParams.tokenOut,
amountInRaw,
amountOutRaw,
swapState.swapFeePercentage,
locals.totalSwapFeeAmountRaw
);
}
/***************************************************************************
Add Liquidity
***************************************************************************/
/// @inheritdoc IVaultMain
function addLiquidity(
AddLiquidityParams memory params
)
external
onlyWhenUnlocked
withInitializedPool(params.pool)
returns (uint256[] memory amountsIn, uint256 bptAmountOut, bytes memory returnData)
{
// Round balances up when adding liquidity:
// If proportional, higher balances = higher proportional amountsIn, favoring the pool.
// If unbalanced, higher balances = lower invariant ratio with fees.
// bptOut = supply * (ratio - 1), so lower ratio = less bptOut, favoring the pool.
_ensureUnpaused(params.pool);
_addLiquidityCalled().tSet(params.pool, true);
// `_loadPoolDataUpdatingBalancesAndYieldFees` is non-reentrant, as it updates storage as well
// as filling in poolData in memory. Since the add liquidity hooks are reentrant and could do anything,
// including change these balances, we cannot defer settlement until `_addLiquidity`.
//
// Sets all fields in `poolData`. Side effects: updates `_poolTokenBalances`, and
// `_aggregateFeeAmounts` in storage.
PoolData memory poolData = _loadPoolDataUpdatingBalancesAndYieldFees(params.pool, Rounding.ROUND_UP);
InputHelpers.ensureInputLengthMatch(poolData.tokens.length, params.maxAmountsIn.length);
// Amounts are entering pool math, so round down.
// Introducing `maxAmountsInScaled18` here and passing it through to _addLiquidity is not ideal,
// but it avoids the even worse options of mutating amountsIn inside AddLiquidityParams,
// or cluttering the AddLiquidityParams interface by adding amountsInScaled18.
uint256[] memory maxAmountsInScaled18 = params.maxAmountsIn.copyToScaled18ApplyRateRoundDownArray(
poolData.decimalScalingFactors,
poolData.tokenRates
);
if (poolData.poolConfigBits.shouldCallBeforeAddLiquidity()) {
HooksConfigLib.callBeforeAddLiquidityHook(
msg.sender,
maxAmountsInScaled18,
params,
poolData,
_hooksContracts[params.pool]
);
// The hook might have altered the balances, so we need to read them again to ensure that the data
// are fresh moving forward. We also need to upscale (adding liquidity, so round up) again.
poolData.reloadBalancesAndRates(_poolTokenBalances[params.pool], Rounding.ROUND_UP);
// Also update maxAmountsInScaled18, as the rates might have changed.
maxAmountsInScaled18 = params.maxAmountsIn.copyToScaled18ApplyRateRoundDownArray(
poolData.decimalScalingFactors,
poolData.tokenRates
);
}
// The bulk of the work is done here: the corresponding Pool hook is called, and the final balances
// are computed. This function is non-reentrant, as it performs the accounting updates.
//
// Note that poolData is mutated to update the Raw and Live balances, so they are accurate when passed
// into the AfterAddLiquidity hook.
//
// `amountsInScaled18` will be overwritten in the custom case, so we need to pass it back and forth to
// encapsulate that logic in `_addLiquidity`.
uint256[] memory amountsInScaled18;
(amountsIn, amountsInScaled18, bptAmountOut, returnData) = _addLiquidity(
poolData,
params,
maxAmountsInScaled18
);
// AmountsIn can be changed by onAfterAddLiquidity if the hook charges fees or gives discounts.
// Uses msg.sender as the Router (the contract that called the Vault).
if (poolData.poolConfigBits.shouldCallAfterAddLiquidity()) {
// `hooksContract` needed to fix stack too deep.
IHooks hooksContract = _hooksContracts[params.pool];
amountsIn = poolData.poolConfigBits.callAfterAddLiquidityHook(
msg.sender,
amountsInScaled18,
amountsIn,
bptAmountOut,
params,
poolData,
hooksContract
);
}
}
// Avoid "stack too deep" - without polluting the Add/RemoveLiquidity params interface.
struct LiquidityLocals {
uint256 numTokens;
uint256 aggregateSwapFeeAmountRaw;
uint256 tokenIndex;
}
/**
* @dev Calls the appropriate pool hook and calculates the required inputs and outputs for the operation
* considering the given kind, and updates the Vault's internal accounting. This includes:
* - Setting pool balances
* - Taking debt from the liquidity provider
* - Minting pool tokens
* - Emitting events
*
* It is non-reentrant, as it performs external calls and updates the Vault's state accordingly.
*/
function _addLiquidity(
PoolData memory poolData,
AddLiquidityParams memory params,
uint256[] memory maxAmountsInScaled18
)
internal
nonReentrant
returns (
uint256[] memory amountsInRaw,
uint256[] memory amountsInScaled18,
uint256 bptAmountOut,
bytes memory returnData
)
{
LiquidityLocals memory locals;
locals.numTokens = poolData.tokens.length;
amountsInRaw = new uint256[](locals.numTokens);
// `swapFeeAmounts` stores scaled18 amounts first, and is then reused to store raw amounts.
uint256[] memory swapFeeAmounts;
if (params.kind == AddLiquidityKind.PROPORTIONAL) {
bptAmountOut = params.minBptAmountOut;
// Initializes the swapFeeAmounts empty array (no swap fees on proportional add liquidity).
swapFeeAmounts = new uint256[](locals.numTokens);
amountsInScaled18 = BasePoolMath.computeProportionalAmountsIn(
poolData.balancesLiveScaled18,
_totalSupply(params.pool),
bptAmountOut
);
} else if (params.kind == AddLiquidityKind.DONATION) {
poolData.poolConfigBits.requireDonationEnabled();
swapFeeAmounts = new uint256[](maxAmountsInScaled18.length);
bptAmountOut = 0;
amountsInScaled18 = maxAmountsInScaled18;
} else if (params.kind == AddLiquidityKind.UNBALANCED) {
poolData.poolConfigBits.requireUnbalancedLiquidityEnabled();
amountsInScaled18 = maxAmountsInScaled18;
// Deep copy given max amounts in raw to calculated amounts in raw to avoid scaling later, ensuring that
// `maxAmountsIn` is preserved.
ScalingHelpers.copyToArray(params.maxAmountsIn, amountsInRaw);
(bptAmountOut, swapFeeAmounts) = BasePoolMath.computeAddLiquidityUnbalanced(
poolData.balancesLiveScaled18,
maxAmountsInScaled18,
_totalSupply(params.pool),
poolData.poolConfigBits.getStaticSwapFeePercentage(),
IBasePool(params.pool)
);
} else if (params.kind == AddLiquidityKind.SINGLE_TOKEN_EXACT_OUT) {
poolData.poolConfigBits.requireUnbalancedLiquidityEnabled();
bptAmountOut = params.minBptAmountOut;
locals.tokenIndex = InputHelpers.getSingleInputIndex(maxAmountsInScaled18);
amountsInScaled18 = maxAmountsInScaled18;
(amountsInScaled18[locals.tokenIndex], swapFeeAmounts) = BasePoolMath
.computeAddLiquiditySingleTokenExactOut(
poolData.balancesLiveScaled18,
locals.tokenIndex,
bptAmountOut,
_totalSupply(params.pool),
poolData.poolConfigBits.getStaticSwapFeePercentage(),
IBasePool(params.pool)
);
} else if (params.kind == AddLiquidityKind.CUSTOM) {
poolData.poolConfigBits.requireAddLiquidityCustomEnabled();
// Uses msg.sender as the Router (the contract that called the Vault).
(amountsInScaled18, bptAmountOut, swapFeeAmounts, returnData) = IPoolLiquidity(params.pool)
.onAddLiquidityCustom(
msg.sender,
maxAmountsInScaled18,
params.minBptAmountOut,
poolData.balancesLiveScaled18,
params.userData
);
} else {
revert InvalidAddLiquidityKind();
}
// At this point we have the calculated BPT amount.
if (bptAmountOut < params.minBptAmountOut) {
revert BptAmountOutBelowMin(bptAmountOut, params.minBptAmountOut);
}
_ensureValidTradeAmount(bptAmountOut);
for (uint256 i = 0; i < locals.numTokens; ++i) {
uint256 amountInRaw;
// 1) Calculate raw amount in.
{
uint256 amountInScaled18 = amountsInScaled18[i];
_ensureValidTradeAmount(amountInScaled18);
// If the value in memory is not set, convert scaled amount to raw.
if (amountsInRaw[i] == 0) {
// amountsInRaw are amounts actually entering the Pool, so we round up.
// Do not mutate in place yet, as we need them scaled for the `onAfterAddLiquidity` hook.
amountInRaw = amountInScaled18.toRawUndoRateRoundUp(
poolData.decimalScalingFactors[i],
poolData.tokenRates[i]
);
amountsInRaw[i] = amountInRaw;
} else {
// Exact in requests will have the raw amount in memory already, so we use it moving forward and
// skip downscaling.
amountInRaw = amountsInRaw[i];
}
}
IERC20 token = poolData.tokens[i];
// 2) Check limits for raw amounts.
if (amountInRaw > params.maxAmountsIn[i]) {
revert AmountInAboveMax(token, amountInRaw, params.maxAmountsIn[i]);
}
// 3) Deltas: Debit of token[i] for amountInRaw.
_takeDebt(token, amountInRaw);
// 4) Compute and charge protocol and creator fees.
// swapFeeAmounts[i] is now raw instead of scaled.
(swapFeeAmounts[i], locals.aggregateSwapFeeAmountRaw) = _computeAndChargeAggregateSwapFees(
poolData,
swapFeeAmounts[i],
params.pool,
token,
i
);
// 5) Pool balances: raw and live.
// We need regular balances to complete the accounting, and the upscaled balances
// to use in the `after` hook later on.
// A pool's token balance increases by amounts in after adding liquidity, minus fees.
poolData.updateRawAndLiveBalance(
i,
poolData.balancesRaw[i] + amountInRaw - locals.aggregateSwapFeeAmountRaw,
Rounding.ROUND_DOWN
);
}
// 6) Store pool balances, raw and live.
_writePoolBalancesToStorage(params.pool, poolData);
// 7) BPT supply adjustment.
// When adding liquidity, we must mint tokens concurrently with updating pool balances,
// as the pool's math relies on totalSupply.
_mint(address(params.pool), params.to, bptAmountOut);
// 8) Off-chain events.
emit LiquidityAdded(
params.pool,
params.to,
params.kind,
_totalSupply(params.pool),
amountsInRaw,
swapFeeAmounts
);
}
/***************************************************************************
Remove Liquidity
***************************************************************************/
/// @inheritdoc IVaultMain
function removeLiquidity(
RemoveLiquidityParams memory params
)
external
onlyWhenUnlocked
withInitializedPool(params.pool)
returns (uint256 bptAmountIn, uint256[] memory amountsOut, bytes memory returnData)
{
// Round down when removing liquidity:
// If proportional, lower balances = lower proportional amountsOut, favoring the pool.
// If unbalanced, lower balances = lower invariant ratio without fees.
// bptIn = supply * (1 - ratio), so lower ratio = more bptIn, favoring the pool.
_ensureUnpaused(params.pool);
// `_loadPoolDataUpdatingBalancesAndYieldFees` is non-reentrant, as it updates storage as well
// as filling in poolData in memory. Since the swap hooks are reentrant and could do anything, including
// change these balances, we cannot defer settlement until `_removeLiquidity`.
//
// Sets all fields in `poolData`. Side effects: updates `_poolTokenBalances` and
// `_aggregateFeeAmounts in storage.
PoolData memory poolData = _loadPoolDataUpdatingBalancesAndYieldFees(params.pool, Rounding.ROUND_DOWN);
InputHelpers.ensureInputLengthMatch(poolData.tokens.length, params.minAmountsOut.length);
// Amounts are entering pool math; higher amounts would burn more BPT, so round up to favor the pool.
// Do not mutate minAmountsOut, so that we can directly compare the raw limits later, without potentially
// losing precision by scaling up and then down.
uint256[] memory minAmountsOutScaled18 = params.minAmountsOut.copyToScaled18ApplyRateRoundUpArray(
poolData.decimalScalingFactors,
poolData.tokenRates
);
// Uses msg.sender as the Router (the contract that called the Vault).
if (poolData.poolConfigBits.shouldCallBeforeRemoveLiquidity()) {
HooksConfigLib.callBeforeRemoveLiquidityHook(
minAmountsOutScaled18,
msg.sender,
params,
poolData,
_hooksContracts[params.pool]
);
// The hook might alter the balances, so we need to read them again to ensure that the data is
// fresh moving forward. We also need to upscale (removing liquidity, so round down) again.
poolData.reloadBalancesAndRates(_poolTokenBalances[params.pool], Rounding.ROUND_DOWN);
// Also update minAmountsOutScaled18, as the rates might have changed.
minAmountsOutScaled18 = params.minAmountsOut.copyToScaled18ApplyRateRoundUpArray(
poolData.decimalScalingFactors,
poolData.tokenRates
);
}
// The bulk of the work is done here: the corresponding Pool hook is called, and the final balances
// are computed. This function is non-reentrant, as it performs the accounting updates.
//
// Note that poolData is mutated to update the Raw and Live balances, so they are accurate when passed
// into the AfterRemoveLiquidity hook.
uint256[] memory amountsOutScaled18;
(bptAmountIn, amountsOut, amountsOutScaled18, returnData) = _removeLiquidity(
poolData,
params,
minAmountsOutScaled18
);
// AmountsOut can be changed by onAfterRemoveLiquidity if the hook charges fees or gives discounts.
// Uses msg.sender as the Router (the contract that called the Vault).
if (poolData.poolConfigBits.shouldCallAfterRemoveLiquidity()) {
// `hooksContract` needed to fix stack too deep.
IHooks hooksContract = _hooksContracts[params.pool];
amountsOut = poolData.poolConfigBits.callAfterRemoveLiquidityHook(
msg.sender,
amountsOutScaled18,
amountsOut,
bptAmountIn,
params,
poolData,
hooksContract
);
}
}
/**
* @dev Calls the appropriate pool hook and calculates the required inputs and outputs for the operation
* considering the given kind, and updates the Vault's internal accounting. This includes:
* - Setting pool balances
* - Supplying credit to the liquidity provider
* - Burning pool tokens
* - Emitting events
*
* It is non-reentrant, as it performs external calls and updates the Vault's state accordingly.
*/
function _removeLiquidity(
PoolData memory poolData,
RemoveLiquidityParams memory params,
uint256[] memory minAmountsOutScaled18
)
internal
nonReentrant
returns (
uint256 bptAmountIn,
uint256[] memory amountsOutRaw,
uint256[] memory amountsOutScaled18,
bytes memory returnData
)
{
LiquidityLocals memory locals;
locals.numTokens = poolData.tokens.length;
amountsOutRaw = new uint256[](locals.numTokens);
// `swapFeeAmounts` stores scaled18 amounts first, and is then reused to store raw amounts.
uint256[] memory swapFeeAmounts;
if (params.kind == RemoveLiquidityKind.PROPORTIONAL) {
bptAmountIn = params.maxBptAmountIn;
swapFeeAmounts = new uint256[](locals.numTokens);
amountsOutScaled18 = BasePoolMath.computeProportionalAmountsOut(
poolData.balancesLiveScaled18,
_totalSupply(params.pool),
bptAmountIn
);
// Charge roundtrip fee.
if (_addLiquidityCalled().tGet(params.pool)) {
uint256 swapFeePercentage = poolData.poolConfigBits.getStaticSwapFeePercentage();
for (uint256 i = 0; i < locals.numTokens; ++i) {
swapFeeAmounts[i] = amountsOutScaled18[i].mulUp(swapFeePercentage);
amountsOutScaled18[i] -= swapFeeAmounts[i];
}
}
} else if (params.kind == RemoveLiquidityKind.SINGLE_TOKEN_EXACT_IN) {
poolData.poolConfigBits.requireUnbalancedLiquidityEnabled();
bptAmountIn = params.maxBptAmountIn;
amountsOutScaled18 = minAmountsOutScaled18;
locals.tokenIndex = InputHelpers.getSingleInputIndex(params.minAmountsOut);
(amountsOutScaled18[locals.tokenIndex], swapFeeAmounts) = BasePoolMath
.computeRemoveLiquiditySingleTokenExactIn(
poolData.balancesLiveScaled18,
locals.tokenIndex,
bptAmountIn,
_totalSupply(params.pool),
poolData.poolConfigBits.getStaticSwapFeePercentage(),
IBasePool(params.pool)
);
} else if (params.kind == RemoveLiquidityKind.SINGLE_TOKEN_EXACT_OUT) {
poolData.poolConfigBits.requireUnbalancedLiquidityEnabled();
amountsOutScaled18 = minAmountsOutScaled18;
locals.tokenIndex = InputHelpers.getSingleInputIndex(params.minAmountsOut);
amountsOutRaw[locals.tokenIndex] = params.minAmountsOut[locals.tokenIndex];
(bptAmountIn, swapFeeAmounts) = BasePoolMath.computeRemoveLiquiditySingleTokenExactOut(
poolData.balancesLiveScaled18,
locals.tokenIndex,
amountsOutScaled18[locals.tokenIndex],
_totalSupply(params.pool),
poolData.poolConfigBits.getStaticSwapFeePercentage(),
IBasePool(params.pool)
);
} else if (params.kind == RemoveLiquidityKind.CUSTOM) {
poolData.poolConfigBits.requireRemoveLiquidityCustomEnabled();
// Uses msg.sender as the Router (the contract that called the Vault).
(bptAmountIn, amountsOutScaled18, swapFeeAmounts, returnData) = IPoolLiquidity(params.pool)
.onRemoveLiquidityCustom(
msg.sender,
params.maxBptAmountIn,
minAmountsOutScaled18,
poolData.balancesLiveScaled18,
params.userData
);
} else {
revert InvalidRemoveLiquidityKind();
}
if (bptAmountIn > params.maxBptAmountIn) {
revert BptAmountInAboveMax(bptAmountIn, params.maxBptAmountIn);
}
_ensureValidTradeAmount(bptAmountIn);
for (uint256 i = 0; i < locals.numTokens; ++i) {
uint256 amountOutRaw;
// 1) Calculate raw amount out.
{
uint256 amountOutScaled18 = amountsOutScaled18[i];
_ensureValidTradeAmount(amountOutScaled18);
// If the value in memory is not set, convert scaled amount to raw.
if (amountsOutRaw[i] == 0) {
// amountsOut are amounts exiting the Pool, so we round down.
// Do not mutate in place yet, as we need them scaled for the `onAfterRemoveLiquidity` hook.
amountOutRaw = amountOutScaled18.toRawUndoRateRoundDown(
poolData.decimalScalingFactors[i],
poolData.tokenRates[i]
);
amountsOutRaw[i] = amountOutRaw;
} else {
// Exact out requests will have the raw amount in memory already, so we use it moving forward and
// skip downscaling.
amountOutRaw = amountsOutRaw[i];
}
}
IERC20 token = poolData.tokens[i];
// 2) Check limits for raw amounts.
if (amountOutRaw < params.minAmountsOut[i]) {
revert AmountOutBelowMin(token, amountOutRaw, params.minAmountsOut[i]);
}
// 3) Deltas: Credit token[i] for amountOutRaw.
_supplyCredit(token, amountOutRaw);
// 4) Compute and charge protocol and creator fees.
// swapFeeAmounts[i] is now raw instead of scaled.
(swapFeeAmounts[i], locals.aggregateSwapFeeAmountRaw) = _computeAndChargeAggregateSwapFees(
poolData,
swapFeeAmounts[i],
params.pool,
token,
i
);
// 5) Pool balances: raw and live.
// We need regular balances to complete the accounting, and the upscaled balances
// to use in the `after` hook later on.
// A Pool's token balance always decreases after an exit (potentially by 0).
// Also adjust by protocol and pool creator fees.
poolData.updateRawAndLiveBalance(
i,
poolData.balancesRaw[i] - (amountOutRaw + locals.aggregateSwapFeeAmountRaw),
Rounding.ROUND_DOWN
);
}
// 6) Store pool balances, raw and live.
_writePoolBalancesToStorage(params.pool, poolData);
// 7) BPT supply adjustment.