Skip to content
Verified contractExactUNLICENSED

OLYHookLib

Address0xe0e5ef74ab02b7f2fcd8de204cd8e2a319513721
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.30

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.30+commit.73712a01
Language
solidity
Optimization
Yes, 600 runs
EVM version
cancun
License
UNLICENSED
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,851,592
Creation transaction
0x87a61160a0…186d5f4f23

71 files

The source code is large: one file is shown at a time. Choose a file in the list.

src/libs/OLYHookLib.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.30;

// OpenZeppelin
import {ERC20Burnable} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";

// Uniswap V4 Core
import {BalanceDelta} from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import {PoolId} from "@uniswap/v4-core/src/types/PoolId.sol";
import {ModifyLiquidityParams, SwapParams} from "@uniswap/v4-core/src/types/PoolOperation.sol";
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {StateLibrary} from "@uniswap/v4-core/src/libraries/StateLibrary.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {FullMath} from "@uniswap/v4-core/src/libraries/FullMath.sol";
import {Currency, CurrencyLibrary} from "@uniswap/v4-core/src/types/Currency.sol";
import {CurrencySettler} from "@uniswap/v4-core/test/utils/CurrencySettler.sol";

import {OLYHook, Epoch, EpochLibrary} from "@core/OLYHook.sol";

