Verified contractPartialMIT
GeodeHook
Address0xb68ef30b0e55172c8aa38ea4f3bca99c789d8088
- Balance
0 ETH
- Transactions
1,670
- Compiler
solc 0.8.27
- Same code
1 more contract
Details
- Compiler
- solc 0.8.27+commit.40a35a09
- Language
- solidity
- Optimization
- Yes, 10 runs
- EVM version
- cancun
- Via IR
- yes
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,060,425
- Creation transaction
- 0xdaa1466672…c61a4aafd7
34 files
- src/GeodeHook.solmain56.72 KB
- lib/permit2/src/interfaces/IEIP712.sol144 B
- lib/permit2/src/interfaces/ISignatureTransfer.sol6.88 KB
- lib/v4-core/src/interfaces/IExtsload.sol1.02 KB
- lib/v4-core/src/interfaces/IExttload.sol699 B
- lib/v4-core/src/interfaces/IHooks.sol8.23 KB
- lib/v4-core/src/interfaces/IPoolManager.sol12.84 KB
- lib/v4-core/src/interfaces/IProtocolFees.sol2.49 KB
- lib/v4-core/src/interfaces/callback/IUnlockCallback.sol488 B
- lib/v4-core/src/interfaces/external/IERC20Minimal.sol3.04 KB
- lib/v4-core/src/interfaces/external/IERC6909Claims.sol3.16 KB
- lib/v4-core/src/libraries/BitMath.sol2.61 KB
- lib/v4-core/src/libraries/CustomRevert.sol5.17 KB
- lib/v4-core/src/libraries/FixedPoint128.sol297 B
- lib/v4-core/src/libraries/FullMath.sol5.46 KB
- lib/v4-core/src/libraries/Hooks.sol16.51 KB
- lib/v4-core/src/libraries/LPFeeLibrary.sol3.6 KB
- lib/v4-core/src/libraries/LiquidityMath.sol742 B
- lib/v4-core/src/libraries/ParseBytes.sol1.2 KB
- lib/v4-core/src/libraries/Position.sol4.81 KB
- lib/v4-core/src/libraries/SafeCast.sol2.27 KB
- lib/v4-core/src/libraries/StateLibrary.sol16.03 KB
- lib/v4-core/src/libraries/TickMath.sol12.38 KB
- lib/v4-core/src/types/BalanceDelta.sol2.34 KB
- lib/v4-core/src/types/BeforeSwapDelta.sol1.47 KB
- lib/v4-core/src/types/Currency.sol5.46 KB
- lib/v4-core/src/types/PoolId.sol539 B
- lib/v4-core/src/types/PoolKey.sol805 B
- lib/v4-core/src/types/PoolOperation.sol907 B
- src/interfaces/IGeodeHook.sol7.47 KB
- src/libraries/ClearingPriceLib.sol7.68 KB
- src/libraries/ConstantProductCurveLib.sol12.96 KB
- src/libraries/GeodeTypes.sol8.62 KB
- src/libraries/IntentLib.sol4.64 KB
src/GeodeHook.sol
// SPDX-License-Identifier: MIT
//
// ██████╗ ███████╗ ██████╗ ██████╗ ███████╗
// ██╔════╝ ██╔════╝██╔═══██╗██╔══██╗██╔════╝
// ██║ ███╗█████╗ ██║ ██║██║ ██║█████╗
// ██║ ██║██╔══╝ ██║ ██║██║ ██║██╔══╝
// ╚██████╔╝███████╗╚██████╔╝██████╔╝███████╗
// ╚═════╝ ╚══════╝ ╚═════╝ ╚═════╝ ╚══════╝
//
// Geode Protocol — Permanent Curve Venue on Uniswap v4
// https://geode.ag
//
pragma solidity ^0.8.26;
import {IPoolManager} from "v4-core/src/interfaces/IPoolManager.sol";
import {IHooks} from "v4-core/src/interfaces/IHooks.sol";
import {IUnlockCallback} from "v4-core/src/interfaces/callback/IUnlockCallback.sol";
import {Hooks} from "v4-core/src/libraries/Hooks.sol";
import {StateLibrary} from "v4-core/src/libraries/StateLibrary.sol";
import {PoolKey} from "v4-core/src/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "v4-core/src/types/PoolId.sol";
import {BalanceDelta} from "v4-core/src/types/BalanceDelta.sol";
import {BeforeSwapDelta, BeforeSwapDeltaLibrary} from "v4-core/src/types/BeforeSwapDelta.sol";
import {Currency, CurrencyLibrary} from "v4-core/src/types/Currency.sol";
import {SwapParams, ModifyLiquidityParams} from "v4-core/src/types/PoolOperation.sol";
import {TickMath} from "v4-core/src/libraries/TickMath.sol";
import {ISignatureTransfer} from "permit2/src/interfaces/ISignatureTransfer.sol";
import {IERC20Minimal} from "v4-core/src/interfaces/external/IERC20Minimal.sol";
import {GeodeIntent, BatchState, SettlementResult, PoolConfig, LaunchState, LaunchPhase, GeodeTypes} from "./libraries/GeodeTypes.sol";
import {ClearingPriceLib} from "./libraries/ClearingPriceLib.sol";
import {ConstantProductCurveLib} from "./libraries/ConstantProductCurveLib.sol";
import {IntentLib} from "./libraries/IntentLib.sol";
import {IGeodeHook} from "./interfaces/IGeodeHook.sol";
/// @title GeodeHook
/// @author Geode Protocol (https://geode.ag)
/// @notice Uniswap v4 hook powering permanent bonding curves with MEV-protected batch settlement.
/// @dev Each launched token lives on a permanent virtual constant-product curve (geocurve).
/// Traders interact via two paths:
/// - Direct Swap: Instant execution against the curve via beforeSwap (0.3% fee, 3-way split)
/// - Batch Intent: Gasless EIP-712 intents settled at a uniform clearing price (0.1% fee)
///
/// Key architectural invariants:
/// 1. PERMANENT CURVE: No graduation, no migration — the curve is the venue forever
/// 2. SURPLUS-ONLY CUSTODY: The hook holds only accumulated fees and curve reserves.
/// Settlement tokens never rest in the hook between transactions.
/// 3. PERMISSIONLESS: Anyone can call geodeSettleBatch() and earn surplus rewards.
/// 4. IMMUTABLE: No admin keys, no upgradeability, no privileged roles.
/// 5. ON-CHAIN ONLY: No off-chain state dependency for any contract function.
contract GeodeHook is IHooks, IGeodeHook, IUnlockCallback {
using PoolIdLibrary for PoolKey;
using CurrencyLibrary for Currency;
using StateLibrary for IPoolManager;
// ─── Immutables ─────────────────────────────────────────────────────────────
IPoolManager public immutable poolManager;
ISignatureTransfer public immutable permit2;
address public immutable protocolTreasury;
address public immutable factory;
/// @notice Protocol's share of direct swap fees (1/3 of total)
uint256 public constant PROTOCOL_FEE_SHARE_BPS = 3333;
/// @notice Curve reserve's share of direct swap fees (1/3 of total)
uint256 public constant CURVE_RESERVE_FEE_SHARE_BPS = 3334;
// Remaining 1/3 goes to surplus (for settler gas reimbursement)
// ─── State ──────────────────────────────────────────────────────────────────
/// @notice Per-pool configuration (set once via geodeInitializePool)
mapping(PoolId => PoolConfig) internal _poolConfigs;
/// @notice Whether a pool has been configured
mapping(PoolId => bool) public poolInitialized;
/// @notice Last block at which a pool was settled
mapping(PoolId => uint256) public lastSettledBlock;
/// @notice Most recent batch state per pool (overwritten each cycle)
mapping(PoolId => BatchState) internal _currentBatch;
/// @notice Accumulated currency0 surplus per pool from direct swap fees
mapping(PoolId => uint256) public surplusCurrency0;
/// @notice Accumulated currency1 surplus per pool from direct swap fees
mapping(PoolId => uint256) public surplusCurrency1;
/// @notice Per-pool launch curve state (only used for launch-mode pools)
mapping(PoolId => LaunchState) internal _launchStates;
/// @notice Launch token reserve per pool (tokens held by hook for curve dispensing)
mapping(PoolId => uint256) public launchTokenReserve;
/// @notice Launch ETH reserve per pool (ETH accumulated from curve sales)
mapping(PoolId => uint256) public launchEthReserve;
// ─── Errors ─────────────────────────────────────────────────────────────────
error OnlyPoolManager();
error OnlyFactory();
error PoolAlreadyInitialized();
error PoolNotConfigured();
error BatchTooEarly(uint256 currentBlock, uint256 earliestAllowed);
error InvalidBatchSize();
error LaunchAlreadyRegistered();
error InsufficientCurveReserve();
// ─── Constructor ────────────────────────────────────────────────────────────
constructor(IPoolManager _poolManager, ISignatureTransfer _permit2, address _protocolTreasury, address _factory) {
poolManager = _poolManager;
permit2 = _permit2;
protocolTreasury = _protocolTreasury;
factory = _factory;
}
// ─── Modifiers ──────────────────────────────────────────────────────────────
modifier onlyPoolManager() {
_checkPoolManager();
_;
}
function _checkPoolManager() internal view {
if (msg.sender != address(poolManager)) revert OnlyPoolManager();
}
// ─── Hook Permissions ───────────────────────────────────────────────────────
function getHookPermissions() public pure returns (Hooks.Permissions memory) {
return Hooks.Permissions({
beforeInitialize: false,
afterInitialize: false,
beforeAddLiquidity: false,
afterAddLiquidity: false,
beforeRemoveLiquidity: false,
afterRemoveLiquidity: false,
beforeSwap: true,
afterSwap: false,
beforeDonate: false,
afterDonate: false,
beforeSwapReturnDelta: true,
afterSwapReturnDelta: false,
afterAddLiquidityReturnDelta: false,
afterRemoveLiquidityReturnDelta: false
});
}
// ─── Hook Callbacks (IHooks) ────────────────────────────────────────────────
/// @notice Called before every swap. For curve pools: implements direct bonding curve trading.
/// For standard pools: captures a direct swap fee from AMM output.
/// @dev Curve pools: the hook computes bonding curve output and returns the full delta via
/// BEFORE_SWAP_RETURNS_DELTA, completely bypassing the AMM. The pool has no liquidity;
/// the hook IS the market maker. Fee is 0.3% split three ways:
/// 1/3 → curve ETH reserve (permanent floor price increase)
/// 1/3 → surplus pool (funds settler gas reimbursement)
/// 1/3 → protocol treasury
/// Standard pools: fee charged on unspecified (output) side, split treasury/surplus.
/// When geodeSettleBatch() routes residual (sender == address(this)), no fee is applied.
function beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata)
external
override
onlyPoolManager
returns (bytes4, BeforeSwapDelta, uint24)
{
// Internal settlement residual — no fee, pass through
if (sender == address(this)) {
return (IHooks.beforeSwap.selector, BeforeSwapDeltaLibrary.ZERO_DELTA, 0);
}
PoolId poolId = key.toId();
LaunchState storage ls = _launchStates[poolId];
// ── Curve pool: hook handles entire swap via bonding curve ──
if (ls.tokenAddress != address(0) && ls.phase == LaunchPhase.Active) {
return _curveDirectSwap(key, poolId, ls, params, sender);
}
// ── Standard pool (non-curve): charge flat fee, let AMM execute ──
PoolConfig storage config = _poolConfigs[poolId];
if (config.directSwapFeeBps > 0) {
uint256 absAmount = params.amountSpecified < 0
? uint256(-params.amountSpecified)
: uint256(params.amountSpecified);
uint256 feeAmount = (absAmount * config.directSwapFeeBps) / GeodeTypes.BPS_DENOMINATOR;
if (feeAmount > 0) {
// Determine unspecified currency (output side of the swap)
bool exactInput = params.amountSpecified < 0;
bool unspecifiedIsCurrency1 = (params.zeroForOne == exactInput);
Currency unspecified = unspecifiedIsCurrency1 ? key.currency1 : key.currency0;
// Split fee: ~33% to protocol treasury, ~67% to surplus
uint256 protocolFee = (feeAmount * PROTOCOL_FEE_SHARE_BPS) / GeodeTypes.BPS_DENOMINATOR;
uint256 surplusFee = feeAmount - protocolFee;
if (protocolFee > 0) {
poolManager.take(unspecified, protocolTreasury, protocolFee);
}
if (surplusFee > 0) {
poolManager.take(unspecified, address(this), surplusFee);
}
if (unspecifiedIsCurrency1) {
surplusCurrency1[poolId] += surplusFee;
} else {
surplusCurrency0[poolId] += surplusFee;
}
emit GeodeDirectSwap(poolId, sender, config.directSwapFeeBps, feeAmount);
emit GeodeProtocolFeeCollected(poolId, unspecified, protocolFee);
BeforeSwapDelta delta = BeforeSwapDelta.wrap(int256(feeAmount));
return (IHooks.beforeSwap.selector, delta, 0);
}
}
return (IHooks.beforeSwap.selector, BeforeSwapDeltaLibrary.ZERO_DELTA, 0);
}
/// @notice Implements direct bonding curve swap via beforeSwap delta return.
/// @dev The hook computes the curve output, transfers tokens, and returns the full delta
/// so the AMM (which has no liquidity) does nothing. Fee is split three ways:
/// 1/3 to curve reserve (permanent), 1/3 to surplus, 1/3 to treasury.
function _curveDirectSwap(
PoolKey calldata key,
PoolId poolId,
LaunchState storage ls,
SwapParams calldata params,
address sender
) internal returns (bytes4, BeforeSwapDelta, uint24) {
PoolConfig storage config = _poolConfigs[poolId];
bool tokenIsCurrency0 = (ls.tokenAddress == Currency.unwrap(key.currency0));
Currency tokenCurrency = tokenIsCurrency0 ? key.currency0 : key.currency1;
Currency ethCurrency = tokenIsCurrency0 ? key.currency1 : key.currency0;
// Determine if this is a curve BUY (ETH→TOKEN) or SELL (TOKEN→ETH)
// zeroForOne = true means swapping currency0 → currency1
bool isCurveBuy;
if (tokenIsCurrency0) {
isCurveBuy = !params.zeroForOne; // currency1(ETH) → currency0(TOKEN)
} else {
isCurveBuy = params.zeroForOne; // currency0(ETH) → currency1(TOKEN)
}
// We only support exactInput swaps on the curve
require(params.amountSpecified < 0, "Curve: exactInput only");
uint256 inputAmount = uint256(-params.amountSpecified);
// ── Fee calculation: 0.3% split three ways ──
uint256 totalFee = (inputAmount * config.directSwapFeeBps) / GeodeTypes.BPS_DENOMINATOR;
uint256 netInput = inputAmount - totalFee;
uint256 reserveFee = (totalFee * CURVE_RESERVE_FEE_SHARE_BPS) / GeodeTypes.BPS_DENOMINATOR;
uint256 protocolFee = (totalFee * PROTOCOL_FEE_SHARE_BPS) / GeodeTypes.BPS_DENOMINATOR;
uint256 surplusFee = totalFee - reserveFee - protocolFee;
uint256 outputAmount;
if (isCurveBuy) {
// ETH → TOKEN: dispense from curve reserve
outputAmount = ConstantProductCurveLib.tokensForEth(
ls.virtualTokenReserve, ls.virtualEthReserve,
ls.cumulativeSupplyDistributed, ls.ethReserve, netInput
);
if (launchTokenReserve[poolId] < outputAmount) revert InsufficientCurveReserve();
// Update curve state
launchTokenReserve[poolId] -= outputAmount;
launchEthReserve[poolId] += netInput + reserveFee; // reserveFee stays in curve permanently
ls.ethReserve += netInput + reserveFee;
ls.cumulativeSupplyDistributed += outputAmount;
// 1. Take ETH input from PM (user must pre-settle before swap)
poolManager.take(ethCurrency, address(this), netInput + reserveFee);
// 2. Send TOKEN from hook to PoolManager for the swapper
poolManager.sync(tokenCurrency);
IERC20Minimal(ls.tokenAddress).transfer(address(poolManager), outputAmount);
poolManager.settle();
} else {
// TOKEN → ETH: absorb tokens, return ETH from reserve
outputAmount = ConstantProductCurveLib.ethReturnOnSell(
ls.virtualTokenReserve, ls.virtualEthReserve,
ls.cumulativeSupplyDistributed, ls.ethReserve, netInput
);
if (launchEthReserve[poolId] < outputAmount) revert InsufficientCurveReserve();
// Update curve state (reserveFee is in token terms here, stays in token reserve)
launchTokenReserve[poolId] += netInput + reserveFee;
launchEthReserve[poolId] -= outputAmount;
ls.ethReserve -= outputAmount;
ls.cumulativeSupplyDistributed -= (netInput + reserveFee); // all absorbed tokens reduce distributed
// 1. Take token input from PM (user must pre-settle before swap)
poolManager.take(tokenCurrency, address(this), netInput + reserveFee);
// 2. Send ETH from hook to PM for the swapper
poolManager.sync(ethCurrency);
IERC20Minimal(Currency.unwrap(ethCurrency)).transfer(address(poolManager), outputAmount);
poolManager.settle();
}
// ── Distribute non-reserve fees ──
// Protocol fee → treasury
if (protocolFee > 0) {
Currency feeCurrency = isCurveBuy ? ethCurrency : tokenCurrency;
poolManager.take(feeCurrency, protocolTreasury, protocolFee);
emit GeodeProtocolFeeCollected(poolId, feeCurrency, protocolFee);
}
// Surplus fee → hook (for settler gas reimbursement)
if (surplusFee > 0) {
Currency feeCurrency = isCurveBuy ? ethCurrency : tokenCurrency;
poolManager.take(feeCurrency, address(this), surplusFee);
// Track in appropriate surplus bucket
if ((isCurveBuy && tokenIsCurrency0) || (!isCurveBuy && !tokenIsCurrency0)) {
surplusCurrency1[poolId] += surplusFee;
} else {
surplusCurrency0[poolId] += surplusFee;
}
}
emit GeodeCurveSwap(
poolId, sender, isCurveBuy, inputAmount, outputAmount,
totalFee, reserveFee, launchEthReserve[poolId]
);
// Return delta: hook absorbs full specified input, provides full unspecified output
// deltaSpecified > 0 means "hook credits specified side" (absorbs user's input for AMM)
// deltaUnspecified > 0 means "hook credits unspecified side" (provides output)
// Since pool has no liquidity, AMM processes nothing. Hook handles everything.
int128 deltaSpecified = int128(int256(inputAmount));
int128 deltaUnspecified = -int128(int256(outputAmount));
BeforeSwapDelta delta = BeforeSwapDelta.wrap(
int256(deltaSpecified) << 128 | int256(uint256(uint128(deltaUnspecified)))
);
return (IHooks.beforeSwap.selector, delta, 0);
}
/// @inheritdoc IHooks
function afterSwap(address, PoolKey calldata, SwapParams calldata, BalanceDelta, bytes calldata)
external pure override returns (bytes4, int128)
{
return (IHooks.afterSwap.selector, 0);
}
/// @inheritdoc IHooks
function beforeInitialize(address, PoolKey calldata, uint160) external pure override returns (bytes4) {
return IHooks.beforeInitialize.selector;
}
/// @inheritdoc IHooks
function afterInitialize(address, PoolKey calldata, uint160, int24) external pure override returns (bytes4) {
return IHooks.afterInitialize.selector;
}
/// @inheritdoc IHooks
function beforeAddLiquidity(address, PoolKey calldata, ModifyLiquidityParams calldata, bytes calldata)
external pure override returns (bytes4)
{
return IHooks.beforeAddLiquidity.selector;
}
/// @inheritdoc IHooks
function afterAddLiquidity(address, PoolKey calldata, ModifyLiquidityParams calldata, BalanceDelta, BalanceDelta, bytes calldata)
external pure override returns (bytes4, BalanceDelta)
{
return (IHooks.afterAddLiquidity.selector, BalanceDelta.wrap(0));
}
/// @inheritdoc IHooks
function beforeRemoveLiquidity(address, PoolKey calldata, ModifyLiquidityParams calldata, bytes calldata)
external pure override returns (bytes4)
{
return IHooks.beforeRemoveLiquidity.selector;
}
/// @inheritdoc IHooks
function afterRemoveLiquidity(address, PoolKey calldata, ModifyLiquidityParams calldata, BalanceDelta, BalanceDelta, bytes calldata)
external pure override returns (bytes4, BalanceDelta)
{
return (IHooks.afterRemoveLiquidity.selector, BalanceDelta.wrap(0));
}
/// @inheritdoc IHooks
function beforeDonate(address, PoolKey calldata, uint256, uint256, bytes calldata)
external pure override returns (bytes4)
{
return IHooks.beforeDonate.selector;
}
/// @inheritdoc IHooks
function afterDonate(address, PoolKey calldata, uint256, uint256, bytes calldata)
external pure override returns (bytes4)
{
return IHooks.afterDonate.selector;
}
// ─── Pool Configuration ─────────────────────────────────────────────────────
/// @inheritdoc IGeodeHook
function geodeInitializePool(PoolKey calldata key, PoolConfig calldata config) external {
PoolId poolId = key.toId();
if (poolInitialized[poolId]) revert PoolAlreadyInitialized();
if (config.maxBatchSize == 0 || config.maxBatchSize > GeodeTypes.ABSOLUTE_MAX_BATCH_SIZE) {
revert InvalidBatchSize();
}
// Curve pools (with deployer set) can only be initialized by the factory
if (config.deployer != address(0) && msg.sender != factory) revert OnlyFactory();
_poolConfigs[poolId] = config;
poolInitialized[poolId] = true;
emit GeodePoolConfigured(poolId, config.batchInterval, config.directSwapFeeBps, config.settlementFeeBps, config.maxBatchSize);
}
// ─── Batch Settlement ───────────────────────────────────────────────────────
/// @inheritdoc IGeodeHook
function geodeSettleBatch(
PoolKey calldata key,
GeodeIntent[] calldata buys,
GeodeIntent[] calldata sells,
bytes[] calldata buySignatures,
bytes[] calldata sellSignatures
) external override {
PoolId poolId = key.toId();
PoolConfig storage config = _poolConfigs[poolId];
if (!poolInitialized[poolId]) revert PoolNotConfigured();
// Enforce batch interval
uint256 earliest = lastSettledBlock[poolId] + config.batchInterval;
if (block.number < earliest) {
revert BatchTooEarly(block.number, earliest);
}
// Validate pool bindings and deadlines (sig verification done by Permit2 in callback)
IntentLib.validateIntents(buys, buySignatures, poolId);
IntentLib.validateIntents(sells, sellSignatures, poolId);
// Compute clearing price and determine fills
(SettlementResult memory result, bool[] memory buyFills, bool[] memory sellFills) =
_computeSettlement(key, poolId, buys, sells);
// Update batch state
_currentBatch[poolId] = BatchState({
blockNumber: block.number,
totalBuyVolume: result.internalMatch0,
totalSellVolume: result.internalMatch1,
buyIntentCount: buys.length,
sellIntentCount: sells.length,
settled: true
});
lastSettledBlock[poolId] = block.number;
// Emit fill events
for (uint256 i = 0; i < buys.length; i++) {
if (buyFills[i]) {
bytes32 intentHash = IntentLib.hashIntent(buys[i]);
uint256 amountOut = (buys[i].amountIn * GeodeTypes.Q128) / result.clearingPrice;
emit GeodeIntentFilled(intentHash, buys[i].owner, buys[i].amountIn, amountOut, result.clearingPrice);
}
}
for (uint256 i = 0; i < sells.length; i++) {
if (sellFills[i]) {
bytes32 intentHash = IntentLib.hashIntent(sells[i]);
uint256 amountOut = (sells[i].amountIn * result.clearingPrice) / GeodeTypes.Q128;
emit GeodeIntentFilled(intentHash, sells[i].owner, sells[i].amountIn, amountOut, result.clearingPrice);
}
}
// Execute token transfers via PoolManager unlock callback
// Pass gasStart for gas reimbursement calculation
uint256 gasStart = gasleft();
poolManager.unlock(abi.encode(
key, buys, sells, buySignatures, sellSignatures, buyFills, sellFills, result, msg.sender, gasStart
));
emit GeodeBatchSettled(
poolId,
block.number,
result.clearingPrice,
result.internalMatch0,
result.internalMatch1,
result.residualSwapAmount,
result.residualZeroForOne,
result.buyFees,
result.sellFees,
0, // gasReimbursement — computed inside unlock, not easily accessible here
result.ammCounterfactualPrice,
msg.sender
);
}
/// @notice Query AMM price and compute clearing price + fills
/// @dev Extracted to its own function to avoid stack-too-deep in geodeSettleBatch.
/// Reads pool config from storage directly to minimize caller stack usage.
function _computeSettlement(
PoolKey calldata key,
PoolId poolId,
GeodeIntent[] calldata buys,
GeodeIntent[] calldata sells
) internal view returns (SettlementResult memory result, bool[] memory buyFills, bool[] memory sellFills) {
PoolConfig storage config = _poolConfigs[poolId];
// ── Phase-aware routing ──
LaunchState memory ls = _launchStates[poolId];
if (ls.tokenAddress != address(0)) {
if (ls.phase == LaunchPhase.Active) {
// Curve settlement — curve price replaces AMM price
// The curve lib expects: buys = ETH→token, sells = token→ETH.
// In Uniswap, buys = tokenIn is currency0, sells = tokenIn is currency1.
// If token IS currency0, pool buys/sells are swapped
// relative to curve semantics, so we flip them.
bool tokenIsCurrency0 = (ls.tokenAddress == Currency.unwrap(key.currency0));
if (tokenIsCurrency0) {
// Token is currency0: pool buys (tokenIn=token) are curve sells,
// pool sells (tokenIn=WETH) are curve buys. Swap arrays.
(result, sellFills, buyFills) = ConstantProductCurveLib.computeLaunchSettlement(
sells, buys, config.maxBatchSize, ls,
config.settlementFeeBps, uint256(config.deployerRoyaltyBps)
);
// Swap fees back to match pool ordering
(result.buyFees, result.sellFees) = (result.sellFees, result.buyFees);
return (result, buyFills, sellFills);
} else {
return ConstantProductCurveLib.computeLaunchSettlement(
buys, sells, config.maxBatchSize, ls,
config.settlementFeeBps, uint256(config.deployerRoyaltyBps)
);
}
}
// Curve pool in Active phase is always handled above
}
// ── Standard Geode: AMM spot price as clearing price ──
(uint160 sqrtPriceX96,,,) = poolManager.getSlot0(poolId);
uint256 ammSpotPriceQ128;
if (sqrtPriceX96 > 0) {
ammSpotPriceQ128 = (uint256(sqrtPriceX96) * uint256(sqrtPriceX96)) >> 64;
} else {
ammSpotPriceQ128 = GeodeTypes.Q128;
}
(result, buyFills, sellFills) = ClearingPriceLib.computeClearingPrice(
buys, sells, config.maxBatchSize, ammSpotPriceQ128,
config.settlementFeeBps
);
}
/// @notice Route residual through AMM (or curve in launch mode), distribute outputs, pay settler
/// @dev Uses actual AMM swap deltas (not predictions) for distribution in standard mode.
/// In launch mode, residual routes to/from hook reserve via the bonding curve.
/// internalMatch0/1 are exact deposit amounts that cross internally.
/// residualSwapAmount is the exact amount to route through the AMM.
/// The swap's returned BalanceDelta is the source of truth for output.
function _routeAndDistribute(
PoolKey memory key,
GeodeIntent[] memory buys,
GeodeIntent[] memory sells,
bool[] memory buyFills,
bool[] memory sellFills,
SettlementResult memory result,
address settler,
uint256 gasStart
) internal {
PoolId poolId = key.toId();
// Compute exact deposit totals
uint256 totalBuyInput = 0;
uint256 totalSellInput = 0;
for (uint256 i = 0; i < buys.length; i++) {
if (buyFills[i]) totalBuyInput += buys[i].amountIn;
}
for (uint256 i = 0; i < sells.length; i++) {
if (sellFills[i]) totalSellInput += sells[i].amountIn;
}
if (_launchStates[poolId].tokenAddress != address(0) && _launchStates[poolId].phase == LaunchPhase.Active) {
_routeAndDistributeLaunchMode(
key, buys, sells, buyFills, sellFills, result,
settler, totalBuyInput, totalSellInput, gasStart
);
return;
}
// ── Standard pool: Route residual through AMM ──
uint256 swapOutput = 0;
if (result.residualSwapAmount > 0) {
// forge-lint: disable-next-line(unsafe-typecast)
int256 amountSpecified = -int256(result.residualSwapAmount);
uint160 sqrtPriceLimit = result.residualZeroForOne
? TickMath.MIN_SQRT_PRICE + 1
: TickMath.MAX_SQRT_PRICE - 1;
BalanceDelta swapDelta = poolManager.swap(
key,
SwapParams({
zeroForOne: result.residualZeroForOne,
amountSpecified: amountSpecified,
sqrtPriceLimitX96: sqrtPriceLimit
}),
""
);
// Capture the actual output (positive delta = tokens received by hook)
// AND actual input consumed (negative delta = tokens sent by hook)
uint256 actualInputConsumed;
if (result.residualZeroForOne) {
int128 amt1 = swapDelta.amount1();
if (amt1 > 0) swapOutput = uint256(uint128(amt1));
// amount0 is negative (hook sends currency0)
int128 amt0 = swapDelta.amount0();
actualInputConsumed = amt0 < 0 ? uint256(uint128(-amt0)) : 0;
} else {
int128 amt0 = swapDelta.amount0();
if (amt0 > 0) swapOutput = uint256(uint128(amt0));
// amount1 is negative (hook sends currency1)
int128 amt1 = swapDelta.amount1();
actualInputConsumed = amt1 < 0 ? uint256(uint128(-amt1)) : 0;
}
}
// ── Distribute outputs (fees already carved from input before routing) ──
_distributeBuyOutputs(key, buys, buyFills, totalBuyInput,
result.internalMatch1,
result.residualZeroForOne ? swapOutput : 0
);
_distributeSellOutputs(key, sells, sellFills, totalSellInput,
result.internalMatch0,
result.residualZeroForOne ? 0 : swapOutput
);
// ── Pay settler: batch fees + gas-capped surplus reimbursement ──
// Fees are always fully retained since they were carved from input deposits
_paySettler(key, poolId, result.buyFees, result.sellFees, settler, gasStart);
}
/// @notice Curve-mode routing: dispense/absorb tokens via bonding curve, no AMM swap
/// @dev In curve mode:
/// - Net buy residual: hook dispenses tokens from reserve at curve price
/// - Net sell residual: hook absorbs tokens back, returns ETH from reserve
/// - Deployer royalty is paid before settler reward
function _routeAndDistributeLaunchMode(
PoolKey memory key,
GeodeIntent[] memory buys,
GeodeIntent[] memory sells,
bool[] memory buyFills,
bool[] memory sellFills,
SettlementResult memory result,
address settler,
uint256 totalBuyInput,
uint256 totalSellInput,
uint256 gasStart
) internal {
PoolId poolId = key.toId();
PoolConfig storage config = _poolConfigs[poolId];
LaunchState storage ls = _launchStates[poolId];
// Determine which currency is the token vs ETH
// Token ordering depends on address: if token < WETH, token is currency0
Currency ethCurrency;
Currency tokenCurrency;
bool tokenIsCurrency0 = (ls.tokenAddress == Currency.unwrap(key.currency0));
if (tokenIsCurrency0) {
tokenCurrency = key.currency0;
ethCurrency = key.currency1;
} else {
ethCurrency = key.currency0;
tokenCurrency = key.currency1;
}
// ── Handle curve dispensing/absorbing ──
// When tokenIsCurrency0: pool "sells" (tokenIn=WETH) are the curve buyers,
// and pool "buys" (tokenIn=token) are the curve sellers.
// The result fields (curveDispensed, curveAbsorbed, internalMatch, fees)
// are in curve semantics because we swapped arrays in _computeSettlement.
// But totalBuyInput/totalSellInput are still in pool semantics.
uint256 ethInput = tokenIsCurrency0 ? totalSellInput : totalBuyInput;
uint256 tokenInput = tokenIsCurrency0 ? totalBuyInput : totalSellInput;
uint256 ethFees = tokenIsCurrency0 ? result.sellFees : result.buyFees;
uint256 tokenFees = tokenIsCurrency0 ? result.buyFees : result.sellFees;
uint256 curveTokenOutput = 0; // tokens for ETH-senders from curve
uint256 curveEthOutput = 0; // ETH for token-senders from curve
if (result.curveDispensed > 0) {
// Net buy: hook dispenses tokens from reserve
if (launchTokenReserve[poolId] < result.curveDispensed) {
revert InsufficientLaunchReserve();
}
launchTokenReserve[poolId] -= result.curveDispensed;
curveTokenOutput = result.curveDispensed;
// ETH going to curve = net ETH input minus internally matched
uint256 netBuyForCurve = (ethInput - ethFees) - result.internalMatch0;
launchEthReserve[poolId] += netBuyForCurve;
ls.ethReserve += netBuyForCurve;
// Update cumulative supply
ls.cumulativeSupplyDistributed += result.curveDispensed;
// Take curve-bound ETH to the hook
if (netBuyForCurve > 0) {
poolManager.take(ethCurrency, address(this), netBuyForCurve);
}
// Dispense tokens from hook
poolManager.sync(tokenCurrency);
IERC20Minimal(Currency.unwrap(tokenCurrency)).transfer(
address(poolManager), result.curveDispensed
);
poolManager.settle();
}
if (result.curveAbsorbed > 0) {
// Net sell: hook absorbs tokens, returns ETH
uint256 ethToReturn = ConstantProductCurveLib.ethReturnOnSell(
ls.virtualTokenReserve, ls.virtualEthReserve,
ls.cumulativeSupplyDistributed, ls.ethReserve, result.curveAbsorbed
);
if (launchEthReserve[poolId] < ethToReturn) {
ethToReturn = launchEthReserve[poolId];
}
launchTokenReserve[poolId] += result.curveAbsorbed;
launchEthReserve[poolId] -= ethToReturn;
ls.ethReserve -= ethToReturn;
ls.cumulativeSupplyDistributed -= result.curveAbsorbed;
curveEthOutput = ethToReturn;
// Take absorbed tokens to the hook
poolManager.take(tokenCurrency, address(this), result.curveAbsorbed);
// Return ETH
if (ethToReturn > 0) {
poolManager.sync(ethCurrency);
IERC20Minimal(Currency.unwrap(ethCurrency)).transfer(
address(poolManager), ethToReturn
);
poolManager.settle();
}
}
// ── Distribute outputs ──
// When tokenIsCurrency0: pool "sells" sent ETH and should receive tokens.
// _distributeSellOutputs sends currency0 (token) — correct for token output.
// _distributeBuyOutputs sends currency1 (token when !tokenIsCurrency0, ETH when tokenIsCurrency0).
// _distributeBuyOutputs gives currency1 to buys. _distributeSellOutputs gives currency0 to sells.
if (tokenIsCurrency0) {
// Pool buys (tokenIn=MOG) get ETH output → _distributeBuyOutputs gives currency1 (=ETH) ✓
_distributeBuyOutputs(key, buys, buyFills, totalBuyInput,
result.internalMatch0, curveEthOutput // ETH from curve for token-senders
);
// Pool sells (tokenIn=WETH) get MOG output → _distributeSellOutputs gives currency0 (=MOG) ✓
_distributeSellOutputs(key, sells, sellFills, totalSellInput,
result.internalMatch1, curveTokenOutput // tokens from curve for ETH-senders
);
} else {
// Standard ordering: buys get tokens (currency1), sells get ETH (currency0)
_distributeBuyOutputs(key, buys, buyFills, totalBuyInput,
result.internalMatch1, curveTokenOutput
);
_distributeSellOutputs(key, sells, sellFills, totalSellInput,
result.internalMatch0, curveEthOutput
);
}
// ── Fund deployer royalty from surplus ──
if (result.deployerRoyalty > 0 && config.deployer != address(0)) {
_fundDeployerRoyalty(poolId, key, result.deployerRoyalty, config.deployer);
}
// ── Distribute ETH to sellers (fees already carved from input) ──
// (handled above in the if/else block)
// ── Pay settler: batch fees + gas-capped surplus reimbursement ──
_paySettler(key, poolId, result.buyFees, result.sellFees, settler, gasStart);
}
/// @notice Fund deployer royalty from accumulated surplus
/// @dev Called before settler reward in the draw-down waterfall during launch mode
function _fundDeployerRoyalty(
PoolId poolId,
PoolKey memory key,
uint256 royaltyAmount,
address deployer
) internal {
if (royaltyAmount == 0) return;
// Draw from surplus (same waterfall as settler: currency0 first, then currency1)
uint256 remaining = royaltyAmount;
uint256 bal0 = surplusCurrency0[poolId];
if (bal0 > 0 && remaining > 0) {
uint256 draw0 = bal0 < remaining ? bal0 : remaining;
surplusCurrency0[poolId] = bal0 - draw0;
remaining -= draw0;
_paySurplus(key.currency0, deployer, draw0);
}
if (remaining > 0) {
uint256 bal1 = surplusCurrency1[poolId];
if (bal1 > 0) {
uint256 draw1 = bal1 < remaining ? bal1 : remaining;
surplusCurrency1[poolId] = bal1 - draw1;
remaining -= draw1;
_paySurplus(key.currency1, deployer, draw1);
}
}
if (royaltyAmount - remaining > 0) {
emit GeodeDeployerRoyaltyPaid(poolId, deployer, royaltyAmount - remaining);
}
}
/// @notice Fund settler reward from accumulated surplus, returning per-currency draw amounts.
/// @dev Draw-down order: surplusCurrency0 first, then surplusCurrency1.
/// @return draw0 Amount drawn from surplusCurrency0
/// @return draw1 Amount drawn from surplusCurrency1
function _fundSettlerFromSurplus(
PoolId poolId,
PoolKey memory key,
uint256 totalReward,
address settler
) internal returns (uint256 draw0, uint256 draw1) {
uint256 remaining = totalReward;
if (remaining == 0) return (0, 0);
// Step 1: Draw from surplusCurrency0
uint256 bal0 = surplusCurrency0[poolId];
if (bal0 > 0) {
draw0 = bal0 < remaining ? bal0 : remaining;
surplusCurrency0[poolId] = bal0 - draw0;
remaining -= draw0;
_paySurplus(key.currency0, settler, draw0);
}
if (remaining == 0) return (draw0, draw1);
// Step 2: Draw from surplusCurrency1
uint256 bal1 = surplusCurrency1[poolId];
if (bal1 > 0) {
draw1 = bal1 < remaining ? bal1 : remaining;
surplusCurrency1[poolId] = bal1 - draw1;
remaining -= draw1;
_paySurplus(key.currency1, settler, draw1);
}
}
/// @notice Transfer surplus-held tokens to a recipient via the PoolManager.
/// @dev Four-step dance: sync → transfer → settle → take.
/// sync checkpoints PoolManager's balance; transfer+settle credits hook's delta;
/// take sends tokens to recipient and debits hook's delta. Net zero for hook.
function _paySurplus(Currency currency, address recipient, uint256 amount) internal {
poolManager.sync(currency);
IERC20Minimal(Currency.unwrap(currency)).transfer(address(poolManager), amount);
poolManager.settle();
poolManager.take(currency, recipient, amount);
}
/// @notice Distribute currency1 to filled buy intents
/// @dev Total currency1 = internalMatch1 + swapOutputCurrency1 (already net of fees).
/// Pro-rata by buyer amountIn with remainder-to-last for dust.
function _distributeBuyOutputs(
PoolKey memory key,
GeodeIntent[] memory buys,
bool[] memory buyFills,
uint256 totalBuyInput,
uint256 internalMatch1,
uint256 swapOutputCurrency1
) internal {
if (totalBuyInput == 0) return;
uint256 totalCurrency1 = internalMatch1 + swapOutputCurrency1;
// Find last filled buyer for remainder-to-last
uint256 lastFilledIdx = 0;
for (uint256 i = 0; i < buys.length; i++) {
if (buyFills[i]) lastFilledIdx = i;
}
uint256 distributed = 0;
for (uint256 i = 0; i < buys.length; i++) {
if (!buyFills[i]) continue;
uint256 amountOut;
if (i == lastFilledIdx) {
amountOut = totalCurrency1 - distributed;
} else {
amountOut = (totalCurrency1 * buys[i].amountIn) / totalBuyInput;
distributed += amountOut;
}
if (amountOut > 0) {
poolManager.take(key.currency1, buys[i].owner, amountOut);
}
}
}
/// @notice Distribute currency0 to filled sell intents
/// @dev Total currency0 = internalMatch0 + swapOutputCurrency0 (already net of fees).
/// Pro-rata by seller amountIn with remainder-to-last for dust.
function _distributeSellOutputs(
PoolKey memory key,
GeodeIntent[] memory sells,
bool[] memory sellFills,
uint256 totalSellInput,
uint256 internalMatch0,
uint256 swapOutputCurrency0
) internal {
uint256 totalCurrency0 = internalMatch0 + swapOutputCurrency0;
if (totalCurrency0 == 0) return;
if (totalSellInput == 0) return;
// Find last filled seller for remainder-to-last
uint256 lastFilledIdx = 0;
for (uint256 i = 0; i < sells.length; i++) {
if (sellFills[i]) lastFilledIdx = i;
}
uint256 totalSellerPaid = 0;
for (uint256 i = 0; i < sells.length; i++) {
if (!sellFills[i]) continue;
uint256 netOut;
if (i == lastFilledIdx) {
netOut = totalCurrency0 - totalSellerPaid;
} else {
netOut = (totalCurrency0 * sells[i].amountIn) / totalSellInput;
totalSellerPaid += netOut;
}
if (netOut > 0) {
poolManager.take(key.currency0, sells[i].owner, netOut);
}
}
}
/// @notice Pay settler: batch settlement fees + gas-capped surplus reimbursement
/// @dev Settlement fees come from unrouted input deposits (carved before matching).
/// Gas reimbursement draws from surplus with a strict cap.
/// Emits SettlerPaid with exact per-currency breakdown for auditability.
function _paySettler(
PoolKey memory key,
PoolId poolId,
uint256 retainedBuyFees,
uint256 retainedSellFees,
address settler,
uint256 gasStart
) internal {
// Pay retained buyFees (currency0) to settler
if (retainedBuyFees > 0) {
poolManager.take(key.currency0, settler, retainedBuyFees);
}
// Pay retained sellFees (currency1) to settler
if (retainedSellFees > 0) {
poolManager.take(key.currency1, settler, retainedSellFees);
}
// Gas-capped surplus reimbursement (liveness backstop)
PoolConfig storage config = _poolConfigs[poolId];
uint256 gasUsed = gasStart - gasleft();
uint256 gasCost = gasUsed * tx.gasprice;
uint256 gasReimbursement = (gasCost * config.gasReimbursementMultiplier) / 100;
if (gasReimbursement > config.maxGasReimbursement) {
gasReimbursement = config.maxGasReimbursement;
}
uint256 gasReimb0 = 0;
uint256 gasReimb1 = 0;
if (gasReimbursement > 0) {
(gasReimb0, gasReimb1) = _fundSettlerFromSurplus(poolId, key, gasReimbursement, settler);
}
emit SettlerPaid(poolId, settler, retainedBuyFees, retainedSellFees, gasReimb0, gasReimb1);
}
// ─── Internal: Permit2 Token Pull ───────────────────────────────────────────
/// @notice Pull tokens from an intent owner via Permit2 permitWitnessTransferFrom
/// @dev Permit2 validates the signature, verifies the witness, and transfers tokens
/// from owner directly to the PoolManager. Then sync()+settle() credits the delta.
function _pullViaPermit2(GeodeIntent memory intent, bytes memory signature) internal {
bytes32 witness = IntentLib.computeWitnessHashMem(intent);
permit2.permitWitnessTransferFrom(
ISignatureTransfer.PermitTransferFrom({
permitted: ISignatureTransfer.TokenPermissions({
token: intent.tokenIn,
amount: intent.amountIn
}),
nonce: intent.nonce,
deadline: intent.deadline
}),
ISignatureTransfer.SignatureTransferDetails({
to: address(poolManager),
requestedAmount: intent.amountIn
}),
intent.owner,
witness,
GeodeTypes.WITNESS_TYPE_STRING,
signature
);
}
// ─── View Functions ─────────────────────────────────────────────────────────
/// @inheritdoc IGeodeHook
function getBatchState(PoolId poolId) external view override returns (BatchState memory) {
return _currentBatch[poolId];
}
/// @inheritdoc IGeodeHook
function getPoolConfig(PoolId poolId) external view override returns (PoolConfig memory) {
return _poolConfigs[poolId];
}
/// @inheritdoc IGeodeHook
function getSurplusCurrency0(PoolId poolId) external view override returns (uint256) {
return surplusCurrency0[poolId];
}
/// @inheritdoc IGeodeHook
function getSurplusCurrency1(PoolId poolId) external view override returns (uint256) {
return surplusCurrency1[poolId];
}
/// @inheritdoc IGeodeHook
function getLastSettledBlock(PoolId poolId) external view override returns (uint256) {
return lastSettledBlock[poolId];
}
/// @inheritdoc IGeodeHook
function canSettle(PoolId poolId) external view override returns (bool) {
if (!poolInitialized[poolId]) return false;
return block.number >= lastSettledBlock[poolId] + _poolConfigs[poolId].batchInterval;
}
/// @inheritdoc IGeodeHook
function getLaunchState(PoolId poolId) external view override returns (LaunchState memory) {
return _launchStates[poolId];
}
/// @inheritdoc IGeodeHook
function getLaunchMetrics(PoolId poolId) external view override returns (
uint256 currentPriceQ96,
uint256 marketCap,
uint256 fdv,
uint256 ethRaised,
uint256 circulatingSupply
) {
LaunchState storage ls = _launchStates[poolId];
uint256 x = ls.cumulativeSupplyDistributed;
// Constant-product price in 1e18 fixed-point
uint256 priceX18 = ConstantProductCurveLib.curvePrice(
ls.virtualTokenReserve, ls.virtualEthReserve, x, ls.ethReserve
);
// Convert to Q96 for backward-compatible return type
currentPriceQ96 = (priceX18 << 96) / 1e18;
// Market cap = price × circulating supply
marketCap = (priceX18 * x) / 1e18;
// FDV = price × total supply
fdv = (priceX18 * ls.totalSupply) / 1e18;
ethRaised = ls.ethReserve;
circulatingSupply = x;
}
// ─── Launch Registration (called by GeodeFactory) ────────────────────────────
/// @notice Register a launched token's state. Called by the factory after deployment.
/// @dev The factory deploys the ERC20, configures the hook, then calls this to set up
/// curve tracking. The curve is permanent — no graduation.
function registerLaunch(
PoolId poolId,
address tokenAddress,
uint256 totalSupply,
uint256 virtualTokenReserve,
uint256 virtualEthReserve
) external {
// Only the factory can register launches
if (msg.sender != factory) revert OnlyFactory();
// Prevent re-registration (one-shot: only callable once per pool)
LaunchState storage ls = _launchStates[poolId];
if (ls.tokenAddress != address(0)) revert LaunchAlreadyRegistered();
ls.totalSupply = totalSupply;
ls.tokenAddress = tokenAddress;
ls.virtualTokenReserve = virtualTokenReserve;
ls.virtualEthReserve = virtualEthReserve;
ls.cumulativeSupplyDistributed = 0;
ls.ethReserve = 0;
ls.curveSupply = totalSupply;
ls.phase = LaunchPhase.Active;
// Track the token reserve held by the hook
launchTokenReserve[poolId] = totalSupply;
launchEthReserve[poolId] = 0;
}
/// @notice Called by PoolManager during unlock. Handles settlement flow.
/// @dev All deltas MUST net to zero within the unlock context.
function unlockCallback(bytes calldata data) external override returns (bytes memory) {
if (msg.sender != address(poolManager)) revert OnlyPoolManager();
return _settlementUnlockCallback(data);
}
/// @notice Settlement unlock callback
function _settlementUnlockCallback(bytes calldata data) internal returns (bytes memory) {
(
PoolKey memory key,
GeodeIntent[] memory buys,
GeodeIntent[] memory sells,
bytes[] memory buySignatures,
bytes[] memory sellSignatures,
bool[] memory buyFills,
bool[] memory sellFills,
SettlementResult memory result,
address settler,
uint256 gasStart
) = abi.decode(data, (PoolKey, GeodeIntent[], GeodeIntent[], bytes[], bytes[], bool[], bool[], SettlementResult, address, uint256));
// ── Step 1: Pull tokenIn from filled BUYERS (currency0) via Permit2 ──
{
uint256 totalCurrency0In = 0;
for (uint256 i = 0; i < buys.length; i++) {
if (buyFills[i]) totalCurrency0In += buys[i].amountIn;
}
if (totalCurrency0In > 0) {
poolManager.sync(key.currency0);
for (uint256 i = 0; i < buys.length; i++) {
if (!buyFills[i]) continue;
_pullViaPermit2(buys[i], buySignatures[i]);
}
poolManager.settle();
}
}
// ── Step 2: Pull tokenIn from filled SELLERS (currency1) via Permit2 ──
{
uint256 totalCurrency1In = 0;
for (uint256 i = 0; i < sells.length; i++) {
if (sellFills[i]) totalCurrency1In += sells[i].amountIn;
}
if (totalCurrency1In > 0) {
poolManager.sync(key.currency1);
for (uint256 i = 0; i < sells.length; i++) {
if (!sellFills[i]) continue;
_pullViaPermit2(sells[i], sellSignatures[i]);
}
poolManager.settle();
}
}
// ── Steps 3-5: Route residual, distribute outputs, pay settler ──
_routeAndDistribute(key, buys, sells, buyFills, sellFills, result, settler, gasStart);
return "";
}
}
lib/permit2/src/interfaces/IEIP712.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IEIP712 {
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
lib/permit2/src/interfaces/ISignatureTransfer.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IEIP712} from "./IEIP712.sol";
/// @title SignatureTransfer
/// @notice Handles ERC20 token transfers through signature based actions
/// @dev Requires user's token approval on the Permit2 contract
interface ISignatureTransfer is IEIP712 {
/// @notice Thrown when the requested amount for a transfer is larger than the permissioned amount
/// @param maxAmount The maximum amount a spender can request to transfer
error InvalidAmount(uint256 maxAmount);
/// @notice Thrown when the number of tokens permissioned to a spender does not match the number of tokens being transferred
/// @dev If the spender does not need to transfer the number of tokens permitted, the spender can request amount 0 to be transferred
error LengthMismatch();
/// @notice Emits an event when the owner successfully invalidates an unordered nonce.
event UnorderedNonceInvalidation(address indexed owner, uint256 word, uint256 mask);
/// @notice The token and amount details for a transfer signed in the permit transfer signature
struct TokenPermissions {
// ERC20 token address
address token;
// the maximum amount that can be spent
uint256 amount;
}
/// @notice The signed permit message for a single token transfer
struct PermitTransferFrom {
TokenPermissions permitted;
// a unique value for every token owner's signature to prevent signature replays
uint256 nonce;
// deadline on the permit signature
uint256 deadline;
}
/// @notice Specifies the recipient address and amount for batched transfers.
/// @dev Recipients and amounts correspond to the index of the signed token permissions array.
/// @dev Reverts if the requested amount is greater than the permitted signed amount.
struct SignatureTransferDetails {
// recipient address
address to;
// spender requested amount
uint256 requestedAmount;
}
/// @notice Used to reconstruct the signed permit message for multiple token transfers
/// @dev Do not need to pass in spender address as it is required that it is msg.sender
/// @dev Note that a user still signs over a spender address
struct PermitBatchTransferFrom {
// the tokens and corresponding amounts permitted for a transfer
TokenPermissions[] permitted;
// a unique value for every token owner's signature to prevent signature replays
uint256 nonce;
// deadline on the permit signature
uint256 deadline;
}
/// @notice A map from token owner address and a caller specified word index to a bitmap. Used to set bits in the bitmap to prevent against signature replay protection
/// @dev Uses unordered nonces so that permit messages do not need to be spent in a certain order
/// @dev The mapping is indexed first by the token owner, then by an index specified in the nonce
/// @dev It returns a uint256 bitmap
/// @dev The index, or wordPosition is capped at type(uint248).max
function nonceBitmap(address, uint256) external view returns (uint256);
/// @notice Transfers a token using a signed permit message
/// @dev Reverts if the requested amount is greater than the permitted signed amount
/// @param permit The permit data signed over by the owner
/// @param owner The owner of the tokens to transfer
/// @param transferDetails The spender's requested transfer details for the permitted token
/// @param signature The signature to verify
function permitTransferFrom(
PermitTransferFrom memory permit,
SignatureTransferDetails calldata transferDetails,
address owner,
bytes calldata signature
) external;
/// @notice Transfers a token using a signed permit message
/// @notice Includes extra data provided by the caller to verify signature over
/// @dev The witness type string must follow EIP712 ordering of nested structs and must include the TokenPermissions type definition
/// @dev Reverts if the requested amount is greater than the permitted signed amount
/// @param permit The permit data signed over by the owner
/// @param owner The owner of the tokens to transfer
/// @param transferDetails The spender's requested transfer details for the permitted token
/// @param witness Extra data to include when checking the user signature
/// @param witnessTypeString The EIP-712 type definition for remaining string stub of the typehash
/// @param signature The signature to verify
function permitWitnessTransferFrom(
PermitTransferFrom memory permit,
SignatureTransferDetails calldata transferDetails,
address owner,
bytes32 witness,
string calldata witnessTypeString,
bytes calldata signature
) external;
/// @notice Transfers multiple tokens using a signed permit message
/// @param permit The permit data signed over by the owner
/// @param owner The owner of the tokens to transfer
/// @param transferDetails Specifies the recipient and requested amount for the token transfer
/// @param signature The signature to verify
function permitTransferFrom(
PermitBatchTransferFrom memory permit,
SignatureTransferDetails[] calldata transferDetails,
address owner,
bytes calldata signature
) external;
/// @notice Transfers multiple tokens using a signed permit message
/// @dev The witness type string must follow EIP712 ordering of nested structs and must include the TokenPermissions type definition
/// @notice Includes extra data provided by the caller to verify signature over
/// @param permit The permit data signed over by the owner
/// @param owner The owner of the tokens to transfer
/// @param transferDetails Specifies the recipient and requested amount for the token transfer
/// @param witness Extra data to include when checking the user signature
/// @param witnessTypeString The EIP-712 type definition for remaining string stub of the typehash
/// @param signature The signature to verify
function permitWitnessTransferFrom(
PermitBatchTransferFrom memory permit,
SignatureTransferDetails[] calldata transferDetails,
address owner,
bytes32 witness,
string calldata witnessTypeString,
bytes calldata signature
) external;
/// @notice Invalidates the bits specified in mask for the bitmap at the word position
/// @dev The wordPos is maxed at type(uint248).max
/// @param wordPos A number to index the nonceBitmap at
/// @param mask A bitmap masked against msg.sender's current bitmap at the word position
function invalidateUnorderedNonces(uint256 wordPos, uint256 mask) external;
}
lib/v4-core/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);
}
lib/v4-core/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);
}
lib/v4-core/src/interfaces/IHooks.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";
import {BeforeSwapDelta} from "../types/BeforeSwapDelta.sol";
/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits
/// of the address that the hooks contract is deployed to.
/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400
/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.
/// See the Hooks library for the full spec.
/// @dev Should only be callable by the v4 PoolManager.
interface IHooks {
/// @notice The hook called before the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param key The key for the pool being initialized
/// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
/// @return bytes4 The function selector for the hook
function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96) external returns (bytes4);
/// @notice The hook called after the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param key The key for the pool being initialized
/// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
/// @param tick The current tick after the state of a pool is initialized
/// @return bytes4 The function selector for the hook
function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)
external
returns (bytes4);
/// @notice The hook called before liquidity is added
/// @param sender The initial msg.sender for the add liquidity call
/// @param key The key for the pool
/// @param params The parameters for adding liquidity
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeAddLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after liquidity is added
/// @param sender The initial msg.sender for the add liquidity call
/// @param key The key for the pool
/// @param params The parameters for adding liquidity
/// @param delta The caller's balance delta after adding liquidity; the sum of principal delta, fees accrued, and hook delta
/// @param feesAccrued The fees accrued since the last time fees were collected from this position
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterAddLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external returns (bytes4, BalanceDelta);
/// @notice The hook called before liquidity is removed
/// @param sender The initial msg.sender for the remove liquidity call
/// @param key The key for the pool
/// @param params The parameters for removing liquidity
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeRemoveLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after liquidity is removed
/// @param sender The initial msg.sender for the remove liquidity call
/// @param key The key for the pool
/// @param params The parameters for removing liquidity
/// @param delta The caller's balance delta after removing liquidity; the sum of principal delta, fees accrued, and hook delta
/// @param feesAccrued The fees accrued since the last time fees were collected from this position
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterRemoveLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external returns (bytes4, BalanceDelta);
/// @notice The hook called before a swap
/// @param sender The initial msg.sender for the swap call
/// @param key The key for the pool
/// @param params The parameters for the swap
/// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BeforeSwapDelta The hook's delta in specified and unspecified currencies. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
/// @return uint24 Optionally override the lp fee, only used if three conditions are met: 1. the Pool has a dynamic fee, 2. the value's 2nd highest bit is set (23rd bit, 0x400000), and 3. the value is less than or equal to the maximum fee (1 million)
function beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata hookData)
external
returns (bytes4, BeforeSwapDelta, uint24);
/// @notice The hook called after a swap
/// @param sender The initial msg.sender for the swap call
/// @param key The key for the pool
/// @param params The parameters for the swap
/// @param delta The amount owed to the caller (positive) or owed to the pool (negative)
/// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return int128 The hook's delta in unspecified currency. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterSwap(
address sender,
PoolKey calldata key,
SwapParams calldata params,
BalanceDelta delta,
bytes calldata hookData
) external returns (bytes4, int128);
/// @notice The hook called before donate
/// @param sender The initial msg.sender for the donate call
/// @param key The key for the pool
/// @param amount0 The amount of token0 being donated
/// @param amount1 The amount of token1 being donated
/// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after donate
/// @param sender The initial msg.sender for the donate call
/// @param key The key for the pool
/// @param amount0 The amount of token0 being donated
/// @param amount1 The amount of token1 being donated
/// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function afterDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external returns (bytes4);
}
lib/v4-core/src/interfaces/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;
}
lib/v4-core/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);
}
lib/v4-core/src/interfaces/callback/IUnlockCallback.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Interface for the callback executed when an address unlocks the pool manager
interface IUnlockCallback {
/// @notice Called by the pool manager on `msg.sender` when the manager is unlocked
/// @param data The data that was passed to the call to unlock
/// @return Any data that you want to be returned from the unlock call
function unlockCallback(bytes calldata data) external returns (bytes memory);
}
lib/v4-core/src/interfaces/external/IERC20Minimal.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Minimal ERC20 interface for Uniswap
/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3
interface IERC20Minimal {
/// @notice Returns an account's balance in the token
/// @param account The account for which to look up the number of tokens it has, i.e. its balance
/// @return The number of tokens held by the account
function balanceOf(address account) external view returns (uint256);
/// @notice Transfers the amount of token from the `msg.sender` to the recipient
/// @param recipient The account that will receive the amount transferred
/// @param amount The number of tokens to send from the sender to the recipient
/// @return Returns true for a successful transfer, false for an unsuccessful transfer
function transfer(address recipient, uint256 amount) external returns (bool);
/// @notice Returns the current allowance given to a spender by an owner
/// @param owner The account of the token owner
/// @param spender The account of the token spender
/// @return The current allowance granted by `owner` to `spender`
function allowance(address owner, address spender) external view returns (uint256);
/// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`
/// @param spender The account which will be allowed to spend a given amount of the owners tokens
/// @param amount The amount of tokens allowed to be used by `spender`
/// @return Returns true for a successful approval, false for unsuccessful
function approve(address spender, uint256 amount) external returns (bool);
/// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`
/// @param sender The account from which the transfer will be initiated
/// @param recipient The recipient of the transfer
/// @param amount The amount of the transfer
/// @return Returns true for a successful transfer, false for unsuccessful
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.
/// @param from The account from which the tokens were sent, i.e. the balance decreased
/// @param to The account to which the tokens were sent, i.e. the balance increased
/// @param value The amount of tokens that were transferred
event Transfer(address indexed from, address indexed to, uint256 value);
/// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.
/// @param owner The account that approved spending of its tokens
/// @param spender The account for which the spending allowance was modified
/// @param value The new allowance from the owner to the spender
event Approval(address indexed owner, address indexed spender, uint256 value);
}
lib/v4-core/src/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);
}
lib/v4-core/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))
}
}
}
lib/v4-core/src/libraries/CustomRevert.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Library for reverting with custom errors efficiently
/// @notice Contains functions for reverting with custom errors with different argument types efficiently
/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with
/// `CustomError.selector.revertWith()`
/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately
library CustomRevert {
/// @dev ERC-7751 error for wrapping bubbled up reverts
error WrappedError(address target, bytes4 selector, bytes reason, bytes details);
/// @dev Reverts with the selector of a custom error in the scratch space
function revertWith(bytes4 selector) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
revert(0, 0x04)
}
}
/// @dev Reverts with a custom error with an address argument in the scratch space
function revertWith(bytes4 selector, address addr) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with an int24 argument in the scratch space
function revertWith(bytes4 selector, int24 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, signextend(2, value))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with a uint160 argument in the scratch space
function revertWith(bytes4 selector, uint160 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with two int24 arguments
function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), signextend(2, value1))
mstore(add(fmp, 0x24), signextend(2, value2))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two uint160 arguments
function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two address arguments
function revertWith(bytes4 selector, address value1, address value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error
/// @dev this method can be vulnerable to revert data bombs
function bubbleUpAndRevertWith(
address revertingContract,
bytes4 revertingFunctionSelector,
bytes4 additionalContext
) internal pure {
bytes4 wrappedErrorSelector = WrappedError.selector;
assembly ("memory-safe") {
// Ensure the size of the revert data is a multiple of 32 bytes
let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)
let fmp := mload(0x40)
// Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason
mstore(fmp, wrappedErrorSelector)
mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(
add(fmp, 0x24),
and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
// offset revert reason
mstore(add(fmp, 0x44), 0x80)
// offset additional context
mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))
// size revert reason
mstore(add(fmp, 0x84), returndatasize())
// revert reason
returndatacopy(add(fmp, 0xa4), 0, returndatasize())
// size additional context
mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)
// additional context
mstore(
add(fmp, add(0xc4, encodedDataSize)),
and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
revert(fmp, add(0xe4, encodedDataSize))
}
}
}
lib/v4-core/src/libraries/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;
}
lib/v4-core/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);
}
}
}
}
lib/v4-core/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;
}
}
lib/v4-core/src/libraries/LPFeeLibrary.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {CustomRevert} from "./CustomRevert.sol";
/// @notice Library of helper functions for a pools LP fee
library LPFeeLibrary {
using LPFeeLibrary for uint24;
using CustomRevert for bytes4;
/// @notice Thrown when the static or dynamic fee on a pool exceeds 100%.
error LPFeeTooLarge(uint24 fee);
/// @notice An lp fee of exactly 0b1000000... signals a dynamic fee pool. This isn't a valid static fee as it is > MAX_LP_FEE
uint24 public constant DYNAMIC_FEE_FLAG = 0x800000;
/// @notice the second bit of the fee returned by beforeSwap is used to signal if the stored LP fee should be overridden in this swap
// only dynamic-fee pools can return a fee via the beforeSwap hook
uint24 public constant OVERRIDE_FEE_FLAG = 0x400000;
/// @notice mask to remove the override fee flag from a fee returned by the beforeSwaphook
uint24 public constant REMOVE_OVERRIDE_MASK = 0xBFFFFF;
/// @notice the lp fee is represented in hundredths of a bip, so the max is 100%
uint24 public constant MAX_LP_FEE = 1000000;
/// @notice returns true if a pool's LP fee signals that the pool has a dynamic fee
/// @param self The fee to check
/// @return bool True of the fee is dynamic
function isDynamicFee(uint24 self) internal pure returns (bool) {
return self == DYNAMIC_FEE_FLAG;
}
/// @notice returns true if an LP fee is valid, aka not above the maximum permitted fee
/// @param self The fee to check
/// @return bool True of the fee is valid
function isValid(uint24 self) internal pure returns (bool) {
return self <= MAX_LP_FEE;
}
/// @notice validates whether an LP fee is larger than the maximum, and reverts if invalid
/// @param self The fee to validate
function validate(uint24 self) internal pure {
if (!self.isValid()) LPFeeTooLarge.selector.revertWith(self);
}
/// @notice gets and validates the initial LP fee for a pool. Dynamic fee pools have an initial fee of 0.
/// @dev if a dynamic fee pool wants a non-0 initial fee, it should call `updateDynamicLPFee` in the afterInitialize hook
/// @param self The fee to get the initial LP from
/// @return initialFee 0 if the fee is dynamic, otherwise the fee (if valid)
function getInitialLPFee(uint24 self) internal pure returns (uint24) {
// the initial fee for a dynamic fee pool is 0
if (self.isDynamicFee()) return 0;
self.validate();
return self;
}
/// @notice returns true if the fee has the override flag set (2nd highest bit of the uint24)
/// @param self The fee to check
/// @return bool True of the fee has the override flag set
function isOverride(uint24 self) internal pure returns (bool) {
return self & OVERRIDE_FEE_FLAG != 0;
}
/// @notice returns a fee with the override flag removed
/// @param self The fee to remove the override flag from
/// @return fee The fee without the override flag set
function removeOverrideFlag(uint24 self) internal pure returns (uint24) {
return self & REMOVE_OVERRIDE_MASK;
}
/// @notice Removes the override flag and validates the fee (reverts if the fee is too large)
/// @param self The fee to remove the override flag from, and then validate
/// @return fee The fee without the override flag set (if valid)
function removeOverrideFlagAndValidate(uint24 self) internal pure returns (uint24 fee) {
fee = self.removeOverrideFlag();
fee.validate();
}
}
lib/v4-core/src/libraries/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)
}
}
}
}
lib/v4-core/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))
}
}
}
lib/v4-core/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;
}
}
lib/v4-core/src/libraries/SafeCast.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {CustomRevert} from "./CustomRevert.sol";
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
using CustomRevert for bytes4;
error SafeCastOverflow();
/// @notice Cast a uint256 to a uint160, revert on overflow
/// @param x The uint256 to be downcasted
/// @return y The downcasted integer, now type uint160
function toUint160(uint256 x) internal pure returns (uint160 y) {
y = uint160(x);
if (y != x) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a uint128, revert on overflow
/// @param x The uint256 to be downcasted
/// @return y The downcasted integer, now type uint128
function toUint128(uint256 x) internal pure returns (uint128 y) {
y = uint128(x);
if (x != y) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a int128 to a uint128, revert on overflow or underflow
/// @param x The int128 to be casted
/// @return y The casted integer, now type uint128
function toUint128(int128 x) internal pure returns (uint128 y) {
if (x < 0) SafeCastOverflow.selector.revertWith();
y = uint128(x);
}
/// @notice Cast a int256 to a int128, revert on overflow or underflow
/// @param x The int256 to be downcasted
/// @return y The downcasted integer, now type int128
function toInt128(int256 x) internal pure returns (int128 y) {
y = int128(x);
if (y != x) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param x The uint256 to be casted
/// @return y The casted integer, now type int256
function toInt256(uint256 x) internal pure returns (int256 y) {
y = int256(x);
if (y < 0) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a int128, revert on overflow
/// @param x The uint256 to be downcasted
/// @return The downcasted integer, now type int128
function toInt128(uint256 x) internal pure returns (int128) {
if (x >= 1 << 127) SafeCastOverflow.selector.revertWith();
return int128(int256(x));
}
}
lib/v4-core/src/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));
}
}
lib/v4-core/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;
}
}
}
lib/v4-core/src/types/BalanceDelta.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {SafeCast} from "../libraries/SafeCast.sol";
/// @dev Two `int128` values packed into a single `int256` where the upper 128 bits represent the amount0
/// and the lower 128 bits represent the amount1.
type BalanceDelta is int256;
using {add as +, sub as -, eq as ==, neq as !=} for BalanceDelta global;
using BalanceDeltaLibrary for BalanceDelta global;
using SafeCast for int256;
function toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) {
assembly ("memory-safe") {
balanceDelta := or(shl(128, _amount0), and(sub(shl(128, 1), 1), _amount1))
}
}
function add(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
int256 res0;
int256 res1;
assembly ("memory-safe") {
let a0 := sar(128, a)
let a1 := signextend(15, a)
let b0 := sar(128, b)
let b1 := signextend(15, b)
res0 := add(a0, b0)
res1 := add(a1, b1)
}
return toBalanceDelta(res0.toInt128(), res1.toInt128());
}
function sub(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
int256 res0;
int256 res1;
assembly ("memory-safe") {
let a0 := sar(128, a)
let a1 := signextend(15, a)
let b0 := sar(128, b)
let b1 := signextend(15, b)
res0 := sub(a0, b0)
res1 := sub(a1, b1)
}
return toBalanceDelta(res0.toInt128(), res1.toInt128());
}
function eq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
return BalanceDelta.unwrap(a) == BalanceDelta.unwrap(b);
}
function neq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
return BalanceDelta.unwrap(a) != BalanceDelta.unwrap(b);
}
/// @notice Library for getting the amount0 and amount1 deltas from the BalanceDelta type
library BalanceDeltaLibrary {
/// @notice A BalanceDelta of 0
BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0);
function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) {
assembly ("memory-safe") {
_amount0 := sar(128, balanceDelta)
}
}
function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) {
assembly ("memory-safe") {
_amount1 := signextend(15, balanceDelta)
}
}
}
lib/v4-core/src/types/BeforeSwapDelta.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Return type of the beforeSwap hook.
// Upper 128 bits is the delta in specified tokens. Lower 128 bits is delta in unspecified tokens (to match the afterSwap hook)
type BeforeSwapDelta is int256;
// Creates a BeforeSwapDelta from specified and unspecified
function toBeforeSwapDelta(int128 deltaSpecified, int128 deltaUnspecified)
pure
returns (BeforeSwapDelta beforeSwapDelta)
{
assembly ("memory-safe") {
beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified))
}
}
/// @notice Library for getting the specified and unspecified deltas from the BeforeSwapDelta type
library BeforeSwapDeltaLibrary {
/// @notice A BeforeSwapDelta of 0
BeforeSwapDelta public constant ZERO_DELTA = BeforeSwapDelta.wrap(0);
/// extracts int128 from the upper 128 bits of the BeforeSwapDelta
/// returned by beforeSwap
function getSpecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaSpecified) {
assembly ("memory-safe") {
deltaSpecified := sar(128, delta)
}
}
/// extracts int128 from the lower 128 bits of the BeforeSwapDelta
/// returned by beforeSwap and afterSwap
function getUnspecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaUnspecified) {
assembly ("memory-safe") {
deltaUnspecified := signextend(15, delta)
}
}
}
lib/v4-core/src/types/Currency.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC20Minimal} from "../interfaces/external/IERC20Minimal.sol";
import {CustomRevert} from "../libraries/CustomRevert.sol";
type Currency is address;
using {greaterThan as >, lessThan as <, greaterThanOrEqualTo as >=, equals as ==} for Currency global;
using CurrencyLibrary for Currency global;
function equals(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) == Currency.unwrap(other);
}
function greaterThan(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) > Currency.unwrap(other);
}
function lessThan(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) < Currency.unwrap(other);
}
function greaterThanOrEqualTo(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) >= Currency.unwrap(other);
}
/// @title CurrencyLibrary
/// @dev This library allows for transferring and holding native tokens and ERC20 tokens
library CurrencyLibrary {
/// @notice Additional context for ERC-7751 wrapped error when a native transfer fails
error NativeTransferFailed();
/// @notice Additional context for ERC-7751 wrapped error when an ERC20 transfer fails
error ERC20TransferFailed();
/// @notice A constant to represent the native currency
Currency public constant ADDRESS_ZERO = Currency.wrap(address(0));
function transfer(Currency currency, address to, uint256 amount) internal {
// altered from https://github.com/transmissions11/solmate/blob/44a9963d4c78111f77caa0e65d677b8b46d6f2e6/src/utils/SafeTransferLib.sol
// modified custom error selectors
bool success;
if (currency.isAddressZero()) {
assembly ("memory-safe") {
// Transfer the ETH and revert if it fails.
success := call(gas(), to, amount, 0, 0, 0, 0)
}
// revert with NativeTransferFailed, containing the bubbled up error as an argument
if (!success) {
CustomRevert.bubbleUpAndRevertWith(to, bytes4(0), NativeTransferFailed.selector);
}
} else {
assembly ("memory-safe") {
// Get a pointer to some free memory.
let fmp := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(fmp, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
mstore(add(fmp, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
mstore(add(fmp, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
success :=
and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the or() call in the
// surrounding and() call or else returndatasize() will be zero during the computation.
call(gas(), currency, 0, fmp, 68, 0, 32)
)
// Now clean the memory we used
mstore(fmp, 0) // 4 byte `selector` and 28 bytes of `to` were stored here
mstore(add(fmp, 0x20), 0) // 4 bytes of `to` and 28 bytes of `amount` were stored here
mstore(add(fmp, 0x40), 0) // 4 bytes of `amount` were stored here
}
// revert with ERC20TransferFailed, containing the bubbled up error as an argument
if (!success) {
CustomRevert.bubbleUpAndRevertWith(
Currency.unwrap(currency), IERC20Minimal.transfer.selector, ERC20TransferFailed.selector
);
}
}
}
function balanceOfSelf(Currency currency) internal view returns (uint256) {
if (currency.isAddressZero()) {
return address(this).balance;
} else {
return IERC20Minimal(Currency.unwrap(currency)).balanceOf(address(this));
}
}
function balanceOf(Currency currency, address owner) internal view returns (uint256) {
if (currency.isAddressZero()) {
return owner.balance;
} else {
return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner);
}
}
function isAddressZero(Currency currency) internal pure returns (bool) {
return Currency.unwrap(currency) == Currency.unwrap(ADDRESS_ZERO);
}
function toId(Currency currency) internal pure returns (uint256) {
return uint160(Currency.unwrap(currency));
}
// If the upper 12 bytes are non-zero, they will be zero-ed out
// Therefore, fromId() and toId() are not inverses of each other
function fromId(uint256 id) internal pure returns (Currency) {
return Currency.wrap(address(uint160(id)));
}
}
lib/v4-core/src/types/PoolId.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "./PoolKey.sol";
type PoolId is bytes32;
/// @notice Library for computing the ID of a pool
library PoolIdLibrary {
/// @notice Returns value equal to keccak256(abi.encode(poolKey))
function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) {
assembly ("memory-safe") {
// 0xa0 represents the total size of the poolKey struct (5 slots of 32 bytes)
poolId := keccak256(poolKey, 0xa0)
}
}
}
lib/v4-core/src/types/PoolKey.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "./Currency.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {PoolIdLibrary} from "./PoolId.sol";
using PoolIdLibrary for PoolKey global;
/// @notice Returns the key for identifying a pool
struct PoolKey {
/// @notice The lower currency of the pool, sorted numerically
Currency currency0;
/// @notice The higher currency of the pool, sorted numerically
Currency currency1;
/// @notice The pool LP fee, capped at 1_000_000. If the highest bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000
uint24 fee;
/// @notice Ticks that involve positions must be a multiple of tick spacing
int24 tickSpacing;
/// @notice The hooks of the pool
IHooks hooks;
}
lib/v4-core/src/types/PoolOperation.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
/// @notice Parameter struct for `ModifyLiquidity` pool operations
struct ModifyLiquidityParams {
// the lower and upper tick of the position
int24 tickLower;
int24 tickUpper;
// how to modify the liquidity
int256 liquidityDelta;
// a value to set if you want unique liquidity positions at the same range
bytes32 salt;
}
/// @notice Parameter struct for `Swap` pool operations
struct SwapParams {
/// Whether to swap token0 for token1 or vice versa
bool zeroForOne;
/// The desired input amount if negative (exactIn), or the desired output amount if positive (exactOut)
int256 amountSpecified;
/// The sqrt price at which, if reached, the swap will stop executing
uint160 sqrtPriceLimitX96;
}
src/interfaces/IGeodeHook.sol
// SPDX-License-Identifier: MIT
//
// ██████╗ ███████╗ ██████╗ ██████╗ ███████╗
// ██╔════╝ ██╔════╝██╔═══██╗██╔══██╗██╔════╝
// ██║ ███╗█████╗ ██║ ██║██║ ██║█████╗
// ██║ ██║██╔══╝ ██║ ██║██║ ██║██╔══╝
// ╚██████╔╝███████╗╚██████╔╝██████╔╝███████╗
// ╚═════╝ ╚══════╝ ╚═════╝ ╚═════╝ ╚══════╝
//
// Geode Protocol — Permanent Curve Venue on Uniswap v4
// https://geode.ag
//
pragma solidity ^0.8.26;
import {PoolKey} from "v4-core/src/types/PoolKey.sol";
import {PoolId} from "v4-core/src/types/PoolId.sol";
import {Currency} from "v4-core/src/types/Currency.sol";
import {GeodeIntent, BatchState, PoolConfig, LaunchState} from "../libraries/GeodeTypes.sol";
/// @title IGeodeHook
/// @author Geode Protocol (https://geode.ag)
/// @notice Public interface for the Geode batch auction hook
interface IGeodeHook {
// ─── Settlement ─────────────────────────────────────────────────────────────
/// @notice Settle a batch of intents for a given pool
/// @dev Permissionless — callable by anyone. Settler earns a reward from surplus.
/// @param key The pool key identifying the target pool
/// @param buys Buy intents sorted by descending limit price
/// @param sells Sell intents sorted by ascending limit price
/// @param buySignatures EIP-712 signatures corresponding to each buy intent
/// @param sellSignatures EIP-712 signatures corresponding to each sell intent
function geodeSettleBatch(
PoolKey calldata key,
GeodeIntent[] calldata buys,
GeodeIntent[] calldata sells,
bytes[] calldata buySignatures,
bytes[] calldata sellSignatures
) external;
// ─── Pool Configuration ─────────────────────────────────────────────────────
/// @notice Configure a pool for batch auctions
/// @dev Can only be called once per pool (before first settlement)
/// @param key The pool key
/// @param config The pool's batch auction parameters
function geodeInitializePool(PoolKey calldata key, PoolConfig calldata config) external;
// ─── View Functions ─────────────────────────────────────────────────────────
/// @notice Get the current batch state for a pool
function getBatchState(PoolId poolId) external view returns (BatchState memory);
/// @notice Get the configuration for a pool
function getPoolConfig(PoolId poolId) external view returns (PoolConfig memory);
/// @notice Get the accumulated currency0 surplus for a pool
function getSurplusCurrency0(PoolId poolId) external view returns (uint256);
/// @notice Get the accumulated currency1 surplus for a pool
function getSurplusCurrency1(PoolId poolId) external view returns (uint256);
/// @notice Get the last settled block number for a pool
function getLastSettledBlock(PoolId poolId) external view returns (uint256);
/// @notice Check whether a pool's batch can be settled now
function canSettle(PoolId poolId) external view returns (bool);
/// @notice Get the launch state for a pool
function getLaunchState(PoolId poolId) external view returns (LaunchState memory);
/// @notice Compute market cap, FDV, and launch metrics for a curve pool
/// @return currentPriceQ96 Current curve price (ETH per token) in Q96
/// @return marketCap currentPrice × circulatingSupply (in wei)
/// @return fdv currentPrice × totalSupply (in wei)
/// @return ethRaised Total ETH in hook reserves from token sales
/// @return circulatingSupply Tokens distributed to buyers
function getLaunchMetrics(PoolId poolId) external view returns (
uint256 currentPriceQ96,
uint256 marketCap,
uint256 fdv,
uint256 ethRaised,
uint256 circulatingSupply
);
// ─── Events ─────────────────────────────────────────────────────────────────
event GeodeBatchSettled(
PoolId indexed poolId,
uint256 indexed blockNumber,
uint256 clearingPrice,
uint256 internalMatch0,
uint256 internalMatch1,
uint256 residualSwapAmount,
bool residualZeroForOne,
uint256 buyFees,
uint256 sellFees,
uint256 gasReimbursement,
uint256 ammCounterfactualPrice,
address settler
);
/// @notice Emitted when the settler is paid, with exact per-currency breakdown
/// @param poolId Pool the batch was settled for
/// @param settler Address of the settler receiving payment
/// @param settlementFee0 Settlement fee paid in currency0 (from buyer input)
/// @param settlementFee1 Settlement fee paid in currency1 (from seller input)
/// @param gasReimbursement0 Gas reimbursement drawn from surplus currency0
/// @param gasReimbursement1 Gas reimbursement drawn from surplus currency1
event SettlerPaid(
PoolId indexed poolId,
address indexed settler,
uint256 settlementFee0,
uint256 settlementFee1,
uint256 gasReimbursement0,
uint256 gasReimbursement1
);
event GeodeDirectSwap(PoolId indexed poolId, address indexed sender, uint24 feeBps, uint256 feeAmount);
event GeodeProtocolFeeCollected(PoolId indexed poolId, Currency currency, uint256 amount);
event GeodeIntentFilled(
bytes32 indexed intentHash, address indexed owner, uint256 amountIn, uint256 amountOut, uint256 clearingPrice
);
event GeodePoolConfigured(
PoolId indexed poolId, uint256 batchInterval, uint24 directSwapFeeBps, uint256 settlementFeeBps, uint256 maxBatchSize
);
event GeodeLaunched(
PoolId indexed poolId,
address indexed deployer,
address indexed tokenAddress,
uint256 totalSupply,
uint256 virtualTokenReserve,
uint256 virtualEthReserve,
uint24 deployerRoyaltyBps
);
/// @notice Emitted on direct curve swaps (via beforeSwap)
event GeodeCurveSwap(
PoolId indexed poolId,
address indexed sender,
bool isCurveBuy,
uint256 inputAmount,
uint256 outputAmount,
uint256 fee,
uint256 reserveFee,
uint256 newEthReserve
);
event GeodeDeployerRoyaltyPaid(
PoolId indexed poolId,
address indexed deployer,
uint256 amount
);
// ─── Errors ──────────────────────────────────────────────────────────────────
error InsufficientLaunchReserve();
}
src/libraries/ClearingPriceLib.sol
// SPDX-License-Identifier: MIT
//
// ██████╗ ███████╗ ██████╗ ██████╗ ███████╗
// ██╔════╝ ██╔════╝██╔═══██╗██╔══██╗██╔════╝
// ██║ ███╗█████╗ ██║ ██║██║ ██║█████╗
// ██║ ██║██╔══╝ ██║ ██║██║ ██║██╔══╝
// ╚██████╔╝███████╗╚██████╔╝██████╔╝███████╗
// ╚═════╝ ╚══════╝ ╚═════╝ ╚═════╝ ╚══════╝
//
// Geode Protocol — Permanent Curve Venue on Uniswap v4
// https://geode.ag
//
pragma solidity ^0.8.26;
import {GeodeIntent, SettlementResult, GeodeTypes} from "./GeodeTypes.sol";
/// @title ClearingPriceLib
/// @author Geode Protocol (https://geode.ag)
/// @notice Pure library implementing the uniform clearing price algorithm for batch auctions
/// @dev Returns exact deposit-denominated quantities — no predictions about AMM output.
/// The hook captures actual swap deltas at execution time and uses them for distribution.
///
/// Settler competition game theory:
/// A malicious settler CAN submit a partial batch (omit intents) to manipulate the clearing
/// price in their favor. The mitigation is settler competition: any settler can submit a
/// better, more complete batch. The first valid settlement for a given window wins.
library ClearingPriceLib {
/// @notice Thrown when buy intents are not sorted by descending limit price
error BuysNotSorted();
/// @notice Thrown when sell intents are not sorted by ascending limit price
error SellsNotSorted();
/// @notice Thrown when batch exceeds maximum size per side
error BatchTooLarge(uint256 count, uint256 max);
/// @notice Compute the uniform clearing price, internal match amounts, and residual for a batch
/// @param buys Buy intents, sorted by implicit limit price DESCENDING (most generous first)
/// @param sells Sell intents, sorted by implicit limit price ASCENDING (cheapest first)
/// @param maxBatchSize Maximum allowed intents per side
/// @param ammSpotPriceQ128 Current AMM spot price in Q128
/// @param settlementFeeBps Settlement fee charged on each filled intent's input (in bps)
/// @return result Settlement result with exact deposit-denominated quantities
/// @return buyFills Boolean array — true if the buy at that index was filled
/// @return sellFills Boolean array — true if the sell at that index was filled
function computeClearingPrice(
GeodeIntent[] memory buys,
GeodeIntent[] memory sells,
uint256 maxBatchSize,
uint256 ammSpotPriceQ128,
uint256 settlementFeeBps
) internal pure returns (SettlementResult memory result, bool[] memory buyFills, bool[] memory sellFills) {
// Enforce batch size limits
if (buys.length > maxBatchSize) revert BatchTooLarge(buys.length, maxBatchSize);
if (sells.length > maxBatchSize) revert BatchTooLarge(sells.length, maxBatchSize);
buyFills = new bool[](buys.length);
sellFills = new bool[](sells.length);
if (buys.length == 0 && sells.length == 0) {
return (result, buyFills, sellFills);
}
_verifySortOrder(buys, sells);
// Clearing price = AMM spot price (v1 simplification)
uint256 clearingPriceQ128 = ammSpotPriceQ128;
// ── Determine which intents fill at clearing price ──
uint256 totalBuyInput = 0; // currency0 from buyers
uint256 totalSellInput = 0; // currency1 from sellers
for (uint256 i = 0; i < buys.length; i++) {
// Buy limit price: amountIn * Q128 / minAmountOut (max price willing to pay)
// minAmountOut == 0 means "accept any price" → always fill
if (buys[i].minAmountOut == 0 || (buys[i].amountIn * GeodeTypes.Q128) / buys[i].minAmountOut >= clearingPriceQ128) {
buyFills[i] = true;
totalBuyInput += buys[i].amountIn;
}
}
for (uint256 i = 0; i < sells.length; i++) {
// Sell limit price: minAmountOut * Q128 / amountIn (min price willing to accept)
// minAmountOut == 0 means "accept any price" → always fill
if (sells[i].minAmountOut == 0 || (sells[i].minAmountOut * GeodeTypes.Q128) / sells[i].amountIn <= clearingPriceQ128) {
sellFills[i] = true;
totalSellInput += sells[i].amountIn;
}
}
// ── Per-intent settlement fees (deducted from input before routing) ──
// Fees come from each intent's own deposit, making one-sided batches
// and wash trades self-funding. Net amounts go to matching/AMM.
uint256 buyFeesAmt = (totalBuyInput * settlementFeeBps) / GeodeTypes.BPS_DENOMINATOR;
uint256 sellFeesAmt = (totalSellInput * settlementFeeBps) / GeodeTypes.BPS_DENOMINATOR;
uint256 netBuyInput = totalBuyInput - buyFeesAmt;
uint256 netSellInput = totalSellInput - sellFeesAmt;
// ── Compute exact internal match amounts and residual from NET inputs ──
// Convert net sell volume to buyer-side units (currency0) at clearing price
uint256 sellVolInQuote = (netSellInput * clearingPriceQ128) / GeodeTypes.Q128;
uint256 internalMatch0;
uint256 internalMatch1;
uint256 residualSwapAmount;
bool residualZeroForOne;
if (netBuyInput >= sellVolInQuote) {
// Net buy pressure: all seller net volume matched, excess buys route through AMM
internalMatch0 = sellVolInQuote;
internalMatch1 = netSellInput;
residualSwapAmount = netBuyInput - sellVolInQuote;
residualZeroForOne = true;
} else {
// Net sell pressure: all buyer net volume matched, excess sells route through AMM
internalMatch0 = netBuyInput;
internalMatch1 = (netBuyInput * GeodeTypes.Q128) / clearingPriceQ128;
residualSwapAmount = netSellInput > internalMatch1
? netSellInput - internalMatch1 : 0;
residualZeroForOne = false;
}
result = SettlementResult({
clearingPrice: clearingPriceQ128,
internalMatch0: internalMatch0,
internalMatch1: internalMatch1,
residualSwapAmount: residualSwapAmount,
residualZeroForOne: residualZeroForOne,
buyFees: buyFeesAmt,
sellFees: sellFeesAmt,
ammCounterfactualPrice: ammSpotPriceQ128,
curveDispensed: 0,
curveAbsorbed: 0,
deployerRoyalty: 0
});
}
/// @notice Verify that buy intents are sorted by descending limit price
/// and sell intents are sorted by ascending limit price
function _verifySortOrder(GeodeIntent[] memory buys, GeodeIntent[] memory sells) private pure {
for (uint256 i = 1; i < buys.length; i++) {
if (buys[i - 1].amountIn * buys[i].minAmountOut < buys[i].amountIn * buys[i - 1].minAmountOut) {
revert BuysNotSorted();
}
}
for (uint256 i = 1; i < sells.length; i++) {
if (sells[i - 1].minAmountOut * sells[i].amountIn > sells[i].minAmountOut * sells[i - 1].amountIn) {
revert SellsNotSorted();
}
}
}
}
src/libraries/ConstantProductCurveLib.sol
// SPDX-License-Identifier: MIT
//
// ██████╗ ███████╗ ██████╗ ██████╗ ███████╗
// ██╔════╝ ██╔════╝██╔═══██╗██╔══██╗██╔════╝
// ██║ ███╗█████╗ ██║ ██║██║ ██║█████╗
// ██║ ██║██╔══╝ ██║ ██║██║ ██║██╔══╝
// ╚██████╔╝███████╗╚██████╔╝██████╔╝███████╗
// ╚═════╝ ╚══════╝ ╚═════╝ ╚═════╝ ╚══════╝
//
// Geode Protocol — Permanent Curve Venue on Uniswap v4
// https://geode.ag
//
pragma solidity ^0.8.26;
import {GeodeIntent, SettlementResult, LaunchState, GeodeTypes} from "./GeodeTypes.sol";
/// @title ConstantProductCurveLib
/// @author Geode Protocol (https://geode.ag)
/// @notice Pure math library for virtual-reserve constant-product bonding curves.
/// @dev Invariant: (Ve + E) · (Vt - S) = Ve · Vt = K
/// Where:
/// Ve = virtual ETH reserve (immutable per pool)
/// Vt = virtual token reserve (immutable per pool, >= curveSupply)
/// E = real ETH raised so far
/// S = real tokens distributed so far
/// Price at state (E, S): price = (Ve + E) / (Vt - S)
/// Starting price (E=0, S=0): price = Ve / Vt
/// All values in raw units: ETH in wei (1e18), tokens in 1e18.
library ConstantProductCurveLib {
/// @notice Thrown when buying would exceed available virtual supply
error ExceedsVirtualSupply();
/// @notice Thrown when selling more tokens than have been distributed
error ExceedsDistributedSupply();
/// @notice Batch size check error
error BatchTooLarge(uint256 count, uint256 max);
// ─── Core Curve Functions ───────────────────────────────────────────────────
/// @notice Current price given the state (real ETH raised, real tokens distributed)
/// @dev price = (Ve + E) / (Vt - S), returned in 1e18 fixed-point (ETH per token)
/// @param Vt Virtual token reserve
/// @param Ve Virtual ETH reserve
/// @param S Cumulative tokens distributed (1e18 units)
/// @param E Cumulative real ETH raised (wei)
/// @return priceX18 Price in 1e18 fixed-point (multiply by token amount / 1e18 to get ETH)
function curvePrice(
uint256 Vt, uint256 Ve, uint256 S, uint256 E
) internal pure returns (uint256 priceX18) {
uint256 denominator = Vt - S;
if (denominator == 0) return type(uint256).max; // infinite price at full distribution
priceX18 = ((Ve + E) * 1e18) / denominator;
}
/// @notice Compute real ETH raised E at a given supply level S (from invariant)
/// @dev From (Ve + E)(Vt - S) = Ve·Vt → E = Ve·Vt/(Vt - S) - Ve
/// @param Vt Virtual token reserve
/// @param Ve Virtual ETH reserve
/// @param S Cumulative tokens distributed
/// @return E Real ETH that has been raised at supply S
function ethAtSupply(
uint256 Vt, uint256 Ve, uint256 S
) internal pure returns (uint256 E) {
if (S == 0) return 0;
uint256 K = Ve * Vt; // invariant constant
uint256 denominator = Vt - S;
if (denominator == 0) return type(uint256).max;
E = K / denominator - Ve;
}
/// @notice ETH cost to buy Δs tokens starting from state (S, E)
/// @dev ethIn = K / (Vt - S - Δs) - (Ve + E)
/// Equivalently: ethIn = K/(Vt - S - Δs) - K/(Vt - S)
/// @param Vt Virtual token reserve
/// @param Ve Virtual ETH reserve
/// @param S Current cumulative supply distributed
/// @param E Current real ETH raised
/// @param deltaS Tokens to buy (1e18 units)
/// @return ethIn ETH cost in wei
function ethCostToBuy(
uint256 Vt, uint256 Ve, uint256 S, uint256 E, uint256 deltaS
) internal pure returns (uint256 ethIn) {
if (deltaS == 0) return 0;
if (S + deltaS >= Vt) revert ExceedsVirtualSupply();
uint256 K = Ve * Vt;
uint256 currentEthSide = Ve + E; // = K / (Vt - S)
uint256 newEthSide = K / (Vt - S - deltaS);
ethIn = newEthSide - currentEthSide;
}
/// @notice ETH returned when selling Δs tokens starting from state (S, E)
/// @dev ethOut = (Ve + E) - K / (Vt - S + Δs)
/// @param Vt Virtual token reserve
/// @param Ve Virtual ETH reserve
/// @param S Current cumulative supply distributed
/// @param E Current real ETH raised
/// @param deltaS Tokens to sell (1e18 units)
/// @return ethOut ETH returned in wei
function ethReturnOnSell(
uint256 Vt, uint256 Ve, uint256 S, uint256 E, uint256 deltaS
) internal pure returns (uint256 ethOut) {
if (deltaS == 0) return 0;
if (deltaS > S) revert ExceedsDistributedSupply();
uint256 K = Ve * Vt;
uint256 currentEthSide = Ve + E; // = K / (Vt - S)
uint256 newEthSide = K / (Vt - S + deltaS); // more tokens in pool → less ETH
ethOut = currentEthSide - newEthSide;
}
/// @notice How many tokens can be bought with `ethIn` ETH from state (S, E)
/// @dev From invariant: new token side = K / (Ve + E + ethIn)
/// Δs = (Vt - S) - K / (Ve + E + ethIn)
/// @param Vt Virtual token reserve
/// @param Ve Virtual ETH reserve
/// @param S Current cumulative supply distributed
/// @param E Current real ETH raised
/// @param ethIn ETH being spent (wei)
/// @return deltaS Tokens purchased (1e18 units)
function tokensForEth(
uint256 Vt, uint256 Ve, uint256 S, uint256 E, uint256 ethIn
) internal pure returns (uint256 deltaS) {
if (ethIn == 0) return 0;
uint256 K = Ve * Vt;
uint256 currentTokenSide = Vt - S;
uint256 newTokenSide = K / (Ve + E + ethIn);
if (newTokenSide >= currentTokenSide) return 0; // rounding edge
deltaS = currentTokenSide - newTokenSide;
}
// ─── Launch Settlement ──────────────────────────────────────────────────────
/// @notice Compute clearing price and settlement for a launch-mode batch
/// @dev Clearing price = curve price at current state.
/// Internal matching happens at this price.
/// Net residual flows to/from hook reserve via the curve.
/// @param buys Buy intents (ETH → token)
/// @param sells Sell intents (token → ETH)
/// @param maxBatchSize Maximum intents per side
/// @param launchState Current launch curve state
/// @param settlementFeeBps Fee charged on each filled intent's input (in bps)
/// @param deployerRoyaltyBps Deployer royalty as bps of matched volume
/// @return result Settlement result
/// @return buyFills Boolean array of filled buys
/// @return sellFills Boolean array of filled sells
function computeLaunchSettlement(
GeodeIntent[] memory buys,
GeodeIntent[] memory sells,
uint256 maxBatchSize,
LaunchState memory launchState,
uint256 settlementFeeBps,
uint256 deployerRoyaltyBps
) internal pure returns (SettlementResult memory result, bool[] memory buyFills, bool[] memory sellFills) {
if (buys.length > maxBatchSize) revert BatchTooLarge(buys.length, maxBatchSize);
if (sells.length > maxBatchSize) revert BatchTooLarge(sells.length, maxBatchSize);
buyFills = new bool[](buys.length);
sellFills = new bool[](sells.length);
if (buys.length == 0 && sells.length == 0) {
return (result, buyFills, sellFills);
}
// Clearing price from constant-product curve (in Q128 for compatibility)
uint256 clearingPriceQ128 = _curvePriceToQ128(
launchState.virtualTokenReserve,
launchState.virtualEthReserve,
launchState.cumulativeSupplyDistributed,
launchState.ethReserve
);
// Determine which intents fill at clearing price
uint256 totalBuyInput = 0; // ETH from buyers
uint256 totalSellInput = 0; // tokens from sellers
for (uint256 i = 0; i < buys.length; i++) {
// minAmountOut == 0 means "accept any price" → always fill
if (buys[i].minAmountOut == 0 || (buys[i].amountIn * GeodeTypes.Q128) / buys[i].minAmountOut >= clearingPriceQ128) {
buyFills[i] = true;
totalBuyInput += buys[i].amountIn;
}
}
for (uint256 i = 0; i < sells.length; i++) {
// minAmountOut == 0 means "accept any price" → always fill
if (sells[i].minAmountOut == 0 || (sells[i].minAmountOut * GeodeTypes.Q128) / sells[i].amountIn <= clearingPriceQ128) {
sellFills[i] = true;
totalSellInput += sells[i].amountIn;
}
}
// ── Per-intent settlement fees (deducted from input before routing) ──
uint256 buyFeesAmt = (totalBuyInput * settlementFeeBps) / GeodeTypes.BPS_DENOMINATOR;
uint256 sellFeesAmt = (totalSellInput * settlementFeeBps) / GeodeTypes.BPS_DENOMINATOR;
uint256 netBuyInput = totalBuyInput - buyFeesAmt; // net ETH going to matching/curve
uint256 netSellInput = totalSellInput - sellFeesAmt; // net tokens going to matching/curve
// Internal matching at clearing price using NET inputs
uint256 sellVolInEth = (netSellInput * clearingPriceQ128) / GeodeTypes.Q128;
uint256 internalMatch0;
uint256 internalMatch1;
uint256 curveDispensed = 0;
uint256 curveAbsorbed = 0;
if (netBuyInput >= sellVolInEth) {
internalMatch0 = sellVolInEth;
internalMatch1 = netSellInput;
uint256 residualEth = netBuyInput - sellVolInEth;
if (residualEth > 0) {
curveDispensed = tokensForEth(
launchState.virtualTokenReserve,
launchState.virtualEthReserve,
launchState.cumulativeSupplyDistributed,
launchState.ethReserve,
residualEth
);
// Cap: never dispense past curveSupply (totalSupply - lpSeed)
if (launchState.curveSupply > 0) {
uint256 maxDispensable = launchState.curveSupply > launchState.cumulativeSupplyDistributed
? launchState.curveSupply - launchState.cumulativeSupplyDistributed
: 0;
if (curveDispensed > maxDispensable) {
curveDispensed = maxDispensable;
}
}
}
} else {
internalMatch0 = netBuyInput;
internalMatch1 = (netBuyInput * GeodeTypes.Q128) / clearingPriceQ128;
uint256 residualTokens = netSellInput > internalMatch1
? netSellInput - internalMatch1 : 0;
if (residualTokens > 0) {
curveAbsorbed = residualTokens;
}
}
// Deployer royalty: sized from matched volume, funded from surplus draw-down in hook
uint256 matchedEthVolume = netBuyInput < sellVolInEth ? netBuyInput : sellVolInEth;
uint256 deployerRoyalty = (matchedEthVolume * deployerRoyaltyBps) / GeodeTypes.BPS_DENOMINATOR;
result = SettlementResult({
clearingPrice: clearingPriceQ128,
internalMatch0: internalMatch0,
internalMatch1: internalMatch1,
residualSwapAmount: 0,
residualZeroForOne: false,
buyFees: buyFeesAmt,
sellFees: sellFeesAmt,
ammCounterfactualPrice: clearingPriceQ128,
curveDispensed: curveDispensed,
curveAbsorbed: curveAbsorbed,
deployerRoyalty: deployerRoyalty
});
}
// ─── Internal Helpers ───────────────────────────────────────────────────────
/// @notice Convert constant-product price to Q128 for settlement compatibility
/// @dev price = (Ve + E) / (Vt - S), scale to Q128
function _curvePriceToQ128(
uint256 Vt, uint256 Ve, uint256 S, uint256 E
) internal pure returns (uint256) {
uint256 denominator = Vt - S;
if (denominator == 0) return type(uint256).max;
// price in Q128 = (Ve + E) * 2^128 / (Vt - S)
// To avoid overflow: split if needed
return ((Ve + E) << 128) / denominator;
}
}
src/libraries/GeodeTypes.sol
// SPDX-License-Identifier: MIT
//
// ██████╗ ███████╗ ██████╗ ██████╗ ███████╗
// ██╔════╝ ██╔════╝██╔═══██╗██╔══██╗██╔════╝
// ██║ ███╗█████╗ ██║ ██║██║ ██║█████╗
// ██║ ██║██╔══╝ ██║ ██║██║ ██║██╔══╝
// ╚██████╔╝███████╗╚██████╔╝██████╔╝███████╗
// ╚═════╝ ╚══════╝ ╚═════╝ ╚═════╝ ╚══════╝
//
// Geode Protocol — Permanent Curve Venue on Uniswap v4
// https://geode.ag
//
pragma solidity ^0.8.26;
import {PoolId} from "v4-core/src/types/PoolId.sol";
/// @title GeodeTypes
/// @author Geode Protocol (https://geode.ag)
/// @notice Shared types and constants for the Geode batch auction hook
library GeodeTypes {
// ─── EIP-712 ────────────────────────────────────────────────────────────────
/// @notice EIP-712 typehash for GeodeIntent — includes poolId for cross-pool replay protection
bytes32 internal constant INTENT_TYPEHASH = keccak256(
"GeodeIntent(bytes32 poolId,address owner,address tokenIn,address tokenOut,"
"uint256 amountIn,uint256 minAmountOut,uint256 deadline,uint256 nonce)"
);
/// @notice EIP-712 domain separator typehash
bytes32 internal constant DOMAIN_TYPEHASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
/// @notice Protocol name for domain separator
string internal constant DOMAIN_NAME = "GeodeHook";
/// @notice Protocol version for domain separator
string internal constant DOMAIN_VERSION = "1";
/// @notice Permit2 witness typehash — contains only fields NOT in PermitTransferFrom
/// @dev tokenIn, amountIn, nonce, deadline are already in PermitTransferFrom.permitted
/// owner is a separate param in permitWitnessTransferFrom
bytes32 internal constant GEODE_WITNESS_TYPEHASH = keccak256(
"GeodeWitness(bytes32 poolId,address tokenOut,uint256 minAmountOut)"
);
/// @notice Permit2 witness type string appended to PermitWitnessTransferFrom stub
/// @dev Full signed type becomes:
/// PermitWitnessTransferFrom(TokenPermissions permitted,address spender,uint256 nonce,uint256 deadline,
/// GeodeWitness witness)GeodeWitness(bytes32 poolId,address tokenOut,uint256 minAmountOut)TokenPermissions(address token,uint256 amount)
string internal constant WITNESS_TYPE_STRING =
"GeodeWitness witness)GeodeWitness(bytes32 poolId,address tokenOut,uint256 minAmountOut)TokenPermissions(address token,uint256 amount)";
// ─── Constants ──────────────────────────────────────────────────────────────
/// @notice Q128 multiplier for fixed-point price representation
uint256 internal constant Q128 = 1 << 128;
/// @notice Maximum allowed batch size per side (absolute ceiling)
uint256 internal constant ABSOLUTE_MAX_BATCH_SIZE = 256;
/// @notice Default batch interval in blocks
uint256 internal constant DEFAULT_BATCH_INTERVAL = 1;
/// @notice Default direct swap fee in bps (0.30%) — for curve pools, split 3 ways
uint24 internal constant DEFAULT_DIRECT_SWAP_FEE_BPS = 30;
/// @notice Default settlement fee per intent in bps (0.10%)
uint256 internal constant DEFAULT_SETTLEMENT_FEE_BPS = 10;
/// @notice Default gas reimbursement multiplier (1.5x = 150)
uint256 internal constant DEFAULT_GAS_REIMBURSEMENT_MULTIPLIER = 150;
/// @notice Default max gas reimbursement per batch (0.01 ETH)
uint256 internal constant DEFAULT_MAX_GAS_REIMBURSEMENT = 0.01 ether;
/// @notice Basis points denominator
uint256 internal constant BPS_DENOMINATOR = 10_000;
}
// ─── Structs (file-level for ergonomic imports) ─────────────────────────────
/// @notice A user's signed trade intent
/// @dev poolId prevents cross-pool replay — an intent signed for pool A cannot settle on pool B
/// @dev Implicit limit price = amountIn / minAmountOut. This couples minimum output with worst
/// acceptable price. Documented trade-off; an explicit maxPriceX96 field may be added in v2.
struct GeodeIntent {
PoolId poolId;
address owner;
address tokenIn;
address tokenOut;
uint256 amountIn;
uint256 minAmountOut;
uint256 deadline;
uint256 nonce;
}
/// @notice Per-pool batch state — overwritten each settlement cycle
struct BatchState {
uint256 blockNumber;
uint256 totalBuyVolume;
uint256 totalSellVolume;
uint256 buyIntentCount;
uint256 sellIntentCount;
bool settled;
}
struct SettlementResult {
uint256 clearingPrice; // Uniform price in Q128 (currency0 per currency1)
uint256 internalMatch0; // Exact currency0 from buyers that crosses internally → sellers
uint256 internalMatch1; // Exact currency1 from sellers that crosses internally → buyers
uint256 residualSwapAmount; // Exact amount to swap through AMM (in input token of the swap)
bool residualZeroForOne; // Swap direction: true = excess buy pressure (currency0→1), false = excess sell (currency1→0)
uint256 buyFees; // Settlement fees from buy-side inputs (currency0)
uint256 sellFees; // Settlement fees from sell-side inputs (currency1)
uint256 ammCounterfactualPrice; // AMM spot price at settlement time — for savings UI
// ─── Launch-mode fields (zero in standard mode) ────────────
uint256 curveDispensed; // Tokens dispensed from hook reserve (net buy residual)
uint256 curveAbsorbed; // Tokens absorbed back into hook (net sell residual)
uint256 deployerRoyalty; // Deployer's share of surplus (from deployerRoyaltyBps)
}
struct PoolConfig {
uint256 batchInterval; // Blocks between allowed settlements
uint24 directSwapFeeBps; // Fee on direct curve swaps (default: 30 bps = 0.3%)
uint256 settlementFeeBps; // Fee on each filled intent's input (e.g., 10 = 0.1%)
uint256 maxBatchSize; // Max intents per side per batch (default: 128)
// ─── Gas reimbursement (surplus-funded, tightly capped) ────────────
uint256 maxGasReimbursement; // Max surplus-funded gas reimbursement per batch (wei)
uint256 gasReimbursementMultiplier; // Multiplier for gas cost (100 = 1x, 150 = 1.5x)
// ─── Curve-pool fields (zero/false for standard pools) ────────────
address deployer; // Deployer address — receives royalties
uint24 deployerRoyaltyBps; // Deployer's share of surplus (immutable after launch)
uint256 virtualTokenReserve; // Virtual token reserve Vt (>= totalSupply for asymptotic)
uint256 virtualEthReserve; // Virtual ETH reserve Ve (starting price = Ve/Vt)
}
/// @notice Launch lifecycle phase
enum LaunchPhase {
None, // Not a launch pool (standard Geode pool)
Active // Permanent bonding curve — dual-path trading (direct + intent)
}
/// @notice Per-pool launch curve state — tracks cumulative distribution and curve position
/// @dev A pool is in curve mode iff tokenAddress != address(0) && phase == Active.
/// The curve is permanent — no graduation, no migration.
struct LaunchState {
uint256 cumulativeSupplyDistributed; // Tokens sold from hook reserve
uint256 totalSupply; // Total supply of the launch token
uint256 virtualTokenReserve; // Cached Vt from PoolConfig for lib access
uint256 virtualEthReserve; // Cached Ve from PoolConfig for lib access
uint256 ethReserve; // ETH accumulated from curve sales
uint256 curveSupply; // Max tokens dispensable via curve (= totalSupply)
address tokenAddress; // Deployed ERC20 address (non-zero = curve token)
LaunchPhase phase; // Current lifecycle phase
}
src/libraries/IntentLib.sol
// SPDX-License-Identifier: MIT
//
// ██████╗ ███████╗ ██████╗ ██████╗ ███████╗
// ██╔════╝ ██╔════╝██╔═══██╗██╔══██╗██╔════╝
// ██║ ███╗█████╗ ██║ ██║██║ ██║█████╗
// ██║ ██║██╔══╝ ██║ ██║██║ ██║██╔══╝
// ╚██████╔╝███████╗╚██████╔╝██████╔╝███████╗
// ╚═════╝ ╚══════╝ ╚═════╝ ╚═════╝ ╚══════╝
//
// Geode Protocol — Permanent Curve Venue on Uniswap v4
// https://geode.ag
//
pragma solidity ^0.8.26;
import {GeodeIntent, GeodeTypes} from "./GeodeTypes.sol";
import {PoolId} from "v4-core/src/types/PoolId.sol";
/// @title IntentLib
/// @author Geode Protocol (https://geode.ag)
/// @notice Library for Permit2 witness computation and intent validation
/// @dev Signature verification is handled by Permit2's permitWitnessTransferFrom.
/// This library provides the witness hash, type string, pool binding validation,
/// and intent identification hashing.
library IntentLib {
/// @notice Thrown when intent targets wrong pool
error PoolIdMismatch(PoolId expected, PoolId actual);
/// @notice Thrown when intent and signature array lengths don't match
error SignatureLengthMismatch(uint256 intents, uint256 signatures);
/// @notice Thrown when intent has expired
error IntentExpired(uint256 deadline, uint256 currentTime);
/// @notice Compute the Permit2 witness hash for a GeodeIntent
/// @dev The witness contains only fields NOT already in PermitTransferFrom:
/// poolId, tokenOut, minAmountOut.
/// tokenIn/amountIn/nonce/deadline are in PermitTransferFrom.permitted.
/// owner is a separate param in permitWitnessTransferFrom.
function computeWitnessHash(GeodeIntent calldata intent) internal pure returns (bytes32) {
return keccak256(
abi.encode(
GeodeTypes.GEODE_WITNESS_TYPEHASH,
PoolId.unwrap(intent.poolId),
intent.tokenOut,
intent.minAmountOut
)
);
}
/// @notice Memory-compatible version of computeWitnessHash
function computeWitnessHashMem(GeodeIntent memory intent) internal pure returns (bytes32) {
return keccak256(
abi.encode(
GeodeTypes.GEODE_WITNESS_TYPEHASH,
PoolId.unwrap(intent.poolId),
intent.tokenOut,
intent.minAmountOut
)
);
}
/// @notice Validate pool binding and deadline for an array of intents
/// @dev Signature verification is handled by Permit2 — this only checks
/// fields that Permit2 doesn't validate (pool binding).
/// Deadline is checked here as a fast-fail before the unlock callback.
function validateIntents(
GeodeIntent[] calldata intents,
bytes[] calldata signatures,
PoolId expectedPoolId
) internal view {
if (intents.length != signatures.length) {
revert SignatureLengthMismatch(intents.length, signatures.length);
}
for (uint256 i = 0; i < intents.length; i++) {
// Check pool binding — prevents cross-pool replay
if (PoolId.unwrap(intents[i].poolId) != PoolId.unwrap(expectedPoolId)) {
revert PoolIdMismatch(expectedPoolId, intents[i].poolId);
}
// Fast-fail on expired intents before entering the unlock callback
if (intents[i].deadline < block.timestamp) {
revert IntentExpired(intents[i].deadline, block.timestamp);
}
}
}
/// @notice Compute a unique hash identifying an intent (for events, not signing)
/// @param intent The intent to hash
/// @return A deterministic hash of all intent fields
function hashIntent(GeodeIntent calldata intent) internal pure returns (bytes32) {
return keccak256(
abi.encode(
GeodeTypes.INTENT_TYPEHASH,
PoolId.unwrap(intent.poolId),
intent.owner,
intent.tokenIn,
intent.tokenOut,
intent.amountIn,
intent.minAmountOut,
intent.deadline,
intent.nonce
)
);
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": false,
"bytecodeHash": "none",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 10,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"forge-std/=lib/forge-std/src/",
"v4-core/=lib/v4-core/",
"v4-periphery/=lib/v4-periphery/",
"permit2/=lib/permit2/",
"@openzeppelin/contracts/=lib/v4-core/lib/openzeppelin-contracts/contracts/",
"solmate/=lib/v4-core/lib/solmate/",
"@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
"@uniswap/v4-core/=lib/v4-periphery/lib/v4-core/",
"ds-test/=lib/permit2/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-gas-snapshot/=lib/permit2/lib/forge-gas-snapshot/src/",
"hardhat/=lib/v4-core/node_modules/hardhat/",
"openzeppelin-contracts/=lib/permit2/lib/openzeppelin-contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.