Skip to content
Verified contractPartialUNLICENSED

OLYHook

Address0xae518866f528db0382f125906e1cfecac3ef58a2
Balance

0 ETH

 

Transactions

1

 

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
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,155,037
Creation transaction
0xe22e1b791c…cc37ee3e4e
Libraries
src/OLYHook.sol:OLYHookLib0xe0e5…513721src/OLYHook.sol:MarketCapLib0xb920…d36685src/OLYHook.sol:TruncatedOracle0xb90a…3fb443

71 files

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

src/OLYHook.sol

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

// OpenZeppelin
import {IERC1155Receiver} from "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {ERC20Burnable} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";

// Uniswap V4 Core
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol";
import {Hooks} from "@uniswap/v4-core/src/libraries/Hooks.sol";
import {FullMath} from "@uniswap/v4-core/src/libraries/FullMath.sol";
import {PoolId, PoolIdLibrary} from "@uniswap/v4-core/src/types/PoolId.sol";
import {BalanceDelta} from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import {
    toBeforeSwapDelta,
    BeforeSwapDelta,
    BeforeSwapDeltaLibrary
} from "@uniswap/v4-core/src/types/BeforeSwapDelta.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {StateLibrary} from "@uniswap/v4-core/src/libraries/StateLibrary.sol";
import {Currency, CurrencyLibrary} from "@uniswap/v4-core/src/types/Currency.sol";
import {ModifyLiquidityParams, SwapParams} from "@uniswap/v4-core/src/types/PoolOperation.sol";

import {IOLYHook} from "@interfaces/IOLYHook.sol";

// Core
import {OLYHookLib} from "@libs/OLYHookLib.sol";
import {BaseHookUpgradeable} from "@core/BaseHookUpgradeable.sol";
import {TruncGeoOracleUpgradeable} from "@core/oracle/TruncGeoOracleUpgradeable.sol";
import {MarketCapLib} from "@core/libs/MarketCapLib.sol";
import {EthPrice} from "@core/EthPrice.sol";

type Epoch is uint232;

library EpochLibrary {
    function equals(Epoch a, Epoch b) internal pure returns (bool) {
        return Epoch.unwrap(a) == Epoch.unwrap(b);
    }

    function unsafeIncrement(Epoch a) internal pure returns (Epoch) {
        unchecked {
            return Epoch.wrap(Epoch.unwrap(a) + 1);
        }
    }
}

