Verified contractPartialBUSL-1.1
AegisHook
Address0x8f29bd5c8429730fa4c46e6295c4e679ededd0cc
- 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, 100 runs
- EVM version
- cancun
- Via IR
- yes
- License
- BUSL-1.1
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,144,768
- Creation transaction
- 0xfb9a0c609b…438bae4068
71 files
- contracts/AegisHook.solmain22.94 KB
- contracts/interfaces/IAegisDependencies.sol2.95 KB
- contracts/interfaces/IAegisEngine.sol19.79 KB
- contracts/interfaces/IAegisHook.sol5.35 KB
- contracts/interfaces/IHookAuthorizable.sol161 B
- contracts/interfaces/ILimitOrderManager.sol10.23 KB
- contracts/interfaces/IOracleManager.sol5.97 KB
- contracts/interfaces/IV4PositionManager.sol863 B
- contracts/interfaces/dfm/IDynamicFeeManager.sol3.88 KB
- contracts/libraries/ae/Constants.sol3.27 KB
- contracts/libraries/ae/math/LUnitMath.sol6.67 KB
- contracts/libraries/ae/math/SqrtMath.sol1.46 KB
- contracts/libraries/dfm/Errors.sol534 B
- contracts/libraries/dfm/PrecisionConstants.sol226 B
- contracts/libraries/dfm/RuntimeStructs.sol3.13 KB
- contracts/libraries/hook/CurrentSwapHookFeeCache.sol3.38 KB
- contracts/libraries/hook/HookRuntime.sol1.54 KB
- contracts/libraries/hook/PackedRuntime.sol2.87 KB
- contracts/types/AegisStructs.sol348 B
- dependencies/@openzeppelin-contracts-5.1.0/access/Ownable.sol3.1 KB
- dependencies/@openzeppelin-contracts-5.1.0/token/ERC20/IERC20.sol2.78 KB
- dependencies/@openzeppelin-contracts-5.1.0/token/ERC721/IERC721Receiver.sol997 B
- dependencies/@openzeppelin-contracts-5.1.0/utils/Context.sol963 B
- dependencies/@openzeppelin-contracts-5.1.0/utils/Pausable.sol2.83 KB
- dependencies/@openzeppelin-contracts-5.1.0/utils/math/SafeCast.sol34.94 KB
- dependencies/v4-core-main/lib/solmate/src/utils/FixedPointMathLib.sol10.05 KB
- dependencies/v4-core-main/src/interfaces/IExtsload.sol1.02 KB
- dependencies/v4-core-main/src/interfaces/IExttload.sol699 B
- dependencies/v4-core-main/src/interfaces/IHooks.sol8.23 KB
- dependencies/v4-core-main/src/interfaces/IPoolManager.sol12.84 KB
- dependencies/v4-core-main/src/interfaces/IProtocolFees.sol2.49 KB
- dependencies/v4-core-main/src/interfaces/external/IERC20Minimal.sol3.04 KB
- dependencies/v4-core-main/src/interfaces/external/IERC6909Claims.sol3.16 KB
- dependencies/v4-core-main/src/libraries/BitMath.sol2.61 KB
- dependencies/v4-core-main/src/libraries/CustomRevert.sol5.17 KB
- dependencies/v4-core-main/src/libraries/FixedPoint128.sol297 B
- dependencies/v4-core-main/src/libraries/FixedPoint96.sol366 B
- dependencies/v4-core-main/src/libraries/FullMath.sol5.46 KB
- dependencies/v4-core-main/src/libraries/Hooks.sol16.51 KB
- dependencies/v4-core-main/src/libraries/LPFeeLibrary.sol3.6 KB
- dependencies/v4-core-main/src/libraries/LiquidityMath.sol742 B
- dependencies/v4-core-main/src/libraries/ParseBytes.sol1.2 KB
- dependencies/v4-core-main/src/libraries/Position.sol4.81 KB
- dependencies/v4-core-main/src/libraries/SafeCast.sol2.27 KB
- dependencies/v4-core-main/src/libraries/SqrtPriceMath.sol14.08 KB
- dependencies/v4-core-main/src/libraries/StateLibrary.sol16.03 KB
- dependencies/v4-core-main/src/libraries/TickMath.sol12.38 KB
- dependencies/v4-core-main/src/libraries/UnsafeMath.sol1.17 KB
- dependencies/v4-core-main/src/types/BalanceDelta.sol2.34 KB
- dependencies/v4-core-main/src/types/BeforeSwapDelta.sol1.47 KB
- dependencies/v4-core-main/src/types/Currency.sol5.46 KB
- dependencies/v4-core-main/src/types/PoolId.sol539 B
- dependencies/v4-core-main/src/types/PoolKey.sol805 B
- dependencies/v4-core-main/src/types/PoolOperation.sol907 B
- dependencies/v4-periphery-main/lib/permit2/src/interfaces/IAllowanceTransfer.sol7.7 KB
- dependencies/v4-periphery-main/lib/permit2/src/interfaces/IEIP712.sol144 B
- dependencies/v4-periphery-main/src/base/ImmutableState.sol818 B
- dependencies/v4-periphery-main/src/interfaces/IEIP712_v4.sol328 B
- dependencies/v4-periphery-main/src/interfaces/IERC721Permit_v4.sol2.14 KB
- dependencies/v4-periphery-main/src/interfaces/IImmutableState.sol365 B
- dependencies/v4-periphery-main/src/interfaces/IMulticall_v4.sol774 B
- dependencies/v4-periphery-main/src/interfaces/INotifier.sol3.2 KB
- dependencies/v4-periphery-main/src/interfaces/IPermit2Forwarder.sol1.44 KB
- dependencies/v4-periphery-main/src/interfaces/IPoolInitializer_v4.sol782 B
- dependencies/v4-periphery-main/src/interfaces/IPositionManager.sol3.5 KB
- dependencies/v4-periphery-main/src/interfaces/ISubscriber.sol2.27 KB
- dependencies/v4-periphery-main/src/interfaces/IUnorderedNonce.sol799 B
- dependencies/v4-periphery-main/src/interfaces/external/IWETH9.sol364 B
- dependencies/v4-periphery-main/src/libraries/LiquidityAmounts.sol3.77 KB
- dependencies/v4-periphery-main/src/libraries/PositionInfoLibrary.sol3.95 KB
- dependencies/v4-periphery-main/src/utils/BaseHook.sol7.1 KB
contracts/AegisHook.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
// - - - OZ Imports - - -
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { Pausable } from "@openzeppelin/contracts/utils/Pausable.sol";
// - - - Uniswap Imports - - -
import { Hooks } from "@uniswap/v4-core/src/libraries/Hooks.sol";
import { LPFeeLibrary } from "@uniswap/v4-core/src/libraries/LPFeeLibrary.sol";
import { StateLibrary } from "@uniswap/v4-core/src/libraries/StateLibrary.sol";
import { FullMath } from "@uniswap/v4-core/src/libraries/FullMath.sol";
import { Currency, CurrencyLibrary } from "@uniswap/v4-core/src/types/Currency.sol";
import { PoolKey } from "@uniswap/v4-core/src/types/PoolKey.sol";
import { PoolId, PoolIdLibrary } from "@uniswap/v4-core/src/types/PoolId.sol";
import { toBalanceDelta, BalanceDelta, BalanceDeltaLibrary } from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import {
BeforeSwapDelta,
BeforeSwapDeltaLibrary,
toBeforeSwapDelta
} from "@uniswap/v4-core/src/types/BeforeSwapDelta.sol";
import { SwapParams } from "@uniswap/v4-core/src/types/PoolOperation.sol";
import { IPoolManager } from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import { LiquidityAmounts } from "@uniswap/v4-periphery/src/libraries/LiquidityAmounts.sol";
import { BaseHook } from "@uniswap/v4-periphery/src/utils/BaseHook.sol";
// - - - local imports - - -
import { Errors } from "./libraries/dfm/Errors.sol";
import { PPM_SCALE } from "./libraries/dfm/PrecisionConstants.sol";
import { LUnitMath } from "./libraries/ae/math/LUnitMath.sol";
import { HookRuntime } from "./libraries/hook/HookRuntime.sol";
import { CurrentSwapHookFeeCache } from "./libraries/hook/CurrentSwapHookFeeCache.sol";
import { ENGINE_MAX_SWAP_FEE_PIPS } from "./libraries/ae/Constants.sol";
import { IAegisHook } from "./interfaces/IAegisHook.sol";
import { IAegisDependencies } from "./interfaces/IAegisDependencies.sol";
import { IDynamicFeeManager } from "./interfaces/dfm/IDynamicFeeManager.sol";
import { IOracleManager } from "./interfaces/IOracleManager.sol";
import { IAegisEngine } from "./interfaces/IAegisEngine.sol";
import { ILimitOrderManager } from "./interfaces/ILimitOrderManager.sol";
/// @title AegisHook
/// @notice Uniswap V4 hook implementing dynamic fees, oracle integration, and automatic fee reinvestment
/// @dev DEFENSIVE DESIGN: All non-initialize OracleManager and DynamicFeeManager calls are wrapped in try-catch
/// to prevent bricking liquidity. The reinvest path's `AEGIS_ENGINE.modifyLiquidity` call is also wrapped
/// because AE market initialization is decoupled from `_afterInitialize` — there is now a window where
/// hook fees can accumulate before the AE market exists; an unwrapped call would revert and brick swaps.
/// PoolManager and LimitOrderManager calls are NOT wrapped as they are expected to be robust and we
/// want to enforce guarantees on those.
contract AegisHook is Ownable, Pausable, BaseHook, IAegisHook {
using StateLibrary for IPoolManager;
using PoolIdLibrary for PoolKey;
using PoolIdLibrary for PoolId;
using CurrencyLibrary for Currency;
using BalanceDeltaLibrary for BalanceDelta;
uint128 public constant MIN_REINVEST_LIQUIDITY = 1_000;
uint32 public constant REINVEST_COOLDOWN = 3600; // 1hr
// NB: 3600 allows for up to a 1hr TWAP in the worst case of 1 second blocks with observations every block
uint16 public constant TARGET_CARDINALITY = 3600;
uint16 public constant CARDINALITY_INCREMENT = 5;
struct PoolConfig {
uint24 hookFeePpm;
uint32 lastReinvest;
// Set to true once `cardinalityNext` has reached `TARGET_CARDINALITY`. Caches the result so
// the steady-state swap path can skip the external `ORACLE_MANAGER.states` call. Closes the
// gas regression introduced when the `block.number % 10` gating was dropped in favor of
// eager per-swap cardinality growth.
bool oracleGrowthComplete;
}
IOracleManager public immutable override ORACLE_MANAGER;
IDynamicFeeManager public immutable override DYNAMIC_FEE_MANAGER;
IAegisEngine public immutable override AEGIS_ENGINE;
ILimitOrderManager public immutable override LIMIT_ORDER_MANAGER;
mapping(PoolId => BalanceDelta) private _pendingFees;
mapping(PoolId => PoolConfig) private _poolConfigs;
constructor(
IAegisDependencies deps,
IAegisEngine aegisEngine,
IOracleManager oracleManager,
IDynamicFeeManager dynamicFeeManager,
ILimitOrderManager limitOrderManager
) BaseHook(deps.poolManager()) Ownable(deps.AEGIS_INITIALIZER()) {
require(deps.initialized(), "AegisDependencies not initialized");
_checkNonZeroAddress(address(aegisEngine));
_checkNonZeroAddress(address(oracleManager));
_checkNonZeroAddress(address(dynamicFeeManager));
_checkNonZeroAddress(address(limitOrderManager));
AEGIS_ENGINE = aegisEngine;
ORACLE_MANAGER = oracleManager;
DYNAMIC_FEE_MANAGER = dynamicFeeManager;
LIMIT_ORDER_MANAGER = limitOrderManager;
}
/// @notice Accept native ETH sent by PoolManager during hook reinvestment settlement.
receive() external payable {
if (msg.sender != address(poolManager)) {
revert Errors.UnauthorizedCaller(msg.sender);
}
}
// - - - Views - - -
/// @inheritdoc BaseHook
function getHookPermissions() public pure virtual override returns (Hooks.Permissions memory) {
return Hooks.Permissions({
beforeInitialize: false,
afterInitialize: true,
beforeAddLiquidity: false,
afterAddLiquidity: false,
beforeRemoveLiquidity: false,
afterRemoveLiquidity: false,
beforeSwap: true,
afterSwap: true,
beforeDonate: false,
afterDonate: false,
beforeSwapReturnDelta: true,
afterSwapReturnDelta: true,
afterAddLiquidityReturnDelta: false,
afterRemoveLiquidityReturnDelta: false
});
}
/// @inheritdoc IAegisHook
function pendingFees(PoolId id) public view override returns (uint128 amount0, uint128 amount1) {
BalanceDelta pending = _pendingFees[id];
(amount0, amount1) = (uint128(pending.amount0()), uint128(pending.amount1()));
}
/// @inheritdoc IAegisHook
function hookFeePpm(PoolId poolId) public view override returns (uint24) {
return _poolConfigs[poolId].hookFeePpm;
}
// - - - Admin Setters - - -
/// @inheritdoc IAegisHook
function pause(bool doPause) external override onlyOwner {
if (doPause) {
_pause();
} else {
_unpause();
}
}
/// @inheritdoc IAegisHook
function setHookFeePpm(PoolId poolId, uint24 feePpm) external override onlyOwner {
if (feePpm > PPM_SCALE) revert Errors.ParameterOutOfRange(feePpm, 0, PPM_SCALE);
_poolConfigs[poolId].hookFeePpm = feePpm;
emit HookFeePpmUpdated(poolId, feePpm);
}
/// @inheritdoc IAegisHook
function withdrawMarketShares(PoolId poolId, address to, uint256 amount) external override onlyOwner {
_checkNonZeroAddress(to);
if (amount > 0) {
uint256 tokenId = uint256(PoolId.unwrap(poolId));
AEGIS_ENGINE.transfer(to, tokenId, amount);
emit SharesWithdrawn(poolId, to, amount);
}
}
// - - - Hook Callbacks - - -
/// @inheritdoc BaseHook
function _beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata)
internal
virtual
override
returns (bytes4, BeforeSwapDelta hookSwapDelta, uint24)
{
PoolId poolId = key.toId();
// Eagerly grow oracle cardinality on every swap until TARGET_CARDINALITY is reached.
// A previous design only attempted growth on `block.number % 10 == 0`, which let an attacker
// swap on non-tenth blocks to overwrite the only stored observation (cardinality stayed at
// 1). Eager growth ensures the very first attacker swap also bumps `cardinalityNext`, so the
// subsequent `_afterSwap` write preserves the genesis observation. Steady-state cost is
// preserved by caching `oracleGrowthComplete` once the target is reached.
if (!_poolConfigs[poolId].oracleGrowthComplete) {
try ORACLE_MANAGER.states(poolId) returns (uint16, uint16, uint16 cardinalityNext) {
if (cardinalityNext < TARGET_CARDINALITY) {
try ORACLE_MANAGER.increaseCardinalityNext(poolId, cardinalityNext + CARDINALITY_INCREMENT) { }
catch (bytes memory errorData) {
emit ExternalCallFailed(poolId, address(ORACLE_MANAGER), "ICN", errorData);
}
} else {
_poolConfigs[poolId].oracleGrowthComplete = true;
}
} catch (bytes memory errorData) {
emit ExternalCallFailed(poolId, address(ORACLE_MANAGER), "states", errorData);
}
}
(, int24 preSwapTick,,) = poolManager.getSlot0(poolId);
uint24 activeFee;
try DYNAMIC_FEE_MANAGER.prepareSwap(key, preSwapTick) returns (uint24 fee) {
activeFee = fee;
} catch (bytes memory errorData) {
emit ExternalCallFailed(poolId, address(DYNAMIC_FEE_MANAGER), "PS", errorData);
}
if (activeFee == 0) revert Errors.InvalidFee(); // NB: invariant; should never happen
// Cap the v4 pool swap fee for AegisEngine-initiated swaps to favor micro-liquidation
// economics. The cap applies to `activeFee`, which is the scale factor used to compute
// both the pool LP fee AND the hook fee — but the hook fee is still charged on top of the
// capped pool fee, not absorbed into it. With `hookFeePpm = 100%`, the engine's all-in
// fee on a swap is approximately twice `ENGINE_MAX_SWAP_FEE_PIPS` (i.e. ≈ 0.2%), well
// within the 2% `MICRO_LIQ_CONSERVATIVE_HAIRCUT_PIPS` budget. Stacking is intentional.
if (sender == address(AEGIS_ENGINE) && activeFee > ENGINE_MAX_SWAP_FEE_PIPS) {
activeFee = ENGINE_MAX_SWAP_FEE_PIPS;
}
HookRuntime.Runtime memory runtime =
HookRuntime.Runtime({ dynamicFee: activeFee, preSwapTick: preSwapTick, sender: sender });
HookRuntime.store(poolId, runtime);
// V4 hook-fee accounting constraint: `BeforeSwapDelta` only adjusts the SPECIFIED currency,
// and `afterSwap`'s int128 return only adjusts the UNSPECIFIED currency. Since we always
// want the hook fee charged in the INPUT currency:
// - exactOut: input is unspecified → compute in afterSwap (actual input known by then).
// - exactIn: input is specified → compute in beforeSwap from the requested input.
// See https://github.com/Uniswap/docs/issues/967.
if (params.amountSpecified < 0) {
// i.e. exactIn swap
hookSwapDelta = _beforeSwapExactIn(poolId, key, params, runtime);
}
return (BaseHook.beforeSwap.selector, hookSwapDelta, (activeFee | LPFeeLibrary.OVERRIDE_FEE_FLAG));
}
/// @inheritdoc BaseHook
function _afterSwap(address, PoolKey calldata key, SwapParams calldata params, BalanceDelta delta, bytes calldata)
internal
virtual
override
returns (bytes4, int128)
{
PoolId poolId = key.toId();
HookRuntime.Runtime memory runtime = HookRuntime.load(poolId);
(, int24 postSwapTick,,) = poolManager.getSlot0(poolId);
if (postSwapTick != runtime.preSwapTick) {
try ORACLE_MANAGER.afterSwap(key, runtime.preSwapTick) { }
catch (bytes memory errorData) {
emit ExternalCallFailed(poolId, address(ORACLE_MANAGER), "AS", errorData);
}
}
try DYNAMIC_FEE_MANAGER.finalizeSwap(key, runtime.preSwapTick, postSwapTick) { }
catch (bytes memory errorData) {
emit ExternalCallFailed(poolId, address(DYNAMIC_FEE_MANAGER), "FS", errorData);
}
LIMIT_ORDER_MANAGER.onAfterSwap(key, params);
int128 hookFeeReturned;
if (params.amountSpecified > 0) {
// i.e. exactOut swap
bool zeroIsInput = params.zeroForOne;
int128 inputAmount = zeroIsInput ? delta.amount0() : delta.amount1();
hookFeeReturned = _afterSwapExactOut(poolId, key, zeroIsInput, inputAmount, runtime);
}
_tryReinvest(poolId, key);
// Flush the current swap's hook fee — held in `CurrentSwapHookFeeCache` by `_chargeHookFee`
// — into `_pendingFees` for the next reinvest cycle. Done unconditionally so all
// `_tryReinvest` early-return paths (paused / cooldown / threshold / failed engine call)
// still result in the fee accruing. Skips the SSTORE if the cache was empty.
BalanceDelta currentSwapFee = CurrentSwapHookFeeCache.consume(poolId);
if (BalanceDelta.unwrap(currentSwapFee) != 0) {
_pendingFees[poolId] = _pendingFees[poolId] + currentSwapFee;
}
return (BaseHook.afterSwap.selector, hookFeeReturned);
}
/// @inheritdoc BaseHook
/// @dev AE market initialization is intentionally NOT performed here. The AE market must
/// remain uninitialized until OracleManager can durably serve consult(TWAP_WINDOW_SECONDS);
/// anyone may call AegisEngine.initialize(key) once the oracle is warm. Until then
/// debt-bearing flows are blocked at the engine boundary, ensuring debt cannot exist
/// in a market that lacks the price-history liquidation needs.
function _afterInitialize(address, PoolKey calldata key, uint160, int24 tick)
internal
virtual
override
returns (bytes4)
{
if (!LPFeeLibrary.isDynamicFee(key.fee)) revert Errors.InvalidFee();
ORACLE_MANAGER.recordAfterInitialize(key, tick);
DYNAMIC_FEE_MANAGER.initialize(key, tick);
LIMIT_ORDER_MANAGER.onAfterInitialize(key, tick);
return BaseHook.afterInitialize.selector;
}
// - - - Internal helpers - - -
function _beforeSwapExactIn(
PoolId poolId,
PoolKey calldata key,
SwapParams calldata params,
HookRuntime.Runtime memory runtime
) private returns (BeforeSwapDelta hookSwapDelta) {
uint128 hookFeeAmount = _computeHookFeeFromAmountIn(poolId, uint256(-params.amountSpecified), runtime.dynamicFee);
if (hookFeeAmount == 0) return BeforeSwapDeltaLibrary.ZERO_DELTA;
(uint128 fee0, uint128 fee1) = _chargeHookFee(poolId, key, params.zeroForOne, hookFeeAmount);
emit HookFee(poolId, runtime.sender, fee0, fee1);
// forge-lint: disable-next-line(unsafe-typecast) -- hook fees are capped at type(int128).max
int128 deltaSpecifiedInt = int128(hookFeeAmount);
hookSwapDelta = toBeforeSwapDelta(deltaSpecifiedInt, 0);
}
function _afterSwapExactOut(
PoolId poolId,
PoolKey calldata key,
bool zeroIsInput,
int128 inputAmount,
HookRuntime.Runtime memory runtime
) private returns (int128 hookFeeReturned) {
// forge-lint: disable-next-line(unsafe-typecast) -- input amount is negative by definition
uint128 hookFeeAmount = _computeHookFeeFromAmountIn(poolId, uint256(-int256(inputAmount)), runtime.dynamicFee);
(uint128 fee0, uint128 fee1) = _chargeHookFee(poolId, key, zeroIsInput, hookFeeAmount);
emit HookFee(poolId, runtime.sender, fee0, fee1);
// forge-lint: disable-next-line(unsafe-typecast) -- hook fees are capped at type(int128).max
hookFeeReturned = int128(hookFeeAmount);
}
// we cut the hook fee out of the specified input amount
function _computeHookFeeFromAmountIn(PoolId poolId, uint256 amountIn, uint24 dynamicFee)
private
view
returns (uint128 hookFeeAmount)
{
uint256 hookFeeCutPpm = _poolConfigs[poolId].hookFeePpm;
if (hookFeeCutPpm == 0) return 0; // save some gas
// TOB-AEGIS-11: Round down intermediate to avoid double round-up bias (max 1 wei vs 2 wei).
uint256 swapFeeAmount = FullMath.mulDiv(amountIn, dynamicFee, PPM_SCALE);
uint256 hookFeeAmountRaw = FullMath.mulDivRoundingUp(swapFeeAmount, hookFeeCutPpm, PPM_SCALE);
// forge-lint: disable-start(unsafe-typecast) -- cast to uint128 is safe by construction
hookFeeAmount =
(hookFeeAmountRaw > uint256(int256(type(int128).max))) ? uint128(type(int128).max) : uint128(hookFeeAmountRaw);
// forge-lint: disable-end
}
/// @dev Charge the hook fee for the current swap. The 6909 claim is minted immediately
/// (recording the fee against the swapper's eventual settlement) and `HookFee` is
/// emitted, but the `_pendingFees` update is DEFERRED via `CurrentSwapHookFeeCache`.
/// `_tryReinvest` therefore reads `_pendingFees` without the current swap's
/// contribution; the cached delta is folded back into `_pendingFees` at end of
/// `_afterSwap` (see `CurrentSwapHookFeeCache.consume` call there).
function _chargeHookFee(PoolId poolId, PoolKey calldata key, bool zeroIsInput, uint128 amount)
private
returns (uint128 fee0, uint128 fee1)
{
Currency feeCurrency = zeroIsInput ? key.currency0 : key.currency1;
poolManager.mint(address(this), feeCurrency.toId(), amount);
BalanceDelta newHookFees;
if (zeroIsInput) {
newHookFees = toBalanceDelta(int128(amount), 0);
fee0 = amount;
} else {
newHookFees = toBalanceDelta(0, int128(amount));
fee1 = amount;
}
CurrentSwapHookFeeCache.add(poolId, newHookFees);
}
/// @dev Reinvest pending fees into a full-range LP position via the engine.
///
/// Per-swap deferral (see `CurrentSwapHookFeeCache` and `_chargeHookFee`) is the
/// strict invariant against spending the IN-FLIGHT swap's own fee: that fee is held
/// in transient storage and not folded into `_pendingFees` until end of `_afterSwap`,
/// so the read inside this function never includes the currently-running swap's
/// contribution.
///
/// The cooldown gate prevents only REPEATED reinvest attempts within the same
/// `block.timestamp` — once a reinvest fires (success or caught-failure branch),
/// `lastReinvest = block.timestamp` blocks all subsequent attempts until the next
/// block.
///
/// The PM-balance guard (`_canPoolManagerPayReinvest`) prevents a residual DoS: if
/// PM's underlying ERC20 reserves for either currency are LESS than that currency's
/// `_pendingFees` amount, the eventual `take` inside `_payEngineDelta` would revert
/// with an underlying ERC20 insufficient-balance error. That revert lands AFTER the
/// engine call returned (outside the catch's reachable scope), so it would bubble
/// up and brick the swap. The guard skips reinvest silently in that case (no
/// `lastReinvest` bump) so the swap completes and a subsequent swap retries reinvest
/// once PM's reserves recover. Affected scenarios include sophisticated unlockers
/// that thin PM via `poolManager.take` for internal-balance accounting before
/// triggering an Aegis swap mid-flow, and very-low-reserve pools.
function _tryReinvest(PoolId poolId, PoolKey calldata key) private {
if (paused()) return;
PoolConfig storage config = _poolConfigs[poolId];
// Enforce cooldown between reinvestments
if (block.timestamp < config.lastReinvest + REINVEST_COOLDOWN) return;
BalanceDelta pending = _pendingFees[poolId];
(uint256 amount0, uint256 amount1) = pendingFees(poolId);
if (amount0 < MIN_REINVEST_LIQUIDITY || amount1 < MIN_REINVEST_LIQUIDITY) return;
// PM-balance guard: see this function's NatSpec for why. Conservative — uses pending
// amounts as the upper bound on what `_payEngineDelta` will eventually `take`. The
// engine consumes at most `pending` per side (full-range LP at any price), so
// `pmBal >= pending` is sufficient.
if (!_canPoolManagerPayReinvest(key, amount0, amount1)) return;
(uint160 sqrtPriceX96,,,) = poolManager.getSlot0(poolId);
(uint160 minSqrtPriceX96, uint160 maxSqrtPriceX96) = LUnitMath.getActualFullRangePrices(key.tickSpacing);
uint128 liquidityMintable =
LiquidityAmounts.getLiquidityForAmounts(sqrtPriceX96, minSqrtPriceX96, maxSqrtPriceX96, amount0, amount1);
if (liquidityMintable < MIN_REINVEST_LIQUIDITY) return;
// Wrapped in try/catch following this contract's defensive-design pattern: AE market init
// is decoupled from `_afterInitialize`, so there's a window where the AE market isn't yet
// initialized while swaps can still accumulate hook fees. Without this wrap, the engine's
// `_syncMarket → checkMarketInitializedInEngine` revert would propagate up through
// `_afterSwap` and brick all swaps until init. On failure we also bump `lastReinvest` so
// subsequent swaps don't repeatedly retry within the cooldown window (would otherwise emit
// `ExternalCallFailed` on every swap during pre-init). The next reinvest attempt happens
// at most `REINVEST_COOLDOWN` after the most recent failure; pending fees stay accumulated
// and are reinvested then.
try AEGIS_ENGINE.modifyLiquidity(poolId, int128(liquidityMintable), address(this)) returns (
uint256, BalanceDelta modifyFullRangeDelta
) {
_pendingFees[poolId] = pending + modifyFullRangeDelta;
config.lastReinvest = uint32(block.timestamp);
_payEngineDelta(key.currency0, modifyFullRangeDelta.amount0());
_payEngineDelta(key.currency1, modifyFullRangeDelta.amount1());
emit HookFeeReinvested(
poolId, address(0), uint128(-modifyFullRangeDelta.amount0()), uint128(-modifyFullRangeDelta.amount1())
);
} catch (bytes memory errorData) {
config.lastReinvest = uint32(block.timestamp);
emit ExternalCallFailed(poolId, address(AEGIS_ENGINE), "ML", errorData);
}
}
/// @dev See `_tryReinvest` NatSpec for rationale. Uses `pending` amounts as a conservative
/// upper bound on the `take` amounts that `_payEngineDelta` will perform.
function _canPoolManagerPayReinvest(PoolKey calldata key, uint256 amount0, uint256 amount1)
private
view
returns (bool)
{
return key.currency0.balanceOf(address(poolManager)) >= amount0
&& key.currency1.balanceOf(address(poolManager)) >= amount1;
}
function _payEngineDelta(Currency currency, int128 delta) private {
if (delta < 0) {
// we only need to pay the AegisEngine on a negative delta(i.e. AegisEngine owes PoolManager)
uint256 amountToPay = uint128(-delta);
// we've got to do this dance as we can't burn ERC6909 with a designated recipient of the positive transient delta
// See: https://github.com/Uniswap/v4-core/issues/985
poolManager.burn(address(this), currency.toId(), amountToPay);
poolManager.take(currency, address(this), amountToPay);
poolManager.sync(currency);
if (currency.isAddressZero()) {
poolManager.settleFor{ value: amountToPay }(address(AEGIS_ENGINE));
} else {
// forge-lint: disable-next-line(erc20-unchecked-transfer) -- handled safely in CurrencyLibrary
currency.transfer(address(poolManager), amountToPay);
poolManager.settleFor(address(AEGIS_ENGINE));
}
}
}
// - - - Utils Helpers - - -
function _checkNonZeroAddress(address addressToCheck) private pure {
if (addressToCheck == address(0)) revert Errors.ZeroAddress();
}
}
contracts/interfaces/IAegisDependencies.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
import { IPoolManager } from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import { IPositionManager } from "@uniswap/v4-periphery/src/interfaces/IPositionManager.sol";
import { IAllowanceTransfer } from "permit2/src/interfaces/IAllowanceTransfer.sol";
import { IWETH9 } from "@uniswap/v4-periphery/src/interfaces/external/IWETH9.sol";
/// @title Aegis Dependencies Interface
/// @notice Stores chain-specific external dependencies for deterministic cross-chain deployment
/// @dev Deployed via CREATE2 for identical address across chains.
/// Anyone can deploy contracts, but AEGIS_INITIALIZER (EOA or GnosisSafe at same address
/// across chains) must call initialize() and becomes owner of all Aegis contracts.
interface IAegisDependencies {
/// @notice Thrown when caller is not the authorized initializer
error UnauthorizedInitializer();
/// @notice Thrown when contract is already initialized
error AlreadyInitialized();
/// @notice Thrown when a zero address is provided
error ZeroAddress();
/// @notice Emitted when dependencies are initialized
/// @param poolManager The Uniswap V4 PoolManager address
/// @param positionManager The Uniswap V4 PositionManager address
/// @param permit2 The Permit2 contract address
/// @param weth9 The WETH9 contract address
event Initialized(address indexed poolManager, address indexed positionManager, address permit2, address weth9);
/// @notice Returns the privileged address that can call initialize() and owns all Aegis contracts
/// @dev Can be an EOA or a GnosisSafe deployed at the same address across chains.
/// This address is hardcoded to enable deterministic CREATE2 deployment by anyone.
// forge-lint: disable-next-line(mixed-case-function)
function AEGIS_INITIALIZER() external pure returns (address);
/// @notice Returns whether the contract has been initialized
function initialized() external view returns (bool);
/// @notice Returns the Uniswap V4 PoolManager
function poolManager() external view returns (IPoolManager);
/// @notice Returns the Uniswap V4 PositionManager
function positionManager() external view returns (IPositionManager);
/// @notice Returns the Permit2 contract
function permit2() external view returns (IAllowanceTransfer);
/// @notice Returns the WETH9 contract
function weth9() external view returns (IWETH9);
/// @notice Initialize with chain-specific addresses (one-time only)
/// @dev Can only be called by AEGIS_INITIALIZER and only once
/// @param _poolManager Uniswap V4 PoolManager address
/// @param _positionManager Uniswap V4 PositionManager address
/// @param _permit2 Permit2 contract address
/// @param _weth9 WETH9 contract address
function initialize(
IPoolManager _poolManager,
IPositionManager _positionManager,
IAllowanceTransfer _permit2,
IWETH9 _weth9
) external;
}
contracts/interfaces/IAegisEngine.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
import { PoolId } from "@uniswap/v4-core/src/types/PoolId.sol";
import { PoolKey } from "@uniswap/v4-core/src/types/PoolKey.sol";
import { Currency } from "@uniswap/v4-core/src/types/Currency.sol";
import { BalanceDelta } from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import { IExtsload } from "@uniswap/v4-core/src/interfaces/IExtsload.sol";
import { IExttload } from "@uniswap/v4-core/src/interfaces/IExttload.sol";
import { IERC6909Claims } from "@uniswap/v4-core/src/interfaces/external/IERC6909Claims.sol";
import { IHooks } from "@uniswap/v4-core/src/interfaces/IHooks.sol";
import { IERC721Receiver } from "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import { NftRef, NftKind } from "../types/AegisStructs.sol";
/// @title IAegisEngine
/// @notice Interface for the Aegis V2 liquidity and credit engine built on Uniswap V4
/// @dev Core engine managing pooled full-range LP positions, pool-scoped sL shares (ERC-6909),
/// and equity-neutral borrow/repay in L-units with oracle-free solvency via √K floor
///
/// @dev POOLMANAGER DELTA MANAGEMENT PATTERN:
/// AegisEngine operations create PoolManager (PM) transient deltas that must be settled
/// within the PM.unlock frame. The engine follows a two-tier closure pattern:
///
/// TIER 1 - Session-Protected Operations (internal closure):
/// Functions: modifyIdle, modifyDebt, donateIdle
/// Behavior: Close PM deltas internally via _closeDeltasWithErc6909 (converts to ERC6909 balances)
/// Router: SHOULD still call CLOSE_AE for defensive settlement
///
/// TIER 2 - Public Market Operations (caller-managed closure):
/// Functions: modifyLiquidity
/// Behavior: Leaves PM deltas OPEN for caller flexibility (enables batching multiple operations)
/// Router: MUST settle deltas via SETTLE_AE/TAKE_AE/CLOSE_AE actions or transaction reverts
///
/// When integrating from a custom contract:
/// 1. Ensure you're in a PM.unlock() callback
/// 2. Track AE's currencyDelta via poolManager.currencyDelta(address(aegisEngine), currency)
/// 3. Settle negative deltas (AE owes PM): poolManager.settleFor(address(aegisEngine))
/// 4. Take positive deltas (PM owes AE): aegisEngine.flushPositiveDelta(currency, recipient)
interface IAegisEngine is IERC6909Claims, IERC721Receiver, IExtsload, IExttload {
// - - - - - - Events - - - - - -
// - - - Market Events - - -
/// @notice Emitted when a new market is initialized in the engine
/// @param poolId The Uniswap V4 pool identifier
/// @param currency0 The first currency in the pair
/// @param currency1 The second currency in the pair
/// @param fee The pool fee in hundredths of a basis point (Uniswap V4 units, e.g., 500 = 0.05%)
/// @param tickSpacing The pool's tick spacing
/// @param hooks The hook contract address
event MarketInitialized(
PoolId indexed poolId,
Currency indexed currency0,
Currency indexed currency1,
uint24 fee,
int24 tickSpacing,
IHooks hooks
);
/// @notice Emitted when liquidity is deposited or redeemed from a market
/// @param poolId The pool identifier
/// @param account The account receiving shares (deposit) or burning shares (redeem)
/// @param liquidityOrSharesDelta The input parameter (positive = add L-units, negative = burn shares, zero = poke)
/// @param deltaShares Shares minted or burned
/// @param liquidityDelta Actual L-units added or removed
/// @param deltaAmounts Token amount changes (negative = deposit/spent, positive = redeem/received)
event LiquidityModified(
PoolId indexed poolId,
address indexed account,
int128 liquidityOrSharesDelta,
uint256 deltaShares,
int128 liquidityDelta,
BalanceDelta deltaAmounts
);
/// @notice Emitted when interest accrues on a market
/// @param poolId The pool identifier
/// @param ratePerSecondWad Effective interest rate per second after capping (WAD precision, max 100% APR)
/// @param interestAccruedWad The total interest accrued in L-units (WAD precision)
/// @param borrowIndexWadAfter The borrow index after accrual (WAD precision)
event InterestAccrued(
PoolId indexed poolId, uint256 ratePerSecondWad, uint256 interestAccruedWad, uint256 borrowIndexWadAfter
);
/// @notice Emitted when trading fees are collected and reinvested as liquidity
/// @param poolId The pool identifier
/// @param feesCollected Net residues delta after full-range rebalance (includes fee collection and position adjustment)
/// @param liquidityMinted Actual liquidity minted to equity (0 if below MIN_LIQUIDITY threshold)
/// @param equityLWadAfter The total equity after reinvestment (WAD precision)
event TradingFeesReinvested(
PoolId indexed poolId, BalanceDelta feesCollected, uint128 liquidityMinted, uint256 equityLWadAfter
);
/// @notice Emitted when protocol takes a share of accrued interest
/// @param poolId The pool identifier
/// @param recipient The address receiving the protocol fee shares
/// @param sharesMinted The number of shares minted to the protocol
/// @param protocolFeeAmount The protocol fee in L-units (WAD precision)
event ProtocolFeeMinted(
PoolId indexed poolId, address indexed recipient, uint256 sharesMinted, uint256 protocolFeeAmount
);
// - - - Vault Events - - -
/// @notice Emitted when a new vault is created
/// @param vaultId The newly minted vault token ID
/// @param poolId The pool this vault is bound to
/// @param owner The initial owner of the vault NFT
event VaultCreated(uint256 indexed vaultId, PoolId indexed poolId, address indexed owner);
/// @notice Emitted when a vault NFT is burned
/// @param vaultId The burned vault token ID
/// @param owner The owner who burned the vault
event VaultBurned(uint256 indexed vaultId, address indexed owner);
/// @notice Emitted when a vault is locked, capturing its health state
/// @param vaultId The vault identifier
/// @param ltvPips The loan-to-value ratio in pips (e.g., 950000 = 95%)
event VaultLocked(uint256 indexed vaultId, uint256 ltvPips);
/// @notice Emitted when vault idle balances change
/// @param vaultId The vault identifier
/// @param delta Balance changes (positive = deposit, negative = withdraw)
event IdleModified(uint256 indexed vaultId, BalanceDelta delta);
/// @notice Emitted when vault debt changes
/// @param vaultId The vault identifier
/// @param principalDeltaRequested The requested principal delta (positive = borrow, negative = repay)
/// @param principalDeltaActual The actual principal delta applied (may differ on repay due to geometric mean)
/// @param borrowIndexWad The borrow index at time of operation (WAD precision)
/// @param deltaIdle Resulting idle balance change
event DebtModified(
uint256 indexed vaultId,
int128 principalDeltaRequested,
int136 principalDeltaActual,
uint256 borrowIndexWad,
BalanceDelta deltaIdle
);
/// @notice Emitted when tokens are donated to a vault's idle balance
/// @param vaultId The vault receiving the donation
/// @param amounts The donation amounts (always positive)
event IdleDonated(uint256 indexed vaultId, BalanceDelta amounts);
/// @notice Emitted when an NFT is attached to a vault
/// @param vaultId The vault identifier
/// @param tokenId The NFT token ID
/// @param kind The NFT kind (CL_V4 or LO)
/// @param from The address that sent the NFT
/// @param liquidity Liquidity of the position at time of attachment (static snapshot)
event NftAttached(uint256 indexed vaultId, uint256 indexed tokenId, NftKind kind, address from, uint128 liquidity);
/// @notice Emitted when an NFT is detached from a vault
/// @param vaultId The vault identifier
/// @param tokenId The NFT token ID
/// @param kind The NFT kind (CL_V4 or LO)
/// @param to The address receiving the NFT
event NftDetached(uint256 indexed vaultId, uint256 indexed tokenId, NftKind kind, address indexed to);
// - - - Keeper Events - - -
/// @notice Emitted when an NFT is peeled from a vault
/// @param vaultId The vault identifier
/// @param caller The address that triggered the peel
/// @param nft The NFT reference (kind + tokenId)
/// @param xRealized The total currency0 amount from NFT redemption
/// @param yRealized The total currency1 amount from NFT redemption
/// @param idleDelta The idle balance change applied to vault (bounty = amountsRealized - idleDelta)
/// @param initialLtvPips The vault's LTV before the peel operation
event NftPeeled(
uint256 indexed vaultId,
address indexed caller,
NftRef nft,
uint256 xRealized,
uint256 yRealized,
BalanceDelta idleDelta,
uint256 initialLtvPips
);
/// @notice Emitted when a vault is micro-liquidated via swap
/// @param vaultId The vault identifier
/// @param caller The address that triggered the micro-liquidation
/// @param zeroForOne The swap direction
/// @param swapDelta Swap amounts from PoolManager (not amount taken from idle)
/// @param debtRepaidRl Actual principal debt repaid (after geometric mean adjustment)
/// @param idleDelta Net vault idle change after swap, mint, and keeper fee
/// @param keeperFee The keeper fee charged (0-1% based on LTV)
/// @param initialLtvPips The vault's LTV before the micro-liquidation operation
event VaultMicroLiquidated(
uint256 indexed vaultId,
address indexed caller,
bool zeroForOne,
BalanceDelta swapDelta,
uint136 debtRepaidRl,
BalanceDelta idleDelta,
BalanceDelta keeperFee,
uint256 initialLtvPips
);
// - - - Admin Events - - -
/// @notice Emitted when the default rate oracle is updated
/// @param oracle The new default rate oracle address
/// @param fullUtilRate The full utilization rate (1e18 scale)
event DefaultRateOracleSet(address indexed oracle, uint64 fullUtilRate);
/// @notice Emitted when a pool-specific rate oracle is set
/// @param poolId The pool identifier
/// @param oracle The rate oracle address
/// @param fullUtilRate The full utilization rate (1e18 scale)
event PoolRateOracleSet(PoolId indexed poolId, address indexed oracle, uint64 fullUtilRate);
/// @notice Emitted when a market's protocol fee is updated
/// @param poolId The pool identifier
/// @param protocolFeePips The new protocol fee in pips
event MarketProtocolFeeSet(PoolId indexed poolId, uint24 protocolFeePips);
/// @notice Emitted when a market's LTV thresholds are updated
/// @param poolId The pool identifier
/// @param maxLtvPips The new MAX LTV threshold in pips
/// @param hardLtvPips The new HARD LTV threshold in pips
event MarketLtvThresholdsSet(PoolId indexed poolId, uint24 maxLtvPips, uint24 hardLtvPips);
// - - - - - - Functions - - - - - -
// - - - Admin Functions - - -
/// @notice Authorize a hook to be used with the engine
/// @dev Only callable by the contract owner
/// @param hook The hook address to authorize
function authorizeHook(address hook) external;
/// @notice Configure the default variable rate oracle used when pools lack overrides
/// @dev Only callable by the contract owner
/// @param oracle The rate oracle address
/// @param fullUtilRate The full utilization rate (1e18 scale)
function setDefaultRateOracle(address oracle, uint64 fullUtilRate) external;
/// @notice Configure a per-market rate oracle
/// @dev Only callable by the contract owner
/// @param poolId The pool identifier
/// @param oracle The rate oracle address
/// @param fullUtilRate The full utilization rate (1e18 scale)
function setPoolRateOracle(PoolId poolId, address oracle, uint64 fullUtilRate) external;
/// @notice Set the protocol fee for a specific market
/// @dev Only callable by the contract owner
/// @param poolId The pool identifier
/// @param newProtocolFeePips The new protocol fee in pips (0-1000000)
function setMarketProtocolFee(PoolId poolId, uint24 newProtocolFeePips) external;
/// @notice Set per-market LTV thresholds for micro-liquidation and lock guard
/// @dev Only callable by the contract owner. Validates maxLtvPips < hardLtvPips <= MAX_HARD_LTV_PIPS (99.8%)
/// and ensures minimum ramp width (0.1%) for liquidation math.
/// @param poolId The pool identifier
/// @param newMaxLtvPips The new MAX LTV threshold in pips (micro-liq start, lock guard)
/// @param newHardLtvPips The new HARD LTV threshold in pips (full repay, max keeper fee)
function setMarketLtvThresholds(PoolId poolId, uint24 newMaxLtvPips, uint24 newHardLtvPips) external;
// - - - Market Functions - - -
/// @notice Initialize a new market in the engine for a given Uniswap V4 pool
/// @dev The pool must already be initialized in PoolManager and have an authorized hook
/// @param key The Uniswap V4 PoolKey
function initialize(PoolKey calldata key) external;
/// @notice Modify market liquidity using a signed parameter with dual semantics.
/// @dev Positive values add full-range liquidity in L-units and mint shares; negative values burn market shares
/// and withdraw a proportional amount of liquidity. Zero is a poke-only call that only collects/reinvests fees.
/// @param poolId The pool identifier for the liquidity operation
/// @param liquidityOrSharesDelta Signed amount encoding the operation:
/// > 0: full-range liquidity to add (in L-units)
/// < 0: market shares (ERC6909) to burn
/// = 0: poke-only (collect/reinvest fees without changing equity or shares)
/// @param recipientOrOwner For deposits: shares recipient. For redeems: shares owner.
/// @return deltaShares Number of shares minted (deposit) or burned (redeem)
/// @return modifyFullRangeDelta Currency amounts change (negative for deposit/spend, positive for redeem/receive)
function modifyLiquidity(PoolId poolId, int128 liquidityOrSharesDelta, address recipientOrOwner)
external
returns (uint256 deltaShares, BalanceDelta modifyFullRangeDelta);
// - - - Vault Functions - - -
/// @notice Create a new vault associated with the provided pool
/// @dev Mints an ERC-721 vault NFT to specified owner via VaultRegistry
/// @param poolId The pool identifier this vault will be bound to
/// @param owner The address that will own the vault NFT
/// @return vaultId The newly minted vault token ID
function createVault(PoolId poolId, address owner) external returns (uint256 vaultId);
/// @notice Burn an empty vault NFT
/// @dev Vault must have no debt, no idle balances, no attached positions, and be locked
/// @param vaultId The vault ID to burn
function burnVault(uint256 vaultId) external;
/// @notice Start an Aegis Engine session with callback execution
/// @dev Enforces that all unlocked vaults are re-locked and no pending NFT attaches remain
/// @param data Calldata to pass to the callback
/// @return result Data returned from the callback
function aeStart(bytes calldata data) external returns (bytes memory result);
/// @notice Unlock a vault for the current AE session
/// @dev Can only be called within an aeStart session. Caller must be authorized for the vault.
/// @param vaultId The vault to unlock
function unlockVault(uint256 vaultId) external;
/// @notice Re-lock a previously unlocked vault, enforcing solvency checks
/// @dev Reverts if vault LTV exceeds per-market maxLtvPips or pool utilization exceeds cap
/// @param vaultId The vault to lock
/// @return ltvPips The loan-to-value ratio in pips after locking
function lockVault(uint256 vaultId) external returns (uint256 ltvPips);
/// @notice Modify vault idle balances using signed delta (V4 pattern)
/// @dev Only callable by the vault's session operator (within an aeStart session)
/// @param vaultId The vault to modify
/// @param delta Signed balance delta (positive = deposit, negative = withdraw)
/// @return balancesAfter The vault's idle balances after modification
function modifyIdle(uint256 vaultId, BalanceDelta delta) external returns (BalanceDelta balancesAfter);
/// @notice Donate tokens to a vault's idle balance (only when vault is locked)
/// @dev Permissionless - anyone can donate to any vault. Vault must be locked to prevent
/// interference with active user sessions. Requires at least one currency amount to
/// meet the MIN_LIQUIDITY threshold. Caller must ensure AegisEngine has negative
/// PM deltas to settle (via SETTLE_AE or CLOSE_AE router actions).
/// @param vaultId The vault to donate to
/// @param amount0 Amount of currency0 to donate (must be >= MIN_LIQUIDITY if amount1 < MIN_LIQUIDITY)
/// @param amount1 Amount of currency1 to donate (must be >= MIN_LIQUIDITY if amount0 < MIN_LIQUIDITY)
/// @return balancesAfter The vault's idle balances after donation
function donateIdle(uint256 vaultId, uint128 amount0, uint128 amount1) external returns (BalanceDelta balancesAfter);
/// @notice Modify vault debt using signed principal delta (V4 pattern)
/// @dev Only callable by the vault's session operator. Positive = borrow, negative = repay.
/// Borrow removes liquidity from full-range and adds to idle; repay does the reverse.
/// @param vaultId The vault to modify
/// @param principalDelta Signed principal amount in L-units (positive = borrow, negative = repay)
/// @return liquidityDelta Full range liquidity change (negative for borrow, positive for repay)
/// @return vaultIdleDelta Resulting idle balance change
function modifyDebt(uint256 vaultId, int128 principalDelta)
external
returns (int136 liquidityDelta, BalanceDelta vaultIdleDelta);
/// @notice Declare intent to attach an NFT to a vault
/// @dev The caller must push the NFT to AE in the same frame via ERC721.safeTransferFrom
/// with abi.encode(vaultId) as the data payload. Only callable by session operator.
/// WARNING: Current v4-periphery PositionManager blocks ERC721 transfers when PoolManager is unlocked.
/// @param vaultId The vault to attach the NFT to
/// @param ref The NFT reference (kind and tokenId)
function attachUserNft(uint256 vaultId, NftRef calldata ref) external;
/// @notice Detach an NFT currently under AE custody and transfer it to recipient
/// @dev Only callable by the vault's session operator
/// WARNING: Current v4-periphery PositionManager blocks ERC721 transfers when PoolManager is unlocked.
/// @param vaultId The vault to detach from
/// @param ref The NFT reference (kind and tokenId)
/// @param to The recipient address
function detachUserNft(uint256 vaultId, NftRef calldata ref, address to) external;
// - - - Keeper Functions - - -
/// @notice Unified entry point for peel or micro-liquidation of an unhealthy vault
/// @dev If vault has attached NFTs, peels one NFT. Otherwise performs micro-liquidation.
/// Vault must be locked. TWAP alignment is enforced. Keeper receives bounty via positive delta.
/// @param vaultId The vault to liquidate
/// @param maybeNft The NFT reference to peel (only used if peel path is taken)
function peelOrMicroLiquidate(uint256 vaultId, NftRef calldata maybeNft) external;
// - - - Utility Functions - - -
/// @notice Flush AE's positive PoolManager delta for a given currency to an external recipient
/// @dev Useful for keepers to claim bounties after peel/micro-liquidation or for users on removing currency assets
/// @param currency The currency to flush
/// @param to The recipient address
/// @return amountFlushed The amount transferred
function flushPositiveDelta(Currency currency, address to) external returns (uint256 amountFlushed);
}
contracts/interfaces/IAegisHook.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
import { PoolId } from "@uniswap/v4-core/src/types/PoolId.sol";
import { IHooks } from "@uniswap/v4-core/src/interfaces/IHooks.sol";
import { IDynamicFeeManager } from "./dfm/IDynamicFeeManager.sol";
import { IAegisEngine } from "./IAegisEngine.sol";
import { IOracleManager } from "./IOracleManager.sol";
import { ILimitOrderManager } from "./ILimitOrderManager.sol";
/// @title IAegisHook
/// @notice Uniswap V4 hook interface for Aegis protocol with dynamic fees, oracle integration, and automatic fee reinvestment
/// @dev Extends IHooks with additional functionality for fee management and oracle coordination
interface IAegisHook is IHooks {
// - - - Events - - -
/// @notice Emitted when hook fees are collected from a swap
/// @param poolId The pool identifier where the fee was collected
/// @param sender The address that initiated the swap
/// @param feeAmount0 The amount of currency0 collected as hook fee
/// @param feeAmount1 The amount of currency1 collected as hook fee
event HookFee(PoolId indexed poolId, address indexed sender, uint128 feeAmount0, uint128 feeAmount1);
/// @notice Emitted when accumulated hook fees are reinvested into the pool as liquidity
/// @param poolId The pool identifier where fees were reinvested
/// @param sender The address that triggered the reinvestment (typically address(0) for automatic reinvestment)
/// @param feeAmount0 The amount of currency0 reinvested
/// @param feeAmount1 The amount of currency1 reinvested
event HookFeeReinvested(PoolId indexed poolId, address indexed sender, uint128 feeAmount0, uint128 feeAmount1);
/// @notice Emitted when the hook fee percentage is updated for a pool
/// @param poolId The pool identifier
/// @param hookFeePpm The new hook fee in parts per million
event HookFeePpmUpdated(PoolId indexed poolId, uint256 hookFeePpm);
/// @notice Emitted when an external call to ORACLE_MANAGER or DYNAMIC_FEE_MANAGER fails
/// @param poolId The pool identifier where the failure occurred
/// @param externalContract The address of the external contract that failed
/// @param functionId id for the function that failed
/// @param errorData The error data returned from the failed call
event ExternalCallFailed(PoolId indexed poolId, address indexed externalContract, string functionId, bytes errorData);
/// @notice Emitted when market shares (sL tokens) are withdrawn by the owner
/// @param poolId The pool identifier for which shares were withdrawn
/// @param recipient The address receiving the shares
/// @param amount The amount of shares withdrawn
event SharesWithdrawn(PoolId indexed poolId, address indexed recipient, uint256 amount);
// - - - Constants & Immutables - - -
// forge-lint: disable-start(mixed-case-function)
/// @notice Minimum liquidity required to trigger automatic fee reinvestment
function MIN_REINVEST_LIQUIDITY() external view returns (uint128);
/// @notice The dynamic fee manager responsible for computing swap fees
function DYNAMIC_FEE_MANAGER() external view returns (IDynamicFeeManager);
/// @notice The oracle manager responsible for TWAP and price observations
function ORACLE_MANAGER() external view returns (IOracleManager);
/// @notice The Aegis Engine core contract that manages vaults and lending markets
function AEGIS_ENGINE() external view returns (IAegisEngine);
/// @notice The limit order manager responsible for filling tick-aligned limit orders
function LIMIT_ORDER_MANAGER() external view returns (ILimitOrderManager);
// forge-lint: disable-end(mixed-case-function)
// - - - Admin Functions - - -
/// @notice Pause or unpause the hook's fee reinvestment functionality
/// @dev Only callable by owner. When paused, fees accumulate but are not automatically reinvested
/// @param doPause True to pause, false to unpause
function pause(bool doPause) external;
/// @notice Set the hook fee percentage for a specific pool
/// @dev Only callable by owner. Fee is taken as a percentage of the swap fee
/// @param poolId The pool identifier
/// @param hookFeePpm The hook fee in parts per million (1_000_000 = 100%)
function setHookFeePpm(PoolId poolId, uint24 hookFeePpm) external;
/// @notice Withdraw market shares (sL tokens) accumulated from fee reinvestment
/// @dev Only callable by owner. Shares are ERC-6909 tokens held by the hook contract.
/// @param poolId The pool identifier for which to withdraw shares
/// @param to The recipient address
/// @param amount The amount of shares to withdraw
function withdrawMarketShares(PoolId poolId, address to, uint256 amount) external;
// - - - View Functions - - -
/// @notice Get the hook fee percentage for a specific pool
/// @param poolId The pool identifier
/// @return The hook fee in parts per million
function hookFeePpm(PoolId poolId) external view returns (uint24);
/// @notice Get the pending fees accumulated for a specific pool
/// @dev These fees are eligible for reinvestment once thresholds are met
/// @param poolId The pool identifier
/// @return amount0 The pending amount of currency0
/// @return amount1 The pending amount of currency1
function pendingFees(PoolId poolId) external view returns (uint128 amount0, uint128 amount1);
}
contracts/interfaces/IHookAuthorizable.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
interface IHookAuthorizable {
function authorizedHooks(address hook) external view returns (bool);
}
contracts/interfaces/ILimitOrderManager.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
import { PoolId } from "@uniswap/v4-core/src/types/PoolId.sol";
import { PoolKey } from "@uniswap/v4-core/src/types/PoolKey.sol";
import { Currency } from "@uniswap/v4-core/src/types/Currency.sol";
import { IHooks } from "@uniswap/v4-core/src/interfaces/IHooks.sol";
import { SwapParams } from "@uniswap/v4-core/src/types/PoolOperation.sol";
import { IHookAuthorizable } from "./IHookAuthorizable.sol";
import { IV4PositionManager } from "./IV4PositionManager.sol";
/// @dev Order epoch identifier reused from Uniswap example so we can leverage existing bucket logic.
type Epoch is uint232;
/// @notice Metadata tracked per order NFT.
struct Order {
PoolId poolId;
Epoch epoch;
// Lower bound of the 1-tick-wide interval. The order's range is always
// [tickLower, tickLower + tickSpacing) regardless of `zeroForOne`.
int24 tickLower;
bool zeroForOne;
uint128 liquidity;
}
/// @notice Per-epoch aggregates reused from the hook example.
struct EpochInfo {
bool filled;
uint256 token0Total;
uint256 token1Total;
uint128 liquidityTotal;
}
/// @notice Per-order cumulative fee-growth snapshot recorded at placement time.
/// Prevents late entrants from diluting fees accrued before they joined an epoch.
struct FeeGrowthCursor {
uint256 feeGrowth0LastX128;
uint256 feeGrowth1LastX128;
}
/// @notice Per-epoch payout parameters recorded at fill time.
/// Stores principal per-liquidity and the fee-growth boundary so each order
/// can compute its exact entitlement on withdraw.
struct EpochPayout {
uint256 principal0PerLiquidityX128;
uint256 principal1PerLiquidityX128;
uint256 feeGrowth0EndX128;
uint256 feeGrowth1EndX128;
}
/// @title Limit Order Manager Interface
/// @notice Exposes the external surface for managing tick-aligned limit order epochs and NFT ownership.
interface ILimitOrderManager is IHookAuthorizable, IV4PositionManager {
/// @notice Thrown when zero address is provided
error ZeroAddress();
/// @notice Thrown when AegisDependencies is not initialized.
error DepsNotInitialized();
/// @notice Thrown when an action requires non-zero liquidity.
error ZeroLiquidity();
/// @notice Thrown when liquidity operations detect the position is still in range.
error InRange();
/// @notice Thrown when attempting to place liquidity on the wrong side of the current price.
error CrossedRange();
/// @notice Thrown when attempting to cancel an order that has already been filled.
error Filled();
/// @notice Thrown when attempting to withdraw proceeds from an order that has not been filled.
error NotFilled();
/// @notice Thrown when the supplied deadline has already expired.
error DeadlinePassed(uint256 deadline);
/// @notice Thrown when receiving ERC1155 tokens from an unexpected sender.
error NotPoolManagerToken();
/// @notice Thrown when attempting to transfer an NFT while the PoolManager is unlocked.
error PoolManagerMustBeLocked();
/// @notice Emitted when a new limit order NFT is minted.
/// @param tokenId The unique identifier of the minted order NFT.
/// @param epoch The epoch bucket the order belongs to.
/// @param key The pool key for the underlying pool.
/// @param tickLower The lower tick boundary aligned to tick spacing.
/// @param zeroForOne True if the order sells currency0 for currency1.
/// @param liquidity The liquidity contributed to the epoch.
event OrderPlaced(
uint256 indexed tokenId, Epoch indexed epoch, PoolKey key, int24 tickLower, bool zeroForOne, uint128 liquidity
);
/// @notice Emitted when an epoch becomes filled by a tick crossing.
/// @param epoch The filled epoch.
/// @param key The associated pool key.
/// @param tickLower The tick boundary that was crossed.
/// @param zeroForOne True if liquidity was sold from currency0 into currency1.
event OrderFilled(Epoch indexed epoch, PoolKey key, int24 tickLower, bool zeroForOne);
/// @notice Emitted when an order NFT is cancelled before fill.
/// @param tokenId The identifier of the cancelled order NFT.
/// @param epoch The epoch the order contributed to.
/// @param key The pool key for the order's pool.
/// @param tickLower The tick boundary for the order.
/// @param zeroForOne True if the order was selling currency0.
/// @param liquidity The amount of liquidity that was cancelled.
event OrderCancelled(
uint256 indexed tokenId, Epoch indexed epoch, PoolKey key, int24 tickLower, bool zeroForOne, uint128 liquidity
);
/// @notice Emitted when filled order proceeds are withdrawn and the NFT is burned.
/// @param tokenId The identifier of the order NFT being settled.
/// @param epoch The epoch from which proceeds were withdrawn.
/// @param amount0 The amount of currency0 sent to the receiver.
/// @param amount1 The amount of currency1 sent to the receiver.
event OrderWithdrawn(uint256 indexed tokenId, Epoch indexed epoch, uint256 amount0, uint256 amount1);
/// @notice Returns the cached tickLower value used to detect crossings for a pool.
/// @param poolId The identifier of the pool.
/// @return tickLowerLast The last recorded lower tick.
function tickLowerLasts(PoolId poolId) external view returns (int24 tickLowerLast);
/// @notice Returns the next epoch identifier that will be assigned to a new bucket.
/// @return nextEpoch The next epoch value.
function epochNext() external view returns (Epoch nextEpoch);
/// @notice Returns details for an order by token identifier.
/// @param tokenId The NFT identifier.
/// @return poolId The pool id the order references.
/// @return epoch The epoch bucket the order belongs to.
/// @return tickLower The order's lower tick boundary.
/// @return zeroForOne True if the order sells currency0(i.e. lies to the right of the price).
/// @return liquidity The liquidity amount provided.
function orders(uint256 tokenId)
external
view
returns (PoolId poolId, Epoch epoch, int24 tickLower, bool zeroForOne, uint128 liquidity);
/// @notice Returns the current epoch bucket for a pool/tick/direction key.
/// @param slot The hashed slot key derived from pool key, tick, and side.
/// @return epoch The epoch identifier assigned to the slot.
function epochs(bytes32 slot) external view returns (Epoch epoch);
/// @notice Authorizes a hook contract for soft-enforcement callbacks. Idempotent for already-authorized hooks.
/// @param hook The hook contract to authorize.
function authorizeHook(address hook) external;
/// @notice Records the baseline tick after pool initialization.
/// @param key The pool key being initialized.
/// @param tick The initialized tick returned by the pool manager.
function onAfterInitialize(PoolKey calldata key, int24 tick) external;
/// @notice Fills limit-order epochs whose ticks were crossed by a swap.
/// @param key The pool key where the swap occurred.
/// @param params The swap parameters supplied to the pool manager.
function onAfterSwap(PoolKey calldata key, SwapParams calldata params) external;
/// @notice Returns the epoch assigned to a pool key, tick, and direction tuple.
/// @param key The pool key to inspect.
/// @param tickLower The truncated lower tick.
/// @param zeroForOne True if querying the sell-currency0 side.
/// @return epoch The epoch identifier currently assigned.
function getEpoch(PoolKey memory key, int24 tickLower, bool zeroForOne) external view returns (Epoch epoch);
/// @notice Returns the cached pool key for a given pool id.
/// @param poolId The pool id to query.
/// @return currency0 Pool base currency
/// @return currency1 Pool quote currency
/// @return fee The fee tier
/// @return tickSpacing Pool tick spacing
/// @return hooks The configured hook address
function poolKeys(PoolId poolId)
external
view
returns (Currency currency0, Currency currency1, uint24 fee, int24 tickSpacing, IHooks hooks);
/// @notice Returns aggregate information for an epoch bucket.
/// @param epoch The epoch identifier to query.
/// @return filled True if the epoch has been filled.
/// @return token0Total The total amount of currency0 held by the epoch.
/// @return token1Total The total amount of currency1 held by the epoch.
/// @return liquidityTotal The total liquidity remaining in the epoch.
function epochInfos(Epoch epoch)
external
view
returns (bool filled, uint256 token0Total, uint256 token1Total, uint128 liquidityTotal);
/// @notice Returns the fee-growth cursor for an order, set at placement time.
/// @param tokenId The NFT identifier.
/// @return feeGrowth0LastX128 Cumulative fee-growth for currency0 at placement.
/// @return feeGrowth1LastX128 Cumulative fee-growth for currency1 at placement.
function orderFeeGrowthCursors(uint256 tokenId)
external
view
returns (uint256 feeGrowth0LastX128, uint256 feeGrowth1LastX128);
/// @notice Returns the payout parameters for a filled epoch.
/// @param epoch The epoch identifier.
/// @return principal0PerLiquidityX128 Q128 principal of currency0 per unit of liquidity.
/// @return principal1PerLiquidityX128 Q128 principal of currency1 per unit of liquidity.
/// @return feeGrowth0EndX128 Cumulative fee-growth for currency0 at fill boundary.
/// @return feeGrowth1EndX128 Cumulative fee-growth for currency1 at fill boundary.
function epochPayouts(Epoch epoch)
external
view
returns (
uint256 principal0PerLiquidityX128,
uint256 principal1PerLiquidityX128,
uint256 feeGrowth0EndX128,
uint256 feeGrowth1EndX128
);
/// @notice Per-pool bitmap tracking ticks with an active (non-default) epoch slot.
/// @param poolId The pool identifier.
/// @param wordPos The compressed tick word position.
/// @return word The bitmap word for the given word position.
function epochTickBitmap(PoolId poolId, int16 wordPos) external view returns (uint256 word);
/// @notice Returns the next ERC721 token identifier that will be minted.
/// @return tokenId The value of the incremental counter.
function nextTokenId() external view returns (uint256 tokenId);
}
contracts/interfaces/IOracleManager.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
import { IPoolManager } from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import { PoolId } from "@uniswap/v4-core/src/types/PoolId.sol";
import { PoolKey } from "@uniswap/v4-core/src/types/PoolKey.sol";
import { IHookAuthorizable } from "./IHookAuthorizable.sol";
/// @title Oracle Manager Interface
/// @notice Defines the soft-enforcement surface that production hooks must call to maintain oracle state.
interface IOracleManager is IHookAuthorizable {
/// @notice Thrown when zero address is provided
error ZeroAddress();
/// @notice Thrown when AegisDependencies is not initialized.
error DepsNotInitialized();
/// @notice Thrown when attempting to observe zero seconds in the past.
error InvalidSecondsAgo();
/// @notice Thrown by `requireSafeFor` when the oracle cannot durably serve the requested window.
error OracleNotSafeForWindow();
/// @notice Observation ring-buffer metadata for a pool.
struct ObservationState {
uint16 index;
uint16 cardinality;
uint16 cardinalityNext;
}
/// @notice Returns the underlying PoolManager the oracle observes.
/// forge-lint: disable-next-line(mixed-case-function)
function POOL_MANAGER() external view returns (IPoolManager);
/// @notice Returns an observation entry for a pool by index.
/// @param id The pool identifier whose observation is requested.
/// @param observationIndex The observation index within the ring buffer.
/// @return blockTimestamp The block timestamp for the observation.
/// @return prevTick The previous printed tick stored with the observation.
/// @return tickCumulative The cumulative tick value.
/// @return initialized Whether the observation slot is initialized.
function observations(PoolId id, uint256 observationIndex)
external
view
returns (uint32 blockTimestamp, int24 prevTick, int48 tickCumulative, bool initialized);
/// @notice Returns the observation state metadata for a pool.
/// @param id The pool identifier whose state is requested.
/// @return index The index of the most recently written observation.
/// @return cardinality The number of populated observation slots.
/// @return cardinalityNext The configured target cardinality.
function states(PoolId id) external view returns (uint16 index, uint16 cardinality, uint16 cardinalityNext);
/// @notice Authorizes a hook to call mutation functions. Idempotent if the hook is already authorized.
/// @param hook The hook contract address to authorize.
function authorizeHook(address hook) external;
/// @notice Records the first oracle observation immediately after pool initialization.
/// @dev Should be invoked from a hook's `afterInitialize` implementation once the pool has been created.
/// @param key The corresponding pool key.
/// @param tick The initialized tick returned by the pool manager.
function recordAfterInitialize(PoolKey calldata key, int24 tick) external;
/// @notice Updates the oracle after a swap; for gas efficiency only needs to be called if the tick changes
/// @dev Should be invoked from a hook's `afterSwap` callback.
/// @param key The pool key on which a swap is about to occur.
function afterSwap(PoolKey calldata key, int24 preSwapTick) external;
/// @notice Observes the pool at requested time offsets.
/// @param id The pool identifier to observe.
/// @param secondsAgos Offsets into the past for which cumulative values should be returned.
/// @return tickCumulatives The cumulative ticks at each requested offset.
function observe(PoolId id, uint32[] calldata secondsAgos) external view returns (int48[] memory tickCumulatives);
/// @notice Computes the time-weighted average tick over the provided interval.
/// @param id The pool identifier to consult.
/// @param secondsAgo The lookback window for the TWAP calculation.
/// @return arithmeticMeanTick The arithmetic mean tick across the interval.
function consult(PoolId id, uint32 secondsAgo) external view returns (int24 arithmeticMeanTick);
/// @notice Increases the cardinality target for a pool's observation buffer.
/// @param id The pool identifier whose observation buffer should grow.
/// @param cardinalityNext The desired new cardinality target.
/// @return cardinalityNextOld The previous target value.
/// @return cardinalityNextNew The updated target.
function increaseCardinalityNext(PoolId id, uint16 cardinalityNext)
external
returns (uint16 cardinalityNextOld, uint16 cardinalityNextNew);
/// @notice Reverts with `OracleNotSafeForWindow` if `safeFor(id, secondsAgo)` is false. Cheap
/// internal-revert path for callers (e.g. AegisEngine market init) that don't need to
/// branch on the result.
/// @param id The pool identifier to inspect.
/// @param secondsAgo The lookback window the caller wants to be durably servable.
function requireSafeFor(PoolId id, uint32 secondsAgo) external view;
/// @notice Whether the oracle can durably serve a `consult(id, secondsAgo)` lookup right now AND
/// continue to do so even under continuous adversarial 1-per-block writes.
/// @dev Returns true iff (a) `state.cardinality >= secondsAgo + 1` (retention capacity assuming
/// 1s worst-case blocks) AND (b) the oldest initialized observation has
/// `blockTimestamp <= block.timestamp - secondsAgo` (history available at the moment of
/// the call). Reverts with `InvalidSecondsAgo` if `secondsAgo == 0`, mirroring `consult`.
/// Property: whenever this function returns true, `consult(id, secondsAgo)` does not revert.
/// @param id The pool identifier to inspect.
/// @param secondsAgo The lookback window the caller wants to be durably servable.
/// @return ok True iff the oracle is safe to serve the requested lookback durably.
function safeFor(PoolId id, uint32 secondsAgo) external view returns (bool ok);
}
contracts/interfaces/IV4PositionManager.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
/// @notice this interface is common between the PositionManager and the LimitOrderManager
interface IV4PositionManager {
/// @notice Executes a batch of limit-order actions while unlocking the pool manager.
/// @param unlockData ABI-encoded `(bytes actions, bytes[] params)` payload understood by the action router.
/// @param deadline Timestamp after which the call is no longer valid.
function modifyLiquidities(bytes calldata unlockData, uint256 deadline) external payable;
/// @notice Executes limit-order actions assuming the pool manager is already unlocked.
/// @param actions Packed action identifiers.
/// @param params ABI-encoded parameters aligned with each action.
function modifyLiquiditiesWithoutUnlock(bytes calldata actions, bytes[] calldata params) external payable;
}
contracts/interfaces/dfm/IDynamicFeeManager.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { PoolId } from "@uniswap/v4-core/src/types/PoolId.sol";
import { PoolKey } from "@uniswap/v4-core/src/types/PoolKey.sol";
import { RuntimeStructs } from "../../libraries/dfm/RuntimeStructs.sol";
/// @title IDynamicFeeManager
/// @notice Interface for dynamic fee management with adaptive tick caps and auto-tuning
/// @dev Manages runtime state and computes dynamic fees based on policy configuration
interface IDynamicFeeManager {
/// @notice Swap quote containing all fee components and state flags
struct SwapQuote {
uint24 activeFee; // The fee charged for this swap (PPM)
uint24 baseFee; // Base fee component (PPM)
uint24 surgeFee; // Surge fee component (PPM)
uint24 maxTicksPerBlock; // Current adaptive tick cap
bool manualOverride; // True if manual fee override is active
bool perSwapMode; // True if per-swap cap mode, false if per-block
bool inCapEvent; // True if currently in surge mode (cap event active)
}
// === Events ===
/// @notice Emitted when a pool is initialized
event PoolInitialized(PoolId indexed poolId);
/// @notice Emitted when surge mode is toggled
event CapToggled(PoolId indexed poolId, bool inSurgeMode);
/// @notice Emitted when fee state changes
event FeeStateChanged(PoolId indexed poolId, uint256 baseFee, uint256 surgeFee, bool inCapEvent);
/// @notice Emitted when the adaptive tick cap is adjusted
event MaxTicksPerBlockUpdated(PoolId indexed poolId, uint24 oldTickCap, uint24 newTickCap);
/// @notice Emitted when auto-tuning is paused or unpaused
event AutoTunePaused(PoolId indexed poolId, bool paused);
// === Governance ===
/// @notice Sets whether auto-tuning is paused for a pool
/// @param poolId The pool identifier
/// @param paused True to pause auto-tuning, false to unpause
function setAutoTunePaused(PoolId poolId, bool paused) external;
// === Hook Surface ===
/// @notice Initializes dynamic fee management for a new pool
/// @param key The pool key
/// @param initialTick The initial tick (unused but required by hook interface)
function initialize(PoolKey calldata key, int24 initialTick) external;
/// @notice Prepares for a swap by computing the active fee
/// @param key The pool key
/// @param preSwapTick The tick before swap
/// @return activeFee The fee to charge for this swap
function prepareSwap(PoolKey calldata key, int24 preSwapTick) external returns (uint24 activeFee);
/// @notice Finalizes a swap by updating state and detecting cap violations
/// @param key The pool key
/// @param preSwapTick The tick before swap
/// @param postSwapTick The tick after swap
/// @return tickWasCapped True if tick movement exceeded cap
function finalizeSwap(PoolKey calldata key, int24 preSwapTick, int24 postSwapTick)
external
returns (bool tickWasCapped);
// === View Functions ===
/// @notice Returns the current adaptive tick cap for a pool
/// @param poolId The pool identifier
/// @return tickCap The current tick movement cap
function currentTickCap(PoolId poolId) external view returns (uint24 tickCap);
/// @notice Returns whether a pool is currently in surge mode
/// @param poolId The pool identifier
/// @return inSurgeMode True if surge mode is active
function isInSurgeMode(PoolId poolId) external view returns (bool inSurgeMode);
/// @notice Returns a complete fee quote for a pool
/// @param poolId The pool identifier
/// @return quote The assembled swap quote
function feeQuote(PoolId poolId) external view returns (SwapQuote memory quote);
/// @notice Returns the runtime state for a pool
/// @param poolId The pool identifier
/// @return state The runtime state snapshot
function runtimeState(PoolId poolId) external view returns (RuntimeStructs.RuntimeState memory state);
}
contracts/libraries/ae/Constants.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
uint256 constant WAD = 1e18;
uint256 constant PIPS_DENOMINATOR = 1_000_000;
// Risk constants (compile-time) shared across engine modules:
uint32 constant TWAP_WINDOW_SECONDS = 30 minutes;
// Minimum active oracle cardinality required to durably serve consult(TWAP_WINDOW_SECONDS).
// With 1-second worst-case blocks (Aegis targets Unichain), a ring of N slots writing once per
// block holds at most N-1 seconds of history after wraparound. Therefore TWAP_WINDOW_SECONDS + 1
// slots guarantee the oldest stored observation is always >= TWAP_WINDOW_SECONDS old, even under
// continuous adversarial overwrites. Future deployments on chains with sub-1s blocktimes must
// raise this floor.
// Cast to uint16 is safe: TWAP_WINDOW_SECONDS = 1800, well below uint16 max (65535).
// forge-lint: disable-next-line(unsafe-typecast)
uint16 constant MIN_CARDINALITY_FOR_TWAP = uint16(TWAP_WINDOW_SECONDS) + 1;
uint256 constant UTILIZATION_CAP_PIPS = 950_000; // 95%
uint256 constant MAX_RATE_PER_SECOND_WAD = 31_688_730_000; // ~100% APR cap (based on 365.24-day year, simple interest)
int24 constant N_TICKS = 5;
uint24 constant MAX_TICK_DEVIATION = 25;
uint24 constant EMERGENCY_TICK_DEVIATION = 250; // 10x normal; for critically unhealthy vaults (LTV >= hardLtvPips)
uint32 constant PEEL_BOUNTY_PIPS = 100; // 0.01%
// Conservative haircut for micro‑liquidation swap sizing at tick‑limit.
// 2% total: covers pool fee (≤ 1%) and keeper fee budget (≤ 1%) with a single haircut.
uint32 constant MICRO_LIQ_CONSERVATIVE_HAIRCUT_PIPS = 20_000; // 2%
// Per-market micro-liquidation LTV thresholds (computed from pool fee at market init)
// Oracle + price band buffer: covers 25-tick normal TWAP deviation + 5-tick swap limit + safety margin
// NOTE: emergency path (EMERGENCY_TICK_DEVIATION = 250) for critically unhealthy vaults exceeds this budget;
// acceptable because the alternative is complete liquidation lockout (TOB-AEGIS-13).
uint24 constant MICRO_LIQ_ORACLE_BUFFER_PIPS = 4_000; // 0.4%
// Minimum LTV ramp width to avoid pathological narrow ramps in low-fee pools
uint24 constant MICRO_LIQ_MIN_RAMP_WIDTH_PIPS = 1_000; // 0.1% (10 bps)
// Maximum swap fee used for LTV threshold calculation (for static fee pools)
uint24 constant MICRO_LIQ_MAX_SWAP_FEE_PIPS = 10_000; // 1.0%
// Maximum keeper fee at per-market hardLtvPips
uint32 constant MICRO_LIQ_FEE_MAX_PIPS = 10_000; // 1%
// Maximum allowed hardLtvPips to ensure safety margin for oracle deviations
uint24 constant MAX_HARD_LTV_PIPS = 998_000; // 99.8%
// Maximum v4 pool swap fee charged when AegisEngine is the sender (micro-liquidations).
// Provides favorable swap terms for protocol-initiated liquidations. Note: the hook fee
// configured per-pool via `AegisHook.setHookFeePpm` may stack on top of this capped pool
// fee — see `AegisHook._beforeSwap` for the rationale and the worst-case all-in math.
uint24 constant ENGINE_MAX_SWAP_FEE_PIPS = 1_000; // 0.1%
uint128 constant MIN_LIQUIDITY = 1_000; // to mint or allowable for NFT attaches
// Permanent holder for the MIN_LIQUIDITY shares locked on the first deposit to each market.
address constant DEAD_SHARES_HOLDER = address(0xdead);
uint8 constant MAX_NFTS_PER_VAULT = 4;
contracts/libraries/ae/math/LUnitMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { FullMath } from "@uniswap/v4-core/src/libraries/FullMath.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import { SqrtPriceMath } from "@uniswap/v4-core/src/libraries/SqrtPriceMath.sol";
import { TickMath } from "@uniswap/v4-core/src/libraries/TickMath.sol";
import { WAD } from "../Constants.sol";
import { SqrtMath } from "./SqrtMath.sol";
/// @notice Pure helpers for maintaining the L-unit ledger.
library LUnitMath {
/// @notice Convert minted full-range liquidity into L-unit principal (floor).
function principalFromLiquidity(uint256 liquidityMinted, uint256 borrowIndexWad)
internal
pure
returns (uint128 rLEffective)
{
uint256 value = FullMath.mulDiv(liquidityMinted, WAD, borrowIndexWad);
return SafeCast.toUint128(value);
}
/// @notice Compute the real full-range liquidity needed to cover a target principal (ceil).
function liquidityForPrincipal(uint128 rLTarget, uint256 borrowIndexWad)
internal
pure
returns (uint128 liquidityNeeded)
{
uint256 value = FullMath.mulDivRoundingUp(uint256(rLTarget), borrowIndexWad, WAD);
return SafeCast.toUint128(value);
}
/// @notice Calculate geometric mean for full-range position at current price
/// @dev Used by conservative bridge to determine actual √K value provided for a given liquidity amount.
/// This is the core calculation that determines the conservative bridge cap in Vault.applyDebt().
/// @param tickSpacing Pool tick spacing to determine actual full-range tick bounds
/// @param liquidityDelta Target liquidity for full-range position (MIN_TICK to MAX_TICK)
/// @param sqrtPriceX96 Current sqrt price from pool.slot0()
/// @return geometricMean √(amount0 · amount1) representing actual √K value
function geometricMeanForLiquidity(int24 tickSpacing, uint128 liquidityDelta, uint160 sqrtPriceX96)
internal
pure
returns (uint256 geometricMean)
{
(uint160 minSqrtPriceX96, uint160 maxSqrtPriceX96) = LUnitMath.getActualFullRangePrices(tickSpacing);
geometricMean = geometricMeanForLiquidity(minSqrtPriceX96, maxSqrtPriceX96, liquidityDelta, sqrtPriceX96);
}
/// @notice Calculate geometric mean for full-range position with pre-computed price bounds
/// @dev Overload for callers that already have minSqrtPriceX96 and maxSqrtPriceX96 cached.
/// Used by router to avoid redundant getActualFullRangePrices() calls.
/// @param minSqrtPriceX96 Sqrt price at minimum tick (from getActualFullRangePrices)
/// @param maxSqrtPriceX96 Sqrt price at maximum tick (from getActualFullRangePrices)
/// @param liquidityDelta Target liquidity for full-range position
/// @param sqrtPriceX96 Current sqrt price from pool.slot0()
/// @return geometricMean √(amount0 · amount1) representing actual √K value
function geometricMeanForLiquidity(
uint160 minSqrtPriceX96,
uint160 maxSqrtPriceX96,
uint128 liquidityDelta,
uint160 sqrtPriceX96
) internal pure returns (uint256 geometricMean) {
// Calculate token amounts needed for full-range position (rounded up per Uniswap convention)
uint256 amount0 = SqrtPriceMath.getAmount0Delta(sqrtPriceX96, maxSqrtPriceX96, liquidityDelta, true);
uint256 amount1 = SqrtPriceMath.getAmount1Delta(minSqrtPriceX96, sqrtPriceX96, liquidityDelta, true);
// Geometric mean = √(amount0 · amount1) with overflow protection
geometricMean = SqrtMath.sqrtProductLowerBound(amount0, amount1);
}
/// @notice Preview conservative bridge impact for full-range repay position.
/// @dev Call BEFORE repaying to understand potential deviation from geometric mean.
/// The relative deviation is M-invariant (same whether borrowIndex = 1.0 or 2.5).
/// Users should check relativeDeviation against acceptable thresholds before repaying.
/// Note: The geometric mean calculation matches `geometricMeanForLiquidity()`, but this function
/// also returns the individual token amounts and deviation metrics for analysis.
/// @param liquidityDelta Target liquidity to mint for full-range position (MIN_TICK to MAX_TICK)
/// @param sqrtPriceX96 Current sqrt price from pool.slot0()
/// @return amount0Required Token0 needed for mint (rounded up per Uniswap)
/// @return amount1Required Token1 needed for mint (rounded up per Uniswap)
/// @return geometricMean √(amount0·amount1) - actual √K value provided
/// @return deviation Absolute |liquidityDelta - geometricMean|
/// @return relativeDeviation deviation / liquidityDelta (1e18 = 100%)
function previewConservativeBridge(int24 tickSpacing, uint128 liquidityDelta, uint160 sqrtPriceX96)
internal
pure
returns (
uint256 amount0Required,
uint256 amount1Required,
uint256 geometricMean,
uint256 deviation,
uint256 relativeDeviation
)
{
(uint160 minSqrtPriceX96, uint160 maxSqrtPriceX96) = LUnitMath.getActualFullRangePrices(tickSpacing);
// Compute token amounts for full-range position (MIN_TICK to MAX_TICK)
// Round up to ensure sufficient tokens are pulled
amount0Required = SqrtPriceMath.getAmount0Delta(sqrtPriceX96, maxSqrtPriceX96, liquidityDelta, true);
amount1Required = SqrtPriceMath.getAmount1Delta(minSqrtPriceX96, sqrtPriceX96, liquidityDelta, true);
// Geometric mean = √(amount0 · amount1) with overflow protection - represents actual √K value
geometricMean = SqrtMath.sqrtProductLowerBound(amount0Required, amount1Required);
// Absolute deviation between liquidity and geometric mean
deviation = liquidityDelta > geometricMean ? liquidityDelta - geometricMean : geometricMean - liquidityDelta;
// Relative deviation (WAD scale: 1e18 = 100%)
relativeDeviation = FullMath.mulDiv(deviation, WAD, liquidityDelta);
}
function getActualFullRangeTicks(int24 tickSpacing) internal pure returns (int24 minTick, int24 maxTick) {
minTick = _roundTowardZero(TickMath.MIN_TICK, tickSpacing);
maxTick = _roundTowardZero(TickMath.MAX_TICK, tickSpacing);
}
function getActualFullRangePrices(int24 tickSpacing)
internal
pure
returns (uint160 minSqrtPriceX96, uint160 maxSqrtPriceX96)
{
(int24 minTick, int24 maxTick) = getActualFullRangeTicks(tickSpacing);
minSqrtPriceX96 = TickMath.getSqrtPriceAtTick(minTick);
maxSqrtPriceX96 = TickMath.getSqrtPriceAtTick(maxTick);
}
function _roundTowardZero(int24 value, int24 spacing) private pure returns (int24) {
int24 remainder = value % spacing;
if (remainder == 0) return value;
return value - remainder;
}
}
contracts/libraries/ae/math/SqrtMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { FixedPointMathLib } from "solmate/src/utils/FixedPointMathLib.sol";
/// @notice Overflow-safe square root operations
/// @dev Provides lower-bound sqrt computation that handles potential uint256 overflow in multiplication
library SqrtMath {
/// @notice Computes floor(√(A·B)) with overflow protection
/// @dev If A·B would overflow uint256, returns √A · √B instead (still ≤ √(A·B))
/// This provides a conservative lower bound in all cases:
/// - If product fits: returns exact floor(√(A·B))
/// - If product overflows: returns √A · √B which is ≤ √(A·B)
/// @param a First factor
/// @param b Second factor
/// @return result floor(√(A·B)) if product fits, else √A · √B (lower bound)
function sqrtProductLowerBound(uint256 a, uint256 b) internal pure returns (uint256 result) {
if (a == 0 || b == 0) return 0;
if (fitsMul(a, b)) {
unchecked {
return FixedPointMathLib.sqrt(a * b);
}
}
return FixedPointMathLib.sqrt(a) * FixedPointMathLib.sqrt(b);
}
/// @notice Checks if multiplication a*b fits in uint256 without overflow
/// @param a First factor
/// @param b Second factor
/// @return True if a*b does not overflow uint256
function fitsMul(uint256 a, uint256 b) internal pure returns (bool) {
if (a == 0 || b == 0) return true;
return b <= type(uint256).max / a;
}
}
contracts/libraries/dfm/Errors.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Errors
/// @notice Shared custom error definitions for the Aegis contracts
library Errors {
// - - - Access control - - -
error UnauthorizedCaller(address caller);
// - - - Validation - - -
error ZeroAddress();
error NotInitialized();
error AlreadyInitialized();
error InvalidHookAuthorization(address expected, address actual);
error InvalidFee();
error InvalidSwapDelta();
error ParameterOutOfRange(uint256 value, uint256 min, uint256 max);
}
contracts/libraries/dfm/PrecisionConstants.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @dev Standard high-precision scaling factor (10^18)
uint256 constant WAD = 1e18;
/// @dev Parts-per-million scaling factor (10^6)
uint256 constant PPM_SCALE = 1e6;
contracts/libraries/dfm/RuntimeStructs.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
/// @title RuntimeStructs
/// @notice Packed storage structure for dynamic runtime state per pool
/// @dev Optimized for gas efficiency with a single 256-bit storage slot per pool
library RuntimeStructs {
/// @notice Runtime state tracking per pool
/// @dev Packed into a single 256-bit storage slot (242 bits used, 14 bits free)
///
/// Layout (LSB to MSB):
/// ┌──────────┬──────────┬──────────┬─────────┬────────┬──────────┬───────────┬──────────┬──────────┐
/// │capEvent │lastFreq │lastCap │lastCap │current │autoTuning│initialized│blockInit │blockInit │
/// │Frequency │Update │Adjustment│Block │TickCap │Paused │ │ialTick │TickBlock │
/// │(64) │(32) │(32) │(32) │(24) │(1) │(1) │(24) │(32) │
/// └──────────┴──────────┴──────────┴─────────┴────────┴──────────┴───────────┴──────────┴──────────┘
/// Total: 64+32+32+32+24+1+1+24+32 = 242 bits
///
/// Field descriptions:
/// - capEventFrequency: Accumulated metric tracking how often cap events occur (PPM * seconds)
/// Increments by ONE_DAY_PPM on cap, decays linearly over time
/// - lastFrequencyUpdate: Timestamp when capEventFrequency was last updated (used for decay calc)
/// - lastCapAdjustment: Timestamp when currentTickCap was last auto-tuned
/// - lastCapBlock: Block number of last cap event (used in per-block mode to gate one event per block)
/// - currentTickCap: Current adaptive tick movement cap (auto-tuned between minTickCap and maxTickCap)
/// - autoTuningPaused: If true, auto-tuning is disabled (currentTickCap won't be adjusted)
/// - initialized: If true, pool has been initialized and runtime state is valid
/// - blockInitialTick: Tick at start of current block (latched on first finalizeSwap per block)
/// - blockInitialTickBlock: Block number when blockInitialTick was last set
struct RuntimeState {
uint64 capEventFrequency; // Cap frequency accumulator (PPM * seconds)
uint32 lastFrequencyUpdate; // Timestamp of last frequency update (seconds)
uint32 lastCapAdjustment; // Timestamp of last tick cap auto-tune (seconds)
uint32 lastCapBlock; // Last block number with cap event (per-block mode only)
uint24 currentTickCap; // Current adaptive tick movement cap (ticks)
bool autoTuningPaused; // Auto-tuning enabled/disabled flag
bool initialized; // Pool initialization flag
int24 blockInitialTick; // Tick at start of current block (for per-block cap detection)
uint32 blockInitialTickBlock; // Block number when blockInitialTick was last set
}
}
contracts/libraries/hook/CurrentSwapHookFeeCache.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { PoolId } from "@uniswap/v4-core/src/types/PoolId.sol";
import { BalanceDelta } from "@uniswap/v4-core/src/types/BalanceDelta.sol";
/// @notice Per-pool transient (EIP-1153) accumulator for the in-flight swap's hook fee.
/// @dev Strict invariant of the AegisHook deferred-accounting fix: the hook fee charged by the
/// CURRENT `_afterSwap` invocation is held here — NOT in `_pendingFees` — until after
/// `_tryReinvest` runs. That keeps the in-flight swap's own contribution out of the
/// pool of fees `_tryReinvest` is allowed to spend, which is necessary because the
/// underlying ERC20 backing the just-minted 6909 claim is not yet settled to PoolManager.
///
/// End-of-`_afterSwap` calls `consume` to read the accumulated delta AND clear the slot
/// atomically; the result is then folded into `_pendingFees` for consideration by the
/// next reinvest cycle.
///
/// SINGLE-ACTIVE-FRAME ASSUMPTION: this slot represents AT MOST ONE active swap frame
/// per pool at any time. Producer (`_chargeHookFee`) accumulates into the slot during
/// that frame's `_beforeSwap` / `_afterSwap`; consumer (`_afterSwap` end) drains and
/// clears it before that frame returns. The library does NOT implement stack-like
/// semantics: if a same-pool swap were to nest INSIDE the original swap's frame (e.g.,
/// a downstream callback initiating another swap on the same pool before the original's
/// `consume` runs), the nested frame's `add` would mix into the slot and its `consume`
/// would drain BOTH frames' fees — leaving the outer frame's `consume` reading zero and
/// its fee never flushing to `_pendingFees`.
///
/// Today this is safe because no AegisHook callback path (OracleManager, DynamicFeeManager,
/// LimitOrderManager) initiates a swap on the same pool. If that ever changes, this
/// library must be updated to either (a) gate against same-pool re-entry or (b) implement
/// a stack-like per-frame slot.
library CurrentSwapHookFeeCache {
// bytes32(uint256(keccak256("Aegis.CurrentSwapHookFee")) - 1)
bytes32 internal constant BASE_SLOT = 0xb23de3da0f71fd610efb091aa47680f79d3ffeda2078bc427b0f1ecd3c18ca48;
function slot(PoolId id) internal pure returns (bytes32 slotKey) {
slotKey = keccak256(abi.encodePacked(BASE_SLOT, PoolId.unwrap(id)));
}
/// @notice Accumulate `delta` into the per-pool transient slot.
function add(PoolId id, BalanceDelta delta) internal {
bytes32 slotKey = slot(id);
int256 packed;
assembly ("memory-safe") {
packed := tload(slotKey)
}
BalanceDelta updated = BalanceDelta.wrap(packed) + delta;
int256 newPacked = BalanceDelta.unwrap(updated);
assembly ("memory-safe") {
tstore(slotKey, newPacked)
}
}
/// @notice Read the accumulated delta and clear the slot atomically.
/// @return delta The accumulated `BalanceDelta`; `BalanceDelta.wrap(0)` if the slot was empty.
function consume(PoolId id) internal returns (BalanceDelta delta) {
bytes32 slotKey = slot(id);
int256 packed;
assembly ("memory-safe") {
packed := tload(slotKey)
}
delta = BalanceDelta.wrap(packed);
if (packed != 0) {
assembly ("memory-safe") {
tstore(slotKey, 0)
}
}
}
}
contracts/libraries/hook/HookRuntime.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { PoolId } from "@uniswap/v4-core/src/types/PoolId.sol";
import { PackedRuntime, PackedRuntimeLib } from "./PackedRuntime.sol";
/// @title HookRuntime
/// @notice Library for storing and loading swap runtime data in transient storage using EIP-1153
/// @dev Uses PackedRuntime to efficiently pack all runtime data into a single 256-bit slot
library HookRuntime {
using PackedRuntimeLib for PackedRuntime;
/// @notice Swap runtime data structure
struct Runtime {
uint24 dynamicFee;
int24 preSwapTick;
address sender;
}
/// @notice Store runtime data in transient storage
/// @dev Packs all data into a single tstore operation for gas efficiency
/// @param poolId The pool identifier to use as storage key
/// @param runtime The runtime data to store
function store(PoolId poolId, Runtime memory runtime) internal {
PackedRuntime packed = PackedRuntimeLib.pack(runtime.dynamicFee, runtime.preSwapTick, runtime.sender);
assembly {
tstore(poolId, packed)
}
}
/// @notice Load runtime data from transient storage
/// @dev Unpacks data from a single tload operation
/// @param poolId The pool identifier to use as storage key
/// @return runtime The unpacked runtime data
function load(PoolId poolId) internal view returns (Runtime memory runtime) {
PackedRuntime packed;
assembly {
packed := tload(poolId)
}
(runtime.dynamicFee, runtime.preSwapTick, runtime.sender) = packed.unpack();
}
}
contracts/libraries/hook/PackedRuntime.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice A packed representation of swap runtime data in a single 256-bit slot
/// @dev Layout: [unused 48 bits][dynamicFee 24 bits][preSwapTick 24 bits][sender 160 bits]
type PackedRuntime is bytes32;
/// @title PackedRuntimeLib
/// @notice Library for packing and unpacking swap runtime data into a single storage slot
library PackedRuntimeLib {
// Bit layout constants for packing/unpacking
uint256 private constant TICK_OFFSET = 160;
uint256 private constant FEE_OFFSET = 184;
/// @notice Pack runtime data into a single bytes32 value
/// @param fee The dynamic swap fee (24 bits)
/// @param tick The tick before the swap (24 bits, stored as int24)
/// @param sender_ The address that initiated the swap (160 bits)
/// @return packed The packed runtime data
function pack(uint24 fee, int24 tick, address sender_) internal pure returns (PackedRuntime packed) {
// forge-lint: disable-start(unsafe-typecast) -- casting is safe by construction: int24 → uint24, addresses fit in uint160
bytes32 data = bytes32(uint256(uint160(sender_))) | bytes32(uint256(uint24(tick)) << TICK_OFFSET)
| bytes32(uint256(fee) << FEE_OFFSET);
// forge-lint: disable-end
packed = PackedRuntime.wrap(data);
}
/// @notice Extract the dynamic fee from packed runtime data
/// @param packed The packed runtime data
/// @return The dynamic fee (24 bits)
function dynamicFee(PackedRuntime packed) internal pure returns (uint24) {
return uint24(uint256(PackedRuntime.unwrap(packed)) >> FEE_OFFSET);
}
/// @notice Extract the pre-swap tick from packed runtime data
/// @param packed The packed runtime data
/// @return The pre-swap tick (int24)
function preSwapTick(PackedRuntime packed) internal pure returns (int24) {
return int24(uint24(uint256(PackedRuntime.unwrap(packed)) >> TICK_OFFSET));
}
/// @notice Extract the sender address from packed runtime data
/// @param packed The packed runtime data
/// @return The sender address (160 bits)
function sender(PackedRuntime packed) internal pure returns (address) {
return address(uint160(uint256(PackedRuntime.unwrap(packed))));
}
/// @notice Unpack all runtime data at once
/// @param packed The packed runtime data
/// @return fee The dynamic fee
/// @return tick The pre-swap tick
/// @return sender_ The sender address
function unpack(PackedRuntime packed) internal pure returns (uint24 fee, int24 tick, address sender_) {
bytes32 data = PackedRuntime.unwrap(packed);
uint256 value = uint256(data);
// forge-lint: disable-start(unsafe-typecast) -- casting is safe: values are masked and within bounds
fee = uint24(value >> FEE_OFFSET);
tick = int24(uint24(value >> TICK_OFFSET));
sender_ = address(uint160(value));
// forge-lint: disable-end
}
}
contracts/types/AegisStructs.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Enumerates the supported NFT kinds a vault may custody.
enum NftKind {
CL_V4,
LO
}
/// @notice Lightweight reference to a custodied NFT.
/// @dev Packed into a single storage slot: uint8 kind + uint248 tokenId = 256 bits
struct NftRef {
NftKind kind;
uint248 tokenId;
}
dependencies/@openzeppelin-contracts-5.1.0/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
dependencies/@openzeppelin-contracts-5.1.0/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
dependencies/@openzeppelin-contracts-5.1.0/token/ERC721/IERC721Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.20;
/**
* @title ERC-721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC-721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be
* reverted.
*
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
dependencies/@openzeppelin-contracts-5.1.0/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
dependencies/@openzeppelin-contracts-5.1.0/utils/Pausable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
bool private _paused;
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
dependencies/@openzeppelin-contracts-5.1.0/utils/math/SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev An uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}
dependencies/v4-core-main/lib/solmate/src/utils/FixedPointMathLib.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)
library FixedPointMathLib {
/*//////////////////////////////////////////////////////////////
SIMPLIFIED FIXED POINT OPERATIONS
//////////////////////////////////////////////////////////////*/
uint256 internal constant MAX_UINT256 = 2**256 - 1;
uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.
function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.
}
function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.
}
function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.
}
function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.
}
/*//////////////////////////////////////////////////////////////
LOW LEVEL FIXED POINT OPERATIONS
//////////////////////////////////////////////////////////////*/
function mulDivDown(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))
if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {
revert(0, 0)
}
// Divide x * y by the denominator.
z := div(mul(x, y), denominator)
}
}
function mulDivUp(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))
if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {
revert(0, 0)
}
// If x * y modulo the denominator is strictly greater than 0,
// 1 is added to round up the division of x * y by the denominator.
z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator))
}
}
function rpow(
uint256 x,
uint256 n,
uint256 scalar
) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
switch x
case 0 {
switch n
case 0 {
// 0 ** 0 = 1
z := scalar
}
default {
// 0 ** n = 0
z := 0
}
}
default {
switch mod(n, 2)
case 0 {
// If n is even, store scalar in z for now.
z := scalar
}
default {
// If n is odd, store x in z for now.
z := x
}
// Shifting right by 1 is like dividing by 2.
let half := shr(1, scalar)
for {
// Shift n right by 1 before looping to halve it.
n := shr(1, n)
} n {
// Shift n right by 1 each iteration to halve it.
n := shr(1, n)
} {
// Revert immediately if x ** 2 would overflow.
// Equivalent to iszero(eq(div(xx, x), x)) here.
if shr(128, x) {
revert(0, 0)
}
// Store x squared.
let xx := mul(x, x)
// Round to the nearest number.
let xxRound := add(xx, half)
// Revert if xx + half overflowed.
if lt(xxRound, xx) {
revert(0, 0)
}
// Set x to scaled xxRound.
x := div(xxRound, scalar)
// If n is even:
if mod(n, 2) {
// Compute z * x.
let zx := mul(z, x)
// If z * x overflowed:
if iszero(eq(div(zx, x), z)) {
// Revert if x is non-zero.
if iszero(iszero(x)) {
revert(0, 0)
}
}
// Round to the nearest number.
let zxRound := add(zx, half)
// Revert if zx + half overflowed.
if lt(zxRound, zx) {
revert(0, 0)
}
// Return properly scaled zxRound.
z := div(zxRound, scalar)
}
}
}
}
}
/*//////////////////////////////////////////////////////////////
GENERAL NUMBER UTILITIES
//////////////////////////////////////////////////////////////*/
function sqrt(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
let y := x // We start y at x, which will help us make our initial estimate.
z := 181 // The "correct" value is 1, but this saves a multiplication later.
// This segment is to get a reasonable initial estimate for the Babylonian method. With a bad
// start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.
// We check y >= 2^(k + 8) but shift right by k bits
// each branch to ensure that if x >= 256, then y >= 256.
if iszero(lt(y, 0x10000000000000000000000000000000000)) {
y := shr(128, y)
z := shl(64, z)
}
if iszero(lt(y, 0x1000000000000000000)) {
y := shr(64, y)
z := shl(32, z)
}
if iszero(lt(y, 0x10000000000)) {
y := shr(32, y)
z := shl(16, z)
}
if iszero(lt(y, 0x1000000)) {
y := shr(16, y)
z := shl(8, z)
}
// Goal was to get z*z*y within a small factor of x. More iterations could
// get y in a tighter range. Currently, we will have y in [256, 256*2^16).
// We ensured y >= 256 so that the relative difference between y and y+1 is small.
// That's not possible if x < 256 but we can just verify those cases exhaustively.
// Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.
// Correctness can be checked exhaustively for x < 256, so we assume y >= 256.
// Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.
// For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range
// (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.
// Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate
// sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.
// There is no overflow risk here since y < 2^136 after the first branch above.
z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.
// Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
// If x+1 is a perfect square, the Babylonian method cycles between
// floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.
// See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
// Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.
// If you don't care whether the floor or ceil square root is returned, you can remove this statement.
z := sub(z, lt(div(x, z), z))
}
}
function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Mod x by y. Note this will return
// 0 instead of reverting if y is zero.
z := mod(x, y)
}
}
function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
// Divide x by y. Note this will return
// 0 instead of reverting if y is zero.
r := div(x, y)
}
}
function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Add 1 to x * y if x % y > 0. Note this will
// return 0 instead of reverting if y is zero.
z := add(gt(mod(x, y), 0), div(x, y))
}
}
}
dependencies/v4-core-main/src/interfaces/IExtsload.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Interface for functions to access any storage slot in a contract
interface IExtsload {
/// @notice Called by external contracts to access granular pool state
/// @param slot Key of slot to sload
/// @return value The value of the slot as bytes32
function extsload(bytes32 slot) external view returns (bytes32 value);
/// @notice Called by external contracts to access granular pool state
/// @param startSlot Key of slot to start sloading from
/// @param nSlots Number of slots to load into return value
/// @return values List of loaded values.
function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes32[] memory values);
/// @notice Called by external contracts to access sparse pool state
/// @param slots List of slots to SLOAD from.
/// @return values List of loaded values.
function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}
dependencies/v4-core-main/src/interfaces/IExttload.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/// @notice Interface for functions to access any transient storage slot in a contract
interface IExttload {
/// @notice Called by external contracts to access transient storage of the contract
/// @param slot Key of slot to tload
/// @return value The value of the slot as bytes32
function exttload(bytes32 slot) external view returns (bytes32 value);
/// @notice Called by external contracts to access sparse transient pool state
/// @param slots List of slots to tload
/// @return values List of loaded values
function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}
dependencies/v4-core-main/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);
}
dependencies/v4-core-main/src/interfaces/IPoolManager.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {Currency} from "../types/Currency.sol";
import {PoolKey} from "../types/PoolKey.sol";
import {IHooks} from "./IHooks.sol";
import {IERC6909Claims} from "./external/IERC6909Claims.sol";
import {IProtocolFees} from "./IProtocolFees.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {PoolId} from "../types/PoolId.sol";
import {IExtsload} from "./IExtsload.sol";
import {IExttload} from "./IExttload.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";
/// @notice Interface for the PoolManager
interface IPoolManager is IProtocolFees, IERC6909Claims, IExtsload, IExttload {
/// @notice Thrown when a currency is not netted out after the contract is unlocked
error CurrencyNotSettled();
/// @notice Thrown when trying to interact with a non-initialized pool
error PoolNotInitialized();
/// @notice Thrown when unlock is called, but the contract is already unlocked
error AlreadyUnlocked();
/// @notice Thrown when a function is called that requires the contract to be unlocked, but it is not
error ManagerLocked();
/// @notice Pools are limited to type(int16).max tickSpacing in #initialize, to prevent overflow
error TickSpacingTooLarge(int24 tickSpacing);
/// @notice Pools must have a positive non-zero tickSpacing passed to #initialize
error TickSpacingTooSmall(int24 tickSpacing);
/// @notice PoolKey must have currencies where address(currency0) < address(currency1)
error CurrenciesOutOfOrderOrEqual(address currency0, address currency1);
/// @notice Thrown when a call to updateDynamicLPFee is made by an address that is not the hook,
/// or on a pool that does not have a dynamic swap fee.
error UnauthorizedDynamicLPFeeUpdate();
/// @notice Thrown when trying to swap amount of 0
error SwapAmountCannotBeZero();
///@notice Thrown when native currency is passed to a non native settlement
error NonzeroNativeValue();
/// @notice Thrown when `clear` is called with an amount that is not exactly equal to the open currency delta.
error MustClearExactPositiveDelta();
/// @notice Emitted when a new pool is initialized
/// @param id The abi encoded hash of the pool key struct for the new pool
/// @param currency0 The first currency of the pool by address sort order
/// @param currency1 The second currency of the pool by address sort order
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @param tickSpacing The minimum number of ticks between initialized ticks
/// @param hooks The hooks contract address for the pool, or address(0) if none
/// @param sqrtPriceX96 The price of the pool on initialization
/// @param tick The initial tick of the pool corresponding to the initialized price
event Initialize(
PoolId indexed id,
Currency indexed currency0,
Currency indexed currency1,
uint24 fee,
int24 tickSpacing,
IHooks hooks,
uint160 sqrtPriceX96,
int24 tick
);
/// @notice Emitted when a liquidity position is modified
/// @param id The abi encoded hash of the pool key struct for the pool that was modified
/// @param sender The address that modified the pool
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param liquidityDelta The amount of liquidity that was added or removed
/// @param salt The extra data to make positions unique
event ModifyLiquidity(
PoolId indexed id, address indexed sender, int24 tickLower, int24 tickUpper, int256 liquidityDelta, bytes32 salt
);
/// @notice Emitted for swaps between currency0 and currency1
/// @param id The abi encoded hash of the pool key struct for the pool that was modified
/// @param sender The address that initiated the swap call, and that received the callback
/// @param amount0 The delta of the currency0 balance of the pool
/// @param amount1 The delta of the currency1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of the price of the pool after the swap
/// @param fee The swap fee in hundredths of a bip
event Swap(
PoolId indexed id,
address indexed sender,
int128 amount0,
int128 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick,
uint24 fee
);
/// @notice Emitted for donations
/// @param id The abi encoded hash of the pool key struct for the pool that was donated to
/// @param sender The address that initiated the donate call
/// @param amount0 The amount donated in currency0
/// @param amount1 The amount donated in currency1
event Donate(PoolId indexed id, address indexed sender, uint256 amount0, uint256 amount1);
/// @notice All interactions on the contract that account deltas require unlocking. A caller that calls `unlock` must implement
/// `IUnlockCallback(msg.sender).unlockCallback(data)`, where they interact with the remaining functions on this contract.
/// @dev The only functions callable without an unlocking are `initialize` and `updateDynamicLPFee`
/// @param data Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)`
/// @return The data returned by the call to `IUnlockCallback(msg.sender).unlockCallback(data)`
function unlock(bytes calldata data) external returns (bytes memory);
/// @notice Initialize the state for a given pool ID
/// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
/// @param key The pool key for the pool to initialize
/// @param sqrtPriceX96 The initial square root price
/// @return tick The initial tick of the pool
function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick);
/// @notice Modify the liquidity for the given pool
/// @dev Poke by calling with a zero liquidityDelta
/// @param key The pool to modify liquidity in
/// @param params The parameters for modifying the liquidity
/// @param hookData The data to pass through to the add/removeLiquidity hooks
/// @return callerDelta The balance delta of the caller of modifyLiquidity. This is the total of both principal, fee deltas, and hook deltas if applicable
/// @return feesAccrued The balance delta of the fees generated in the liquidity range. Returned for informational purposes
/// @dev Note that feesAccrued can be artificially inflated by a malicious actor and integrators should be careful using the value
/// For pools with a single liquidity position, actors can donate to themselves to inflate feeGrowthGlobal (and consequently feesAccrued)
/// atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme
function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData)
external
returns (BalanceDelta callerDelta, BalanceDelta feesAccrued);
/// @notice Swap against the given pool
/// @param key The pool to swap in
/// @param params The parameters for swapping
/// @param hookData The data to pass through to the swap hooks
/// @return swapDelta The balance delta of the address swapping
/// @dev Swapping on low liquidity pools may cause unexpected swap amounts when liquidity available is less than amountSpecified.
/// Additionally note that if interacting with hooks that have the BEFORE_SWAP_RETURNS_DELTA_FLAG or AFTER_SWAP_RETURNS_DELTA_FLAG
/// the hook may alter the swap input/output. Integrators should perform checks on the returned swapDelta.
function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData)
external
returns (BalanceDelta swapDelta);
/// @notice Donate the given currency amounts to the in-range liquidity providers of a pool
/// @dev Calls to donate can be frontrun adding just-in-time liquidity, with the aim of receiving a portion donated funds.
/// Donors should keep this in mind when designing donation mechanisms.
/// @dev This function donates to in-range LPs at slot0.tick. In certain edge-cases of the swap algorithm, the `sqrtPrice` of
/// a pool can be at the lower boundary of tick `n`, but the `slot0.tick` of the pool is already `n - 1`. In this case a call to
/// `donate` would donate to tick `n - 1` (slot0.tick) not tick `n` (getTickAtSqrtPrice(slot0.sqrtPriceX96)).
/// Read the comments in `Pool.swap()` for more information about this.
/// @param key The key of the pool to donate to
/// @param amount0 The amount of currency0 to donate
/// @param amount1 The amount of currency1 to donate
/// @param hookData The data to pass through to the donate hooks
/// @return BalanceDelta The delta of the caller after the donate
function donate(PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
external
returns (BalanceDelta);
/// @notice Writes the current ERC20 balance of the specified currency to transient storage
/// This is used to checkpoint balances for the manager and derive deltas for the caller.
/// @dev This MUST be called before any ERC20 tokens are sent into the contract, but can be skipped
/// for native tokens because the amount to settle is determined by the sent value.
/// However, if an ERC20 token has been synced and not settled, and the caller instead wants to settle
/// native funds, this function can be called with the native currency to then be able to settle the native currency
function sync(Currency currency) external;
/// @notice Called by the user to net out some value owed to the user
/// @dev Will revert if the requested amount is not available, consider using `mint` instead
/// @dev Can also be used as a mechanism for free flash loans
/// @param currency The currency to withdraw from the pool manager
/// @param to The address to withdraw to
/// @param amount The amount of currency to withdraw
function take(Currency currency, address to, uint256 amount) external;
/// @notice Called by the user to pay what is owed
/// @return paid The amount of currency settled
function settle() external payable returns (uint256 paid);
/// @notice Called by the user to pay on behalf of another address
/// @param recipient The address to credit for the payment
/// @return paid The amount of currency settled
function settleFor(address recipient) external payable returns (uint256 paid);
/// @notice WARNING - Any currency that is cleared, will be non-retrievable, and locked in the contract permanently.
/// A call to clear will zero out a positive balance WITHOUT a corresponding transfer.
/// @dev This could be used to clear a balance that is considered dust.
/// Additionally, the amount must be the exact positive balance. This is to enforce that the caller is aware of the amount being cleared.
function clear(Currency currency, uint256 amount) external;
/// @notice Called by the user to move value into ERC6909 balance
/// @param to The address to mint the tokens to
/// @param id The currency address to mint to ERC6909s, as a uint256
/// @param amount The amount of currency to mint
/// @dev The id is converted to a uint160 to correspond to a currency address
/// If the upper 12 bytes are not 0, they will be 0-ed out
function mint(address to, uint256 id, uint256 amount) external;
/// @notice Called by the user to move value from ERC6909 balance
/// @param from The address to burn the tokens from
/// @param id The currency address to burn from ERC6909s, as a uint256
/// @param amount The amount of currency to burn
/// @dev The id is converted to a uint160 to correspond to a currency address
/// If the upper 12 bytes are not 0, they will be 0-ed out
function burn(address from, uint256 id, uint256 amount) external;
/// @notice Updates the pools lp fees for the a pool that has enabled dynamic lp fees.
/// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
/// @param key The key of the pool to update dynamic LP fees for
/// @param newDynamicLPFee The new dynamic pool LP fee
function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external;
}
dependencies/v4-core-main/src/interfaces/IProtocolFees.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "../types/Currency.sol";
import {PoolId} from "../types/PoolId.sol";
import {PoolKey} from "../types/PoolKey.sol";
/// @notice Interface for all protocol-fee related functions in the pool manager
interface IProtocolFees {
/// @notice Thrown when protocol fee is set too high
error ProtocolFeeTooLarge(uint24 fee);
/// @notice Thrown when collectProtocolFees or setProtocolFee is not called by the controller.
error InvalidCaller();
/// @notice Thrown when collectProtocolFees is attempted on a token that is synced.
error ProtocolFeeCurrencySynced();
/// @notice Emitted when the protocol fee controller address is updated in setProtocolFeeController.
event ProtocolFeeControllerUpdated(address indexed protocolFeeController);
/// @notice Emitted when the protocol fee is updated for a pool.
event ProtocolFeeUpdated(PoolId indexed id, uint24 protocolFee);
/// @notice Given a currency address, returns the protocol fees accrued in that currency
/// @param currency The currency to check
/// @return amount The amount of protocol fees accrued in the currency
function protocolFeesAccrued(Currency currency) external view returns (uint256 amount);
/// @notice Sets the protocol fee for the given pool
/// @param key The key of the pool to set a protocol fee for
/// @param newProtocolFee The fee to set
function setProtocolFee(PoolKey memory key, uint24 newProtocolFee) external;
/// @notice Sets the protocol fee controller
/// @param controller The new protocol fee controller
function setProtocolFeeController(address controller) external;
/// @notice Collects the protocol fees for a given recipient and currency, returning the amount collected
/// @dev This will revert if the contract is unlocked
/// @param recipient The address to receive the protocol fees
/// @param currency The currency to withdraw
/// @param amount The amount of currency to withdraw
/// @return amountCollected The amount of currency successfully withdrawn
function collectProtocolFees(address recipient, Currency currency, uint256 amount)
external
returns (uint256 amountCollected);
/// @notice Returns the current protocol fee controller address
/// @return address The current protocol fee controller address
function protocolFeeController() external view returns (address);
}
dependencies/v4-core-main/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);
}
dependencies/v4-core-main/src/interfaces/external/IERC6909Claims.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Interface for claims over a contract balance, wrapped as a ERC6909
interface IERC6909Claims {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event OperatorSet(address indexed owner, address indexed operator, bool approved);
event Approval(address indexed owner, address indexed spender, uint256 indexed id, uint256 amount);
event Transfer(address caller, address indexed from, address indexed to, uint256 indexed id, uint256 amount);
/*//////////////////////////////////////////////////////////////
FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @notice Owner balance of an id.
/// @param owner The address of the owner.
/// @param id The id of the token.
/// @return amount The balance of the token.
function balanceOf(address owner, uint256 id) external view returns (uint256 amount);
/// @notice Spender allowance of an id.
/// @param owner The address of the owner.
/// @param spender The address of the spender.
/// @param id The id of the token.
/// @return amount The allowance of the token.
function allowance(address owner, address spender, uint256 id) external view returns (uint256 amount);
/// @notice Checks if a spender is approved by an owner as an operator
/// @param owner The address of the owner.
/// @param spender The address of the spender.
/// @return approved The approval status.
function isOperator(address owner, address spender) external view returns (bool approved);
/// @notice Transfers an amount of an id from the caller to a receiver.
/// @param receiver The address of the receiver.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always, unless the function reverts
function transfer(address receiver, uint256 id, uint256 amount) external returns (bool);
/// @notice Transfers an amount of an id from a sender to a receiver.
/// @param sender The address of the sender.
/// @param receiver The address of the receiver.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always, unless the function reverts
function transferFrom(address sender, address receiver, uint256 id, uint256 amount) external returns (bool);
/// @notice Approves an amount of an id to a spender.
/// @param spender The address of the spender.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always
function approve(address spender, uint256 id, uint256 amount) external returns (bool);
/// @notice Sets or removes an operator for the caller.
/// @param operator The address of the operator.
/// @param approved The approval status.
/// @return bool True, always
function setOperator(address operator, bool approved) external returns (bool);
}
dependencies/v4-core-main/src/libraries/BitMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title BitMath
/// @dev This library provides functionality for computing bit properties of an unsigned integer
/// @author Solady (https://github.com/Vectorized/solady/blob/8200a70e8dc2a77ecb074fc2e99a2a0d36547522/src/utils/LibBit.sol)
library BitMath {
/// @notice Returns the index of the most significant bit of the number,
/// where the least significant bit is at index 0 and the most significant bit is at index 255
/// @param x the value for which to compute the most significant bit, must be greater than 0
/// @return r the index of the most significant bit
function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0);
assembly ("memory-safe") {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// forgefmt: disable-next-item
r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020500060203020504000106050205030304010505030400000000))
}
}
/// @notice Returns the index of the least significant bit of the number,
/// where the least significant bit is at index 0 and the most significant bit is at index 255
/// @param x the value for which to compute the least significant bit, must be greater than 0
/// @return r the index of the least significant bit
function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0);
assembly ("memory-safe") {
// Isolate the least significant bit.
x := and(x, sub(0, x))
// For the upper 3 bits of the result, use a De Bruijn-like lookup.
// Credit to adhusson: https://blog.adhusson.com/cheap-find-first-set-evm/
// forgefmt: disable-next-item
r := shl(5, shr(252, shl(shl(2, shr(250, mul(x,
0xb6db6db6ddddddddd34d34d349249249210842108c6318c639ce739cffffffff))),
0x8040405543005266443200005020610674053026020000107506200176117077)))
// For the lower 5 bits of the result, use a De Bruijn lookup.
// forgefmt: disable-next-item
r := or(r, byte(and(div(0xd76453e0, shr(r, x)), 0x1f),
0x001f0d1e100c1d070f090b19131c1706010e11080a1a141802121b1503160405))
}
}
}
dependencies/v4-core-main/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))
}
}
}
dependencies/v4-core-main/src/libraries/FixedPoint128.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title FixedPoint128
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
library FixedPoint128 {
uint256 internal constant Q128 = 0x100000000000000000000000000000000;
}
dependencies/v4-core-main/src/libraries/FixedPoint96.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
dependencies/v4-core-main/src/libraries/FullMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0 = a * b; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
assembly ("memory-safe") {
result := div(prod0, denominator)
}
return result;
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly ("memory-safe") {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly ("memory-safe") {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = (0 - denominator) & denominator;
// Divide denominator by power of two
assembly ("memory-safe") {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly ("memory-safe") {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly ("memory-safe") {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the preconditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) != 0) {
require(++result > 0);
}
}
}
}
dependencies/v4-core-main/src/libraries/Hooks.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "../types/PoolKey.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {SafeCast} from "./SafeCast.sol";
import {LPFeeLibrary} from "./LPFeeLibrary.sol";
import {BalanceDelta, toBalanceDelta, BalanceDeltaLibrary} from "../types/BalanceDelta.sol";
import {BeforeSwapDelta, BeforeSwapDeltaLibrary} from "../types/BeforeSwapDelta.sol";
import {IPoolManager} from "../interfaces/IPoolManager.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";
import {ParseBytes} from "./ParseBytes.sol";
import {CustomRevert} from "./CustomRevert.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.
library Hooks {
using LPFeeLibrary for uint24;
using Hooks for IHooks;
using SafeCast for int256;
using BeforeSwapDeltaLibrary for BeforeSwapDelta;
using ParseBytes for bytes;
using CustomRevert for bytes4;
uint160 internal constant ALL_HOOK_MASK = uint160((1 << 14) - 1);
uint160 internal constant BEFORE_INITIALIZE_FLAG = 1 << 13;
uint160 internal constant AFTER_INITIALIZE_FLAG = 1 << 12;
uint160 internal constant BEFORE_ADD_LIQUIDITY_FLAG = 1 << 11;
uint160 internal constant AFTER_ADD_LIQUIDITY_FLAG = 1 << 10;
uint160 internal constant BEFORE_REMOVE_LIQUIDITY_FLAG = 1 << 9;
uint160 internal constant AFTER_REMOVE_LIQUIDITY_FLAG = 1 << 8;
uint160 internal constant BEFORE_SWAP_FLAG = 1 << 7;
uint160 internal constant AFTER_SWAP_FLAG = 1 << 6;
uint160 internal constant BEFORE_DONATE_FLAG = 1 << 5;
uint160 internal constant AFTER_DONATE_FLAG = 1 << 4;
uint160 internal constant BEFORE_SWAP_RETURNS_DELTA_FLAG = 1 << 3;
uint160 internal constant AFTER_SWAP_RETURNS_DELTA_FLAG = 1 << 2;
uint160 internal constant AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 1;
uint160 internal constant AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 0;
struct Permissions {
bool beforeInitialize;
bool afterInitialize;
bool beforeAddLiquidity;
bool afterAddLiquidity;
bool beforeRemoveLiquidity;
bool afterRemoveLiquidity;
bool beforeSwap;
bool afterSwap;
bool beforeDonate;
bool afterDonate;
bool beforeSwapReturnDelta;
bool afterSwapReturnDelta;
bool afterAddLiquidityReturnDelta;
bool afterRemoveLiquidityReturnDelta;
}
/// @notice Thrown if the address will not lead to the specified hook calls being called
/// @param hooks The address of the hooks contract
error HookAddressNotValid(address hooks);
/// @notice Hook did not return its selector
error InvalidHookResponse();
/// @notice Additional context for ERC-7751 wrapped error when a hook call fails
error HookCallFailed();
/// @notice The hook's delta changed the swap from exactIn to exactOut or vice versa
error HookDeltaExceedsSwapAmount();
/// @notice Utility function intended to be used in hook constructors to ensure
/// the deployed hooks address causes the intended hooks to be called
/// @param permissions The hooks that are intended to be called
/// @dev permissions param is memory as the function will be called from constructors
function validateHookPermissions(IHooks self, Permissions memory permissions) internal pure {
if (
permissions.beforeInitialize != self.hasPermission(BEFORE_INITIALIZE_FLAG)
|| permissions.afterInitialize != self.hasPermission(AFTER_INITIALIZE_FLAG)
|| permissions.beforeAddLiquidity != self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG)
|| permissions.afterAddLiquidity != self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG)
|| permissions.beforeRemoveLiquidity != self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG)
|| permissions.afterRemoveLiquidity != self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)
|| permissions.beforeSwap != self.hasPermission(BEFORE_SWAP_FLAG)
|| permissions.afterSwap != self.hasPermission(AFTER_SWAP_FLAG)
|| permissions.beforeDonate != self.hasPermission(BEFORE_DONATE_FLAG)
|| permissions.afterDonate != self.hasPermission(AFTER_DONATE_FLAG)
|| permissions.beforeSwapReturnDelta != self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)
|| permissions.afterSwapReturnDelta != self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)
|| permissions.afterAddLiquidityReturnDelta != self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG)
|| permissions.afterRemoveLiquidityReturnDelta
!= self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
) {
HookAddressNotValid.selector.revertWith(address(self));
}
}
/// @notice Ensures that the hook address includes at least one hook flag or dynamic fees, or is the 0 address
/// @param self The hook to verify
/// @param fee The fee of the pool the hook is used with
/// @return bool True if the hook address is valid
function isValidHookAddress(IHooks self, uint24 fee) internal pure returns (bool) {
// The hook can only have a flag to return a hook delta on an action if it also has the corresponding action flag
if (!self.hasPermission(BEFORE_SWAP_FLAG) && self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) return false;
if (!self.hasPermission(AFTER_SWAP_FLAG) && self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)) return false;
if (!self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG) && self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG))
{
return false;
}
if (
!self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)
&& self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
) return false;
// If there is no hook contract set, then fee cannot be dynamic
// If a hook contract is set, it must have at least 1 flag set, or have a dynamic fee
return address(self) == address(0)
? !fee.isDynamicFee()
: (uint160(address(self)) & ALL_HOOK_MASK > 0 || fee.isDynamicFee());
}
/// @notice performs a hook call using the given calldata on the given hook that doesn't return a delta
/// @return result The complete data returned by the hook
function callHook(IHooks self, bytes memory data) internal returns (bytes memory result) {
bool success;
assembly ("memory-safe") {
success := call(gas(), self, 0, add(data, 0x20), mload(data), 0, 0)
}
// Revert with FailedHookCall, containing any error message to bubble up
if (!success) CustomRevert.bubbleUpAndRevertWith(address(self), bytes4(data), HookCallFailed.selector);
// The call was successful, fetch the returned data
assembly ("memory-safe") {
// allocate result byte array from the free memory pointer
result := mload(0x40)
// store new free memory pointer at the end of the array padded to 32 bytes
mstore(0x40, add(result, and(add(returndatasize(), 0x3f), not(0x1f))))
// store length in memory
mstore(result, returndatasize())
// copy return data to result
returndatacopy(add(result, 0x20), 0, returndatasize())
}
// Length must be at least 32 to contain the selector. Check expected selector and returned selector match.
if (result.length < 32 || result.parseSelector() != data.parseSelector()) {
InvalidHookResponse.selector.revertWith();
}
}
/// @notice performs a hook call using the given calldata on the given hook
/// @return int256 The delta returned by the hook
function callHookWithReturnDelta(IHooks self, bytes memory data, bool parseReturn) internal returns (int256) {
bytes memory result = callHook(self, data);
// If this hook wasn't meant to return something, default to 0 delta
if (!parseReturn) return 0;
// A length of 64 bytes is required to return a bytes4, and a 32 byte delta
if (result.length != 64) InvalidHookResponse.selector.revertWith();
return result.parseReturnDelta();
}
/// @notice modifier to prevent calling a hook if they initiated the action
modifier noSelfCall(IHooks self) {
if (msg.sender != address(self)) {
_;
}
}
/// @notice calls beforeInitialize hook if permissioned and validates return value
function beforeInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96) internal noSelfCall(self) {
if (self.hasPermission(BEFORE_INITIALIZE_FLAG)) {
self.callHook(abi.encodeCall(IHooks.beforeInitialize, (msg.sender, key, sqrtPriceX96)));
}
}
/// @notice calls afterInitialize hook if permissioned and validates return value
function afterInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96, int24 tick)
internal
noSelfCall(self)
{
if (self.hasPermission(AFTER_INITIALIZE_FLAG)) {
self.callHook(abi.encodeCall(IHooks.afterInitialize, (msg.sender, key, sqrtPriceX96, tick)));
}
}
/// @notice calls beforeModifyLiquidity hook if permissioned and validates return value
function beforeModifyLiquidity(
IHooks self,
PoolKey memory key,
ModifyLiquidityParams memory params,
bytes calldata hookData
) internal noSelfCall(self) {
if (params.liquidityDelta > 0 && self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG)) {
self.callHook(abi.encodeCall(IHooks.beforeAddLiquidity, (msg.sender, key, params, hookData)));
} else if (params.liquidityDelta <= 0 && self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG)) {
self.callHook(abi.encodeCall(IHooks.beforeRemoveLiquidity, (msg.sender, key, params, hookData)));
}
}
/// @notice calls afterModifyLiquidity hook if permissioned and validates return value
function afterModifyLiquidity(
IHooks self,
PoolKey memory key,
ModifyLiquidityParams memory params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) internal returns (BalanceDelta callerDelta, BalanceDelta hookDelta) {
if (msg.sender == address(self)) return (delta, BalanceDeltaLibrary.ZERO_DELTA);
callerDelta = delta;
if (params.liquidityDelta > 0) {
if (self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG)) {
hookDelta = BalanceDelta.wrap(
self.callHookWithReturnDelta(
abi.encodeCall(
IHooks.afterAddLiquidity, (msg.sender, key, params, delta, feesAccrued, hookData)
),
self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG)
)
);
callerDelta = callerDelta - hookDelta;
}
} else {
if (self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)) {
hookDelta = BalanceDelta.wrap(
self.callHookWithReturnDelta(
abi.encodeCall(
IHooks.afterRemoveLiquidity, (msg.sender, key, params, delta, feesAccrued, hookData)
),
self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
)
);
callerDelta = callerDelta - hookDelta;
}
}
}
/// @notice calls beforeSwap hook if permissioned and validates return value
function beforeSwap(IHooks self, PoolKey memory key, SwapParams memory params, bytes calldata hookData)
internal
returns (int256 amountToSwap, BeforeSwapDelta hookReturn, uint24 lpFeeOverride)
{
amountToSwap = params.amountSpecified;
if (msg.sender == address(self)) return (amountToSwap, BeforeSwapDeltaLibrary.ZERO_DELTA, lpFeeOverride);
if (self.hasPermission(BEFORE_SWAP_FLAG)) {
bytes memory result = callHook(self, abi.encodeCall(IHooks.beforeSwap, (msg.sender, key, params, hookData)));
// A length of 96 bytes is required to return a bytes4, a 32 byte delta, and an LP fee
if (result.length != 96) InvalidHookResponse.selector.revertWith();
// dynamic fee pools that want to override the cache fee, return a valid fee with the override flag. If override flag
// is set but an invalid fee is returned, the transaction will revert. Otherwise the current LP fee will be used
if (key.fee.isDynamicFee()) lpFeeOverride = result.parseFee();
// skip this logic for the case where the hook return is 0
if (self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) {
hookReturn = BeforeSwapDelta.wrap(result.parseReturnDelta());
// any return in unspecified is passed to the afterSwap hook for handling
int128 hookDeltaSpecified = hookReturn.getSpecifiedDelta();
// Update the swap amount according to the hook's return, and check that the swap type doesn't change (exact input/output)
if (hookDeltaSpecified != 0) {
bool exactInput = amountToSwap < 0;
amountToSwap += hookDeltaSpecified;
if (exactInput ? amountToSwap > 0 : amountToSwap < 0) {
HookDeltaExceedsSwapAmount.selector.revertWith();
}
}
}
}
}
/// @notice calls afterSwap hook if permissioned and validates return value
function afterSwap(
IHooks self,
PoolKey memory key,
SwapParams memory params,
BalanceDelta swapDelta,
bytes calldata hookData,
BeforeSwapDelta beforeSwapHookReturn
) internal returns (BalanceDelta, BalanceDelta) {
if (msg.sender == address(self)) return (swapDelta, BalanceDeltaLibrary.ZERO_DELTA);
int128 hookDeltaSpecified = beforeSwapHookReturn.getSpecifiedDelta();
int128 hookDeltaUnspecified = beforeSwapHookReturn.getUnspecifiedDelta();
if (self.hasPermission(AFTER_SWAP_FLAG)) {
hookDeltaUnspecified += self.callHookWithReturnDelta(
abi.encodeCall(IHooks.afterSwap, (msg.sender, key, params, swapDelta, hookData)),
self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)
).toInt128();
}
BalanceDelta hookDelta;
if (hookDeltaUnspecified != 0 || hookDeltaSpecified != 0) {
hookDelta = (params.amountSpecified < 0 == params.zeroForOne)
? toBalanceDelta(hookDeltaSpecified, hookDeltaUnspecified)
: toBalanceDelta(hookDeltaUnspecified, hookDeltaSpecified);
// the caller has to pay for (or receive) the hook's delta
swapDelta = swapDelta - hookDelta;
}
return (swapDelta, hookDelta);
}
/// @notice calls beforeDonate hook if permissioned and validates return value
function beforeDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
internal
noSelfCall(self)
{
if (self.hasPermission(BEFORE_DONATE_FLAG)) {
self.callHook(abi.encodeCall(IHooks.beforeDonate, (msg.sender, key, amount0, amount1, hookData)));
}
}
/// @notice calls afterDonate hook if permissioned and validates return value
function afterDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
internal
noSelfCall(self)
{
if (self.hasPermission(AFTER_DONATE_FLAG)) {
self.callHook(abi.encodeCall(IHooks.afterDonate, (msg.sender, key, amount0, amount1, hookData)));
}
}
function hasPermission(IHooks self, uint160 flag) internal pure returns (bool) {
return uint160(address(self)) & flag != 0;
}
}
dependencies/v4-core-main/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();
}
}
dependencies/v4-core-main/src/libraries/LiquidityMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Math library for liquidity
library LiquidityMath {
/// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows
/// @param x The liquidity before change
/// @param y The delta by which liquidity should be changed
/// @return z The liquidity delta
function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {
assembly ("memory-safe") {
z := add(and(x, 0xffffffffffffffffffffffffffffffff), signextend(15, y))
if shr(128, z) {
// revert SafeCastOverflow()
mstore(0, 0x93dafdf1)
revert(0x1c, 0x04)
}
}
}
}
dependencies/v4-core-main/src/libraries/ParseBytes.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Parses bytes returned from hooks and the byte selector used to check return selectors from hooks.
/// @dev parseSelector also is used to parse the expected selector
/// For parsing hook returns, note that all hooks return either bytes4 or (bytes4, 32-byte-delta) or (bytes4, 32-byte-delta, uint24).
library ParseBytes {
function parseSelector(bytes memory result) internal pure returns (bytes4 selector) {
// equivalent: (selector,) = abi.decode(result, (bytes4, int256));
assembly ("memory-safe") {
selector := mload(add(result, 0x20))
}
}
function parseFee(bytes memory result) internal pure returns (uint24 lpFee) {
// equivalent: (,, lpFee) = abi.decode(result, (bytes4, int256, uint24));
assembly ("memory-safe") {
lpFee := mload(add(result, 0x60))
}
}
function parseReturnDelta(bytes memory result) internal pure returns (int256 hookReturn) {
// equivalent: (, hookReturnDelta) = abi.decode(result, (bytes4, int256));
assembly ("memory-safe") {
hookReturn := mload(add(result, 0x40))
}
}
}
dependencies/v4-core-main/src/libraries/Position.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import {FullMath} from "./FullMath.sol";
import {FixedPoint128} from "./FixedPoint128.sol";
import {LiquidityMath} from "./LiquidityMath.sol";
import {CustomRevert} from "./CustomRevert.sol";
/// @title Position
/// @notice Positions represent an owner address' liquidity between a lower and upper tick boundary
/// @dev Positions store additional state for tracking fees owed to the position
library Position {
using CustomRevert for bytes4;
/// @notice Cannot update a position with no liquidity
error CannotUpdateEmptyPosition();
// info stored for each user's position
struct State {
// the amount of liquidity owned by this position
uint128 liquidity;
// fee growth per unit of liquidity as of the last update to liquidity or fees owed
uint256 feeGrowthInside0LastX128;
uint256 feeGrowthInside1LastX128;
}
/// @notice Returns the State struct of a position, given an owner and position boundaries
/// @param self The mapping containing all user positions
/// @param owner The address of the position owner
/// @param tickLower The lower tick boundary of the position
/// @param tickUpper The upper tick boundary of the position
/// @param salt A unique value to differentiate between multiple positions in the same range
/// @return position The position info struct of the given owners' position
function get(mapping(bytes32 => State) storage self, address owner, int24 tickLower, int24 tickUpper, bytes32 salt)
internal
view
returns (State storage position)
{
bytes32 positionKey = calculatePositionKey(owner, tickLower, tickUpper, salt);
position = self[positionKey];
}
/// @notice A helper function to calculate the position key
/// @param owner The address of the position owner
/// @param tickLower the lower tick boundary of the position
/// @param tickUpper the upper tick boundary of the position
/// @param salt A unique value to differentiate between multiple positions in the same range, by the same owner. Passed in by the caller.
function calculatePositionKey(address owner, int24 tickLower, int24 tickUpper, bytes32 salt)
internal
pure
returns (bytes32 positionKey)
{
// positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt))
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(add(fmp, 0x26), salt) // [0x26, 0x46)
mstore(add(fmp, 0x06), tickUpper) // [0x23, 0x26)
mstore(add(fmp, 0x03), tickLower) // [0x20, 0x23)
mstore(fmp, owner) // [0x0c, 0x20)
positionKey := keccak256(add(fmp, 0x0c), 0x3a) // len is 58 bytes
// now clean the memory we used
mstore(add(fmp, 0x40), 0) // fmp+0x40 held salt
mstore(add(fmp, 0x20), 0) // fmp+0x20 held tickLower, tickUpper, salt
mstore(fmp, 0) // fmp held owner
}
}
/// @notice Credits accumulated fees to a user's position
/// @param self The individual position to update
/// @param liquidityDelta The change in pool liquidity as a result of the position update
/// @param feeGrowthInside0X128 The all-time fee growth in currency0, per unit of liquidity, inside the position's tick boundaries
/// @param feeGrowthInside1X128 The all-time fee growth in currency1, per unit of liquidity, inside the position's tick boundaries
/// @return feesOwed0 The amount of currency0 owed to the position owner
/// @return feesOwed1 The amount of currency1 owed to the position owner
function update(
State storage self,
int128 liquidityDelta,
uint256 feeGrowthInside0X128,
uint256 feeGrowthInside1X128
) internal returns (uint256 feesOwed0, uint256 feesOwed1) {
uint128 liquidity = self.liquidity;
if (liquidityDelta == 0) {
// disallow pokes for 0 liquidity positions
if (liquidity == 0) CannotUpdateEmptyPosition.selector.revertWith();
} else {
self.liquidity = LiquidityMath.addDelta(liquidity, liquidityDelta);
}
// calculate accumulated fees. overflow in the subtraction of fee growth is expected
unchecked {
feesOwed0 =
FullMath.mulDiv(feeGrowthInside0X128 - self.feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128);
feesOwed1 =
FullMath.mulDiv(feeGrowthInside1X128 - self.feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128);
}
// update the position
self.feeGrowthInside0LastX128 = feeGrowthInside0X128;
self.feeGrowthInside1LastX128 = feeGrowthInside1X128;
}
}
dependencies/v4-core-main/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));
}
}
dependencies/v4-core-main/src/libraries/SqrtPriceMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {SafeCast} from "./SafeCast.sol";
import {FullMath} from "./FullMath.sol";
import {UnsafeMath} from "./UnsafeMath.sol";
import {FixedPoint96} from "./FixedPoint96.sol";
/// @title Functions based on Q64.96 sqrt price and liquidity
/// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas
library SqrtPriceMath {
using SafeCast for uint256;
error InvalidPriceOrLiquidity();
error InvalidPrice();
error NotEnoughLiquidity();
error PriceOverflow();
/// @notice Gets the next sqrt price given a delta of currency0
/// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least
/// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the
/// price less in order to not send too much output.
/// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96),
/// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount).
/// @param sqrtPX96 The starting price, i.e. before accounting for the currency0 delta
/// @param liquidity The amount of usable liquidity
/// @param amount How much of currency0 to add or remove from virtual reserves
/// @param add Whether to add or remove the amount of currency0
/// @return The price after adding or removing amount, depending on add
function getNextSqrtPriceFromAmount0RoundingUp(uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add)
internal
pure
returns (uint160)
{
// we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price
if (amount == 0) return sqrtPX96;
uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;
if (add) {
unchecked {
uint256 product = amount * sqrtPX96;
if (product / amount == sqrtPX96) {
uint256 denominator = numerator1 + product;
if (denominator >= numerator1) {
// always fits in 160 bits
return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator));
}
}
}
// denominator is checked for overflow
return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96) + amount));
} else {
unchecked {
uint256 product = amount * sqrtPX96;
// if the product overflows, we know the denominator underflows
// in addition, we must check that the denominator does not underflow
// equivalent: if (product / amount != sqrtPX96 || numerator1 <= product) revert PriceOverflow();
assembly ("memory-safe") {
if iszero(
and(
eq(div(product, amount), and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff)),
gt(numerator1, product)
)
) {
mstore(0, 0xf5c787f1) // selector for PriceOverflow()
revert(0x1c, 0x04)
}
}
uint256 denominator = numerator1 - product;
return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160();
}
}
}
/// @notice Gets the next sqrt price given a delta of currency1
/// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least
/// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the
/// price less in order to not send too much output.
/// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity
/// @param sqrtPX96 The starting price, i.e., before accounting for the currency1 delta
/// @param liquidity The amount of usable liquidity
/// @param amount How much of currency1 to add, or remove, from virtual reserves
/// @param add Whether to add, or remove, the amount of currency1
/// @return The price after adding or removing `amount`
function getNextSqrtPriceFromAmount1RoundingDown(uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add)
internal
pure
returns (uint160)
{
// if we're adding (subtracting), rounding down requires rounding the quotient down (up)
// in both cases, avoid a mulDiv for most inputs
if (add) {
uint256 quotient = (
amount <= type(uint160).max
? (amount << FixedPoint96.RESOLUTION) / liquidity
: FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity)
);
return (uint256(sqrtPX96) + quotient).toUint160();
} else {
uint256 quotient = (
amount <= type(uint160).max
? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity)
: FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity)
);
// equivalent: if (sqrtPX96 <= quotient) revert NotEnoughLiquidity();
assembly ("memory-safe") {
if iszero(gt(and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff), quotient)) {
mstore(0, 0x4323a555) // selector for NotEnoughLiquidity()
revert(0x1c, 0x04)
}
}
// always fits 160 bits
unchecked {
return uint160(sqrtPX96 - quotient);
}
}
}
/// @notice Gets the next sqrt price given an input amount of currency0 or currency1
/// @dev Throws if price or liquidity are 0, or if the next price is out of bounds
/// @param sqrtPX96 The starting price, i.e., before accounting for the input amount
/// @param liquidity The amount of usable liquidity
/// @param amountIn How much of currency0, or currency1, is being swapped in
/// @param zeroForOne Whether the amount in is currency0 or currency1
/// @return uint160 The price after adding the input amount to currency0 or currency1
function getNextSqrtPriceFromInput(uint160 sqrtPX96, uint128 liquidity, uint256 amountIn, bool zeroForOne)
internal
pure
returns (uint160)
{
// equivalent: if (sqrtPX96 == 0 || liquidity == 0) revert InvalidPriceOrLiquidity();
assembly ("memory-safe") {
if or(
iszero(and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff)),
iszero(and(liquidity, 0xffffffffffffffffffffffffffffffff))
) {
mstore(0, 0x4f2461b8) // selector for InvalidPriceOrLiquidity()
revert(0x1c, 0x04)
}
}
// round to make sure that we don't pass the target price
return zeroForOne
? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true)
: getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true);
}
/// @notice Gets the next sqrt price given an output amount of currency0 or currency1
/// @dev Throws if price or liquidity are 0 or the next price is out of bounds
/// @param sqrtPX96 The starting price before accounting for the output amount
/// @param liquidity The amount of usable liquidity
/// @param amountOut How much of currency0, or currency1, is being swapped out
/// @param zeroForOne Whether the amount out is currency1 or currency0
/// @return uint160 The price after removing the output amount of currency0 or currency1
function getNextSqrtPriceFromOutput(uint160 sqrtPX96, uint128 liquidity, uint256 amountOut, bool zeroForOne)
internal
pure
returns (uint160)
{
// equivalent: if (sqrtPX96 == 0 || liquidity == 0) revert InvalidPriceOrLiquidity();
assembly ("memory-safe") {
if or(
iszero(and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff)),
iszero(and(liquidity, 0xffffffffffffffffffffffffffffffff))
) {
mstore(0, 0x4f2461b8) // selector for InvalidPriceOrLiquidity()
revert(0x1c, 0x04)
}
}
// round to make sure that we pass the target price
return zeroForOne
? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false)
: getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false);
}
/// @notice Gets the amount0 delta between two prices
/// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper),
/// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))
/// @param sqrtPriceAX96 A sqrt price
/// @param sqrtPriceBX96 Another sqrt price
/// @param liquidity The amount of usable liquidity
/// @param roundUp Whether to round the amount up or down
/// @return uint256 Amount of currency0 required to cover a position of size liquidity between the two passed prices
function getAmount0Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint128 liquidity, bool roundUp)
internal
pure
returns (uint256)
{
unchecked {
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
// equivalent: if (sqrtPriceAX96 == 0) revert InvalidPrice();
assembly ("memory-safe") {
if iszero(and(sqrtPriceAX96, 0xffffffffffffffffffffffffffffffffffffffff)) {
mstore(0, 0x00bfc921) // selector for InvalidPrice()
revert(0x1c, 0x04)
}
}
uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;
uint256 numerator2 = sqrtPriceBX96 - sqrtPriceAX96;
return roundUp
? UnsafeMath.divRoundingUp(FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtPriceBX96), sqrtPriceAX96)
: FullMath.mulDiv(numerator1, numerator2, sqrtPriceBX96) / sqrtPriceAX96;
}
}
/// @notice Equivalent to: `a >= b ? a - b : b - a`
function absDiff(uint160 a, uint160 b) internal pure returns (uint256 res) {
assembly ("memory-safe") {
let diff :=
sub(and(a, 0xffffffffffffffffffffffffffffffffffffffff), and(b, 0xffffffffffffffffffffffffffffffffffffffff))
// mask = 0 if a >= b else -1 (all 1s)
let mask := sar(255, diff)
// if a >= b, res = a - b = 0 ^ (a - b)
// if a < b, res = b - a = ~~(b - a) = ~(-(b - a) - 1) = ~(a - b - 1) = (-1) ^ (a - b - 1)
// either way, res = mask ^ (a - b + mask)
res := xor(mask, add(mask, diff))
}
}
/// @notice Gets the amount1 delta between two prices
/// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))
/// @param sqrtPriceAX96 A sqrt price
/// @param sqrtPriceBX96 Another sqrt price
/// @param liquidity The amount of usable liquidity
/// @param roundUp Whether to round the amount up, or down
/// @return amount1 Amount of currency1 required to cover a position of size liquidity between the two passed prices
function getAmount1Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint128 liquidity, bool roundUp)
internal
pure
returns (uint256 amount1)
{
uint256 numerator = absDiff(sqrtPriceAX96, sqrtPriceBX96);
uint256 denominator = FixedPoint96.Q96;
uint256 _liquidity = uint256(liquidity);
/**
* Equivalent to:
* amount1 = roundUp
* ? FullMath.mulDivRoundingUp(liquidity, sqrtPriceBX96 - sqrtPriceAX96, FixedPoint96.Q96)
* : FullMath.mulDiv(liquidity, sqrtPriceBX96 - sqrtPriceAX96, FixedPoint96.Q96);
* Cannot overflow because `type(uint128).max * type(uint160).max >> 96 < (1 << 192)`.
*/
amount1 = FullMath.mulDiv(_liquidity, numerator, denominator);
assembly ("memory-safe") {
amount1 := add(amount1, and(gt(mulmod(_liquidity, numerator, denominator), 0), roundUp))
}
}
/// @notice Helper that gets signed currency0 delta
/// @param sqrtPriceAX96 A sqrt price
/// @param sqrtPriceBX96 Another sqrt price
/// @param liquidity The change in liquidity for which to compute the amount0 delta
/// @return int256 Amount of currency0 corresponding to the passed liquidityDelta between the two prices
function getAmount0Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, int128 liquidity)
internal
pure
returns (int256)
{
unchecked {
return liquidity < 0
? getAmount0Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(-liquidity), false).toInt256()
: -getAmount0Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(liquidity), true).toInt256();
}
}
/// @notice Helper that gets signed currency1 delta
/// @param sqrtPriceAX96 A sqrt price
/// @param sqrtPriceBX96 Another sqrt price
/// @param liquidity The change in liquidity for which to compute the amount1 delta
/// @return int256 Amount of currency1 corresponding to the passed liquidityDelta between the two prices
function getAmount1Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, int128 liquidity)
internal
pure
returns (int256)
{
unchecked {
return liquidity < 0
? getAmount1Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(-liquidity), false).toInt256()
: -getAmount1Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(liquidity), true).toInt256();
}
}
}
dependencies/v4-core-main/src/libraries/StateLibrary.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolId} from "../types/PoolId.sol";
import {IPoolManager} from "../interfaces/IPoolManager.sol";
import {Position} from "./Position.sol";
/// @notice A helper library to provide state getters that use extsload
library StateLibrary {
/// @notice index of pools mapping in the PoolManager
bytes32 public constant POOLS_SLOT = bytes32(uint256(6));
/// @notice index of feeGrowthGlobal0X128 in Pool.State
uint256 public constant FEE_GROWTH_GLOBAL0_OFFSET = 1;
// feeGrowthGlobal1X128 offset in Pool.State = 2
/// @notice index of liquidity in Pool.State
uint256 public constant LIQUIDITY_OFFSET = 3;
/// @notice index of TicksInfo mapping in Pool.State: mapping(int24 => TickInfo) ticks;
uint256 public constant TICKS_OFFSET = 4;
/// @notice index of tickBitmap mapping in Pool.State
uint256 public constant TICK_BITMAP_OFFSET = 5;
/// @notice index of Position.State mapping in Pool.State: mapping(bytes32 => Position.State) positions;
uint256 public constant POSITIONS_OFFSET = 6;
/**
* @notice Get Slot0 of the pool: sqrtPriceX96, tick, protocolFee, lpFee
* @dev Corresponds to pools[poolId].slot0
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @return sqrtPriceX96 The square root of the price of the pool, in Q96 precision.
* @return tick The current tick of the pool.
* @return protocolFee The protocol fee of the pool.
* @return lpFee The swap fee of the pool.
*/
function getSlot0(IPoolManager manager, PoolId poolId)
internal
view
returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee)
{
// slot key of Pool.State value: `pools[poolId]`
bytes32 stateSlot = _getPoolStateSlot(poolId);
bytes32 data = manager.extsload(stateSlot);
// 24 bits |24bits|24bits |24 bits|160 bits
// 0x000000 |000bb8|000000 |ffff75 |0000000000000000fe3aa841ba359daa0ea9eff7
// ---------- | fee |protocolfee | tick | sqrtPriceX96
assembly ("memory-safe") {
// bottom 160 bits of data
sqrtPriceX96 := and(data, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
// next 24 bits of data
tick := signextend(2, shr(160, data))
// next 24 bits of data
protocolFee := and(shr(184, data), 0xFFFFFF)
// last 24 bits of data
lpFee := and(shr(208, data), 0xFFFFFF)
}
}
/**
* @notice Retrieves the tick information of a pool at a specific tick.
* @dev Corresponds to pools[poolId].ticks[tick]
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param tick The tick to retrieve information for.
* @return liquidityGross The total position liquidity that references this tick
* @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)
* @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
* @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
*/
function getTickInfo(IPoolManager manager, PoolId poolId, int24 tick)
internal
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128
)
{
bytes32 slot = _getTickInfoSlot(poolId, tick);
// read all 3 words of the TickInfo struct
bytes32[] memory data = manager.extsload(slot, 3);
assembly ("memory-safe") {
let firstWord := mload(add(data, 32))
liquidityNet := sar(128, firstWord)
liquidityGross := and(firstWord, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
feeGrowthOutside0X128 := mload(add(data, 64))
feeGrowthOutside1X128 := mload(add(data, 96))
}
}
/**
* @notice Retrieves the liquidity information of a pool at a specific tick.
* @dev Corresponds to pools[poolId].ticks[tick].liquidityGross and pools[poolId].ticks[tick].liquidityNet. A more gas efficient version of getTickInfo
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param tick The tick to retrieve liquidity for.
* @return liquidityGross The total position liquidity that references this tick
* @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)
*/
function getTickLiquidity(IPoolManager manager, PoolId poolId, int24 tick)
internal
view
returns (uint128 liquidityGross, int128 liquidityNet)
{
bytes32 slot = _getTickInfoSlot(poolId, tick);
bytes32 value = manager.extsload(slot);
assembly ("memory-safe") {
liquidityNet := sar(128, value)
liquidityGross := and(value, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
}
}
/**
* @notice Retrieves the fee growth outside a tick range of a pool
* @dev Corresponds to pools[poolId].ticks[tick].feeGrowthOutside0X128 and pools[poolId].ticks[tick].feeGrowthOutside1X128. A more gas efficient version of getTickInfo
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param tick The tick to retrieve fee growth for.
* @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
* @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
*/
function getTickFeeGrowthOutside(IPoolManager manager, PoolId poolId, int24 tick)
internal
view
returns (uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128)
{
bytes32 slot = _getTickInfoSlot(poolId, tick);
// offset by 1 word, since the first word is liquidityGross + liquidityNet
bytes32[] memory data = manager.extsload(bytes32(uint256(slot) + 1), 2);
assembly ("memory-safe") {
feeGrowthOutside0X128 := mload(add(data, 32))
feeGrowthOutside1X128 := mload(add(data, 64))
}
}
/**
* @notice Retrieves the global fee growth of a pool.
* @dev Corresponds to pools[poolId].feeGrowthGlobal0X128 and pools[poolId].feeGrowthGlobal1X128
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @return feeGrowthGlobal0 The global fee growth for token0.
* @return feeGrowthGlobal1 The global fee growth for token1.
* @dev Note that feeGrowthGlobal can be artificially inflated
* For pools with a single liquidity position, actors can donate to themselves to freely inflate feeGrowthGlobal
* atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme
*/
function getFeeGrowthGlobals(IPoolManager manager, PoolId poolId)
internal
view
returns (uint256 feeGrowthGlobal0, uint256 feeGrowthGlobal1)
{
// slot key of Pool.State value: `pools[poolId]`
bytes32 stateSlot = _getPoolStateSlot(poolId);
// Pool.State, `uint256 feeGrowthGlobal0X128`
bytes32 slot_feeGrowthGlobal0X128 = bytes32(uint256(stateSlot) + FEE_GROWTH_GLOBAL0_OFFSET);
// read the 2 words of feeGrowthGlobal
bytes32[] memory data = manager.extsload(slot_feeGrowthGlobal0X128, 2);
assembly ("memory-safe") {
feeGrowthGlobal0 := mload(add(data, 32))
feeGrowthGlobal1 := mload(add(data, 64))
}
}
/**
* @notice Retrieves total the liquidity of a pool.
* @dev Corresponds to pools[poolId].liquidity
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @return liquidity The liquidity of the pool.
*/
function getLiquidity(IPoolManager manager, PoolId poolId) internal view returns (uint128 liquidity) {
// slot key of Pool.State value: `pools[poolId]`
bytes32 stateSlot = _getPoolStateSlot(poolId);
// Pool.State: `uint128 liquidity`
bytes32 slot = bytes32(uint256(stateSlot) + LIQUIDITY_OFFSET);
liquidity = uint128(uint256(manager.extsload(slot)));
}
/**
* @notice Retrieves the tick bitmap of a pool at a specific tick.
* @dev Corresponds to pools[poolId].tickBitmap[tick]
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param tick The tick to retrieve the bitmap for.
* @return tickBitmap The bitmap of the tick.
*/
function getTickBitmap(IPoolManager manager, PoolId poolId, int16 tick)
internal
view
returns (uint256 tickBitmap)
{
// slot key of Pool.State value: `pools[poolId]`
bytes32 stateSlot = _getPoolStateSlot(poolId);
// Pool.State: `mapping(int16 => uint256) tickBitmap;`
bytes32 tickBitmapMapping = bytes32(uint256(stateSlot) + TICK_BITMAP_OFFSET);
// slot id of the mapping key: `pools[poolId].tickBitmap[tick]
bytes32 slot = keccak256(abi.encodePacked(int256(tick), tickBitmapMapping));
tickBitmap = uint256(manager.extsload(slot));
}
/**
* @notice Retrieves the position information of a pool without needing to calculate the `positionId`.
* @dev Corresponds to pools[poolId].positions[positionId]
* @param poolId The ID of the pool.
* @param owner The owner of the liquidity position.
* @param tickLower The lower tick of the liquidity range.
* @param tickUpper The upper tick of the liquidity range.
* @param salt The bytes32 randomness to further distinguish position state.
* @return liquidity The liquidity of the position.
* @return feeGrowthInside0LastX128 The fee growth inside the position for token0.
* @return feeGrowthInside1LastX128 The fee growth inside the position for token1.
*/
function getPositionInfo(
IPoolManager manager,
PoolId poolId,
address owner,
int24 tickLower,
int24 tickUpper,
bytes32 salt
) internal view returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128) {
// positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt))
bytes32 positionKey = Position.calculatePositionKey(owner, tickLower, tickUpper, salt);
(liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128) = getPositionInfo(manager, poolId, positionKey);
}
/**
* @notice Retrieves the position information of a pool at a specific position ID.
* @dev Corresponds to pools[poolId].positions[positionId]
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param positionId The ID of the position.
* @return liquidity The liquidity of the position.
* @return feeGrowthInside0LastX128 The fee growth inside the position for token0.
* @return feeGrowthInside1LastX128 The fee growth inside the position for token1.
*/
function getPositionInfo(IPoolManager manager, PoolId poolId, bytes32 positionId)
internal
view
returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128)
{
bytes32 slot = _getPositionInfoSlot(poolId, positionId);
// read all 3 words of the Position.State struct
bytes32[] memory data = manager.extsload(slot, 3);
assembly ("memory-safe") {
liquidity := mload(add(data, 32))
feeGrowthInside0LastX128 := mload(add(data, 64))
feeGrowthInside1LastX128 := mload(add(data, 96))
}
}
/**
* @notice Retrieves the liquidity of a position.
* @dev Corresponds to pools[poolId].positions[positionId].liquidity. More gas efficient for just retrieiving liquidity as compared to getPositionInfo
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param positionId The ID of the position.
* @return liquidity The liquidity of the position.
*/
function getPositionLiquidity(IPoolManager manager, PoolId poolId, bytes32 positionId)
internal
view
returns (uint128 liquidity)
{
bytes32 slot = _getPositionInfoSlot(poolId, positionId);
liquidity = uint128(uint256(manager.extsload(slot)));
}
/**
* @notice Calculate the fee growth inside a tick range of a pool
* @dev pools[poolId].feeGrowthInside0LastX128 in Position.State is cached and can become stale. This function will calculate the up to date feeGrowthInside
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param tickLower The lower tick of the range.
* @param tickUpper The upper tick of the range.
* @return feeGrowthInside0X128 The fee growth inside the tick range for token0.
* @return feeGrowthInside1X128 The fee growth inside the tick range for token1.
*/
function getFeeGrowthInside(IPoolManager manager, PoolId poolId, int24 tickLower, int24 tickUpper)
internal
view
returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128)
{
(uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128) = getFeeGrowthGlobals(manager, poolId);
(uint256 lowerFeeGrowthOutside0X128, uint256 lowerFeeGrowthOutside1X128) =
getTickFeeGrowthOutside(manager, poolId, tickLower);
(uint256 upperFeeGrowthOutside0X128, uint256 upperFeeGrowthOutside1X128) =
getTickFeeGrowthOutside(manager, poolId, tickUpper);
(, int24 tickCurrent,,) = getSlot0(manager, poolId);
unchecked {
if (tickCurrent < tickLower) {
feeGrowthInside0X128 = lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;
feeGrowthInside1X128 = lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;
} else if (tickCurrent >= tickUpper) {
feeGrowthInside0X128 = upperFeeGrowthOutside0X128 - lowerFeeGrowthOutside0X128;
feeGrowthInside1X128 = upperFeeGrowthOutside1X128 - lowerFeeGrowthOutside1X128;
} else {
feeGrowthInside0X128 = feeGrowthGlobal0X128 - lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;
feeGrowthInside1X128 = feeGrowthGlobal1X128 - lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;
}
}
}
function _getPoolStateSlot(PoolId poolId) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(PoolId.unwrap(poolId), POOLS_SLOT));
}
function _getTickInfoSlot(PoolId poolId, int24 tick) internal pure returns (bytes32) {
// slot key of Pool.State value: `pools[poolId]`
bytes32 stateSlot = _getPoolStateSlot(poolId);
// Pool.State: `mapping(int24 => TickInfo) ticks`
bytes32 ticksMappingSlot = bytes32(uint256(stateSlot) + TICKS_OFFSET);
// slot key of the tick key: `pools[poolId].ticks[tick]
return keccak256(abi.encodePacked(int256(tick), ticksMappingSlot));
}
function _getPositionInfoSlot(PoolId poolId, bytes32 positionId) internal pure returns (bytes32) {
// slot key of Pool.State value: `pools[poolId]`
bytes32 stateSlot = _getPoolStateSlot(poolId);
// Pool.State: `mapping(bytes32 => Position.State) positions;`
bytes32 positionMapping = bytes32(uint256(stateSlot) + POSITIONS_OFFSET);
// slot of the mapping key: `pools[poolId].positions[positionId]
return keccak256(abi.encodePacked(positionId, positionMapping));
}
}
dependencies/v4-core-main/src/libraries/TickMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {BitMath} from "./BitMath.sol";
import {CustomRevert} from "./CustomRevert.sol";
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
using CustomRevert for bytes4;
/// @notice Thrown when the tick passed to #getSqrtPriceAtTick is not between MIN_TICK and MAX_TICK
error InvalidTick(int24 tick);
/// @notice Thrown when the price passed to #getTickAtSqrtPrice does not correspond to a price between MIN_TICK and MAX_TICK
error InvalidSqrtPrice(uint160 sqrtPriceX96);
/// @dev The minimum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**-128
/// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**128
/// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
int24 internal constant MAX_TICK = 887272;
/// @dev The minimum tick spacing value drawn from the range of type int16 that is greater than 0, i.e. min from the range [1, 32767]
int24 internal constant MIN_TICK_SPACING = 1;
/// @dev The maximum tick spacing value drawn from the range of type int16, i.e. max from the range [1, 32767]
int24 internal constant MAX_TICK_SPACING = type(int16).max;
/// @dev The minimum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_PRICE = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_PRICE = 1461446703485210103287273052203988822378723970342;
/// @dev A threshold used for optimized bounds check, equals `MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1`
uint160 internal constant MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE =
1461446703485210103287273052203988822378723970342 - 4295128739 - 1;
/// @notice Given a tickSpacing, compute the maximum usable tick
function maxUsableTick(int24 tickSpacing) internal pure returns (int24) {
unchecked {
return (MAX_TICK / tickSpacing) * tickSpacing;
}
}
/// @notice Given a tickSpacing, compute the minimum usable tick
function minUsableTick(int24 tickSpacing) internal pure returns (int24) {
unchecked {
return (MIN_TICK / tickSpacing) * tickSpacing;
}
}
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the price of the two assets (currency1/currency0)
/// at the given tick
function getSqrtPriceAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
unchecked {
uint256 absTick;
assembly ("memory-safe") {
tick := signextend(2, tick)
// mask = 0 if tick >= 0 else -1 (all 1s)
let mask := sar(255, tick)
// if tick >= 0, |tick| = tick = 0 ^ tick
// if tick < 0, |tick| = ~~|tick| = ~(-|tick| - 1) = ~(tick - 1) = (-1) ^ (tick - 1)
// either way, |tick| = mask ^ (tick + mask)
absTick := xor(mask, add(mask, tick))
}
if (absTick > uint256(int256(MAX_TICK))) InvalidTick.selector.revertWith(tick);
// The tick is decomposed into bits, and for each bit with index i that is set, the product of 1/sqrt(1.0001^(2^i))
// is calculated (using Q128.128). The constants used for this calculation are rounded to the nearest integer
// Equivalent to:
// price = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
// or price = int(2**128 / sqrt(1.0001)) if (absTick & 0x1) else 1 << 128
uint256 price;
assembly ("memory-safe") {
price := xor(shl(128, 1), mul(xor(shl(128, 1), 0xfffcb933bd6fad37aa2d162d1a594001), and(absTick, 0x1)))
}
if (absTick & 0x2 != 0) price = (price * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) price = (price * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) price = (price * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) price = (price * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) price = (price * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) price = (price * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) price = (price * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) price = (price * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) price = (price * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) price = (price * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) price = (price * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) price = (price * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) price = (price * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) price = (price * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) price = (price * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) price = (price * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) price = (price * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) price = (price * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) price = (price * 0x48a170391f7dc42444e8fa2) >> 128;
assembly ("memory-safe") {
// if (tick > 0) price = type(uint256).max / price;
if sgt(tick, 0) { price := div(not(0), price) }
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtPrice of the output price is always consistent
// `sub(shl(32, 1), 1)` is `type(uint32).max`
// `price + type(uint32).max` will not overflow because `price` fits in 192 bits
sqrtPriceX96 := shr(32, add(price, sub(shl(32, 1), 1)))
}
}
}
/// @notice Calculates the greatest tick value such that getSqrtPriceAtTick(tick) <= sqrtPriceX96
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_PRICE, as MIN_SQRT_PRICE is the lowest value getSqrtPriceAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt price for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the getSqrtPriceAtTick(tick) is less than or equal to the input sqrtPriceX96
function getTickAtSqrtPrice(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
unchecked {
// Equivalent: if (sqrtPriceX96 < MIN_SQRT_PRICE || sqrtPriceX96 >= MAX_SQRT_PRICE) revert InvalidSqrtPrice();
// second inequality must be >= because the price can never reach the price at the max tick
// if sqrtPriceX96 < MIN_SQRT_PRICE, the `sub` underflows and `gt` is true
// if sqrtPriceX96 >= MAX_SQRT_PRICE, sqrtPriceX96 - MIN_SQRT_PRICE > MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1
if ((sqrtPriceX96 - MIN_SQRT_PRICE) > MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE) {
InvalidSqrtPrice.selector.revertWith(sqrtPriceX96);
}
uint256 price = uint256(sqrtPriceX96) << 32;
uint256 r = price;
uint256 msb = BitMath.mostSignificantBit(r);
if (msb >= 128) r = price >> (msb - 127);
else r = price << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // Q22.128 number
// Magic number represents the ceiling of the maximum value of the error when approximating log_sqrt10001(x)
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
// Magic number represents the minimum value of the error when approximating log_sqrt10001(x), when
// sqrtPrice is from the range (2^-64, 2^64). This is safe as MIN_SQRT_PRICE is more than 2^-64. If MIN_SQRT_PRICE
// is changed, this may need to be changed too
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtPriceAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
}
dependencies/v4-core-main/src/libraries/UnsafeMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Math functions that do not check inputs or outputs
/// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks
library UnsafeMath {
/// @notice Returns ceil(x / y)
/// @dev division by 0 will return 0, and should be checked externally
/// @param x The dividend
/// @param y The divisor
/// @return z The quotient, ceil(x / y)
function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
assembly ("memory-safe") {
z := add(div(x, y), gt(mod(x, y), 0))
}
}
/// @notice Calculates floor(a×b÷denominator)
/// @dev division by 0 will return 0, and should be checked externally
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result, floor(a×b÷denominator)
function simpleMulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
assembly ("memory-safe") {
result := div(mul(a, b), denominator)
}
}
}
dependencies/v4-core-main/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)
}
}
}
dependencies/v4-core-main/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)
}
}
}
dependencies/v4-core-main/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)));
}
}
dependencies/v4-core-main/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)
}
}
}
dependencies/v4-core-main/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;
}
dependencies/v4-core-main/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;
}
dependencies/v4-periphery-main/lib/permit2/src/interfaces/IAllowanceTransfer.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IEIP712} from "./IEIP712.sol";
/// @title AllowanceTransfer
/// @notice Handles ERC20 token permissions through signature based allowance setting and ERC20 token transfers by checking allowed amounts
/// @dev Requires user's token approval on the Permit2 contract
interface IAllowanceTransfer is IEIP712 {
/// @notice Thrown when an allowance on a token has expired.
/// @param deadline The timestamp at which the allowed amount is no longer valid
error AllowanceExpired(uint256 deadline);
/// @notice Thrown when an allowance on a token has been depleted.
/// @param amount The maximum amount allowed
error InsufficientAllowance(uint256 amount);
/// @notice Thrown when too many nonces are invalidated.
error ExcessiveInvalidation();
/// @notice Emits an event when the owner successfully invalidates an ordered nonce.
event NonceInvalidation(
address indexed owner, address indexed token, address indexed spender, uint48 newNonce, uint48 oldNonce
);
/// @notice Emits an event when the owner successfully sets permissions on a token for the spender.
event Approval(
address indexed owner, address indexed token, address indexed spender, uint160 amount, uint48 expiration
);
/// @notice Emits an event when the owner successfully sets permissions using a permit signature on a token for the spender.
event Permit(
address indexed owner,
address indexed token,
address indexed spender,
uint160 amount,
uint48 expiration,
uint48 nonce
);
/// @notice Emits an event when the owner sets the allowance back to 0 with the lockdown function.
event Lockdown(address indexed owner, address token, address spender);
/// @notice The permit data for a token
struct PermitDetails {
// ERC20 token address
address token;
// the maximum amount allowed to spend
uint160 amount;
// timestamp at which a spender's token allowances become invalid
uint48 expiration;
// an incrementing value indexed per owner,token,and spender for each signature
uint48 nonce;
}
/// @notice The permit message signed for a single token allowance
struct PermitSingle {
// the permit data for a single token alownce
PermitDetails details;
// address permissioned on the allowed tokens
address spender;
// deadline on the permit signature
uint256 sigDeadline;
}
/// @notice The permit message signed for multiple token allowances
struct PermitBatch {
// the permit data for multiple token allowances
PermitDetails[] details;
// address permissioned on the allowed tokens
address spender;
// deadline on the permit signature
uint256 sigDeadline;
}
/// @notice The saved permissions
/// @dev This info is saved per owner, per token, per spender and all signed over in the permit message
/// @dev Setting amount to type(uint160).max sets an unlimited approval
struct PackedAllowance {
// amount allowed
uint160 amount;
// permission expiry
uint48 expiration;
// an incrementing value indexed per owner,token,and spender for each signature
uint48 nonce;
}
/// @notice A token spender pair.
struct TokenSpenderPair {
// the token the spender is approved
address token;
// the spender address
address spender;
}
/// @notice Details for a token transfer.
struct AllowanceTransferDetails {
// the owner of the token
address from;
// the recipient of the token
address to;
// the amount of the token
uint160 amount;
// the token to be transferred
address token;
}
/// @notice A mapping from owner address to token address to spender address to PackedAllowance struct, which contains details and conditions of the approval.
/// @notice The mapping is indexed in the above order see: allowance[ownerAddress][tokenAddress][spenderAddress]
/// @dev The packed slot holds the allowed amount, expiration at which the allowed amount is no longer valid, and current nonce thats updated on any signature based approvals.
function allowance(address user, address token, address spender)
external
view
returns (uint160 amount, uint48 expiration, uint48 nonce);
/// @notice Approves the spender to use up to amount of the specified token up until the expiration
/// @param token The token to approve
/// @param spender The spender address to approve
/// @param amount The approved amount of the token
/// @param expiration The timestamp at which the approval is no longer valid
/// @dev The packed allowance also holds a nonce, which will stay unchanged in approve
/// @dev Setting amount to type(uint160).max sets an unlimited approval
function approve(address token, address spender, uint160 amount, uint48 expiration) external;
/// @notice Permit a spender to a given amount of the owners token via the owner's EIP-712 signature
/// @dev May fail if the owner's nonce was invalidated in-flight by invalidateNonce
/// @param owner The owner of the tokens being approved
/// @param permitSingle Data signed over by the owner specifying the terms of approval
/// @param signature The owner's signature over the permit data
function permit(address owner, PermitSingle memory permitSingle, bytes calldata signature) external;
/// @notice Permit a spender to the signed amounts of the owners tokens via the owner's EIP-712 signature
/// @dev May fail if the owner's nonce was invalidated in-flight by invalidateNonce
/// @param owner The owner of the tokens being approved
/// @param permitBatch Data signed over by the owner specifying the terms of approval
/// @param signature The owner's signature over the permit data
function permit(address owner, PermitBatch memory permitBatch, bytes calldata signature) external;
/// @notice Transfer approved tokens from one address to another
/// @param from The address to transfer from
/// @param to The address of the recipient
/// @param amount The amount of the token to transfer
/// @param token The token address to transfer
/// @dev Requires the from address to have approved at least the desired amount
/// of tokens to msg.sender.
function transferFrom(address from, address to, uint160 amount, address token) external;
/// @notice Transfer approved tokens in a batch
/// @param transferDetails Array of owners, recipients, amounts, and tokens for the transfers
/// @dev Requires the from addresses to have approved at least the desired amount
/// of tokens to msg.sender.
function transferFrom(AllowanceTransferDetails[] calldata transferDetails) external;
/// @notice Enables performing a "lockdown" of the sender's Permit2 identity
/// by batch revoking approvals
/// @param approvals Array of approvals to revoke.
function lockdown(TokenSpenderPair[] calldata approvals) external;
/// @notice Invalidate nonces for a given (token, spender) pair
/// @param token The token to invalidate nonces for
/// @param spender The spender to invalidate nonces for
/// @param newNonce The new nonce to set. Invalidates all nonces less than it.
/// @dev Can't invalidate more than 2**16 nonces per transaction.
function invalidateNonces(address token, address spender, uint48 newNonce) external;
}
dependencies/v4-periphery-main/lib/permit2/src/interfaces/IEIP712.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IEIP712 {
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
dependencies/v4-periphery-main/src/base/ImmutableState.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {IImmutableState} from "../interfaces/IImmutableState.sol";
/// @title Immutable State
/// @notice A collection of immutable state variables, commonly used across multiple contracts
contract ImmutableState is IImmutableState {
/// @inheritdoc IImmutableState
IPoolManager public immutable poolManager;
/// @notice Thrown when the caller is not PoolManager
error NotPoolManager();
/// @notice Only allow calls from the PoolManager contract
modifier onlyPoolManager() {
if (msg.sender != address(poolManager)) revert NotPoolManager();
_;
}
constructor(IPoolManager _poolManager) {
poolManager = _poolManager;
}
}
dependencies/v4-periphery-main/src/interfaces/IEIP712_v4.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title IEIP712_v4
/// @notice Interface for the EIP712 contract
interface IEIP712_v4 {
/// @notice Returns the domain separator for the current chain.
/// @return bytes32 The domain separator
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
dependencies/v4-periphery-main/src/interfaces/IERC721Permit_v4.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title IERC721Permit_v4
/// @notice Interface for the ERC721Permit_v4 contract
interface IERC721Permit_v4 {
error SignatureDeadlineExpired();
error NoSelfPermit();
error Unauthorized();
/// @notice Approve of a specific token ID for spending by spender via signature
/// @param spender The account that is being approved
/// @param tokenId The ID of the token that is being approved for spending
/// @param deadline The deadline timestamp by which the call must be mined for the approve to work
/// @param nonce a unique value, for an owner, to prevent replay attacks; an unordered nonce where the top 248 bits correspond to a word and the bottom 8 bits calculate the bit position of the word
/// @param signature Concatenated data from a valid secp256k1 signature from the holder, i.e. abi.encodePacked(r, s, v)
/// @dev payable so it can be multicalled with NATIVE related actions
function permit(address spender, uint256 tokenId, uint256 deadline, uint256 nonce, bytes calldata signature)
external
payable;
/// @notice Set an operator with full permission to an owner's tokens via signature
/// @param owner The address that is setting the operator
/// @param operator The address that will be set as an operator for the owner
/// @param approved The permission to set on the operator
/// @param deadline The deadline timestamp by which the call must be mined for the approve to work
/// @param nonce a unique value, for an owner, to prevent replay attacks; an unordered nonce where the top 248 bits correspond to a word and the bottom 8 bits calculate the bit position of the word
/// @param signature Concatenated data from a valid secp256k1 signature from the holder, i.e. abi.encodePacked(r, s, v)
/// @dev payable so it can be multicalled with NATIVE related actions
function permitForAll(
address owner,
address operator,
bool approved,
uint256 deadline,
uint256 nonce,
bytes calldata signature
) external payable;
}
dependencies/v4-periphery-main/src/interfaces/IImmutableState.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
/// @title IImmutableState
/// @notice Interface for the ImmutableState contract
interface IImmutableState {
/// @notice The Uniswap v4 PoolManager contract
function poolManager() external view returns (IPoolManager);
}
dependencies/v4-periphery-main/src/interfaces/IMulticall_v4.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title IMulticall_v4
/// @notice Interface for the Multicall_v4 contract
interface IMulticall_v4 {
/// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed
/// @dev The `msg.value` is passed onto all subcalls, even if a previous subcall has consumed the ether.
/// Subcalls can instead use `address(this).value` to see the available ETH, and consume it using {value: x}.
/// @param data The encoded function data for each of the calls to make to this contract
/// @return results The results from each of the calls passed in via data
function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
}
dependencies/v4-periphery-main/src/interfaces/INotifier.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {ISubscriber} from "./ISubscriber.sol";
/// @title INotifier
/// @notice Interface for the Notifier contract
interface INotifier {
/// @notice Thrown when unsubscribing without a subscriber
error NotSubscribed();
/// @notice Thrown when a subscriber does not have code
error NoCodeSubscriber();
/// @notice Thrown when a user specifies a gas limit too low to avoid valid unsubscribe notifications
error GasLimitTooLow();
/// @notice Wraps the revert message of the subscriber contract on a reverting subscription
error SubscriptionReverted(address subscriber, bytes reason);
/// @notice Wraps the revert message of the subscriber contract on a reverting modify liquidity notification
error ModifyLiquidityNotificationReverted(address subscriber, bytes reason);
/// @notice Wraps the revert message of the subscriber contract on a reverting burn notification
error BurnNotificationReverted(address subscriber, bytes reason);
/// @notice Thrown when a tokenId already has a subscriber
error AlreadySubscribed(uint256 tokenId, address subscriber);
/// @notice Emitted on a successful call to subscribe
event Subscription(uint256 indexed tokenId, address indexed subscriber);
/// @notice Emitted on a successful call to unsubscribe
event Unsubscription(uint256 indexed tokenId, address indexed subscriber);
/// @notice Returns the subscriber for a respective position
/// @param tokenId the ERC721 tokenId
/// @return subscriber the subscriber contract
function subscriber(uint256 tokenId) external view returns (ISubscriber subscriber);
/// @notice Enables the subscriber to receive notifications for a respective position
/// @param tokenId the ERC721 tokenId
/// @param newSubscriber the address of the subscriber contract
/// @param data caller-provided data that's forwarded to the subscriber contract
/// @dev Calling subscribe when a position is already subscribed will revert
/// @dev payable so it can be multicalled with NATIVE related actions
/// @dev will revert if pool manager is locked
function subscribe(uint256 tokenId, address newSubscriber, bytes calldata data) external payable;
/// @notice Removes the subscriber from receiving notifications for a respective position
/// @param tokenId the ERC721 tokenId
/// @dev Callers must specify a high gas limit (remaining gas should be higher than unsubscriberGasLimit) such that the subscriber can be notified
/// @dev payable so it can be multicalled with NATIVE related actions
/// @dev Must always allow a user to unsubscribe. In the case of a malicious subscriber, a user can always unsubscribe safely, ensuring liquidity is always modifiable.
/// @dev will revert if pool manager is locked
function unsubscribe(uint256 tokenId) external payable;
/// @notice Returns and determines the maximum allowable gas-used for notifying unsubscribe
/// @return uint256 the maximum gas limit when notifying a subscriber's `notifyUnsubscribe` function
function unsubscribeGasLimit() external view returns (uint256);
}
dependencies/v4-periphery-main/src/interfaces/IPermit2Forwarder.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IAllowanceTransfer} from "permit2/src/interfaces/IAllowanceTransfer.sol";
/// @title IPermit2Forwarder
/// @notice Interface for the Permit2Forwarder contract
interface IPermit2Forwarder {
/// @notice allows forwarding a single permit to permit2
/// @dev this function is payable to allow multicall with NATIVE based actions
/// @param owner the owner of the tokens
/// @param permitSingle the permit data
/// @param signature the signature of the permit; abi.encodePacked(r, s, v)
/// @return err the error returned by a reverting permit call, empty if successful
function permit(address owner, IAllowanceTransfer.PermitSingle calldata permitSingle, bytes calldata signature)
external
payable
returns (bytes memory err);
/// @notice allows forwarding batch permits to permit2
/// @dev this function is payable to allow multicall with NATIVE based actions
/// @param owner the owner of the tokens
/// @param _permitBatch a batch of approvals
/// @param signature the signature of the permit; abi.encodePacked(r, s, v)
/// @return err the error returned by a reverting permit call, empty if successful
function permitBatch(address owner, IAllowanceTransfer.PermitBatch calldata _permitBatch, bytes calldata signature)
external
payable
returns (bytes memory err);
}
dependencies/v4-periphery-main/src/interfaces/IPoolInitializer_v4.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
/// @title IPoolInitializer_v4
/// @notice Interface for the PoolInitializer_v4 contract
interface IPoolInitializer_v4 {
/// @notice Initialize a Uniswap v4 Pool
/// @dev If the pool is already initialized, this function will not revert and just return type(int24).max
/// @param key The PoolKey of the pool to initialize
/// @param sqrtPriceX96 The initial starting price of the pool, expressed as a sqrtPriceX96
/// @return The current tick of the pool, or type(int24).max if the pool creation failed, or the pool already existed
function initializePool(PoolKey calldata key, uint160 sqrtPriceX96) external payable returns (int24);
}
dependencies/v4-periphery-main/src/interfaces/IPositionManager.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {PositionInfo} from "../libraries/PositionInfoLibrary.sol";
import {INotifier} from "./INotifier.sol";
import {IImmutableState} from "./IImmutableState.sol";
import {IERC721Permit_v4} from "./IERC721Permit_v4.sol";
import {IEIP712_v4} from "./IEIP712_v4.sol";
import {IMulticall_v4} from "./IMulticall_v4.sol";
import {IPoolInitializer_v4} from "./IPoolInitializer_v4.sol";
import {IUnorderedNonce} from "./IUnorderedNonce.sol";
import {IPermit2Forwarder} from "./IPermit2Forwarder.sol";
/// @title IPositionManager
/// @notice Interface for the PositionManager contract
interface IPositionManager is
INotifier,
IImmutableState,
IERC721Permit_v4,
IEIP712_v4,
IMulticall_v4,
IPoolInitializer_v4,
IUnorderedNonce,
IPermit2Forwarder
{
/// @notice Thrown when the caller is not approved to modify a position
error NotApproved(address caller);
/// @notice Thrown when the block.timestamp exceeds the user-provided deadline
error DeadlinePassed(uint256 deadline);
/// @notice Thrown when calling transfer, subscribe, or unsubscribe when the PoolManager is unlocked.
/// @dev This is to prevent hooks from being able to trigger notifications at the same time the position is being modified.
error PoolManagerMustBeLocked();
/// @notice Unlocks Uniswap v4 PoolManager and batches actions for modifying liquidity
/// @dev This is the standard entrypoint for the PositionManager
/// @param unlockData is an encoding of actions, and parameters for those actions
/// @param deadline is the deadline for the batched actions to be executed
function modifyLiquidities(bytes calldata unlockData, uint256 deadline) external payable;
/// @notice Batches actions for modifying liquidity without unlocking v4 PoolManager
/// @dev This must be called by a contract that has already unlocked the v4 PoolManager
/// @param actions the actions to perform
/// @param params the parameters to provide for the actions
function modifyLiquiditiesWithoutUnlock(bytes calldata actions, bytes[] calldata params) external payable;
/// @notice Used to get the ID that will be used for the next minted liquidity position
/// @return uint256 The next token ID
function nextTokenId() external view returns (uint256);
/// @notice Returns the liquidity of a position
/// @param tokenId the ERC721 tokenId
/// @return liquidity the position's liquidity, as a liquidityAmount
/// @dev this value can be processed as an amount0 and amount1 by using the LiquidityAmounts library
function getPositionLiquidity(uint256 tokenId) external view returns (uint128 liquidity);
/// @notice Returns the pool key and position info of a position
/// @param tokenId the ERC721 tokenId
/// @return poolKey the pool key of the position
/// @return PositionInfo a uint256 packed value holding information about the position including the range (tickLower, tickUpper)
function getPoolAndPositionInfo(uint256 tokenId) external view returns (PoolKey memory, PositionInfo);
/// @notice Returns the position info of a position
/// @param tokenId the ERC721 tokenId
/// @return a uint256 packed value holding information about the position including the range (tickLower, tickUpper)
function positionInfo(uint256 tokenId) external view returns (PositionInfo);
}
dependencies/v4-periphery-main/src/interfaces/ISubscriber.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {BalanceDelta} from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import {PositionInfo} from "../libraries/PositionInfoLibrary.sol";
/// @title ISubscriber
/// @notice Interface that a Subscriber contract should implement to receive updates from the v4 position manager
interface ISubscriber {
/// @notice Called when a position subscribes to this subscriber contract
/// @param tokenId the token ID of the position
/// @param data additional data passed in by the caller
function notifySubscribe(uint256 tokenId, bytes memory data) external;
/// @notice Called when a position unsubscribes from the subscriber
/// @dev This call's gas is capped at `unsubscribeGasLimit` (set at deployment)
/// @dev Because of EIP-150, solidity may only allocate 63/64 of gasleft()
/// @param tokenId the token ID of the position
function notifyUnsubscribe(uint256 tokenId) external;
/// @notice Called when a position is burned
/// @param tokenId the token ID of the position
/// @param owner the current owner of the tokenId
/// @param info information about the position
/// @param liquidity the amount of liquidity decreased in the position, may be 0
/// @param feesAccrued the fees accrued by the position if liquidity was decreased
function notifyBurn(uint256 tokenId, address owner, PositionInfo info, uint256 liquidity, BalanceDelta feesAccrued)
external;
/// @notice Called when a position modifies its liquidity or collects fees
/// @param tokenId the token ID of the position
/// @param liquidityChange the change in liquidity on the underlying position
/// @param feesAccrued the fees to be collected from the position as a result of the modifyLiquidity call
/// @dev Note that feesAccrued can be artificially inflated by a malicious user
/// Pools with a single liquidity position can inflate feeGrowthGlobal (and consequently feesAccrued) by donating to themselves;
/// atomically donating and collecting fees within the same unlockCallback may further inflate feeGrowthGlobal/feesAccrued
function notifyModifyLiquidity(uint256 tokenId, int256 liquidityChange, BalanceDelta feesAccrued) external;
}
dependencies/v4-periphery-main/src/interfaces/IUnorderedNonce.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title IUnorderedNonce
/// @notice Interface for the UnorderedNonce contract
interface IUnorderedNonce {
error NonceAlreadyUsed();
/// @notice mapping of nonces consumed by each address, where a nonce is a single bit on the 256-bit bitmap
/// @dev word is at most type(uint248).max
function nonces(address owner, uint256 word) external view returns (uint256);
/// @notice Revoke a nonce by spending it, preventing it from being used again
/// @dev Used in cases where a valid nonce has not been broadcasted onchain, and the owner wants to revoke the validity of the nonce
/// @dev payable so it can be multicalled with native-token related actions
function revokeNonce(uint256 nonce) external payable;
}
dependencies/v4-periphery-main/src/interfaces/external/IWETH9.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title IWETH9
interface IWETH9 is IERC20 {
/// @notice Deposit ether to get wrapped ether
function deposit() external payable;
/// @notice Withdraw wrapped ether to get ether
function withdraw(uint256) external;
}
dependencies/v4-periphery-main/src/libraries/LiquidityAmounts.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {FullMath} from "@uniswap/v4-core/src/libraries/FullMath.sol";
import {FixedPoint96} from "@uniswap/v4-core/src/libraries/FixedPoint96.sol";
import {SafeCast} from "@uniswap/v4-core/src/libraries/SafeCast.sol";
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
using SafeCast for uint256;
/// @notice Computes the amount of liquidity received for a given amount of token0 and price range
/// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
/// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
/// @param sqrtPriceBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount0 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount0(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint256 amount0)
internal
pure
returns (uint128 liquidity)
{
unchecked {
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
uint256 intermediate = FullMath.mulDiv(sqrtPriceAX96, sqrtPriceBX96, FixedPoint96.Q96);
return FullMath.mulDiv(amount0, intermediate, sqrtPriceBX96 - sqrtPriceAX96).toUint128();
}
}
/// @notice Computes the amount of liquidity received for a given amount of token1 and price range
/// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
/// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
/// @param sqrtPriceBX96 A sqrt price representing the second tick boundary
/// @param amount1 The amount1 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount1(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint256 amount1)
internal
pure
returns (uint128 liquidity)
{
unchecked {
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
return FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtPriceBX96 - sqrtPriceAX96).toUint128();
}
}
/// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtPriceX96 A sqrt price representing the current pool prices
/// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
/// @param sqrtPriceBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount of token0 being sent in
/// @param amount1 The amount of token1 being sent in
/// @return liquidity The maximum amount of liquidity received
function getLiquidityForAmounts(
uint160 sqrtPriceX96,
uint160 sqrtPriceAX96,
uint160 sqrtPriceBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
if (sqrtPriceX96 <= sqrtPriceAX96) {
liquidity = getLiquidityForAmount0(sqrtPriceAX96, sqrtPriceBX96, amount0);
} else if (sqrtPriceX96 < sqrtPriceBX96) {
uint128 liquidity0 = getLiquidityForAmount0(sqrtPriceX96, sqrtPriceBX96, amount0);
uint128 liquidity1 = getLiquidityForAmount1(sqrtPriceAX96, sqrtPriceX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
} else {
liquidity = getLiquidityForAmount1(sqrtPriceAX96, sqrtPriceBX96, amount1);
}
}
}
dependencies/v4-periphery-main/src/libraries/PositionInfoLibrary.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {PoolId} from "@uniswap/v4-core/src/types/PoolId.sol";
/**
* @dev PositionInfo is a packed version of solidity structure.
* Using the packaged version saves gas and memory by not storing the structure fields in memory slots.
*
* Layout:
* 200 bits poolId | 24 bits tickUpper | 24 bits tickLower | 8 bits hasSubscriber
*
* Fields in the direction from the least significant bit:
*
* A flag to know if the tokenId is subscribed to an address
* uint8 hasSubscriber;
*
* The tickUpper of the position
* int24 tickUpper;
*
* The tickLower of the position
* int24 tickLower;
*
* The truncated poolId. Truncates a bytes32 value so the most signifcant (highest) 200 bits are used.
* bytes25 poolId;
*
* Note: If more bits are needed, hasSubscriber can be a single bit.
*
*/
type PositionInfo is uint256;
using PositionInfoLibrary for PositionInfo global;
library PositionInfoLibrary {
PositionInfo internal constant EMPTY_POSITION_INFO = PositionInfo.wrap(0);
uint256 internal constant MASK_UPPER_200_BITS = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000;
uint256 internal constant MASK_8_BITS = 0xFF;
uint24 internal constant MASK_24_BITS = 0xFFFFFF;
uint256 internal constant SET_UNSUBSCRIBE = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00;
uint256 internal constant SET_SUBSCRIBE = 0x01;
uint8 internal constant TICK_LOWER_OFFSET = 8;
uint8 internal constant TICK_UPPER_OFFSET = 32;
/// @dev This poolId is NOT compatible with the poolId used in UniswapV4 core. It is truncated to 25 bytes, and just used to lookup PoolKey in the poolKeys mapping.
function poolId(PositionInfo info) internal pure returns (bytes25 _poolId) {
assembly ("memory-safe") {
_poolId := and(MASK_UPPER_200_BITS, info)
}
}
function tickLower(PositionInfo info) internal pure returns (int24 _tickLower) {
assembly ("memory-safe") {
_tickLower := signextend(2, shr(TICK_LOWER_OFFSET, info))
}
}
function tickUpper(PositionInfo info) internal pure returns (int24 _tickUpper) {
assembly ("memory-safe") {
_tickUpper := signextend(2, shr(TICK_UPPER_OFFSET, info))
}
}
function hasSubscriber(PositionInfo info) internal pure returns (bool _hasSubscriber) {
assembly ("memory-safe") {
_hasSubscriber := and(MASK_8_BITS, info)
}
}
/// @dev this does not actually set any storage
function setSubscribe(PositionInfo info) internal pure returns (PositionInfo _info) {
assembly ("memory-safe") {
_info := or(info, SET_SUBSCRIBE)
}
}
/// @dev this does not actually set any storage
function setUnsubscribe(PositionInfo info) internal pure returns (PositionInfo _info) {
assembly ("memory-safe") {
_info := and(info, SET_UNSUBSCRIBE)
}
}
/// @notice Creates the default PositionInfo struct
/// @dev Called when minting a new position
/// @param _poolKey the pool key of the position
/// @param _tickLower the lower tick of the position
/// @param _tickUpper the upper tick of the position
/// @return info packed position info, with the truncated poolId and the hasSubscriber flag set to false
function initialize(PoolKey memory _poolKey, int24 _tickLower, int24 _tickUpper)
internal
pure
returns (PositionInfo info)
{
bytes25 _poolId = bytes25(PoolId.unwrap(_poolKey.toId()));
assembly {
info :=
or(
or(and(MASK_UPPER_200_BITS, _poolId), shl(TICK_UPPER_OFFSET, and(MASK_24_BITS, _tickUpper))),
shl(TICK_LOWER_OFFSET, and(MASK_24_BITS, _tickLower))
)
}
}
}
dependencies/v4-periphery-main/src/utils/BaseHook.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Hooks} from "@uniswap/v4-core/src/libraries/Hooks.sol";
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol";
import {BalanceDelta} from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {BeforeSwapDelta} from "@uniswap/v4-core/src/types/BeforeSwapDelta.sol";
import {ImmutableState} from "../base/ImmutableState.sol";
import {ModifyLiquidityParams, SwapParams} from "@uniswap/v4-core/src/types/PoolOperation.sol";
/// @title Base Hook
/// @notice abstract contract for hook implementations
abstract contract BaseHook is IHooks, ImmutableState {
error HookNotImplemented();
constructor(IPoolManager _manager) ImmutableState(_manager) {
validateHookAddress(this);
}
/// @notice Returns a struct of permissions to signal which hook functions are to be implemented
/// @dev Used at deployment to validate the address correctly represents the expected permissions
/// @return Permissions struct
function getHookPermissions() public pure virtual returns (Hooks.Permissions memory);
/// @notice Validates the deployed hook address agrees with the expected permissions of the hook
/// @dev this function is virtual so that we can override it during testing,
/// which allows us to deploy an implementation to any address
/// and then etch the bytecode into the correct address
function validateHookAddress(BaseHook _this) internal pure virtual {
Hooks.validateHookPermissions(_this, getHookPermissions());
}
/// @inheritdoc IHooks
function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96)
external
onlyPoolManager
returns (bytes4)
{
return _beforeInitialize(sender, key, sqrtPriceX96);
}
function _beforeInitialize(address, PoolKey calldata, uint160) internal virtual returns (bytes4) {
revert HookNotImplemented();
}
/// @inheritdoc IHooks
function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)
external
onlyPoolManager
returns (bytes4)
{
return _afterInitialize(sender, key, sqrtPriceX96, tick);
}
function _afterInitialize(address, PoolKey calldata, uint160, int24) internal virtual returns (bytes4) {
revert HookNotImplemented();
}
/// @inheritdoc IHooks
function beforeAddLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
bytes calldata hookData
) external onlyPoolManager returns (bytes4) {
return _beforeAddLiquidity(sender, key, params, hookData);
}
function _beforeAddLiquidity(address, PoolKey calldata, ModifyLiquidityParams calldata, bytes calldata)
internal
virtual
returns (bytes4)
{
revert HookNotImplemented();
}
/// @inheritdoc IHooks
function beforeRemoveLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
bytes calldata hookData
) external onlyPoolManager returns (bytes4) {
return _beforeRemoveLiquidity(sender, key, params, hookData);
}
function _beforeRemoveLiquidity(address, PoolKey calldata, ModifyLiquidityParams calldata, bytes calldata)
internal
virtual
returns (bytes4)
{
revert HookNotImplemented();
}
/// @inheritdoc IHooks
function afterAddLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external onlyPoolManager returns (bytes4, BalanceDelta) {
return _afterAddLiquidity(sender, key, params, delta, feesAccrued, hookData);
}
function _afterAddLiquidity(
address,
PoolKey calldata,
ModifyLiquidityParams calldata,
BalanceDelta,
BalanceDelta,
bytes calldata
) internal virtual returns (bytes4, BalanceDelta) {
revert HookNotImplemented();
}
/// @inheritdoc IHooks
function afterRemoveLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external onlyPoolManager returns (bytes4, BalanceDelta) {
return _afterRemoveLiquidity(sender, key, params, delta, feesAccrued, hookData);
}
function _afterRemoveLiquidity(
address,
PoolKey calldata,
ModifyLiquidityParams calldata,
BalanceDelta,
BalanceDelta,
bytes calldata
) internal virtual returns (bytes4, BalanceDelta) {
revert HookNotImplemented();
}
/// @inheritdoc IHooks
function beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata hookData)
external
onlyPoolManager
returns (bytes4, BeforeSwapDelta, uint24)
{
return _beforeSwap(sender, key, params, hookData);
}
function _beforeSwap(address, PoolKey calldata, SwapParams calldata, bytes calldata)
internal
virtual
returns (bytes4, BeforeSwapDelta, uint24)
{
revert HookNotImplemented();
}
/// @inheritdoc IHooks
function afterSwap(
address sender,
PoolKey calldata key,
SwapParams calldata params,
BalanceDelta delta,
bytes calldata hookData
) external onlyPoolManager returns (bytes4, int128) {
return _afterSwap(sender, key, params, delta, hookData);
}
function _afterSwap(address, PoolKey calldata, SwapParams calldata, BalanceDelta, bytes calldata)
internal
virtual
returns (bytes4, int128)
{
revert HookNotImplemented();
}
/// @inheritdoc IHooks
function beforeDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external onlyPoolManager returns (bytes4) {
return _beforeDonate(sender, key, amount0, amount1, hookData);
}
function _beforeDonate(address, PoolKey calldata, uint256, uint256, bytes calldata)
internal
virtual
returns (bytes4)
{
revert HookNotImplemented();
}
/// @inheritdoc IHooks
function afterDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external onlyPoolManager returns (bytes4) {
return _afterDonate(sender, key, amount0, amount1, hookData);
}
function _afterDonate(address, PoolKey calldata, uint256, uint256, bytes calldata)
internal
virtual
returns (bytes4)
{
revert HookNotImplemented();
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "none",
"useLiteralContent": false
},
"optimizer": {
"runs": 100,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@uniswap/v4-core/=dependencies/v4-core-main/",
"@uniswap/v4-periphery/=dependencies/v4-periphery-main/",
"forge-std/=dependencies/forge-std-1.10.0/src/",
"ds-test/=dependencies/v4-core-main/lib/forge-std/lib/ds-test/src/",
"solmate/=dependencies/v4-core-main/lib/solmate/",
"permit2/=dependencies/v4-periphery-main/lib/permit2/",
"@openzeppelin/contracts/=dependencies/@openzeppelin-contracts-5.1.0/",
"@openzeppelin-contracts-5.1.0/=dependencies/@openzeppelin-contracts-5.1.0/",
"forge-std-1.10.0/=dependencies/forge-std-1.10.0/",
"@ensdomains/=dependencies/v4-core-main/node_modules/@ensdomains/",
"erc4626-tests/=dependencies/v4-core-main/lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-gas-snapshot/=dependencies/v4-periphery-main/lib/permit2/lib/forge-gas-snapshot/src/",
"hardhat/=dependencies/v4-core-main/node_modules/hardhat/",
"openzeppelin-contracts/=dependencies/v4-core-main/lib/openzeppelin-contracts/",
"v4-core-main/=dependencies/v4-core-main/src/",
"v4-core/=dependencies/v4-periphery-main/lib/v4-core/src/",
"v4-periphery-main/=dependencies/v4-periphery-main/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.