Verified contractExactMIT
HookController
Address0x93bca6ab731eb8a90ae8b532889751a9edf7c5ed
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.26
- Same code
Only this contract
Details
- Compiler
- solc 0.8.26+commit.8a97fa7a
- Language
- solidity
- Optimization
- Yes, 1,000 runs
- EVM version
- cancun
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,393,579
- Creation transaction
- 0x8972261c2c…b113c7c594
20 files
- src/HookController.solmain17.81 KB
- lib/v4-core/src/interfaces/IHooks.sol8.23 KB
- lib/v4-core/src/interfaces/external/IERC20Minimal.sol3.04 KB
- lib/v4-core/src/libraries/CustomRevert.sol5.17 KB
- lib/v4-core/src/libraries/LPFeeLibrary.sol3.6 KB
- lib/v4-core/src/libraries/SafeCast.sol2.27 KB
- lib/v4-core/src/types/BalanceDelta.sol2.34 KB
- lib/v4-core/src/types/BeforeSwapDelta.sol1.47 KB
- lib/v4-core/src/types/Currency.sol5.46 KB
- lib/v4-core/src/types/PoolId.sol539 B
- lib/v4-core/src/types/PoolKey.sol805 B
- lib/v4-core/src/types/PoolOperation.sol907 B
- src/interfaces/IHookController.sol1.52 KB
- src/interfaces/ILeverController.sol5.7 KB
- src/interfaces/IMindHook.sol5.72 KB
- src/interfaces/IMindModule.sol971 B
- src/interfaces/IModuleRegistry.sol2.49 KB
- src/libraries/BoundsLib.sol7.13 KB
- src/types/Bounds.sol1.49 KB
- src/types/Modules.sol1.39 KB
src/HookController.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol";
import {LPFeeLibrary} from "@uniswap/v4-core/src/libraries/LPFeeLibrary.sol";
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
import {PoolId} from "@uniswap/v4-core/src/types/PoolId.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {IHookController} from "./interfaces/IHookController.sol";
import {ILeverController} from "./interfaces/ILeverController.sol";
import {IMindHook} from "./interfaces/IMindHook.sol";
import {IMindModule} from "./interfaces/IMindModule.sol";
import {IModuleRegistry} from "./interfaces/IModuleRegistry.sol";
import {BoundsLib} from "./libraries/BoundsLib.sol";
import {Bounds} from "./types/Bounds.sol";
import {ModuleRef} from "./types/Modules.sol";
interface IFactoryHook {
function hook() external view returns (IHooks);
}
interface IVaultCreator {
function creator() external view returns (address);
}
/// @title HookController
/// @notice Holds every coin's bounds (fixed at launch, tighten-only) and its current levers, and is the
/// only writer of lever changes. A coin's levers are moved by its vault, on behalf of its mind.
/// @dev No owner and no pause: `currentFees` and `activeModules` are read by MindHook on every swap and
/// can never revert or be switched off. Nothing here can loosen a bound.
contract HookController is ILeverController {
/// @notice Default hook fee at launch (1%), clamped into the coin's range.
uint16 public constant DEFAULT_FEE_BPS = 100;
/// @notice Default credits share at launch (20%), clamped into the coin's range.
uint16 public constant DEFAULT_CREDITS_SHARE_BPS = 2000;
/// @notice Largest LP-fee move per change: 0.25 percentage points, in hundredths of a bip.
uint24 public constant MAX_LP_FEE_STEP = 2500;
/// @notice Largest credits-share move per change: 5 percentage points.
uint16 public constant MAX_CREDITS_SHARE_STEP_BPS = 500;
/// @notice At most this many modules are active per coin (MindHook honours the same number).
uint256 public constant MAX_MODULES = 4;
/// @notice Gas forwarded to a module's `onDeactivate`; a module can never block its deactivation.
uint256 public constant DEACTIVATE_GAS = 100_000;
int24 private constant TICK_SPACING = 200;
/// @notice The CoinFactory (its address is precomputed at deploy time).
address public immutable factory;
/// @notice The platform guardian: may tighten bounds, never loosen them.
address public immutable guardian;
/// @notice Catalogue of audited modules.
IModuleRegistry public immutable moduleRegistry;
struct CoinInfo {
PoolId poolId;
address vault;
}
struct ActiveModule {
address module;
bool isGuard;
uint8 id;
}
/// @inheritdoc ILeverController
mapping(PoolId poolId => address coin) public coinOf;
mapping(address coin => CoinInfo info) private _coins;
mapping(address coin => Bounds bounds) private _bounds;
mapping(PoolId poolId => Levers levers) private _levers;
mapping(PoolId poolId => ActiveModule[] modules) private _modules;
/// @param factory_ The CoinFactory (precomputed).
/// @param guardian_ The platform guardian.
/// @param moduleRegistry_ The ModuleRegistry.
constructor(address factory_, address guardian_, IModuleRegistry moduleRegistry_) {
if (factory_ == address(0) || guardian_ == address(0) || address(moduleRegistry_) == address(0)) {
revert ZeroAddress();
}
factory = factory_;
guardian = guardian_;
moduleRegistry = moduleRegistry_;
}
// ---------------------------------------------------------------- factory
/// @inheritdoc IHookController
function register(address coin, PoolId poolId, address vault, Bounds calldata bounds) external {
if (msg.sender != factory) revert OnlyFactory();
if (coin == address(0) || vault == address(0)) revert ZeroAddress();
if (_coins[coin].vault != address(0)) revert CoinAlreadyRegistered(coin);
_coins[coin] = CoinInfo({poolId: poolId, vault: vault});
coinOf[poolId] = coin;
_bounds[coin] = bounds;
// The vault is the only source of truth for its caps; none are kept here.
delete _bounds[coin].vaultCaps;
// Levers start at the documented defaults, clamped into the creator's ranges. `changedAt` stays
// zero so the mind's first move of each lever is not rate-limited.
Levers storage levers = _levers[poolId];
levers.buyFeeBps = _clamp(DEFAULT_FEE_BPS, bounds.buyFeeMinBps, bounds.buyFeeMaxBps);
levers.sellFeeBps = _clamp(DEFAULT_FEE_BPS, bounds.sellFeeMinBps, bounds.sellFeeMaxBps);
levers.buyFeeMaxBps = bounds.buyFeeMaxBps;
levers.sellFeeMaxBps = bounds.sellFeeMaxBps;
levers.creditsShareBps = _clamp(DEFAULT_CREDITS_SHARE_BPS, bounds.creditsShareMinBps, bounds.creditsShareMaxBps);
emit CoinRegistered(coin, poolId, vault, bounds);
}
// ------------------------------------------------------------------ levers
/// @inheritdoc ILeverController
function setFees(address coin, uint16 buyFeeBps, uint16 sellFeeBps, bytes32 reasonHash) external {
PoolId poolId = _onlyVault(coin);
Bounds storage bounds = _bounds[coin];
Levers storage levers = _levers[poolId];
uint16 oldBuy = levers.buyFeeBps;
if (buyFeeBps != oldBuy) {
if (buyFeeBps < bounds.buyFeeMinBps || buyFeeBps > bounds.buyFeeMaxBps) revert OutOfBounds(Lever.BuyFee);
_checkStep(Lever.BuyFee, oldBuy, buyFeeBps, bounds.maxFeeStepBps);
_checkInterval(Lever.BuyFee, levers.buyFeeChangedAt, bounds.minFeeInterval);
levers.buyFeeBps = buyFeeBps;
levers.buyFeeChangedAt = uint32(block.timestamp);
emit LeverChanged(coin, Lever.BuyFee, oldBuy, buyFeeBps, 0, reasonHash);
}
uint16 oldSell = levers.sellFeeBps;
if (sellFeeBps != oldSell) {
if (sellFeeBps < bounds.sellFeeMinBps || sellFeeBps > bounds.sellFeeMaxBps) {
revert OutOfBounds(Lever.SellFee);
}
_checkStep(Lever.SellFee, oldSell, sellFeeBps, bounds.maxFeeStepBps);
_checkInterval(Lever.SellFee, levers.sellFeeChangedAt, bounds.minFeeInterval);
levers.sellFeeBps = sellFeeBps;
levers.sellFeeChangedAt = uint32(block.timestamp);
emit LeverChanged(coin, Lever.SellFee, oldSell, sellFeeBps, 0, reasonHash);
}
}
/// @inheritdoc ILeverController
function setLpFee(address coin, uint24 lpFee, bytes32 reasonHash) external {
PoolId poolId = _onlyVault(coin);
Bounds storage bounds = _bounds[coin];
Levers storage levers = _levers[poolId];
uint24 old = levers.lpFee;
if (lpFee == old) return;
if (lpFee > bounds.lpFeeMax) revert OutOfBounds(Lever.LpFee);
_checkStep(Lever.LpFee, old, lpFee, MAX_LP_FEE_STEP);
_checkInterval(Lever.LpFee, levers.lpFeeChangedAt, bounds.minFeeInterval);
levers.lpFee = lpFee;
levers.lpFeeChangedAt = uint32(block.timestamp);
emit LeverChanged(coin, Lever.LpFee, old, lpFee, 0, reasonHash);
_hook().syncLpFee(_poolKey(coin), lpFee);
}
/// @inheritdoc ILeverController
function setCreditsShare(address coin, uint16 newShareBps, bytes32 reasonHash) external {
PoolId poolId = _onlyVault(coin);
Bounds storage bounds = _bounds[coin];
Levers storage levers = _levers[poolId];
uint16 old = levers.creditsShareBps;
if (newShareBps == old) return;
if (newShareBps < bounds.creditsShareMinBps || newShareBps > bounds.creditsShareMaxBps) {
revert OutOfBounds(Lever.CreditsShare);
}
_checkStep(Lever.CreditsShare, old, newShareBps, MAX_CREDITS_SHARE_STEP_BPS);
_checkInterval(Lever.CreditsShare, levers.creditsShareChangedAt, bounds.minFeeInterval);
levers.creditsShareBps = newShareBps;
levers.creditsShareChangedAt = uint32(block.timestamp);
emit LeverChanged(coin, Lever.CreditsShare, old, newShareBps, 0, reasonHash);
}
/// @inheritdoc ILeverController
function setVolatility(address coin, bool on, bytes32 reasonHash) external {
PoolId poolId = _onlyVault(coin);
Levers storage levers = _levers[poolId];
bool old = levers.volatilityOn;
if (on == old) return;
levers.volatilityOn = on;
emit LeverChanged(coin, Lever.Volatility, old ? 1 : 0, on ? 1 : 0, 0, reasonHash);
}
/// @inheritdoc ILeverController
function setModule(address coin, uint8 moduleId, bool active, bytes calldata params, bytes32 reasonHash) external {
PoolId poolId = _onlyVault(coin);
if (active) {
_activateModule(coin, poolId, moduleId, params);
} else {
if (!_deactivateModule(coin, poolId, moduleId)) revert ModuleNotActive(moduleId);
}
emit LeverChanged(coin, Lever.Module, active ? 0 : 1, active ? 1 : 0, moduleId, reasonHash);
}
// ---------------------------------------------------------------- tighten
/// @inheritdoc ILeverController
function tightenBounds(address coin, Bounds calldata tighter) external {
CoinInfo memory info = _coins[coin];
if (info.vault == address(0)) revert UnknownCoin(coin);
if (msg.sender != guardian && msg.sender != IVaultCreator(info.vault).creator()) {
revert OnlyGuardianOrCreator();
}
BoundsLib.requireTighter(tighter, _bounds[coin]);
_requireLeversInside(info.poolId, tighter);
_bounds[coin] = tighter;
// The vault owns its caps; they are tightened there, never here.
delete _bounds[coin].vaultCaps;
Levers storage levers = _levers[info.poolId];
levers.buyFeeMaxBps = tighter.buyFeeMaxBps;
levers.sellFeeMaxBps = tighter.sellFeeMaxBps;
emit BoundsTightened(coin, msg.sender, _bounds[coin]);
_dropDisallowedModules(coin, info.poolId, tighter.allowedModulesBitmap);
}
// ------------------------------------------------------------------ views
/// @inheritdoc IHookController
/// @dev One storage read. Never reverts, for any pool id.
function currentFees(PoolId poolId) external view returns (PoolFees memory) {
Levers storage levers = _levers[poolId];
return PoolFees({
buyFeeBps: levers.buyFeeBps,
sellFeeBps: levers.sellFeeBps,
buyFeeMaxBps: levers.buyFeeMaxBps,
sellFeeMaxBps: levers.sellFeeMaxBps,
volatilityOn: levers.volatilityOn,
moduleCount: levers.moduleCount
});
}
/// @inheritdoc IHookController
/// @dev At most `MAX_MODULES` entries. Never reverts.
function activeModules(PoolId poolId) external view returns (ModuleRef[] memory refs) {
ActiveModule[] storage modules = _modules[poolId];
uint256 count = modules.length;
refs = new ModuleRef[](count);
for (uint256 i = 0; i < count; ++i) {
refs[i] = ModuleRef({module: modules[i].module, isGuard: modules[i].isGuard});
}
}
/// @inheritdoc ILeverController
function boundsOf(address coin) external view returns (Bounds memory) {
return _bounds[coin];
}
/// @inheritdoc ILeverController
function leversOf(address coin) external view returns (Levers memory) {
return _levers[_coins[coin].poolId];
}
/// @inheritdoc ILeverController
function creditsShareBps(address coin) external view returns (uint16) {
return _levers[_coins[coin].poolId].creditsShareBps;
}
/// @inheritdoc ILeverController
function isModuleActive(address coin, uint8 moduleId) public view returns (bool) {
ActiveModule[] storage modules = _modules[_coins[coin].poolId];
for (uint256 i = 0; i < modules.length; ++i) {
if (modules[i].id == moduleId) return true;
}
return false;
}
/// @inheritdoc ILeverController
function activeModule(address coin, uint8 moduleId) external view returns (address) {
ActiveModule[] storage modules = _modules[_coins[coin].poolId];
for (uint256 i = 0; i < modules.length; ++i) {
if (modules[i].id == moduleId) return modules[i].module;
}
return address(0);
}
/// @inheritdoc ILeverController
function poolIdOf(address coin) external view returns (PoolId) {
return _coins[coin].poolId;
}
/// @inheritdoc ILeverController
function vaultOf(address coin) external view returns (address) {
return _coins[coin].vault;
}
// -------------------------------------------------------------- internals
function _onlyVault(address coin) private view returns (PoolId) {
CoinInfo memory info = _coins[coin];
if (info.vault == address(0)) revert UnknownCoin(coin);
if (msg.sender != info.vault) revert OnlyVault();
return info.poolId;
}
function _checkStep(Lever lever, uint256 oldValue, uint256 newValue, uint256 maxStep) private pure {
uint256 step = newValue > oldValue ? newValue - oldValue : oldValue - newValue;
if (step > maxStep) revert StepTooLarge(lever);
}
/// @dev `changedAt == 0` means the lever has never been moved, so its first move is free.
function _checkInterval(Lever lever, uint32 changedAt, uint32 minInterval) private view {
if (changedAt == 0) return;
uint256 readyAt = uint256(changedAt) + minInterval;
if (block.timestamp < readyAt) revert TooSoon(lever, readyAt);
}
function _activateModule(address coin, PoolId poolId, uint8 moduleId, bytes calldata params) private {
if (_bounds[coin].allowedModulesBitmap & (uint256(1) << moduleId) == 0) revert ModuleNotAllowed(moduleId);
(address module, bool isGuard, bool listed) = moduleRegistry.moduleInfo(moduleId);
if (module == address(0) || !listed) revert ModuleNotListed(moduleId);
if (isModuleActive(coin, moduleId)) revert ModuleAlreadyActive(moduleId);
ActiveModule[] storage modules = _modules[poolId];
if (modules.length >= MAX_MODULES) revert TooManyModules();
modules.push(ActiveModule({module: module, isGuard: isGuard, id: moduleId}));
_levers[poolId].moduleCount = uint8(modules.length);
// The module validates its own parameters and may refuse the activation.
IMindModule(module).onActivate(poolId, params);
}
/// @dev Returns false if the module was not active. The module is told, but cannot object: a failing
/// `onDeactivate` is reported and ignored so a faulty module can always be switched off.
function _deactivateModule(address coin, PoolId poolId, uint8 moduleId) private returns (bool) {
ActiveModule[] storage modules = _modules[poolId];
uint256 count = modules.length;
for (uint256 i = 0; i < count; ++i) {
if (modules[i].id != moduleId) continue;
address module = modules[i].module;
modules[i] = modules[count - 1];
modules.pop();
_levers[poolId].moduleCount = uint8(count - 1);
try IMindModule(module).onDeactivate{gas: DEACTIVATE_GAS}(poolId) {}
catch {
emit ModuleDeactivationFailed(coin, moduleId, module);
}
return true;
}
return false;
}
/// @dev Tightening must not move a lever (that would bypass the step and interval limits and let a
/// creator or the guardian jump a fee or the credits share). Every lever must already sit inside
/// the new bounds.
function _requireLeversInside(PoolId poolId, Bounds calldata b) private view {
Levers memory l = _levers[poolId];
if (l.buyFeeBps < b.buyFeeMinBps || l.buyFeeBps > b.buyFeeMaxBps) revert LeverOutsideNewBounds(Lever.BuyFee);
if (l.sellFeeBps < b.sellFeeMinBps || l.sellFeeBps > b.sellFeeMaxBps) {
revert LeverOutsideNewBounds(Lever.SellFee);
}
if (l.lpFee > b.lpFeeMax) revert LeverOutsideNewBounds(Lever.LpFee);
if (l.creditsShareBps < b.creditsShareMinBps || l.creditsShareBps > b.creditsShareMaxBps) {
revert LeverOutsideNewBounds(Lever.CreditsShare);
}
}
function _dropDisallowedModules(address coin, PoolId poolId, uint256 allowedBitmap) private {
ActiveModule[] storage modules = _modules[poolId];
// Iterate backwards: deactivation swaps the last entry into the freed position.
for (uint256 i = modules.length; i > 0; --i) {
uint8 id = modules[i - 1].id;
if (allowedBitmap & (uint256(1) << id) != 0) continue;
_deactivateModule(coin, poolId, id);
emit LeverChanged(coin, Lever.Module, 1, 0, id, bytes32(0));
}
}
function _hook() private view returns (IMindHook) {
return IMindHook(address(IFactoryHook(factory).hook()));
}
function _poolKey(address coin) private view returns (PoolKey memory) {
return PoolKey({
currency0: Currency.wrap(address(0)),
currency1: Currency.wrap(coin),
fee: LPFeeLibrary.DYNAMIC_FEE_FLAG,
tickSpacing: TICK_SPACING,
hooks: IFactoryHook(factory).hook()
});
}
function _clamp(uint16 value, uint16 min, uint16 max) private pure returns (uint16) {
if (value < min) return min;
if (value > max) return max;
return value;
}
}
lib/v4-core/src/interfaces/IHooks.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";
import {BeforeSwapDelta} from "../types/BeforeSwapDelta.sol";
/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits
/// of the address that the hooks contract is deployed to.
/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400
/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.
/// See the Hooks library for the full spec.
/// @dev Should only be callable by the v4 PoolManager.
interface IHooks {
/// @notice The hook called before the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param key The key for the pool being initialized
/// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
/// @return bytes4 The function selector for the hook
function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96) external returns (bytes4);
/// @notice The hook called after the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param key The key for the pool being initialized
/// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
/// @param tick The current tick after the state of a pool is initialized
/// @return bytes4 The function selector for the hook
function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)
external
returns (bytes4);
/// @notice The hook called before liquidity is added
/// @param sender The initial msg.sender for the add liquidity call
/// @param key The key for the pool
/// @param params The parameters for adding liquidity
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeAddLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after liquidity is added
/// @param sender The initial msg.sender for the add liquidity call
/// @param key The key for the pool
/// @param params The parameters for adding liquidity
/// @param delta The caller's balance delta after adding liquidity; the sum of principal delta, fees accrued, and hook delta
/// @param feesAccrued The fees accrued since the last time fees were collected from this position
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterAddLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external returns (bytes4, BalanceDelta);
/// @notice The hook called before liquidity is removed
/// @param sender The initial msg.sender for the remove liquidity call
/// @param key The key for the pool
/// @param params The parameters for removing liquidity
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeRemoveLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after liquidity is removed
/// @param sender The initial msg.sender for the remove liquidity call
/// @param key The key for the pool
/// @param params The parameters for removing liquidity
/// @param delta The caller's balance delta after removing liquidity; the sum of principal delta, fees accrued, and hook delta
/// @param feesAccrued The fees accrued since the last time fees were collected from this position
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterRemoveLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external returns (bytes4, BalanceDelta);
/// @notice The hook called before a swap
/// @param sender The initial msg.sender for the swap call
/// @param key The key for the pool
/// @param params The parameters for the swap
/// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BeforeSwapDelta The hook's delta in specified and unspecified currencies. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
/// @return uint24 Optionally override the lp fee, only used if three conditions are met: 1. the Pool has a dynamic fee, 2. the value's 2nd highest bit is set (23rd bit, 0x400000), and 3. the value is less than or equal to the maximum fee (1 million)
function beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata hookData)
external
returns (bytes4, BeforeSwapDelta, uint24);
/// @notice The hook called after a swap
/// @param sender The initial msg.sender for the swap call
/// @param key The key for the pool
/// @param params The parameters for the swap
/// @param delta The amount owed to the caller (positive) or owed to the pool (negative)
/// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return int128 The hook's delta in unspecified currency. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterSwap(
address sender,
PoolKey calldata key,
SwapParams calldata params,
BalanceDelta delta,
bytes calldata hookData
) external returns (bytes4, int128);
/// @notice The hook called before donate
/// @param sender The initial msg.sender for the donate call
/// @param key The key for the pool
/// @param amount0 The amount of token0 being donated
/// @param amount1 The amount of token1 being donated
/// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after donate
/// @param sender The initial msg.sender for the donate call
/// @param key The key for the pool
/// @param amount0 The amount of token0 being donated
/// @param amount1 The amount of token1 being donated
/// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function afterDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external returns (bytes4);
}
lib/v4-core/src/interfaces/external/IERC20Minimal.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Minimal ERC20 interface for Uniswap
/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3
interface IERC20Minimal {
/// @notice Returns an account's balance in the token
/// @param account The account for which to look up the number of tokens it has, i.e. its balance
/// @return The number of tokens held by the account
function balanceOf(address account) external view returns (uint256);
/// @notice Transfers the amount of token from the `msg.sender` to the recipient
/// @param recipient The account that will receive the amount transferred
/// @param amount The number of tokens to send from the sender to the recipient
/// @return Returns true for a successful transfer, false for an unsuccessful transfer
function transfer(address recipient, uint256 amount) external returns (bool);
/// @notice Returns the current allowance given to a spender by an owner
/// @param owner The account of the token owner
/// @param spender The account of the token spender
/// @return The current allowance granted by `owner` to `spender`
function allowance(address owner, address spender) external view returns (uint256);
/// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`
/// @param spender The account which will be allowed to spend a given amount of the owners tokens
/// @param amount The amount of tokens allowed to be used by `spender`
/// @return Returns true for a successful approval, false for unsuccessful
function approve(address spender, uint256 amount) external returns (bool);
/// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`
/// @param sender The account from which the transfer will be initiated
/// @param recipient The recipient of the transfer
/// @param amount The amount of the transfer
/// @return Returns true for a successful transfer, false for unsuccessful
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.
/// @param from The account from which the tokens were sent, i.e. the balance decreased
/// @param to The account to which the tokens were sent, i.e. the balance increased
/// @param value The amount of tokens that were transferred
event Transfer(address indexed from, address indexed to, uint256 value);
/// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.
/// @param owner The account that approved spending of its tokens
/// @param spender The account for which the spending allowance was modified
/// @param value The new allowance from the owner to the spender
event Approval(address indexed owner, address indexed spender, uint256 value);
}
lib/v4-core/src/libraries/CustomRevert.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Library for reverting with custom errors efficiently
/// @notice Contains functions for reverting with custom errors with different argument types efficiently
/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with
/// `CustomError.selector.revertWith()`
/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately
library CustomRevert {
/// @dev ERC-7751 error for wrapping bubbled up reverts
error WrappedError(address target, bytes4 selector, bytes reason, bytes details);
/// @dev Reverts with the selector of a custom error in the scratch space
function revertWith(bytes4 selector) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
revert(0, 0x04)
}
}
/// @dev Reverts with a custom error with an address argument in the scratch space
function revertWith(bytes4 selector, address addr) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with an int24 argument in the scratch space
function revertWith(bytes4 selector, int24 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, signextend(2, value))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with a uint160 argument in the scratch space
function revertWith(bytes4 selector, uint160 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with two int24 arguments
function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), signextend(2, value1))
mstore(add(fmp, 0x24), signextend(2, value2))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two uint160 arguments
function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two address arguments
function revertWith(bytes4 selector, address value1, address value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error
/// @dev this method can be vulnerable to revert data bombs
function bubbleUpAndRevertWith(
address revertingContract,
bytes4 revertingFunctionSelector,
bytes4 additionalContext
) internal pure {
bytes4 wrappedErrorSelector = WrappedError.selector;
assembly ("memory-safe") {
// Ensure the size of the revert data is a multiple of 32 bytes
let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)
let fmp := mload(0x40)
// Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason
mstore(fmp, wrappedErrorSelector)
mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(
add(fmp, 0x24),
and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
// offset revert reason
mstore(add(fmp, 0x44), 0x80)
// offset additional context
mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))
// size revert reason
mstore(add(fmp, 0x84), returndatasize())
// revert reason
returndatacopy(add(fmp, 0xa4), 0, returndatasize())
// size additional context
mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)
// additional context
mstore(
add(fmp, add(0xc4, encodedDataSize)),
and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
revert(fmp, add(0xe4, encodedDataSize))
}
}
}
lib/v4-core/src/libraries/LPFeeLibrary.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {CustomRevert} from "./CustomRevert.sol";
/// @notice Library of helper functions for a pools LP fee
library LPFeeLibrary {
using LPFeeLibrary for uint24;
using CustomRevert for bytes4;
/// @notice Thrown when the static or dynamic fee on a pool exceeds 100%.
error LPFeeTooLarge(uint24 fee);
/// @notice An lp fee of exactly 0b1000000... signals a dynamic fee pool. This isn't a valid static fee as it is > MAX_LP_FEE
uint24 public constant DYNAMIC_FEE_FLAG = 0x800000;
/// @notice the second bit of the fee returned by beforeSwap is used to signal if the stored LP fee should be overridden in this swap
// only dynamic-fee pools can return a fee via the beforeSwap hook
uint24 public constant OVERRIDE_FEE_FLAG = 0x400000;
/// @notice mask to remove the override fee flag from a fee returned by the beforeSwaphook
uint24 public constant REMOVE_OVERRIDE_MASK = 0xBFFFFF;
/// @notice the lp fee is represented in hundredths of a bip, so the max is 100%
uint24 public constant MAX_LP_FEE = 1000000;
/// @notice returns true if a pool's LP fee signals that the pool has a dynamic fee
/// @param self The fee to check
/// @return bool True of the fee is dynamic
function isDynamicFee(uint24 self) internal pure returns (bool) {
return self == DYNAMIC_FEE_FLAG;
}
/// @notice returns true if an LP fee is valid, aka not above the maximum permitted fee
/// @param self The fee to check
/// @return bool True of the fee is valid
function isValid(uint24 self) internal pure returns (bool) {
return self <= MAX_LP_FEE;
}
/// @notice validates whether an LP fee is larger than the maximum, and reverts if invalid
/// @param self The fee to validate
function validate(uint24 self) internal pure {
if (!self.isValid()) LPFeeTooLarge.selector.revertWith(self);
}
/// @notice gets and validates the initial LP fee for a pool. Dynamic fee pools have an initial fee of 0.
/// @dev if a dynamic fee pool wants a non-0 initial fee, it should call `updateDynamicLPFee` in the afterInitialize hook
/// @param self The fee to get the initial LP from
/// @return initialFee 0 if the fee is dynamic, otherwise the fee (if valid)
function getInitialLPFee(uint24 self) internal pure returns (uint24) {
// the initial fee for a dynamic fee pool is 0
if (self.isDynamicFee()) return 0;
self.validate();
return self;
}
/// @notice returns true if the fee has the override flag set (2nd highest bit of the uint24)
/// @param self The fee to check
/// @return bool True of the fee has the override flag set
function isOverride(uint24 self) internal pure returns (bool) {
return self & OVERRIDE_FEE_FLAG != 0;
}
/// @notice returns a fee with the override flag removed
/// @param self The fee to remove the override flag from
/// @return fee The fee without the override flag set
function removeOverrideFlag(uint24 self) internal pure returns (uint24) {
return self & REMOVE_OVERRIDE_MASK;
}
/// @notice Removes the override flag and validates the fee (reverts if the fee is too large)
/// @param self The fee to remove the override flag from, and then validate
/// @return fee The fee without the override flag set (if valid)
function removeOverrideFlagAndValidate(uint24 self) internal pure returns (uint24 fee) {
fee = self.removeOverrideFlag();
fee.validate();
}
}
lib/v4-core/src/libraries/SafeCast.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {CustomRevert} from "./CustomRevert.sol";
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
using CustomRevert for bytes4;
error SafeCastOverflow();
/// @notice Cast a uint256 to a uint160, revert on overflow
/// @param x The uint256 to be downcasted
/// @return y The downcasted integer, now type uint160
function toUint160(uint256 x) internal pure returns (uint160 y) {
y = uint160(x);
if (y != x) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a uint128, revert on overflow
/// @param x The uint256 to be downcasted
/// @return y The downcasted integer, now type uint128
function toUint128(uint256 x) internal pure returns (uint128 y) {
y = uint128(x);
if (x != y) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a int128 to a uint128, revert on overflow or underflow
/// @param x The int128 to be casted
/// @return y The casted integer, now type uint128
function toUint128(int128 x) internal pure returns (uint128 y) {
if (x < 0) SafeCastOverflow.selector.revertWith();
y = uint128(x);
}
/// @notice Cast a int256 to a int128, revert on overflow or underflow
/// @param x The int256 to be downcasted
/// @return y The downcasted integer, now type int128
function toInt128(int256 x) internal pure returns (int128 y) {
y = int128(x);
if (y != x) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param x The uint256 to be casted
/// @return y The casted integer, now type int256
function toInt256(uint256 x) internal pure returns (int256 y) {
y = int256(x);
if (y < 0) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a int128, revert on overflow
/// @param x The uint256 to be downcasted
/// @return The downcasted integer, now type int128
function toInt128(uint256 x) internal pure returns (int128) {
if (x >= 1 << 127) SafeCastOverflow.selector.revertWith();
return int128(int256(x));
}
}
lib/v4-core/src/types/BalanceDelta.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {SafeCast} from "../libraries/SafeCast.sol";
/// @dev Two `int128` values packed into a single `int256` where the upper 128 bits represent the amount0
/// and the lower 128 bits represent the amount1.
type BalanceDelta is int256;
using {add as +, sub as -, eq as ==, neq as !=} for BalanceDelta global;
using BalanceDeltaLibrary for BalanceDelta global;
using SafeCast for int256;
function toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) {
assembly ("memory-safe") {
balanceDelta := or(shl(128, _amount0), and(sub(shl(128, 1), 1), _amount1))
}
}
function add(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
int256 res0;
int256 res1;
assembly ("memory-safe") {
let a0 := sar(128, a)
let a1 := signextend(15, a)
let b0 := sar(128, b)
let b1 := signextend(15, b)
res0 := add(a0, b0)
res1 := add(a1, b1)
}
return toBalanceDelta(res0.toInt128(), res1.toInt128());
}
function sub(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
int256 res0;
int256 res1;
assembly ("memory-safe") {
let a0 := sar(128, a)
let a1 := signextend(15, a)
let b0 := sar(128, b)
let b1 := signextend(15, b)
res0 := sub(a0, b0)
res1 := sub(a1, b1)
}
return toBalanceDelta(res0.toInt128(), res1.toInt128());
}
function eq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
return BalanceDelta.unwrap(a) == BalanceDelta.unwrap(b);
}
function neq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
return BalanceDelta.unwrap(a) != BalanceDelta.unwrap(b);
}
/// @notice Library for getting the amount0 and amount1 deltas from the BalanceDelta type
library BalanceDeltaLibrary {
/// @notice A BalanceDelta of 0
BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0);
function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) {
assembly ("memory-safe") {
_amount0 := sar(128, balanceDelta)
}
}
function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) {
assembly ("memory-safe") {
_amount1 := signextend(15, balanceDelta)
}
}
}
lib/v4-core/src/types/BeforeSwapDelta.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Return type of the beforeSwap hook.
// Upper 128 bits is the delta in specified tokens. Lower 128 bits is delta in unspecified tokens (to match the afterSwap hook)
type BeforeSwapDelta is int256;
// Creates a BeforeSwapDelta from specified and unspecified
function toBeforeSwapDelta(int128 deltaSpecified, int128 deltaUnspecified)
pure
returns (BeforeSwapDelta beforeSwapDelta)
{
assembly ("memory-safe") {
beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified))
}
}
/// @notice Library for getting the specified and unspecified deltas from the BeforeSwapDelta type
library BeforeSwapDeltaLibrary {
/// @notice A BeforeSwapDelta of 0
BeforeSwapDelta public constant ZERO_DELTA = BeforeSwapDelta.wrap(0);
/// extracts int128 from the upper 128 bits of the BeforeSwapDelta
/// returned by beforeSwap
function getSpecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaSpecified) {
assembly ("memory-safe") {
deltaSpecified := sar(128, delta)
}
}
/// extracts int128 from the lower 128 bits of the BeforeSwapDelta
/// returned by beforeSwap and afterSwap
function getUnspecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaUnspecified) {
assembly ("memory-safe") {
deltaUnspecified := signextend(15, delta)
}
}
}
lib/v4-core/src/types/Currency.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC20Minimal} from "../interfaces/external/IERC20Minimal.sol";
import {CustomRevert} from "../libraries/CustomRevert.sol";
type Currency is address;
using {greaterThan as >, lessThan as <, greaterThanOrEqualTo as >=, equals as ==} for Currency global;
using CurrencyLibrary for Currency global;
function equals(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) == Currency.unwrap(other);
}
function greaterThan(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) > Currency.unwrap(other);
}
function lessThan(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) < Currency.unwrap(other);
}
function greaterThanOrEqualTo(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) >= Currency.unwrap(other);
}
/// @title CurrencyLibrary
/// @dev This library allows for transferring and holding native tokens and ERC20 tokens
library CurrencyLibrary {
/// @notice Additional context for ERC-7751 wrapped error when a native transfer fails
error NativeTransferFailed();
/// @notice Additional context for ERC-7751 wrapped error when an ERC20 transfer fails
error ERC20TransferFailed();
/// @notice A constant to represent the native currency
Currency public constant ADDRESS_ZERO = Currency.wrap(address(0));
function transfer(Currency currency, address to, uint256 amount) internal {
// altered from https://github.com/transmissions11/solmate/blob/44a9963d4c78111f77caa0e65d677b8b46d6f2e6/src/utils/SafeTransferLib.sol
// modified custom error selectors
bool success;
if (currency.isAddressZero()) {
assembly ("memory-safe") {
// Transfer the ETH and revert if it fails.
success := call(gas(), to, amount, 0, 0, 0, 0)
}
// revert with NativeTransferFailed, containing the bubbled up error as an argument
if (!success) {
CustomRevert.bubbleUpAndRevertWith(to, bytes4(0), NativeTransferFailed.selector);
}
} else {
assembly ("memory-safe") {
// Get a pointer to some free memory.
let fmp := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(fmp, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
mstore(add(fmp, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
mstore(add(fmp, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
success :=
and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the or() call in the
// surrounding and() call or else returndatasize() will be zero during the computation.
call(gas(), currency, 0, fmp, 68, 0, 32)
)
// Now clean the memory we used
mstore(fmp, 0) // 4 byte `selector` and 28 bytes of `to` were stored here
mstore(add(fmp, 0x20), 0) // 4 bytes of `to` and 28 bytes of `amount` were stored here
mstore(add(fmp, 0x40), 0) // 4 bytes of `amount` were stored here
}
// revert with ERC20TransferFailed, containing the bubbled up error as an argument
if (!success) {
CustomRevert.bubbleUpAndRevertWith(
Currency.unwrap(currency), IERC20Minimal.transfer.selector, ERC20TransferFailed.selector
);
}
}
}
function balanceOfSelf(Currency currency) internal view returns (uint256) {
if (currency.isAddressZero()) {
return address(this).balance;
} else {
return IERC20Minimal(Currency.unwrap(currency)).balanceOf(address(this));
}
}
function balanceOf(Currency currency, address owner) internal view returns (uint256) {
if (currency.isAddressZero()) {
return owner.balance;
} else {
return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner);
}
}
function isAddressZero(Currency currency) internal pure returns (bool) {
return Currency.unwrap(currency) == Currency.unwrap(ADDRESS_ZERO);
}
function toId(Currency currency) internal pure returns (uint256) {
return uint160(Currency.unwrap(currency));
}
// If the upper 12 bytes are non-zero, they will be zero-ed out
// Therefore, fromId() and toId() are not inverses of each other
function fromId(uint256 id) internal pure returns (Currency) {
return Currency.wrap(address(uint160(id)));
}
}
lib/v4-core/src/types/PoolId.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "./PoolKey.sol";
type PoolId is bytes32;
/// @notice Library for computing the ID of a pool
library PoolIdLibrary {
/// @notice Returns value equal to keccak256(abi.encode(poolKey))
function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) {
assembly ("memory-safe") {
// 0xa0 represents the total size of the poolKey struct (5 slots of 32 bytes)
poolId := keccak256(poolKey, 0xa0)
}
}
}
lib/v4-core/src/types/PoolKey.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "./Currency.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {PoolIdLibrary} from "./PoolId.sol";
using PoolIdLibrary for PoolKey global;
/// @notice Returns the key for identifying a pool
struct PoolKey {
/// @notice The lower currency of the pool, sorted numerically
Currency currency0;
/// @notice The higher currency of the pool, sorted numerically
Currency currency1;
/// @notice The pool LP fee, capped at 1_000_000. If the highest bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000
uint24 fee;
/// @notice Ticks that involve positions must be a multiple of tick spacing
int24 tickSpacing;
/// @notice The hooks of the pool
IHooks hooks;
}
lib/v4-core/src/types/PoolOperation.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
/// @notice Parameter struct for `ModifyLiquidity` pool operations
struct ModifyLiquidityParams {
// the lower and upper tick of the position
int24 tickLower;
int24 tickUpper;
// how to modify the liquidity
int256 liquidityDelta;
// a value to set if you want unique liquidity positions at the same range
bytes32 salt;
}
/// @notice Parameter struct for `Swap` pool operations
struct SwapParams {
/// Whether to swap token0 for token1 or vice versa
bool zeroForOne;
/// The desired input amount if negative (exactIn), or the desired output amount if positive (exactOut)
int256 amountSpecified;
/// The sqrt price at which, if reached, the swap will stop executing
uint160 sqrtPriceLimitX96;
}
src/interfaces/IHookController.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {PoolId} from "@uniswap/v4-core/src/types/PoolId.sol";
import {Bounds} from "../types/Bounds.sol";
import {ModuleRef} from "../types/Modules.sol";
/// @notice The part of the HookController the factory and MindHook depend on. Implemented in phase 04.
interface IHookController {
/// @notice The fee levers MindHook reads on every swap.
/// @param buyFeeBps Current ETH hook fee on buys.
/// @param sellFeeBps Current ETH hook fee on sells.
/// @param buyFeeMaxBps The coin's maximum buy fee (bound fixed at launch).
/// @param sellFeeMaxBps The coin's maximum sell fee (bound fixed at launch).
/// @param volatilityOn Whether the built-in volatility extra is switched on.
/// @param moduleCount Number of active modules; `activeModules` is only called when non-zero.
struct PoolFees {
uint16 buyFeeBps;
uint16 sellFeeBps;
uint16 buyFeeMaxBps;
uint16 sellFeeMaxBps;
bool volatilityOn;
uint8 moduleCount;
}
/// @notice Records a new coin and its launch bounds. Factory only.
function register(address coin, PoolId poolId, address vault, Bounds calldata bounds) external;
/// @notice Current fee levers for a pool.
function currentFees(PoolId poolId) external view returns (PoolFees memory);
/// @notice The modules active on a pool (at most four are honoured).
function activeModules(PoolId poolId) external view returns (ModuleRef[] memory);
}
src/interfaces/ILeverController.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {PoolId} from "@uniswap/v4-core/src/types/PoolId.sol";
import {Bounds} from "../types/Bounds.sol";
import {IHookController} from "./IHookController.sol";
/// @notice The HookController's lever interface: what a coin's vault (on behalf of its mind), its
/// creator and the guardian can do, and the views other contracts read.
interface ILeverController is IHookController {
/// @notice The levers a mind can move.
enum Lever {
BuyFee,
SellFee,
LpFee,
CreditsShare,
Volatility,
Module
}
/// @notice Current lever values and bookkeeping for one pool (one storage slot).
struct Levers {
uint16 buyFeeBps;
uint16 sellFeeBps;
uint16 buyFeeMaxBps;
uint16 sellFeeMaxBps;
uint24 lpFee;
uint16 creditsShareBps;
bool volatilityOn;
uint8 moduleCount;
uint32 buyFeeChangedAt;
uint32 sellFeeChangedAt;
uint32 lpFeeChangedAt;
uint32 creditsShareChangedAt;
}
/// @notice A lever moved. `reasonHash` is the keccak of the mind's public reason, stored off-chain.
/// @dev For `Lever.Module`, `oldValue`/`newValue` are 0/1 (inactive/active) and `moduleId` is set.
event LeverChanged(
address indexed coin,
Lever indexed lever,
uint256 oldValue,
uint256 newValue,
uint8 moduleId,
bytes32 reasonHash
);
/// @notice A coin was registered with its launch bounds and starting levers.
event CoinRegistered(address indexed coin, PoolId indexed poolId, address vault, Bounds bounds);
/// @notice A coin's bounds were tightened.
event BoundsTightened(address indexed coin, address indexed by, Bounds bounds);
/// @notice A module's `onDeactivate` reverted; it was deactivated regardless.
event ModuleDeactivationFailed(address indexed coin, uint8 moduleId, address module);
error ZeroAddress();
error OnlyFactory();
error OnlyVault();
error OnlyGuardianOrCreator();
error CoinAlreadyRegistered(address coin);
error UnknownCoin(address coin);
/// @notice The value is outside the coin's bounds.
error OutOfBounds(Lever lever);
/// @notice The change is larger than the allowed step for one change.
error StepTooLarge(Lever lever);
/// @notice The lever was changed too recently; `readyAt` is when it may change again.
error TooSoon(Lever lever, uint256 readyAt);
error ModuleNotAllowed(uint8 moduleId);
error ModuleNotListed(uint8 moduleId);
error ModuleAlreadyActive(uint8 moduleId);
error ModuleNotActive(uint8 moduleId);
error TooManyModules();
/// @notice The new bounds would leave this lever outside its range; tightening never moves levers.
error LeverOutsideNewBounds(Lever lever);
/// @notice Sets the coin's buy and sell hook fees. Vault only.
/// @dev Each side that changes must stay inside its bounds, move by at most `maxFeeStepBps` and be
/// at least `minFeeInterval` after its previous change.
function setFees(address coin, uint16 buyFeeBps, uint16 sellFeeBps, bytes32 reasonHash) external;
/// @notice Sets the pool's dynamic LP fee (hundredths of a bip). Vault only; step- and rate-limited.
function setLpFee(address coin, uint24 lpFee, bytes32 reasonHash) external;
/// @notice Sets the share of fees routed to credits beyond the $100 threshold. Vault only.
function setCreditsShare(address coin, uint16 creditsShareBps, bytes32 reasonHash) external;
/// @notice Switches the hook's volatility extra on or off. Vault only.
function setVolatility(address coin, bool on, bytes32 reasonHash) external;
/// @notice Activates or deactivates a registry module for the coin. Vault only.
/// @param params Activation parameters, validated by the module itself. Ignored on deactivation.
function setModule(address coin, uint8 moduleId, bool active, bytes calldata params, bytes32 reasonHash) external;
/// @notice Replaces the coin's bounds with tighter ones. Guardian or the coin's creator.
/// @dev Tightening never moves a fee lever: it reverts unless every lever is already inside the new
/// bounds (the mind steps a lever first, then the bound can follow). Modules no longer allowed
/// are deactivated.
function tightenBounds(address coin, Bounds calldata tighter) external;
/// @notice The coin's current bounds.
function boundsOf(address coin) external view returns (Bounds memory);
/// @notice The coin's current levers.
function leversOf(address coin) external view returns (Levers memory);
/// @notice Share of fees routed to credits beyond the $100 threshold, read by the FeeRouter.
function creditsShareBps(address coin) external view returns (uint16);
/// @notice Whether `moduleId` is active for the coin.
function isModuleActive(address coin, uint8 moduleId) external view returns (bool);
/// @notice The module contract activated for the coin under `moduleId`, or the zero address.
/// @dev This is the address recorded at activation, not whatever the registry lists now.
function activeModule(address coin, uint8 moduleId) external view returns (address);
/// @notice The coin trading in `poolId`, or the zero address.
function coinOf(PoolId poolId) external view returns (address);
/// @notice The coin's pool.
function poolIdOf(address coin) external view returns (PoolId);
/// @notice The coin's vault, the only address allowed to move its levers.
function vaultOf(address coin) external view returns (address);
}
src/interfaces/IMindHook.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {PoolId} from "@uniswap/v4-core/src/types/PoolId.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {Bounds} from "../types/Bounds.sol";
import {IHookController} from "./IHookController.sol";
/// @notice The shared HOOKMIND hook's own interface (the v4 hook callbacks are in `IHooks`).
interface IMindHook {
/// @notice Per-pool hook state (one storage slot). Everything except the volatility reference is
/// fixed at launch and can never change.
/// @param registered True once the factory has registered the pool.
/// @param launchBlock Block of the launch; anti-snipe decays from here.
/// @param refBlock Block in which `refTick` was recorded.
/// @param snipeStartBps Extra buy fee at the launch block.
/// @param snipeBlocks Blocks over which the extra buy fee decays linearly to zero.
/// @param buyFeeMaxBps The coin's maximum buy hook fee (launch bound).
/// @param sellFeeMaxBps The coin's maximum sell hook fee (launch bound).
/// @param lpFeeMax The coin's maximum dynamic LP fee, in hundredths of a bip (launch bound).
/// @param startTick The pool's starting tick; volatility references are clamped to it.
/// @param refTick Tick at the first swap of `refBlock`.
/// @param prevRefTick Tick at the first swap of the previous active block.
struct PoolState {
bool registered;
uint48 launchBlock;
uint48 refBlock;
uint16 snipeStartBps;
uint8 snipeBlocks;
uint16 buyFeeMaxBps;
uint16 sellFeeMaxBps;
uint24 lpFeeMax;
int24 startTick;
int24 refTick;
int24 prevRefTick;
}
/// @notice The factory registered a freshly launched pool.
event PoolRegistered(PoolId indexed poolId, uint16 snipeStartBps, uint16 snipeBlocks, int24 startTick);
/// @notice A pool's outstanding hook fees were redeemed and sent to the FeeRouter.
event HookFeesCollected(PoolId indexed poolId, uint256 ethAmount);
/// @notice The controller set a pool's dynamic LP fee.
event LpFeeSynced(PoolId indexed poolId, uint24 lpFee);
/// @notice An observer module failed or misbehaved; the swap was unaffected.
event ModuleFailed(PoolId indexed poolId, address indexed module);
error ZeroAddress();
error OnlyFactory();
error OnlyController();
error OnlySelf();
/// @notice The pool key is not the HOOKMIND shape (ETH/coin, dynamic fee, spacing 200, this hook).
error InvalidPoolKey();
error PoolNotInitialized();
error PoolAlreadyRegistered();
error PoolNotRegistered();
/// @notice The bounds handed to `registerPool` exceed the spec's hard ceilings or are inconsistent.
error InvalidPoolConfig();
error LpFeeAboveMax(uint24 lpFee, uint24 lpFeeMax);
/// @notice An ETH-specified swap stopped at its price limit; its fee was charged on the full amount.
error PartialFill();
/// @notice A GUARD module refused this buy.
error SwapBlockedByGuard(address module);
/// @notice Too little gas was left to give an observer its full stipend; retry with more gas.
error InsufficientGasForModules();
/// @notice Raised inside the observer sandbox only; never reaches a swapper.
error ObserverFailed();
/// @notice Only the PoolManager may send ETH to the hook.
error UnexpectedEther();
/// @notice The only address allowed to initialise and register pools.
function factory() external view returns (address);
/// @notice Source of every pool's fee levers and module list.
function controller() external view returns (IHookController);
/// @notice Activates hook state for a freshly initialised pool. Factory only.
/// @param key The coin's pool.
/// @param bounds The coin's launch bounds; the hook keeps its fee maxima and anti-snipe settings.
function registerPool(PoolKey calldata key, Bounds calldata bounds) external;
/// @notice Sets the pool's dynamic LP fee. Controller only; reverts above the coin's `lpFeeMax`.
function syncLpFee(PoolKey calldata key, uint24 lpFee) external;
/// @notice Redeems a pool's accrued hook fees and sends the ETH to the FeeRouter. Permissionless.
function collectFees(PoolId poolId) external returns (uint256 ethAmount);
/// @notice Hook fees accrued for a pool since launch, in wei.
function accruedFees(PoolId poolId) external view returns (uint256);
/// @notice Hook fees already collected for a pool, in wei.
function collectedFees(PoolId poolId) external view returns (uint256);
/// @notice The pool's hook state.
function poolState(PoolId poolId) external view returns (PoolState memory);
/// @notice The pool's tick accumulator, brought up to the current block, and the tick the pool
/// had before any swap of the current block.
/// @dev A time-weighted average tick between two calls is the difference of the two
/// `tickCumulative` values divided by the seconds between them. Neither value can be moved
/// by swaps in the current block. Both are capped at the pool's start tick. A lower tick
/// means a more expensive coin.
/// @param poolId A registered pool.
/// @return tickCumulative Sum of tick x seconds since launch.
/// @return blockTick The pool's tick at the start of this block, capped at its start tick.
function observe(PoolId poolId) external view returns (int128 tickCumulative, int24 blockTick);
/// @notice The total hook fee, in basis points, a swap on this side would pay right now.
function quoteFeeBps(PoolId poolId, bool isBuy) external view returns (uint16);
}
src/interfaces/IMindModule.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {PoolId} from "@uniswap/v4-core/src/types/PoolId.sol";
import {SwapCtx, SwapResult} from "../types/Modules.sol";
/// @notice A hook module. MindHook defines how modules are called; `src/modules` holds the v1 ones.
interface IMindModule {
/// @notice Called when the module is activated for a pool. HookController only.
function onActivate(PoolId poolId, bytes calldata params) external;
/// @notice Called when the module is deactivated for a pool. HookController only.
function onDeactivate(PoolId poolId) external;
/// @notice GUARD modules: called (statically, gas-capped) before a swap; revert to block it.
function guard(PoolId poolId, SwapCtx calldata ctx) external view;
/// @notice OBSERVER modules: called (gas-capped, sandboxed) after a swap; failures are swallowed.
function observe(PoolId poolId, SwapCtx calldata ctx, SwapResult calldata result) external;
}
src/interfaces/IModuleRegistry.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
/// @notice Catalogue of audited hook modules. The controller and vaults use `moduleInfo`; the rest is
/// for the owner (the platform multisig) and for off-chain readers.
interface IModuleRegistry {
/// @notice A registered module.
/// @param module The module contract.
/// @param isGuard True for GUARD modules, false for OBSERVER modules.
/// @param listed False once removed: the module can no longer be activated.
/// @param codehash The module's code hash when it was registered.
/// @param paramSchemaHash Hash of the ABI schema of the module's activation parameters.
/// @param paramBounds The module's parameter bounds, ABI-encoded per its schema, for the policy
/// engine. The module itself enforces them on activation.
struct Entry {
address module;
bool isGuard;
bool listed;
bytes32 codehash;
bytes32 paramSchemaHash;
bytes paramBounds;
}
event ModuleProposed(uint8 indexed moduleId, address indexed module, bool isGuard, bytes32 codehash, uint64 eta);
event ModuleProposalCancelled(uint8 indexed moduleId, address indexed module);
event ModuleAdded(uint8 indexed moduleId, address indexed module, bool isGuard, bytes32 codehash);
event ModuleRemoved(uint8 indexed moduleId, address indexed module);
error ZeroAddress();
error NotAContract(address module);
/// @notice The id is taken; an id is never pointed at another contract, even after removal.
error IdTaken(uint8 moduleId);
error NoProposal(uint8 moduleId);
error ProposalNotReady(uint64 eta);
error ProposalExpired(uint64 expiredAt);
/// @notice The module's code changed between proposal and execution.
error CodehashChanged(uint8 moduleId);
error NotListed(uint8 moduleId);
error RenounceDisabled();
/// @notice Looks up a module by id.
/// @param moduleId Index of the module, matching its bit in a coin's `allowedModulesBitmap`.
/// @return module The module contract, or the zero address if the id was never registered.
/// @return isGuard True for GUARD modules, false for OBSERVER modules.
/// @return listed False once the module has been removed, or if its code no longer matches the
/// hash pinned at registration: it can no longer be activated.
function moduleInfo(uint8 moduleId) external view returns (address module, bool isGuard, bool listed);
}
src/libraries/BoundsLib.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {Bounds, GlobalBounds, VaultCaps} from "../types/Bounds.sol";
/// @notice Validates a coin's launch bounds against the platform's global bounds.
library BoundsLib {
/// @notice Hard ceilings from the spec; no factory can be deployed with looser global bounds.
uint16 internal constant MAX_BPS = 10_000;
uint16 internal constant HARD_MIN_HOOK_FEE_BPS = 50;
uint16 internal constant HARD_MAX_HOOK_FEE_BPS = 300;
uint24 internal constant HARD_MAX_LP_FEE = 10_000;
uint16 internal constant HARD_MAX_FEE_STEP_BPS = 25;
uint32 internal constant HARD_MIN_FEE_INTERVAL = 6 hours;
uint16 internal constant HARD_MIN_CREDITS_SHARE_BPS = 1000;
uint16 internal constant HARD_MAX_CREDITS_SHARE_BPS = 4000;
uint16 internal constant HARD_MAX_SNIPE_START_BPS = 5000;
uint16 internal constant HARD_MAX_SNIPE_BLOCKS = 60;
/// @notice Floors on vault caps: caps can be tightened, but never so far that a treasury is stranded
/// for good. Freezing a vault is what the guardian's pause is for.
uint16 internal constant MIN_CAP_BPS = 10;
uint16 internal constant MIN_SELL_PER_DAY_BPS = 1;
uint16 internal constant MIN_IMPACT_BPS = 10;
uint32 internal constant MAX_COOLDOWN = 7 days;
/// @notice `field` names the first bound that falls outside the global bounds.
error InvalidBounds(bytes32 field);
/// @notice `field` names the first global bound that is inconsistent or looser than the spec allows.
error InvalidGlobalBounds(bytes32 field);
/// @notice Reverts unless `g` is self-consistent and inside the spec's hard ceilings.
function validateGlobal(GlobalBounds memory g) internal pure {
if (
g.hookFeeMinBps < HARD_MIN_HOOK_FEE_BPS || g.hookFeeMinBps > g.hookFeeMaxBps
|| g.hookFeeMaxBps > HARD_MAX_HOOK_FEE_BPS
) {
revert InvalidGlobalBounds("hookFee");
}
if (g.lpFeeMax > HARD_MAX_LP_FEE) revert InvalidGlobalBounds("lpFeeMax");
if (g.maxFeeStepBps > HARD_MAX_FEE_STEP_BPS) revert InvalidGlobalBounds("maxFeeStepBps");
if (g.minFeeInterval < HARD_MIN_FEE_INTERVAL) revert InvalidGlobalBounds("minFeeInterval");
if (
g.creditsShareMinBps < HARD_MIN_CREDITS_SHARE_BPS || g.creditsShareMinBps > g.creditsShareMaxBps
|| g.creditsShareMaxBps > HARD_MAX_CREDITS_SHARE_BPS
) revert InvalidGlobalBounds("creditsShare");
if (g.snipeStartMaxBps > HARD_MAX_SNIPE_START_BPS) revert InvalidGlobalBounds("snipeStartMaxBps");
if (g.snipeBlocksMax > HARD_MAX_SNIPE_BLOCKS) revert InvalidGlobalBounds("snipeBlocksMax");
VaultCaps memory c = g.vaultCaps;
if (
c.perActionBps > MAX_BPS || c.perHourBps > MAX_BPS || c.perDayBps > MAX_BPS || c.sellPerDayBps > MAX_BPS
|| c.maxImpactBps > MAX_BPS
) revert InvalidGlobalBounds("vaultCaps");
}
/// @notice Reverts unless `b` sits entirely inside `g`.
function validate(Bounds memory b, GlobalBounds memory g) internal pure {
_validateFeeRange(b.buyFeeMinBps, b.buyFeeMaxBps, g, "buyFee");
_validateFeeRange(b.sellFeeMinBps, b.sellFeeMaxBps, g, "sellFee");
if (b.lpFeeMax > g.lpFeeMax) revert InvalidBounds("lpFeeMax");
if (b.maxFeeStepBps > g.maxFeeStepBps) revert InvalidBounds("maxFeeStepBps");
if (b.minFeeInterval < g.minFeeInterval) revert InvalidBounds("minFeeInterval");
if (
b.creditsShareMinBps < g.creditsShareMinBps || b.creditsShareMinBps > b.creditsShareMaxBps
|| b.creditsShareMaxBps > g.creditsShareMaxBps
) revert InvalidBounds("creditsShare");
if (b.snipeStartBps > g.snipeStartMaxBps) revert InvalidBounds("snipeStartBps");
if (b.snipeBlocks > g.snipeBlocksMax) revert InvalidBounds("snipeBlocks");
// Anti-snipe is either fully on or fully off: a start fee with no decay window (or the
// reverse) is meaningless and would divide by zero in the hook's linear decay.
if ((b.snipeStartBps == 0) != (b.snipeBlocks == 0)) revert InvalidBounds("snipe");
if (b.allowedModulesBitmap & ~g.allowedModulesBitmap != 0) revert InvalidBounds("allowedModulesBitmap");
_validateVaultCaps(b.vaultCaps, g.vaultCaps);
}
function _validateFeeRange(uint16 minBps, uint16 maxBps, GlobalBounds memory g, bytes32 field) private pure {
if (minBps < g.hookFeeMinBps || minBps > maxBps || maxBps > g.hookFeeMaxBps) revert InvalidBounds(field);
}
/// @dev Each cap must be no looser than `g` and no tighter than the floors above.
function _validateVaultCaps(VaultCaps memory c, VaultCaps memory g) private pure {
if (c.perActionBps > g.perActionBps || c.perActionBps < MIN_CAP_BPS) revert InvalidBounds("perActionBps");
if (c.perHourBps > g.perHourBps || c.perHourBps < MIN_CAP_BPS) revert InvalidBounds("perHourBps");
if (c.perDayBps > g.perDayBps || c.perDayBps < MIN_CAP_BPS) revert InvalidBounds("perDayBps");
if (c.sellPerDayBps > g.sellPerDayBps || c.sellPerDayBps < MIN_SELL_PER_DAY_BPS) {
revert InvalidBounds("sellPerDayBps");
}
if (c.maxImpactBps > g.maxImpactBps || c.maxImpactBps < MIN_IMPACT_BPS) revert InvalidBounds("maxImpactBps");
if (c.cooldown < g.cooldown || c.cooldown > MAX_COOLDOWN) revert InvalidBounds("cooldown");
}
/// @notice Reverts unless `n` is at least as tight as `o` in every lever bound. Used when bounds
/// are tightened after launch: nothing may ever loosen. `vaultCaps` are not compared here
/// (the vault owns them) and the anti-snipe settings must be unchanged (they are immutable).
function requireTighter(Bounds memory n, Bounds memory o) internal pure {
if (n.buyFeeMinBps < o.buyFeeMinBps || n.buyFeeMinBps > n.buyFeeMaxBps || n.buyFeeMaxBps > o.buyFeeMaxBps) {
revert InvalidBounds("buyFee");
}
if (n.sellFeeMinBps < o.sellFeeMinBps || n.sellFeeMinBps > n.sellFeeMaxBps || n.sellFeeMaxBps > o.sellFeeMaxBps)
{
revert InvalidBounds("sellFee");
}
if (n.lpFeeMax > o.lpFeeMax) revert InvalidBounds("lpFeeMax");
if (n.maxFeeStepBps > o.maxFeeStepBps) revert InvalidBounds("maxFeeStepBps");
if (n.minFeeInterval < o.minFeeInterval) revert InvalidBounds("minFeeInterval");
if (
n.creditsShareMinBps < o.creditsShareMinBps || n.creditsShareMinBps > n.creditsShareMaxBps
|| n.creditsShareMaxBps > o.creditsShareMaxBps
) revert InvalidBounds("creditsShare");
if (n.snipeStartBps != o.snipeStartBps || n.snipeBlocks != o.snipeBlocks) revert InvalidBounds("snipe");
if (n.allowedModulesBitmap & ~o.allowedModulesBitmap != 0) revert InvalidBounds("allowedModulesBitmap");
}
/// @notice Reverts unless the vault caps `n` are at least as tight as `o`.
function requireTighterCaps(VaultCaps memory n, VaultCaps memory o) internal pure {
_validateVaultCaps(n, o);
}
}
src/types/Bounds.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
/// @notice Treasury limits of a coin's vault. All `*Bps` values are basis points of the asset balance
/// at window start; `cooldown` is seconds between actions of the same type.
struct VaultCaps {
uint16 perActionBps;
uint16 perHourBps;
uint16 perDayBps;
uint16 sellPerDayBps;
uint16 maxImpactBps;
uint32 cooldown;
}
/// @notice Per-coin bounds chosen by the creator at launch. Fixed for life except tighten-only changes.
/// @dev Hook fees are in basis points; `lpFeeMax` is in v4 LP-fee units (hundredths of a bip).
struct Bounds {
uint16 buyFeeMinBps;
uint16 buyFeeMaxBps;
uint16 sellFeeMinBps;
uint16 sellFeeMaxBps;
uint24 lpFeeMax;
uint16 maxFeeStepBps;
uint32 minFeeInterval;
uint16 creditsShareMinBps;
uint16 creditsShareMaxBps;
uint16 snipeStartBps;
uint16 snipeBlocks;
uint256 allowedModulesBitmap;
VaultCaps vaultCaps;
}
/// @notice Platform-wide limits every coin's `Bounds` must sit inside. Immutable per factory.
/// @dev `vaultCaps` holds maxima for the `*Bps` fields and the minimum for `cooldown`.
struct GlobalBounds {
uint16 hookFeeMinBps;
uint16 hookFeeMaxBps;
uint24 lpFeeMax;
uint16 maxFeeStepBps;
uint32 minFeeInterval;
uint16 creditsShareMinBps;
uint16 creditsShareMaxBps;
uint16 snipeStartMaxBps;
uint16 snipeBlocksMax;
uint256 allowedModulesBitmap;
VaultCaps vaultCaps;
}
src/types/Modules.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
/// @notice A module active on a pool, as reported by the HookController.
/// @param module The module contract (from the audited ModuleRegistry).
/// @param isGuard True for GUARD modules (called before the swap, may block it); false for OBSERVER
/// modules (called after the swap, can never affect it).
struct ModuleRef {
address module;
bool isGuard;
}
/// @notice What a module is told about a swap before it executes.
/// @param trader The real trader when the swap came through HookmindRouter, otherwise the zero address.
/// @param isBuy True when ETH is swapped for the coin.
/// @param exactInput True when the swap specifies its input amount.
/// @param amountSpecified The swap's specified amount (always positive).
/// @param feeBps The total ETH hook fee applied to this swap, in basis points.
struct SwapCtx {
address trader;
bool isBuy;
bool exactInput;
uint256 amountSpecified;
uint16 feeBps;
}
/// @notice What an observer module is told about a swap after it executed.
/// @param ethAmount ETH the trader paid (buy) or received (sell), including/after the hook fee.
/// @param coinAmount Coins the trader received (buy) or paid (sell).
/// @param feeEth The ETH hook fee taken on this swap.
struct SwapResult {
uint256 ethAmount;
uint256 coinAmount;
uint256 feeEth;
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 1000,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"forge-std/=lib/forge-std/src/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"@uniswap/v4-core/=lib/v4-core/",
"v4-core/=lib/v4-core/",
"@uniswap/v4-periphery/=lib/v4-periphery/",
"v4-periphery/=lib/v4-periphery/",
"uniswap-hooks/=lib/uniswap-hooks/",
"permit2/=lib/v4-periphery/lib/permit2/",
"solmate/=lib/v4-core/lib/solmate/",
"@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
"ds-test/=lib/v4-core/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-gas-snapshot/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
"halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"hardhat/=lib/v4-core/node_modules/hardhat/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.