Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merge hooks config with pool config #659

Merged
merged 24 commits into from
Jun 27, 2024
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions pkg/interfaces/contracts/test/IVaultMainMock.sol
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@ interface IVaultMainMock {

function mintERC20(address token, address to, uint256 amount) external;

function setHooksConfig(address pool, HooksConfig calldata config) external;

function manualRegisterPool(address pool, IERC20[] memory tokens) external;

function manualRegisterPoolWithSwapFee(address pool, IERC20[] memory tokens, uint256 swapFeePercentage) external;
Expand Down Expand Up @@ -46,7 +44,9 @@ interface IVaultMainMock {

function manualSetPoolTokenInfo(address, IERC20[] memory, TokenInfo[] memory) external;

function manualSetPoolConfig(address, PoolConfig memory) external;
function manualSetPoolConfig(address pool, PoolConfig memory config) external;

function manualSetHooksConfig(address pool, HooksConfig memory config) external;

function manualSetPoolTokenBalances(address, IERC20[] memory, uint256[] memory, uint256[] memory) external;

Expand Down
1 change: 1 addition & 0 deletions pkg/interfaces/contracts/vault/VaultTypes.sol
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ pragma solidity ^0.8.24;

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IERC4626 } from "@openzeppelin/contracts/interfaces/IERC4626.sol";

import { IRateProvider } from "./IRateProvider.sol";

struct LiquidityManagement {
Expand Down
Original file line number Diff line number Diff line change
@@ -1 +1 @@
177.6k
175.8k
Original file line number Diff line number Diff line change
@@ -1 +1 @@
161.1k
159.3k
Original file line number Diff line number Diff line change
@@ -1 +1 @@
210.9k
209.1k
Original file line number Diff line number Diff line change
@@ -1 +1 @@
177.3k
175.5k
Original file line number Diff line number Diff line change
@@ -1 +1 @@
363.9k
362.0k
Original file line number Diff line number Diff line change
@@ -1 +1 @@
337.9k
336.0k
50 changes: 50 additions & 0 deletions pkg/solidity-utils/contracts/helpers/Cache.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// SPDX-License-Identifier: GPL-3.0-or-later

pragma solidity ^0.8.24;

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

import { StorageSlot } from "../openzeppelin/StorageSlot.sol";

/**
* @dev This library allows to cache the storage value in memory to avoid multiple SLOADs.
elshan-eth marked this conversation as resolved.
Show resolved Hide resolved
*/
library Cache {
elshan-eth marked this conversation as resolved.
Show resolved Hide resolved
struct AddressCache {
address value;
bytes32 slot;
}

/**
* @dev This function initializes the cache for address values.
* We use AddressSlot to get the storage slot value using assembly.
*/
function initAddressCache(
StorageSlot.AddressSlot storage addressSlot
) internal pure returns (AddressCache memory cache) {
bytes32 slot;

// solhint-disable-next-line no-inline-assembly
assembly {
slot := addressSlot.slot
}

cache.slot = slot;
}

function getValue(AddressCache memory cache) internal view returns (address) {
if (cache.value == address(0)) {
elshan-eth marked this conversation as resolved.
Show resolved Hide resolved
address _value;
bytes32 slot = cache.slot;

// solhint-disable-next-line no-inline-assembly
assembly {
_value := sload(slot)
}

cache.value = _value;
}

return cache.value;
}
}
58 changes: 39 additions & 19 deletions pkg/vault/contracts/Vault.sol
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,10 @@ import { FixedPoint } from "@balancer-labs/v3-solidity-utils/contracts/math/Fixe
import { BasePoolMath } from "@balancer-labs/v3-solidity-utils/contracts/math/BasePoolMath.sol";
import { EnumerableMap } from "@balancer-labs/v3-solidity-utils/contracts/openzeppelin/EnumerableMap.sol";
import { StorageSlot } from "@balancer-labs/v3-solidity-utils/contracts/openzeppelin/StorageSlot.sol";
import { Cache } from "@balancer-labs/v3-solidity-utils/contracts/helpers/Cache.sol";

import { VaultStateLib, VaultStateBits, VaultStateBits } from "./lib/VaultStateLib.sol";
import { PoolConfigLib } from "./lib/PoolConfigLib.sol";
import { HooksConfigLib, HooksConfigBits } from "./lib/HooksConfigLib.sol";
import { PackedTokenBalance } from "./lib/PackedTokenBalance.sol";
import { PoolDataLib } from "./lib/PoolDataLib.sol";
import { BufferPackedTokenBalance } from "./lib/BufferPackedBalance.sol";
Expand All @@ -53,6 +53,7 @@ contract Vault is IVaultMain, VaultCommon, Proxy {
using BufferPackedTokenBalance for bytes32;
using TransientStorageHelpers for *;
using StorageSlot for *;
using Cache for Cache.AddressCache;
using PoolDataLib for PoolData;

constructor(IVaultExtension vaultExtension, IAuthorizer authorizer, IProtocolFeeController protocolFeeController) {
Expand Down Expand Up @@ -171,7 +172,6 @@ contract Vault is IVaultMain, VaultCommon, Proxy {
returns (uint256 amountCalculated, uint256 amountIn, uint256 amountOut)
{
_ensureUnpaused(params.pool);
HooksConfigBits hooksConfig = _hooksConfigBits[params.pool];

if (params.amountGivenRaw == 0) {
revert AmountGivenZero();
Expand All @@ -194,7 +194,9 @@ contract Vault is IVaultMain, VaultCommon, Proxy {

IBasePool.PoolSwapParams memory swapParams = _buildPoolSwapParams(params, state, poolData);

if (hooksConfig.callBeforeSwapHook(swapParams, params.pool)) {
Cache.AddressCache memory hooksContractCache = Cache.initAddressCache(_hooksContracts[params.pool]);

if (poolData.poolConfigBits.callBeforeSwapHook(swapParams, params.pool, hooksContractCache)) {
// 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 `onComputeDynamicSwapFee` are called with the current values.
Expand All @@ -211,9 +213,10 @@ contract Vault is IVaultMain, VaultCommon, Proxy {
// At this point, the static swap fee percentage is loaded in the swap state 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.
(bool dynamicSwapFeeCalculated, uint256 dynamicSwapFee) = hooksConfig.callComputeDynamicSwapFeeHook(
(bool dynamicSwapFeeCalculated, uint256 dynamicSwapFee) = poolData.poolConfigBits.callComputeDynamicSwapFeeHook(
swapParams,
state.swapFeePercentage
state.swapFeePercentage,
hooksContractCache
);
if (dynamicSwapFeeCalculated) {
state.swapFeePercentage = dynamicSwapFee;
Expand All @@ -225,17 +228,17 @@ contract Vault is IVaultMain, VaultCommon, Proxy {
uint256 amountCalculatedScaled18;
(amountCalculated, amountCalculatedScaled18, amountIn, amountOut) = _swap(params, state, poolData, swapParams);

// If the hook contract does not exist or does not implement onAfterSwap, HooksConfigLib returns the original
// If the hook contract does not exist or does not implement onAfterSwap, PoolConfigLib returns the original
// amountCalculated. Otherwise, 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)
amountCalculated = hooksConfig.callAfterSwapHook(
amountCalculated = poolData.poolConfigBits.callAfterSwapHook(
amountCalculatedScaled18,
amountCalculated,
msg.sender,
params,
state,
poolData
poolData,
hooksContractCache
);

if (params.kind == SwapKind.EXACT_IN) {
Expand Down Expand Up @@ -498,7 +501,6 @@ contract Vault is IVaultMain, VaultCommon, Proxy {
// bptOut = supply * (ratio - 1), so lower ratio = less bptOut, favoring the pool.

_ensureUnpaused(params.pool);
HooksConfigBits hooksConfig = _hooksConfigBits[params.pool];

// `_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,
Expand All @@ -518,8 +520,16 @@ contract Vault is IVaultMain, VaultCommon, Proxy {
poolData.tokenRates
);

// Uses msg.sender as the router (the contract that called the vault)
elshan-eth marked this conversation as resolved.
Show resolved Hide resolved
if (hooksConfig.callBeforeAddLiquidityHook(msg.sender, maxAmountsInScaled18, params, poolData)) {
Cache.AddressCache memory hooksContractCache = Cache.initAddressCache(_hooksContracts[params.pool]);
if (
poolData.poolConfigBits.callBeforeAddLiquidityHook(
msg.sender,
maxAmountsInScaled18,
params,
poolData,
hooksContractCache
)
) {
// If the hook library returns true, the hook code was executed, and might have altered the balances,
// so we need to read them again to ensure that the data is fresh moving forward.
// We also need to upscale (adding liquidity, so round up) again.
Expand Down Expand Up @@ -547,13 +557,14 @@ contract Vault is IVaultMain, VaultCommon, Proxy {

// 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)
amountsIn = hooksConfig.callAfterAddLiquidityHook(
amountsIn = poolData.poolConfigBits.callAfterAddLiquidityHook(
msg.sender,
amountsInScaled18,
amountsIn,
bptAmountOut,
params,
poolData
poolData,
hooksContractCache
);
}

Expand Down Expand Up @@ -720,8 +731,6 @@ contract Vault is IVaultMain, VaultCommon, Proxy {
// bptIn = supply * (1 - ratio), so lower ratio = more bptIn, favoring the pool.
_ensureUnpaused(params.pool);

HooksConfigBits hooksConfig = _hooksConfigBits[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`.
Expand All @@ -739,8 +748,18 @@ contract Vault is IVaultMain, VaultCommon, Proxy {
poolData.tokenRates
);

Cache.AddressCache memory hooksContractCache = Cache.initAddressCache(_hooksContracts[params.pool]);
elshan-eth marked this conversation as resolved.
Show resolved Hide resolved

// Uses msg.sender as the router (the contract that called the vault)
if (hooksConfig.callBeforeRemoveLiquidityHook(minAmountsOutScaled18, msg.sender, params, poolData)) {
if (
poolData.poolConfigBits.callBeforeRemoveLiquidityHook(
minAmountsOutScaled18,
msg.sender,
params,
poolData,
hooksContractCache
) == true
) {
// 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.
Expand All @@ -766,13 +785,14 @@ contract Vault is IVaultMain, VaultCommon, Proxy {

// 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)
amountsOut = hooksConfig.callAfterRemoveLiquidityHook(
amountsOut = poolData.poolConfigBits.callAfterRemoveLiquidityHook(
msg.sender,
amountsOutScaled18,
amountsOut,
bptAmountIn,
params,
poolData
poolData,
hooksContractCache
);
}

Expand Down
Loading
Loading