/// @title OLYHookLib
/// @notice Library for OLYHook calculations to reduce contract size
/// @dev All functions are public to ensure they are called via DELEGATECALL and not inlined
library OLYHookLib {
    using EpochLibrary for Epoch;
    using StateLibrary for IPoolManager;
    using CurrencyLibrary for Currency;
    using CurrencySettler for Currency;

    // -----------------------------------------
    // Constants
    // -----------------------------------------
    uint16 public constant BPS = 10_000;

    // -----------------------------------------
    // Errors
    // -----------------------------------------
    error InRange();
    error CrossedRange();
    error CallbackFailed();
    error ZeroLiquidity();
    error NotFilled();

    // -----------------------------------------
    // Structs
    // -----------------------------------------
    struct SwapEventData {
        bool zeroForOne;
        uint256 amountIn;
        uint256 amountOut;
        uint256 taxAmount;
        uint256 taxBps;
    }

    // -----------------------------------------
    // Public Functions
    // -----------------------------------------
    /// @notice Calculates liquidity amounts from balance delta
    /// @param isAdd True if adding liquidity, false if removing
    /// @param delta The balance delta
    function emitLiquidityAction(bool isAdd, ModifyLiquidityParams memory params, address sender, BalanceDelta delta)
        public
    {
        int128 amount0Delta = delta.amount0();
        int128 amount1Delta = delta.amount1();

        uint256 amount0 = isAdd
            ? amount0Delta < 0 ? uint256(uint128(-amount0Delta)) : 0
            : amount0Delta > 0 ? uint256(uint128(amount0Delta)) : 0;
        uint256 amount1 = isAdd
            ? amount1Delta < 0 ? uint256(uint128(-amount1Delta)) : 0
            : amount1Delta > 0 ? uint256(uint128(amount1Delta)) : 0;

        emit OLYHook.LiquidityAction(
            isAdd, sender, params.tickLower, params.tickUpper, params.liquidityDelta, amount0, amount1, params.salt
        );
    }

    /// @notice Calculates swap event data for emission
    /// @param params The swap parameters
    /// @param delta The balance delta from the swap
    /// @param taxDelta The tax amount collected (0 if taken in beforeSwap or no tax)
    /// @param taxRouter The tax router address (for checking if tax applies)
    /// @param currentTaxBps The current market sell tax BPS
    /// @return eventData The calculated event data
    function emitSwapEvent(
        address sender,
        SwapParams memory params,
        BalanceDelta delta,
        int128 taxDelta,
        address taxRouter,
        uint256 currentTaxBps,
        uint160 sqrtPriceX96,
        uint256 ethPriceUSD
    ) public returns (SwapEventData memory eventData) {
        bool isExactOutput = params.amountSpecified > 0;

        if (params.zeroForOne) {
            // Buy: User spent token0 (ETH) to receive token1 (OLY)
            // No tax on buys
            eventData.zeroForOne = true;
            eventData.amountIn = uint256(int256(-delta.amount0()));
            eventData.amountOut = uint256(int256(delta.amount1()));
            eventData.taxAmount = 0;
            eventData.taxBps = 0;
        } else {
            // Sell: User spent token1 (OLY) to receive token0 (ETH)
            eventData.zeroForOne = false;
            eventData.amountIn = uint256(int256(-delta.amount1()));

            if (isExactOutput) {
                // Exact Output: User requested specific amount, tax taken in beforeSwap
                // User receives exactly what they requested (amountSpecified)
                // Tax was taken from pool in addition to what user receives
                eventData.amountOut = uint256(int256(params.amountSpecified));
                eventData.taxBps = taxRouter != address(0) ? currentTaxBps : 0;
                eventData.taxAmount = (eventData.amountOut * eventData.taxBps) / (BPS - eventData.taxBps);
            } else {
                // Exact Input: User sold specific OLY amount, tax taken in afterSwap
                // Gross output is what swap produced, user receives (gross - tax)
                uint256 grossAmountOut = uint256(int256(delta.amount0()));
                eventData.taxAmount = uint256(int256(taxDelta));
                eventData.taxBps = eventData.taxAmount > 0 ? currentTaxBps : 0;
                eventData.amountOut =
                    grossAmountOut > eventData.taxAmount ? grossAmountOut - eventData.taxAmount : grossAmountOut;
            }
        }

        emit OLYHook.OLYSwap(
            sender,
            eventData.zeroForOne,
            params.amountSpecified,
            eventData.amountIn,
            eventData.amountOut,
            eventData.taxAmount,
            eventData.taxBps,
            sqrtPriceX96,
            ethPriceUSD
        );
    }

    /// @notice Sends the market-sell tax to the tax router and emits the collection event
    function takeTax(
        IPoolManager poolManager,
        address taxRouter,
        Currency currency0,
        address seller,
        uint256 baseAmount,
        uint256 taxAmount,
        uint256 taxBps
    ) public {
        poolManager.take(currency0, taxRouter, taxAmount);
        emit OLYHook.MarketSellTaxCollected(seller, baseAmount, taxAmount, taxBps);
    }

    /// @notice Current market sell tax, falling back to the top tier if resolution reverts
    function safeGetTaxBps(uint256 ethPriceUSD, uint16 fallbackBps) public view returns (uint256) {
        try OLYHook(payable(address(this))).getCurrentMarketSellTaxBps(ethPriceUSD) returns (uint256 taxBps) {
            return taxBps;
        } catch {
            return fallbackBps;
        }
    }

    /// @notice Debits the caller's share from a filled epoch and applies the limit-order sell tax
    function handleWithdrawAccounting(
        OLYHook.EpochInfo storage epochInfo,
        address caller,
        bool taxEnabled,
        address taxRouter,
        uint16 limitOrderTaxBps
    ) public returns (uint256 amount0, uint256 amount1, uint256 taxAmount, uint128 liquidity) {
        if (!epochInfo.filled) revert NotFilled();

        liquidity = epochInfo.liquidity[caller];
        if (liquidity == 0) revert ZeroLiquidity();
        delete epochInfo.liquidity[caller];

        uint128 liquidityTotal = epochInfo.liquidityTotal;

        amount0 = FullMath.mulDiv(epochInfo.token0Total, liquidity, liquidityTotal);
        amount1 = FullMath.mulDiv(epochInfo.token1Total, liquidity, liquidityTotal);

        epochInfo.token0Total -= amount0;
        epochInfo.token1Total -= amount1;
        epochInfo.liquidityTotal = liquidityTotal - liquidity;

        // Only sell orders (zeroForOne = false) pay tax, deducted from the ETH leg
        if (taxEnabled && !epochInfo.zeroForOne && amount0 > 0 && taxRouter != address(0)) {
            taxAmount = (amount0 * limitOrderTaxBps) / BPS;
            amount0 = amount0 - taxAmount;
        }
    }

    /// @notice Handles LP fees from modifyLiquidity
    /// @param poolManager The pool manager
    /// @param validatorVault The validator vault address for ETH fees (0 to skip)
    /// @param hookAddress The hook contract address (for OLY burn destination)
    /// @param key The pool key
    /// @param deltaFee The fee delta from modifyLiquidity
    /// @dev ETH fees (amount0) are minted as ERC6909 shares to ValidatorVault
    /// @dev OLY fees (amount1) are burned directly
    function handleLiquidityFees(
        IPoolManager poolManager,
        address validatorVault,
        address hookAddress,
        PoolKey calldata key,
        BalanceDelta deltaFee
    ) public {
        uint256 ethFees = 0;
        uint256 olyFees = 0;

        if (deltaFee.amount0() > 0 && validatorVault != address(0)) {
            uint128 amount0Fee = uint128(deltaFee.amount0());
            poolManager.mint(validatorVault, key.currency0.toId(), amount0Fee);
            ethFees = amount0Fee;
        }

        if (deltaFee.amount1() > 0) {
            uint128 amount1Fee = uint128(deltaFee.amount1());
            poolManager.mint(hookAddress, key.currency1.toId(), amount1Fee);
            poolManager.burn(hookAddress, key.currency1.toId(), amount1Fee);
            ERC20Burnable oly = ERC20Burnable(Currency.unwrap(key.currency1));
            uint256 balanceBefore = oly.balanceOf(hookAddress);
            key.currency1.take(poolManager, hookAddress, amount1Fee, false);
            uint256 received = oly.balanceOf(hookAddress) - balanceBefore;
            oly.burn(received);
            olyFees = received;
        }

        if (ethFees > 0 || olyFees > 0) {
            emit OLYHook.FeesCaptured(ethFees, olyFees);
        }
    }

    /// @notice Executes withdraw settlement: burn hook balances and transfer to user / tax router
    /// @param poolManager The pool manager
    /// @param hookAddress The hook contract address (holds ERC6909 balances)
    /// @param taxRouter The tax router address for limit-order sell tax (0 to skip)
    /// @param currency0 Pool currency0 (e.g. ETH)
    /// @param currency1 Pool currency1 (e.g. OLY)
    /// @param token0Amount Amount of token0 to send to user
    /// @param token1Amount Amount of token1 to send to user
    /// @param to User recipient
    /// @param taxAmount Limit-order sell tax (only when zeroForOne = false)
    /// @param zeroForOne True = buy order (no tax), false = sell order (tax may apply)
    function handleWithdraw(
        IPoolManager poolManager,
        address hookAddress,
        address taxRouter,
        Currency currency0,
        Currency currency1,
        uint256 token0Amount,
        uint256 token1Amount,
        address to,
        uint256 taxAmount,
        bool zeroForOne
    ) public {
        if (zeroForOne) {
            // Buy order (zeroForOne = true): User deposited ETH, receives OLY (token1) with NO tax
            if (token1Amount > 0) {
                poolManager.burn(hookAddress, currency1.toId(), token1Amount);
                currency1.take(poolManager, to, token1Amount, false);
            }
            if (token0Amount > 0) {
                poolManager.burn(hookAddress, currency0.toId(), token0Amount);
                currency0.take(poolManager, to, token0Amount, false);
            }
        } else {
            // Sell order (zeroForOne = false): User deposited OLY, receives ETH (token0)
            uint256 totalAmount0 = token0Amount + taxAmount;
            if (totalAmount0 > 0) {
                poolManager.burn(hookAddress, currency0.toId(), totalAmount0);
                if (token0Amount > 0) {
                    currency0.take(poolManager, to, token0Amount, false);
                }
                if (taxAmount > 0 && taxRouter != address(0)) {
                    currency0.take(poolManager, taxRouter, taxAmount, false);
                }
            }
            if (token1Amount > 0) {
                poolManager.burn(hookAddress, currency1.toId(), token1Amount);
                currency1.take(poolManager, to, token1Amount, false);
            }
        }
    }

    /// @notice Executes kill: collect fees, optionally send epoch totals, remove liquidity and send to recipient
    /// @param poolManager The pool manager
    /// @param validatorVault The validator vault address for ETH fees (0 to skip)
    /// @param hookAddress The hook contract address
    /// @param key The pool key
    /// @param tickLower The lower tick of the position
    /// @param liquidityDelta The liquidity to remove (negative)
    /// @param to Recipient of withdrawn amounts
    /// @param removingAllLiquidity True if this kill removes all epoch liquidity
    /// @param epochTotal0 Total token0 in epoch (sent to to when removingAllLiquidity)
    /// @param epochTotal1 Total token1 in epoch (sent to to when removingAllLiquidity)
    /// @return amount0 Token0 amount sent to to
    /// @return amount1 Token1 amount sent to to
    function handleKill(
        IPoolManager poolManager,
        address validatorVault,
        address hookAddress,
        PoolKey calldata key,
        int24 tickLower,
        int256 liquidityDelta,
        address to,
        bool removingAllLiquidity,
        uint256 epochTotal0,
        uint256 epochTotal1
    ) public returns (uint256 amount0, uint256 amount1) {
        int24 tickUpper = tickLower + key.tickSpacing;
        {
            (, BalanceDelta deltaFee) = poolManager.modifyLiquidity(
                key, ModifyLiquidityParams({tickLower: tickLower, tickUpper: tickUpper, liquidityDelta: 0, salt: 0}), ""
            );
            handleLiquidityFees(poolManager, validatorVault, hookAddress, key, deltaFee);
        }
        if (removingAllLiquidity) {
            if (epochTotal0 > 0) key.currency0.take(poolManager, to, epochTotal0, false);
            if (epochTotal1 > 0) key.currency1.take(poolManager, to, epochTotal1, false);
        }
        {
            BalanceDelta delta;
            (delta,) = poolManager.modifyLiquidity(
                key,
                ModifyLiquidityParams({
                    tickLower: tickLower, tickUpper: tickUpper, liquidityDelta: liquidityDelta, salt: 0
                }),
                ""
            );
            if (delta.amount0() > 0) {
                amount0 = uint256(uint128(delta.amount0()));
                key.currency0.take(poolManager, to, amount0, false);
            }
            if (delta.amount1() > 0) {
                amount1 = uint256(uint128(delta.amount1()));
                key.currency1.take(poolManager, to, amount1, false);
            }
        }
    }

    function handlePlaceAfter(
        address caller,
        OLYHook.EpochInfo storage epochInfo,
        bool isNew,
        bool zeroForOne,
        Currency currency0,
        Currency currency1,
        int24 tickLower,
        uint128 liquidity
    ) public {
        if (isNew) {
            epochInfo.zeroForOne = zeroForOne;
            epochInfo.currency0 = currency0;
            epochInfo.currency1 = currency1;
            epochInfo.tickLower = tickLower;
        }

        unchecked {
            epochInfo.liquidityTotal += liquidity;
            epochInfo.liquidity[caller] += liquidity;
        }
    }

    /// @notice Executes place: add liquidity, collect fees, return amounts and settle mode (caller must perform settle)
    /// @param poolManager The pool manager
    /// @param validatorVault The validator vault address for ETH fees (0 to skip)
    /// @param hookAddress The hook contract address
    /// @param key The pool key
    /// @param tickLower The lower tick of the position
    /// @param liquidityDelta The liquidity to add (positive)
    /// @param zeroForOne True if placing a buy order (user pays token0), false if sell (user pays token1)
    /// @return amount0 Token0 amount to settle (user paid ETH when zeroForOne)
    /// @return amount1 Token1 amount to settle (user paid OLY when !zeroForOne)
    function handlePlace(
        IPoolManager poolManager,
        address validatorVault,
        address hookAddress,
        PoolKey calldata key,
        int24 tickLower,
        int256 liquidityDelta,
        bool zeroForOne,
        address owner
    ) public returns (uint256 amount0, uint256 amount1) {
        (BalanceDelta delta, BalanceDelta deltaFee) = poolManager.modifyLiquidity(
            key,
            ModifyLiquidityParams({
                tickLower: tickLower, tickUpper: tickLower + key.tickSpacing, liquidityDelta: liquidityDelta, salt: 0
            }),
            ""
        );
        handleLiquidityFees(poolManager, validatorVault, hookAddress, key, deltaFee);

        int128 principal0 = delta.amount0() - deltaFee.amount0();
        int128 principal1 = delta.amount1() - deltaFee.amount1();

        if (principal0 < 0) {
            if (principal1 != 0) revert InRange();
            if (!zeroForOne) revert CrossedRange();
            amount0 = uint256(uint128(-principal0));
            poolManager.sync(key.currency0);
            poolManager.settle{value: amount0}();
        } else {
            if (principal0 != 0) revert InRange();
            if (zeroForOne) revert CrossedRange();
            amount1 = uint256(uint128(-principal1));
            key.currency1.settle(poolManager, owner, amount1, false);
        }
    }

    /// @notice Executes fill: remove liquidity (negative delta), collect fees, mint principal to hook
    /// @param poolManager The pool manager
    /// @param validatorVault The validator vault address for ETH fees (0 to skip)
    /// @param hookAddress The hook contract address (receives minted principal)
    /// @param key The pool key
    /// @param tickLower The lower tick of the position
    /// @param liquidityDelta The liquidity to remove (negative)
    /// @return amount0 Token0 principal minted to hook
    /// @return amount1 Token1 principal minted to hook
    function handleFill(
        IPoolManager poolManager,
        address validatorVault,
        address hookAddress,
        PoolKey calldata key,
        int24 tickLower,
        int256 liquidityDelta
    ) public returns (uint128 amount0, uint128 amount1) {
        int24 tickUpper = tickLower + key.tickSpacing;
        (BalanceDelta delta, BalanceDelta deltaFee) = poolManager.modifyLiquidity(
            key,
            ModifyLiquidityParams({
                tickLower: tickLower, tickUpper: tickUpper, liquidityDelta: liquidityDelta, salt: 0
            }),
            ""
        );
        handleLiquidityFees(poolManager, validatorVault, hookAddress, key, deltaFee);

        int128 principal0 = delta.amount0() - deltaFee.amount0();
        int128 principal1 = delta.amount1() - deltaFee.amount1();

        if (principal0 > 0) {
            amount0 = uint128(principal0);
            poolManager.mint(hookAddress, key.currency0.toId(), amount0);
        }
        if (principal1 > 0) {
            amount1 = uint128(principal1);
            poolManager.mint(hookAddress, key.currency1.toId(), amount1);
        }
    }

    /// @notice Gets the lower tick
    /// @param tick The current tick
    /// @param tickSpacing The tick spacing
    /// @return tickLower The lower tick
    function _getTickLower(int24 tick, int24 tickSpacing) internal pure returns (int24) {
        int24 compressed = tick / tickSpacing;
        if (tick < 0 && tick % tickSpacing != 0) compressed--; // round towards negative infinity
        return compressed * tickSpacing;
    }
}

Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 600,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "forge-std/=lib/forge-std/src/",
    "@uniswap/v4-core/=lib/universal-router/lib/v4-periphery/lib/v4-core/",
    "@uniswap/v4-periphery/=lib/universal-router/lib/v4-periphery/",
    "@uniswap/v3-core/=lib/v3-core/",
    "@uniswap/v3-periphery/=lib/universal-router/lib/v3-periphery/",
    "@uniswap/universal-router/=lib/universal-router/",
    "permit2/=lib/universal-router/lib/permit2/",
    "@interfaces/=src/interfaces/",
    "@libs/=src/libs/",
    "@core/=src/",
    "@lens/=src/lens/",
    "@utils/=src/utils/",
    "@oracle/=src/oracle/",
    "@test/=test/",
    "@mocks/=test/mocks/",
    "@script/=script/",
    "@openzeppelin/uniswap-hooks/=lib/uniswap-hooks/",
    "@ensdomains/=lib/universal-router/lib/v4-periphery/lib/v4-core/node_modules/@ensdomains/",
    "@uniswap/v2-core/=lib/universal-router/node_modules/@uniswap/v2-core/",
    "ds-test/=lib/universal-router/lib/solmate/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "forge-gas-snapshot/=lib/universal-router/lib/permit2/lib/forge-gas-snapshot/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "hardhat/=lib/universal-router/lib/v4-periphery/lib/v4-core/node_modules/hardhat/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "solmate/=lib/universal-router/lib/solmate/",
    "uniswap-hooks/=lib/uniswap-hooks/src/",
    "universal-router/=lib/universal-router/",
    "v3-core/=lib/v3-core/",
    "v3-periphery/=lib/v3-periphery/contracts/",
    "v4-core/=lib/universal-router/lib/v4-periphery/lib/v4-core/src/",
    "v4-periphery/=lib/universal-router/lib/v4-periphery/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.