contract OLYHook is IOLYHook, BaseHookUpgradeable, TruncGeoOracleUpgradeable, OwnableUpgradeable {
    using EpochLibrary for Epoch;
    using PoolIdLibrary for PoolKey;
    using CurrencyLibrary for Currency;
    using StateLibrary for IPoolManager;

    // -----------------------------------------
    // Types
    // -----------------------------------------
    struct EpochInfo {
        Currency currency0;
        Currency currency1;
        uint256 token0Total;
        uint256 token1Total;
        uint128 liquidityTotal;
        bool filled;
        bool zeroForOne;
        int24 tickLower;
        mapping(address => uint128) liquidity;
    }

    struct KillCallbackData {
        int24 tickLower;
        int256 liquidityDelta;
        address to;
        bool removingAllLiquidity;
        uint256 epochTotal0;
        uint256 epochTotal1;
    }

    struct KillCallbackResult {
        uint256 amount0;
        uint256 amount1;
    }

    struct GetCrossedTicksResult {
        int24 tickLower;
        int24 tickLowerLast;
        int24 lower;
        int24 upper;
        uint160 sqrtPriceX96;
    }

    enum TaxMode {
        FixedTier4,
        FixedTier3,
        FixedTier2,
        Dynamic
    }

    // -----------------------------------------
    // Errors
    // -----------------------------------------
    error ZeroLiquidity();
    error Filled();
    error NotSelf();
    error AlreadyInitialized();
    error CallbackFailed();
    error OnlyPoolManager();
    error InvalidTwapPeriod();
    error OnlyLaunchManager();
    error NotWhitelisted();
    error ZeroAddress();
    error UpgradesDisabled();
    error UnsupportedPool();
    error InvalidTaxTiers();
    error PartialFill();

    // -----------------------------------------
    // Events
    // -----------------------------------------
    event Place(
        address indexed owner,
        Epoch indexed epoch,
        int24 tickLower,
        bool zeroForOne,
        uint128 liquidity,
        uint256 amount0,
        uint256 amount1
    );
    event Fill(
        Epoch indexed epoch, int24 tickLower, bool zeroForOne, uint128 liquidity, uint256 amount0, uint256 amount1
    );
    event Kill(
        address indexed owner,
        Epoch indexed epoch,
        int24 tickLower,
        bool zeroForOne,
        uint128 liquidity,
        uint256 amount0,
        uint256 amount1
    );
    event Withdraw(
        address indexed owner,
        Epoch indexed epoch,
        int24 tickLower,
        bool zeroForOne,
        uint128 liquidityWithdrawn,
        uint256 amount0,
        uint256 amount1,
        uint256 taxAmount
    );
    event TwapPeriodUpdated(uint32 twapPeriod);
    event TaxRouterUpdated(address taxRouter);
    event EthPriceFeedUpdated(address ethPriceFeed);
    event MarketSellTaxCollected(address indexed seller, uint256 ethAmount, uint256 taxAmount, uint256 taxBps);
    event OLYSwap(
        address indexed user, // It is router almost every time
        bool indexed zeroForOne,
        int256 amountSpecified,
        uint256 amountIn,
        uint256 amountOut,
        uint256 taxAmount,
        uint256 taxBps,
        uint160 sqrtPriceX96,
        uint256 ethPriceUSD
    );
    event LiquidityAction(
        bool indexed isAdd,
        address indexed user,
        int24 tickLower,
        int24 tickUpper,
        int256 liquidityDelta,
        uint256 amount0,
        uint256 amount1,
        bytes32 salt
    );
    event FeesCaptured(uint256 ethFees, uint256 olyFees);
    event ValidatorVaultUpdated(address indexed newValidatorVault);
    event MarketSellTaxTiersUpdated(uint16 tier1Bps, uint16 tier2Bps, uint16 tier3Bps, uint16 tier4Bps);

    // -----------------------------------------
    // Constants
    // -----------------------------------------
    bytes internal constant ZERO_BYTES = bytes("");
    Epoch private constant EPOCH_DEFAULT = Epoch.wrap(0);
    uint16 private constant BPS = 10_000;
    uint16 private constant LIMIT_ORDER_TAX_BPS = 200; // 2% tax on limit orders

    /// @notice Hard maximum for any settable market sell tax tier: 10%.
    uint16 public constant MAX_MARKET_SELL_TAX_BPS = 1000;

    // Launch tier rates (BPS) by ascending market cap
    uint16 private constant LAUNCH_TIER1_TAX_BPS = 1000;
    uint16 private constant LAUNCH_TIER2_TAX_BPS = 800;
    uint16 private constant LAUNCH_TIER3_TAX_BPS = 600;
    uint16 private constant LAUNCH_TIER4_TAX_BPS = 400;

    // -----------------------------------------
    // Modifiers
    // -----------------------------------------
    /// @dev Only this address may call this function. Used to mimic internal functions, using an
    /// external call to catch and parse revert reasons
    modifier selfOnly() {
        _selfOnly();
        _;
    }

    // -----------------------------------------
    // State Variables
    // -----------------------------------------
    address private launchManager; // LaunchManager contract address
    Epoch public epochNext; // Next epoch number to assign (initialized to 1 in `initialize`)
    uint32 public twapPeriod; // TWAP period in seconds
    address payable public taxRouter;
    address public ethPriceFeed; // Eth price feed contract ETH/USD
    PoolKey private mainPoolKey; // Cache the main pool key for price calculations
    address public validatorVault; // ValidatorVault address for ETH fee distribution

    /// @notice When false, market-sell and limit-order sell tax are skipped (initialized to true in `initialize`)
    bool public taxEnabled;

    /// @notice Addresses that may call setTaxEnabled
    mapping(address => bool) public taxSetterWhitelist;

    /// @notice Tax mode: FixedTier4, FixedTier3, FixedTier2, or Dynamic (initialized to Dynamic in `initialize`)
    TaxMode public taxMode;

    mapping(PoolId => int24) public tickLowerLasts;
    mapping(PoolId => bool) public tickLowerLastFromAbove;
    mapping(bytes32 => Epoch) private epochs;
    mapping(Epoch => EpochInfo) private epochInfos;

    /// @notice Market sell tax rate (BPS) per market cap tier, capped at MAX_MARKET_SELL_TAX_BPS
    MarketCapLib.TaxTiers public taxTiers;

    /// @notice Cached id of `mainPoolKey`, so pool checks do not rehash the key out of storage
    bytes32 private mainPoolId;

    /// @dev Tax `_beforeSwap` charged up front on an exact-output sell, checked and cleared in `_afterSwap`.
    ///      Transient, so it takes no storage slot.
    uint256 private transient exactOutputSellTax;

    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        _disableInitializers();
    }

    /// @notice Initializes the hook behind its proxy
    /// @param _manager The Uniswap V4 PoolManager
    /// @param _initialOwner The initial owner (controls admin setters)
    /// @param _launchManager The LaunchManager contract address
    function initialize(IPoolManager _manager, address _initialOwner, address _launchManager) external initializer {
        __TruncGeoOracleUpgradeable_init(_manager);
        __Ownable_init(_initialOwner);
        launchManager = _launchManager;

        epochNext = Epoch.wrap(1);
        taxEnabled = true;
        taxMode = TaxMode.Dynamic;

        _setMarketSellTaxTiers(LAUNCH_TIER1_TAX_BPS, LAUNCH_TIER2_TAX_BPS, LAUNCH_TIER3_TAX_BPS, LAUNCH_TIER4_TAX_BPS);
    }

    /// @notice Upgrades are permanently disabled: once a proxy points at this implementation it can
    ///         never be upgraded again, even by the owner. Ownership and admin setters are unaffected.
    function _authorizeUpgrade(address) internal view virtual override {
        revert UpgradesDisabled();
    }

    // -----------------------------------------
    // External
    // -----------------------------------------
    function place(PoolKey calldata key, int24 tickLower, bool zeroForOne, uint128 liquidity) external payable {
        _requireMainPool(key);
        if (liquidity == 0) revert ZeroLiquidity();

        uint256 baselineBalance = address(this).balance - msg.value;

        uint256 amount0;
        uint256 amount1;
        (amount0, amount1) = abi.decode(
            poolManager.unlock(
                abi.encodeCall(
                    this.unlockCallbackPlace, (key, tickLower, zeroForOne, int256(uint256(liquidity)), msg.sender)
                )
            ),
            (uint256, uint256)
        );

        Epoch epoch = getEpoch(key, tickLower, zeroForOne);
        bool isNew = epoch.equals(EPOCH_DEFAULT);
        if (isNew) {
            unchecked {
                _setEpoch(key, tickLower, zeroForOne, epoch = epochNext);
                epochNext = epoch.unsafeIncrement();
            }
        }

        OLYHookLib.handlePlaceAfter(
            msg.sender, epochInfos[epoch], isNew, zeroForOne, key.currency0, key.currency1, tickLower, liquidity
        );

        uint256 currentBalance = address(this).balance;
        if (currentBalance > baselineBalance) {
            uint256 refund;
            unchecked {
                refund = currentBalance - baselineBalance;
            }
            (bool success,) = payable(msg.sender).call{value: refund}("");
            if (!success) revert CallbackFailed();
        }

        emit Place(msg.sender, epoch, tickLower, zeroForOne, liquidity, amount0, amount1);
    }

    function kill(PoolKey calldata key, int24 tickLower, bool zeroForOne, address to) external {
        _requireMainPool(key);
        Epoch epoch = getEpoch(key, tickLower, zeroForOne);
        EpochInfo storage epochInfo = epochInfos[epoch];

        uint128 liquidity = epochInfo.liquidity[msg.sender];
        if (liquidity == 0) revert ZeroLiquidity();
        delete epochInfo.liquidity[msg.sender];

        KillCallbackResult memory result = abi.decode(
            poolManager.unlock(
                abi.encodeCall(
                    this.unlockCallbackKill,
                    (
                        key,
                        KillCallbackData({
                            tickLower: tickLower,
                            liquidityDelta: -int256(uint256(liquidity)),
                            to: to,
                            removingAllLiquidity: liquidity == epochInfo.liquidityTotal,
                            epochTotal0: epochInfo.token0Total,
                            epochTotal1: epochInfo.token1Total
                        })
                    )
                )
            ),
            (KillCallbackResult)
        );
        epochInfo.liquidityTotal -= liquidity;
        emit Kill(msg.sender, epoch, tickLower, zeroForOne, liquidity, result.amount0, result.amount1);
    }

    function withdraw(Epoch epoch, address to) external returns (uint256 amount0, uint256 amount1, uint256 taxAmount) {
        EpochInfo storage epochInfo = epochInfos[epoch];

        uint128 liquidity;
        (amount0, amount1, taxAmount, liquidity) =
            OLYHookLib.handleWithdrawAccounting(epochInfo, msg.sender, taxEnabled, taxRouter, LIMIT_ORDER_TAX_BPS);

        poolManager.unlock(
            abi.encodeCall(
                this.unlockCallbackWithdraw,
                (epochInfo.currency0, epochInfo.currency1, amount0, amount1, to, taxAmount, epochInfo.zeroForOne)
            )
        );
        emit Withdraw(
            msg.sender, epoch, epochInfo.tickLower, epochInfo.zeroForOne, liquidity, amount0, amount1, taxAmount
        );
    }

    /// @notice Sets the TaxRouter address
    /// @param _taxRouter The address of the TaxRouter contract
    function setTaxRouter(address payable _taxRouter) external onlyOwner {
        taxRouter = _taxRouter;
        emit TaxRouterUpdated(_taxRouter);
    }

    /// @notice Sets the ETH price feed address
    /// @param _ethPriceFeed The address of the Chainlink ETH/USD price feed
    function setEthPriceFeed(address _ethPriceFeed) external onlyOwner {
        if (_ethPriceFeed == address(0)) revert ZeroAddress();
        ethPriceFeed = _ethPriceFeed;
        emit EthPriceFeedUpdated(_ethPriceFeed);
    }

    /// @notice Sets the TWAP period
    /// @param _twapPeriod The new TWAP period in seconds (must be between 1 and 60 minutes)
    function setTwapPeriod(uint32 _twapPeriod) external onlyOwner {
        if (_twapPeriod < 1 minutes || _twapPeriod > 60 minutes) revert InvalidTwapPeriod();
        twapPeriod = _twapPeriod;
        emit TwapPeriodUpdated(_twapPeriod);
    }

    /// @notice Sets whether tax is applied on market sells and limit-order sells. Callable only by whitelisted addresses.
    /// @param _enabled True to apply tax, false to skip it
    function setTaxEnabled(bool _enabled) external {
        if (!taxSetterWhitelist[msg.sender]) revert NotWhitelisted();
        taxEnabled = _enabled;
    }

    /// @notice Adds or removes an address from the tax-setter whitelist
    /// @param addr The address to update
    /// @param allowed True to allow calling setTaxEnabled, false to revoke
    function setTaxSetterWhitelist(address addr, bool allowed) external onlyOwner {
        taxSetterWhitelist[addr] = allowed;
    }

    /// @notice Sets the ValidatorVault address
    /// @param _validatorVault The address of the ValidatorVault contract
    function setValidatorVault(address _validatorVault) external onlyOwner {
        if (_validatorVault == address(0)) revert ZeroAddress();
        validatorVault = _validatorVault;
        emit ValidatorVaultUpdated(_validatorVault);
    }

    /// @notice Sets the market sell tax mode
    /// @param _taxMode TaxMode.FixedTier4/3/2 (pinned to that tier) or Dynamic (market-cap based)
    function setTaxMode(TaxMode _taxMode) external onlyOwner {
        taxMode = _taxMode;
    }

    /// @notice Sets the market sell tax rate for each market cap tier, ascending market cap
    /// @dev Checking tier1 against the cap suffices because monotonicity bounds the rest by it.
    function setMarketSellTaxTiers(uint16 _tier1Bps, uint16 _tier2Bps, uint16 _tier3Bps, uint16 _tier4Bps)
        external
        onlyOwner
    {
        _setMarketSellTaxTiers(_tier1Bps, _tier2Bps, _tier3Bps, _tier4Bps);
    }

    function _setMarketSellTaxTiers(uint16 _tier1Bps, uint16 _tier2Bps, uint16 _tier3Bps, uint16 _tier4Bps) internal {
        if (
            _tier1Bps > MAX_MARKET_SELL_TAX_BPS || _tier1Bps < _tier2Bps || _tier2Bps < _tier3Bps
                || _tier3Bps < _tier4Bps
        ) revert InvalidTaxTiers();

        taxTiers = MarketCapLib.TaxTiers(_tier1Bps, _tier2Bps, _tier3Bps, _tier4Bps);

        emit MarketSellTaxTiersUpdated(_tier1Bps, _tier2Bps, _tier3Bps, _tier4Bps);
    }

    // -----------------------------------------
    // Getters
    // -----------------------------------------
    function getEpoch(PoolKey memory key, int24 tickLower, bool zeroForOne) public view returns (Epoch) {
        return epochs[keccak256(abi.encode(key, tickLower, zeroForOne))];
    }

    function getEpochLiquidity(Epoch epoch, address owner) external view returns (uint256) {
        return epochInfos[epoch].liquidity[owner];
    }

    function getEpochInfo(Epoch epoch)
        external
        view
        returns (
            uint128 liquidityTotal,
            uint256 token0Total,
            uint256 token1Total,
            bool filled,
            bool zeroForOne,
            int24 tickLower
        )
    {
        EpochInfo storage info = epochInfos[epoch];
        return (info.liquidityTotal, info.token0Total, info.token1Total, info.filled, info.zeroForOne, info.tickLower);
    }

    // -----------------------------------------
    // Dynamic Tax Calculation Getters
    // -----------------------------------------
    /// @notice Get the current token price in USD
    function getTokenPriceInUsd() external view returns (uint256) {
        return MarketCapLib.getTokenPriceInUsd(address(ethPriceFeed), poolManager, mainPoolKey, twapPeriod);
    }

    /// @notice Get the current market cap
    function getMarketCap() external view returns (uint256) {
        return MarketCapLib.getMarketCap(address(ethPriceFeed), poolManager, mainPoolKey, twapPeriod);
    }

    /// @notice Get the current market sell tax rate (BPS). Uses fixed rate when taxMode is Fixed8/18/28, else dynamic.
    function getCurrentMarketSellTaxBps(uint256 _ethPriceUSD) public view returns (uint256) {
        if (taxMode == TaxMode.FixedTier4) return taxTiers.tier4Bps;
        if (taxMode == TaxMode.FixedTier3) return taxTiers.tier3Bps;
        if (taxMode == TaxMode.FixedTier2) return taxTiers.tier2Bps;
        return MarketCapLib.getCurrentMarketSellTaxBps(
            address(ethPriceFeed), poolManager, mainPoolKey, twapPeriod, _ethPriceUSD, taxTiers
        );
    }

    /// @notice Safe wrapper around getCurrentMarketSellTaxBps that falls back to the highest tax tier
    function _safeGetCurrentMarketSellTaxBps(uint256 _ethPriceUSD) internal view returns (uint256) {
        return OLYHookLib.safeGetTaxBps(_ethPriceUSD, taxTiers.tier1Bps);
    }

    /// @notice Get the current ETH price in USD (1e18 precision), returns 0 on failure
    function _safeGetEthPriceUSD() internal view returns (uint256) {
        return MarketCapLib.safeGetEthPriceUSD(ethPriceFeed);
    }

    // -----------------------------------------
    // Hooks
    // -----------------------------------------
    /// @inheritdoc BaseHookUpgradeable
    function getHookPermissions() public pure override returns (Hooks.Permissions memory) {
        return Hooks.Permissions({
            beforeInitialize: false,
            afterInitialize: true,
            beforeAddLiquidity: true,
            beforeRemoveLiquidity: true,
            afterAddLiquidity: true,
            afterRemoveLiquidity: true,
            beforeSwap: true,
            afterSwap: true,
            beforeDonate: false,
            afterDonate: false,
            beforeSwapReturnDelta: true,
            afterSwapReturnDelta: true,
            afterAddLiquidityReturnDelta: false,
            afterRemoveLiquidityReturnDelta: false
        });
    }

    /// @inheritdoc BaseHookUpgradeable
    function _afterInitialize(address sender, PoolKey calldata key, uint160, int24 tick)
        internal
        override
        returns (bytes4)
    {
        require(sender == launchManager, OnlyLaunchManager());
        require(mainPoolKey.currency1.isAddressZero(), AlreadyInitialized());

        // Store the main pool key for price calculations
        mainPoolKey = key;
        mainPoolId = PoolId.unwrap(key.toId());

        // _afterInitialize for TruncGeoOracle
        _afterInitialize(key, tick);

        PoolId poolId = key.toId();
        _setTickLowerLast(poolId, _getTickLower(tick, key.tickSpacing));
        tickLowerLastFromAbove[poolId] = false;

        return this.afterInitialize.selector;
    }

    /// @inheritdoc BaseHookUpgradeable
    function _beforeAddLiquidity(address, PoolKey calldata _key, ModifyLiquidityParams calldata, bytes calldata)
        internal
        override
        returns (bytes4)
    {
        // _beforeModifyPosition for TruncGeoOracle
        _beforeModifyPosition(_key);
        return this.beforeAddLiquidity.selector;
    }

    /// @inheritdoc BaseHookUpgradeable
    function _beforeRemoveLiquidity(
        address,
        PoolKey calldata key,
        ModifyLiquidityParams calldata params,
        bytes calldata
    ) internal override returns (bytes4) {
        if (params.liquidityDelta < 0) {
            _beforeModifyPosition(key);
        }
        return this.beforeRemoveLiquidity.selector;
    }

    /// @inheritdoc BaseHookUpgradeable
    function _afterAddLiquidity(
        address sender,
        PoolKey calldata,
        ModifyLiquidityParams calldata params,
        BalanceDelta delta,
        BalanceDelta feesAccrued,
        bytes calldata
    ) internal override returns (bytes4, BalanceDelta) {
        OLYHookLib.emitLiquidityAction(true, params, sender, delta - feesAccrued);

        return (this.afterAddLiquidity.selector, delta);
    }

    /// @inheritdoc BaseHookUpgradeable
    function _afterRemoveLiquidity(
        address sender,
        PoolKey calldata,
        ModifyLiquidityParams calldata params,
        BalanceDelta delta,
        BalanceDelta feesAccrued,
        bytes calldata
    ) internal override returns (bytes4, BalanceDelta) {
        OLYHookLib.emitLiquidityAction(false, params, sender, delta - feesAccrued);

        return (this.afterRemoveLiquidity.selector, delta);
    }

    /// @inheritdoc BaseHookUpgradeable
    function _beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata)
        internal
        override
        returns (bytes4, BeforeSwapDelta, uint24)
    {
        _requireMainPool(key);
        // _beforeSwap for TruncGeoOracle
        _beforeSwap(key);

        // Apply dynamic tax for market sells
        // A market sell is when zeroForOne = false (selling token1/OLY for token0/ETH)
        BeforeSwapDelta delta = BeforeSwapDeltaLibrary.ZERO_DELTA;

        if (!taxEnabled || params.zeroForOne || taxRouter == address(0) || params.amountSpecified <= 0) {
            return (this.beforeSwap.selector, delta, 0);
        }

        uint256 netRequested = uint256(int256(params.amountSpecified));
        uint256 taxBps = _safeGetCurrentMarketSellTaxBps(_safeGetEthPriceUSD());
        uint256 taxAmount = (netRequested * taxBps) / (BPS - taxBps);
        if (taxAmount == 0) {
            return (this.beforeSwap.selector, delta, 0);
        }

        _takeTax(key.currency0, sender, netRequested, taxAmount, taxBps);
        exactOutputSellTax = taxAmount;
        delta = toBeforeSwapDelta(int128(uint128(taxAmount)), 0);

        return (this.beforeSwap.selector, delta, 0);
    }

    /// @inheritdoc BaseHookUpgradeable
    function _afterSwap(
        address sender,
        PoolKey calldata key,
        SwapParams calldata params,
        BalanceDelta delta,
        bytes calldata
    ) internal override returns (bytes4, int128) {
        _requireFullExactOutputSellFill(params, delta);

        // Handle limit order fills
        GetCrossedTicksResult memory crossedTicksResult = _getCrossedTicks(key.toId(), key.tickSpacing);
        if (crossedTicksResult.lower <= crossedTicksResult.upper) {
            // note that a zeroForOne swap means that the pool is actually gaining token0, so limit
            // order fills are the opposite of swap fills, hence the inversion below
            bool zeroForOne = !params.zeroForOne;
            for (; crossedTicksResult.lower <= crossedTicksResult.upper; crossedTicksResult.lower += key.tickSpacing) {
                _fillEpoch(key, crossedTicksResult.lower, zeroForOne);
            }
        }

        uint256 _ethPriceUSD = _safeGetEthPriceUSD();
        address activeTaxRouter = taxEnabled ? taxRouter : address(0);
        uint256 taxBps =
            (activeTaxRouter == address(0) || params.zeroForOne) ? 0 : _safeGetCurrentMarketSellTaxBps(_ethPriceUSD);
        int128 taxDelta = _applySellTax(params, delta, sender, key, taxBps);

        // Emit user swap event with actual amounts received
        OLYHookLib.emitSwapEvent(
            sender, params, delta, taxDelta, activeTaxRouter, taxBps, crossedTicksResult.sqrtPriceX96, _ethPriceUSD
        );

        PoolId poolId = key.toId();
        if (crossedTicksResult.tickLower != crossedTicksResult.tickLowerLast) {
            tickLowerLastFromAbove[poolId] = crossedTicksResult.tickLower < crossedTicksResult.tickLowerLast;
        }
        _setTickLowerLast(poolId, crossedTicksResult.tickLower);
        return (IHooks.afterSwap.selector, taxDelta);
    }

    // -----------------------------------------
    // Internal
    // -----------------------------------------
    function _fillEpoch(PoolKey calldata key, int24 lower, bool zeroForOne) internal {
        Epoch epoch = getEpoch(key, lower, zeroForOne);
        if (!epoch.equals(EPOCH_DEFAULT)) {
            EpochInfo storage epochInfo = epochInfos[epoch];

            // Skip if there's no liquidity to fill
            if (epochInfo.liquidityTotal == 0) {
                return;
            }

            epochInfo.filled = true;

            (uint256 amount0, uint256 amount1) =
                _unlockCallbackFill(key, lower, -int256(uint256(epochInfo.liquidityTotal)));

            unchecked {
                epochInfo.token0Total += amount0;
                epochInfo.token1Total += amount1;
            }

            _setEpoch(key, lower, zeroForOne, EPOCH_DEFAULT);

            emit Fill(epoch, lower, zeroForOne, epochInfo.liquidityTotal, amount0, amount1);
        }
    }

    /// @dev `_beforeSwap` sized an exact-output sell's tax on the full request, so only a full fill may
    ///      settle; a partial one would charge the seller tax on ETH the pool never released.
    function _requireFullExactOutputSellFill(SwapParams calldata _params, BalanceDelta _delta) private {
        uint256 chargedTax = exactOutputSellTax;
        if (chargedTax == 0) return;

        exactOutputSellTax = 0;
        require(_delta.amount0() == _params.amountSpecified + int256(chargedTax), PartialFill());
    }

    /// @param _taxBps The market sell tax already resolved by the caller; zero when tax is off,
    ///        no router is set, or the current tier charges nothing
    function _applySellTax(
        SwapParams calldata _params,
        BalanceDelta _delta,
        address _sender,
        PoolKey calldata _key,
        uint256 _taxBps
    ) internal returns (int128 taxDelta) {
        bool isExactOutput = _params.amountSpecified > 0;
        if (_taxBps == 0 || _params.zeroForOne || isExactOutput) {
            return 0;
        }

        int128 amount0Delta = _delta.amount0();
        if (amount0Delta == 0) {
            return 0;
        }

        uint256 outputAmount = uint128(amount0Delta);
        uint256 taxAmount = (outputAmount * _taxBps) / BPS;
        if (taxAmount == 0) {
            return 0;
        }

        _takeTax(_key.currency0, _sender, outputAmount, taxAmount, _taxBps);
        taxDelta = int128(uint128(taxAmount));
    }

    function _takeTax(Currency currency0, address seller, uint256 baseAmount, uint256 taxAmount, uint256 taxBps)
        private
    {
        OLYHookLib.takeTax(poolManager, taxRouter, currency0, seller, baseAmount, taxAmount, taxBps);
    }

    function _unlockCallbackFill(PoolKey calldata key, int24 tickLower, int256 liquidityDelta)
        private
        returns (uint128 amount0, uint128 amount1)
    {
        (amount0, amount1) =
            OLYHookLib.handleFill(poolManager, validatorVault, address(this), key, tickLower, liquidityDelta);
    }

    function _setEpoch(PoolKey memory key, int24 tickLower, bool zeroForOne, Epoch epoch) private {
        epochs[keccak256(abi.encode(key, tickLower, zeroForOne))] = epoch;
    }

    function _setTickLowerLast(PoolId poolId, int24 tickLower) private {
        tickLowerLasts[poolId] = tickLower;
    }

    /// @notice Generic unlock callback that the pool manager calls
    /// @dev This function routes the call to the appropriate specific callback
    /// @param data The encoded function call data
    /// @return result The return data from the specific callback
    function unlockCallback(bytes calldata data) external returns (bytes memory result) {
        if (msg.sender != address(poolManager)) revert OnlyPoolManager();

        // Delegate to the appropriate callback function by calling ourselves
        // The data contains the full function call (selector + arguments)
        (bool success, bytes memory returndata) = address(this).call(data);

        if (success) {
            return returndata;
        }

        // If there's a revert reason, bubble it up
        if (returndata.length > 0) {
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert CallbackFailed();
        }
    }

    function unlockCallbackPlace(
        PoolKey calldata key,
        int24 tickLower,
        bool zeroForOne,
        int256 liquidityDelta,
        address owner
    ) external selfOnly returns (uint256 amount0, uint256 amount1) {
        (amount0, amount1) = OLYHookLib.handlePlace(
            poolManager, validatorVault, address(this), key, tickLower, liquidityDelta, zeroForOne, owner
        );
    }

    function unlockCallbackKill(PoolKey calldata key, KillCallbackData calldata data)
        external
        selfOnly
        returns (KillCallbackResult memory result)
    {
        (result.amount0, result.amount1) = OLYHookLib.handleKill(
            poolManager,
            validatorVault,
            address(this),
            key,
            data.tickLower,
            data.liquidityDelta,
            data.to,
            data.removingAllLiquidity,
            data.epochTotal0,
            data.epochTotal1
        );
    }

    function unlockCallbackWithdraw(
        Currency currency0,
        Currency currency1,
        uint256 token0Amount,
        uint256 token1Amount,
        address to,
        uint256 taxAmount,
        bool zeroForOne
    ) external selfOnly {
        OLYHookLib.handleWithdraw(
            poolManager,
            address(this),
            taxRouter,
            currency0,
            currency1,
            token0Amount,
            token1Amount,
            to,
            taxAmount,
            zeroForOne
        );
    }

    // -----------------------------------------
    // Internal
    // -----------------------------------------
    function _getTickLower(int24 tick, int24 tickSpacing) private pure returns (int24) {
        int24 compressed = tick / tickSpacing;
        if (tick < 0 && tick % tickSpacing != 0) compressed--; // round towards negative infinity
        return compressed * tickSpacing;
    }

    /// @notice Gets the crossed ticks
    /// @param poolId The pool id
    /// @param tickSpacing The tick spacing
    /// @return result The result of the crossed ticks
    function _getCrossedTicks(PoolId poolId, int24 tickSpacing)
        private
        view
        returns (GetCrossedTicksResult memory result)
    {
        int24 tick;
        (result.sqrtPriceX96, tick,,) = poolManager.getSlot0(poolId);
        result.tickLower = _getTickLower(tick, tickSpacing);
        result.tickLowerLast = tickLowerLasts[poolId];

        bool enteredFromAbove = tickLowerLastFromAbove[poolId];

        if (result.tickLower < result.tickLowerLast) {
            result.lower = result.tickLower + tickSpacing;
            result.upper = enteredFromAbove ? result.tickLowerLast : result.tickLowerLast - tickSpacing;
        } else {
            result.lower = enteredFromAbove ? result.tickLowerLast + tickSpacing : result.tickLowerLast;
            result.upper = result.tickLower - tickSpacing;
        }
    }

    function _selfOnly() internal view {
        if (msg.sender != address(this)) revert NotSelf();
    }

    function _requireMainPool(PoolKey calldata key) private view {
        require(PoolId.unwrap(key.toId()) == mainPoolId, UnsupportedPool());
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {
    "src/OLYHook.sol": {
      "OLYHookLib": "0xe0e5ef74ab02b7f2fcd8de204cd8e2a319513721",
      "MarketCapLib": "0xb920cfe56d7a86136c706043299348d1bad36685",
      "TruncatedOracle": "0xb90af92ac1b41a09a40ecf89788d0068703fb443"
    }
  },
  "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.