Verified contractExactMIT
BoundedDynamicFeeHookDeployer
Address0x5d85ee5b3c309149b62a61bee7cdf0a4e0dbc980
- Balance
0 ETH
- Transactions
2
- Compiler
solc 0.8.35
- Same code
Only this contract
Details
- Compiler
- solc 0.8.35+commit.47b9dedd
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,487,358
- Creation transaction
- 0x33965fd303…33c7a469d2
BoundedDynamicFeeHook_v1_Remix.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
// =====================================================================================
// Bounded Dynamic Fee Hook v1 — public Uniswap v4 hook with a dynamic LP fee. Works on any EVM chain
// where Uniswap v4 is deployed (the PoolManager address is a constructor argument).
//
// What it does:
// * Anyone can create a pool with this hook and anyone can add/remove liquidity through the
// normal Uniswap interface. The hook does NOT implement any liquidity callbacks.
// * The hook NEVER holds, receives or moves tokens. It has no deposit/withdraw/sweep functions,
// no pause, no token transfers, no external calls except read-only `extsload` on the PoolManager.
// * On every swap (beforeSwap) it overrides the LP fee. Total fee =
// baseFee
// + slope * max(0, |tick - emaTick| - threshold) (price moved away from its own average)
// + lvrSlope * |tick - refTick| only if the swap pushes the pool price TOWARD the reference
// pool (an arbitrage swap) and a reference pool is set
// + firstInBlockFee for the first swap in a block (where arbitrage usually happens)
// capped at maxFee. The fee is ALWAYS inside [0.50%, 3.00%]: baseFee >= MIN_BASE_FEE (0.50%) and
// maxFee <= MAX_FEE_CAP (3.00%), both enforced on-chain.
// NOTE: firstInBlockFee relies on block.number. On chains where block.number does not count the chain's
// own blocks (for example Arbitrum-based chains), keep firstInBlockFee at 0.
// * The owner can only change fee parameters and the reference pool of a pool, inside hard bounds.
// The owner cannot pause swaps, cannot touch liquidity, cannot touch funds.
// * rangeStatus(...) is a read-only helper: tells whether a position is still around the price and
// which range to move it to. Moving a position is done by its owner in the normal Uniswap UI.
//
// ONE hook permission flag in the address (low 14 bits): beforeSwap (1<<7) = 0x0080. There is no afterSwap:
// the moving average is advanced inside beforeSwap. No return-delta flags.
// The address must not start with 0x91 (Uniswap routing rule); the deployer below enforces both.
//
// Pools must be created with fee = 0x800000 (dynamic fee flag).
// The owner is immutable (no ownership transfer): choose it carefully.
//
// Fee units: hundredths of a basis point, 10_000 = 1.00%, 100 = 0.01%, 1 tick of price ~ 0.01% = 100 units.
// =====================================================================================
struct PoolKey {
address currency0;
address currency1;
uint24 fee; // must be 0x800000 (dynamic fee flag) for this hook
int24 tickSpacing;
address hooks; // address of this hook
}
struct SwapParams {
bool zeroForOne;
int256 amountSpecified;
uint160 sqrtPriceLimitX96;
}
interface IPoolManagerReader {
function extsload(bytes32 slot) external view returns (bytes32);
}
contract BoundedDynamicFeeHook {
// ------------------------------------------------------------------ constants
/// beforeSwap (1<<7) only
uint160 public constant REQUIRED_FLAGS = 0x0080;
uint160 internal constant FLAGS_MASK = (1 << 14) - 1;
uint24 public constant DYNAMIC_FEE_FLAG = 0x800000;
uint24 internal constant OVERRIDE_FEE_FLAG = 0x400000;
/// Hard bounds of the LP fee: the base fee can never be below 5_000 (0.50%), the total never above 30_000 (3.00%)
uint24 public constant MIN_BASE_FEE = 5_000;
uint24 public constant MAX_FEE_CAP = 30_000;
uint32 public constant MIN_WINDOW = 60; // seconds
uint32 public constant MAX_WINDOW = 1 days;
/// Fixed-point precision of the stored EMA tick
int256 internal constant PRECISION = 1_000_000;
// Defaults, used until the owner sets parameters for a pool (extras disabled)
uint24 public constant DEFAULT_BASE_FEE = 5_000; // 0.50%
uint24 public constant DEFAULT_MAX_FEE = 30_000; // 3.00%
uint16 public constant DEFAULT_SLOPE = 15; // +0.0015% per tick beyond the threshold
uint16 public constant DEFAULT_THRESHOLD = 20; // ticks
uint32 public constant DEFAULT_WINDOW = 3_600; // seconds
// ------------------------------------------------------------------ storage
address public immutable poolManager;
address public immutable owner;
struct Params {
uint24 baseFee;
uint24 maxFee;
uint16 slope; // fee units per tick beyond `threshold` away from the EMA
uint16 threshold; // ticks
uint32 window; // EMA window, seconds
uint16 lvrSlope; // fee units per tick of deviation from the reference pool (0 = off)
uint24 firstInBlockFee; // extra fee for the first swap in a block (0 = off)
bool set; // ignored on input, set by the contract
}
struct Oracle {
int64 ema; // EMA of the tick, multiplied by PRECISION
uint32 last; // timestamp of the last EMA update
uint32 lastBlock; // block number of the last swap
bool init;
}
struct RangeInfo {
int24 tick; // current pool tick
int24 refTick; // reference pool tick (equals tick if no reference pool)
bool hasRef;
bool inRange; // tick inside [tickLower, tickUpper)
int24 shift; // |tick - middle of the range|
bool due; // shift >= recenterTicks
int24 suggestedLower; // new range, same width, centered on refTick (or tick), aligned to tickSpacing
int24 suggestedUpper;
}
mapping(bytes32 => Params) internal _params;
mapping(bytes32 => Oracle) public oracles;
/// pool id => reference pool id (0 = none)
mapping(bytes32 => bytes32) public venueOf;
// ------------------------------------------------------------------ events / errors
event ParamsSet(bytes32 indexed poolId, Params params);
event VenueSet(bytes32 indexed poolId, bytes32 indexed venueId);
event VenueCleared(bytes32 indexed poolId);
error NotPoolManager();
error NotOwner();
error ZeroAddress();
error WrongHookAddress();
error WrongHook();
error MustUseDynamicFee();
error BadParams();
error BadVenue();
// ------------------------------------------------------------------ setup
constructor(address _poolManager, address _owner) {
if (_poolManager == address(0) || _owner == address(0)) revert ZeroAddress();
uint160 a = uint160(address(this));
// The PoolManager decides which callbacks to call from the address bits; they must be exactly ours (only beforeSwap).
if ((a & FLAGS_MASK) != REQUIRED_FLAGS) revert WrongHookAddress();
// Uniswap routing rule: addresses starting with 0x91 are never auto-routed.
if ((a >> 152) == 0x91) revert WrongHookAddress();
poolManager = _poolManager;
owner = _owner;
}
modifier onlyPoolManager() {
if (msg.sender != poolManager) revert NotPoolManager();
_;
}
modifier onlyOwner() {
if (msg.sender != owner) revert NotOwner();
_;
}
// ------------------------------------------------------------------ hook callback (the only one)
function beforeSwap(address, PoolKey calldata key, SwapParams calldata params, bytes calldata)
external
onlyPoolManager
returns (bytes4, int256, uint24)
{
uint24 fee = _beforeSwap(poolId(key), params.zeroForOne);
return (this.beforeSwap.selector, int256(0), fee | OVERRIDE_FEE_FLAG);
}
function _beforeSwap(bytes32 id, bool zeroForOne) internal returns (uint24) {
(, int24 tick) = _slot0(id);
Oracle storage o = oracles[id];
Params memory p = _getParams(id);
if (!o.init) {
// first swap of the pool: start the average at the current price
o.ema = int64(int256(tick) * PRECISION);
o.init = true;
} else {
// The pool price has been `tick` since the previous swap, so the average moves toward it now.
o.ema = _advance(o.ema, o.last, tick, p.window, uint32(block.timestamp));
}
o.last = uint32(block.timestamp);
bool firstInBlock = o.lastBlock != uint32(block.number);
o.lastBlock = uint32(block.number);
return _fee(id, p, tick, o.ema, zeroForOne, firstInBlock);
}
// ------------------------------------------------------------------ owner: fee parameters and reference pool only
/// Set fee parameters of one pool. Only bounded fee parameters can be changed, nothing else.
function setParams(PoolKey calldata key, Params calldata p) external onlyOwner {
if (key.hooks != address(this)) revert WrongHook();
if (key.fee != DYNAMIC_FEE_FLAG) revert MustUseDynamicFee();
if (p.baseFee < MIN_BASE_FEE || p.baseFee > p.maxFee || p.maxFee > MAX_FEE_CAP) revert BadParams();
if (p.window < MIN_WINDOW || p.window > MAX_WINDOW) revert BadParams();
bytes32 id = poolId(key);
Params memory q = p;
q.set = true;
_params[id] = q;
emit ParamsSet(id, q);
}
/// Set the reference pool: same two tokens, a plain pool without hooks, already initialized.
/// It is only READ (price). Pick the deepest plain pool of the pair.
function setVenue(PoolKey calldata key, PoolKey calldata venueKey) external onlyOwner {
if (key.hooks != address(this)) revert WrongHook();
if (key.fee != DYNAMIC_FEE_FLAG) revert MustUseDynamicFee();
if (key.currency0 != venueKey.currency0 || key.currency1 != venueKey.currency1 || venueKey.hooks != address(0)) {
revert BadVenue();
}
bytes32 id = poolId(key);
bytes32 vid = poolId(venueKey);
if (vid == id) revert BadVenue();
(uint160 sqrtRef,) = _slot0(vid);
if (sqrtRef == 0) revert BadVenue(); // not initialized
venueOf[id] = vid;
emit VenueSet(id, vid);
}
function clearVenue(PoolKey calldata key) external onlyOwner {
bytes32 id = poolId(key);
delete venueOf[id];
emit VenueCleared(id);
}
// ------------------------------------------------------------------ views
function poolId(PoolKey memory key) public pure returns (bytes32) {
return keccak256(abi.encode(key));
}
function getParams(PoolKey calldata key) external view returns (Params memory) {
return _getParams(poolId(key));
}
/// The fee that the next swap in the given direction would pay, with the inputs used to compute it.
function currentFee(PoolKey calldata key, bool zeroForOne)
external
view
returns (uint24 fee, int24 tick, int256 emaTickScaled, bool initialized)
{
bytes32 id = poolId(key);
(, tick) = _slot0(id);
int64 ema;
(ema, initialized) = _emaNow(id, tick);
emaTickScaled = int256(ema);
fee = _fee(id, _getParams(id), tick, ema, zeroForOne, oracles[id].lastBlock != uint32(block.number));
}
/// Helper for LPs and bots: is the position [tickLower, tickUpper) still around the price, and where to move it.
/// The new range has the same width and is centered on the reference pool price (or the pool price).
/// The hook never moves anyone's position; do it yourself in the Uniswap interface.
function rangeStatus(PoolKey calldata key, int24 tickLower, int24 tickUpper, int24 recenterTicks)
external
view
returns (RangeInfo memory r)
{
if (tickUpper <= tickLower || key.tickSpacing <= 0) revert BadParams();
bytes32 id = poolId(key);
(, r.tick) = _slot0(id);
r.refTick = r.tick;
bytes32 vid = venueOf[id];
if (vid != bytes32(0)) {
(uint160 s, int24 t) = _slot0(vid);
if (s != 0) {
r.refTick = t;
r.hasRef = true;
}
}
r.inRange = r.tick >= tickLower && r.tick < tickUpper;
int24 mid = (tickLower + tickUpper) / 2;
r.shift = r.tick > mid ? r.tick - mid : mid - r.tick;
r.due = r.shift >= recenterTicks;
(r.suggestedLower, r.suggestedUpper) = _suggest(key.tickSpacing, r.refTick, tickUpper - tickLower);
}
// ------------------------------------------------------------------ internal
function _getParams(bytes32 id) internal view returns (Params memory p) {
p = _params[id];
if (!p.set) {
p = Params(DEFAULT_BASE_FEE, DEFAULT_MAX_FEE, DEFAULT_SLOPE, DEFAULT_THRESHOLD, DEFAULT_WINDOW, 0, 0, false);
}
}
/// The average as the next swap would see it (advanced to the current time).
function _emaNow(bytes32 id, int24 tick) internal view returns (int64 ema, bool init) {
Oracle memory o = oracles[id];
init = o.init;
ema = init
? _advance(o.ema, o.last, tick, _getParams(id).window, uint32(block.timestamp))
: int64(int256(tick) * PRECISION);
}
/// Move the stored average toward `tick` by (elapsed time / window), capped at one full window.
function _advance(int64 ema, uint32 last, int24 tick, uint32 window, uint32 nowTs) internal pure returns (int64) {
if (nowTs <= last) return ema;
uint256 dt = nowTs - last;
if (dt > window) dt = window;
int256 e = int256(ema);
e += ((int256(tick) * PRECISION - e) * int256(dt)) / int256(uint256(window));
return int64(e);
}
function _fee(bytes32 id, Params memory p, int24 tick, int64 ema, bool zeroForOne, bool firstInBlock)
internal
view
returns (uint24)
{
uint256 fee = uint256(p.baseFee) + _emaFee(p, tick, ema) + _lvrFee(id, p, tick, zeroForOne);
if (firstInBlock) fee += p.firstInBlockFee;
if (fee > p.maxFee) fee = p.maxFee;
return uint24(fee);
}
/// Extra fee when the price is far from its own moving average.
function _emaFee(Params memory p, int24 tick, int64 ema) internal pure returns (uint256) {
int256 diff = int256(tick) * PRECISION - int256(ema);
uint256 dev = diff >= 0 ? uint256(diff) : uint256(-diff); // |tick - ema| * PRECISION
uint256 thr = uint256(p.threshold) * uint256(PRECISION);
if (dev <= thr) return 0;
return ((dev - thr) * uint256(p.slope)) / uint256(PRECISION);
}
/// Extra fee for swaps that push the pool price toward the reference pool (arbitrage direction).
function _lvrFee(bytes32 id, Params memory p, int24 tick, bool zeroForOne) internal view returns (uint256) {
bytes32 vid = venueOf[id];
if (vid == bytes32(0) || p.lvrSlope == 0) return 0;
(uint160 sqrtRef, int24 tRef) = _slot0(vid);
if (sqrtRef == 0) return 0;
int256 d = int256(tick) - int256(tRef);
// pool price above the reference -> arbitrageur sells token0 to us (zeroForOne); below -> buys token0
bool toward = (d > 0 && zeroForOne) || (d < 0 && !zeroForOne);
if (!toward) return 0;
return uint256(d > 0 ? d : -d) * uint256(p.lvrSlope);
}
function _suggest(int24 sp, int24 center, int24 width) internal pure returns (int24 lo, int24 hi) {
int24 half = (width / 2 / sp) * sp;
if (half == 0) half = sp;
int24 c = (center / sp) * sp;
if (center < 0 && center % sp != 0) c -= sp; // floor to the spacing grid
lo = c - half;
hi = c + half;
int24 minT = (int24(-887272) / sp) * sp;
int24 maxT = (int24(887272) / sp) * sp;
if (lo < minT) lo = minT;
if (hi > maxT) hi = maxT;
}
/// slot0 of a pool, read from PoolManager storage (pools mapping is at slot 6 in all v4 deployments).
function _slot0(bytes32 id) internal view returns (uint160 sqrtPriceX96, int24 tick) {
bytes32 slot = keccak256(abi.encodePacked(id, bytes32(uint256(6))));
uint256 data = uint256(IPoolManagerReader(poolManager).extsload(slot));
sqrtPriceX96 = uint160(data);
tick = int24(uint24(data >> 160));
}
}
// =====================================================================================
// Deployer: finds a CREATE2 salt so that the hook address has exactly the required flag bits
// (0x0080 in the low 14 bits) and does not start with 0x91, then deploys the hook.
// `mine` is a free view call; call it repeatedly with a growing startSalt until found = true.
// Deploy this deployer separately on every chain you use (the hook address differs per chain).
// =====================================================================================
contract BoundedDynamicFeeHookDeployer {
uint160 internal constant FLAGS_MASK = (1 << 14) - 1;
uint160 internal constant WANT = 0x0080;
event HookDeployed(address indexed hook, address indexed owner, address indexed poolManager);
function mine(address poolManager, address hookOwner, uint256 startSalt, uint256 attempts)
external
view
returns (bool found, bytes32 salt, address hookAddress)
{
bytes32 initCodeHash =
keccak256(abi.encodePacked(type(BoundedDynamicFeeHook).creationCode, abi.encode(poolManager, hookOwner)));
unchecked {
for (uint256 i = 0; i < attempts; i++) {
bytes32 s = bytes32(startSalt + i);
uint160 a = uint160(
uint256(keccak256(abi.encodePacked(bytes1(0xff), address(this), s, initCodeHash)))
);
if ((a & FLAGS_MASK) == WANT && (a >> 152) != 0x91) {
return (true, s, address(a));
}
}
}
return (false, bytes32(0), address(0));
}
function deploy(address poolManager, address hookOwner, bytes32 salt) external returns (address hook) {
hook = address(new BoundedDynamicFeeHook{salt: salt}(poolManager, hookOwner));
emit HookDeployed(hook, hookOwner, poolManager);
}
}
Compiler settingsShow
{
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": []
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.