{"sources":{"src/libraries/SpotLib.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.26;\n\nimport {FullMath} from \"v4-core/src/libraries/FullMath.sol\";\n\nlibrary SpotLib {\n    error ZeroSqrtPrice();\n\n    uint256 internal constant Q128 = 1 << 128;\n\n    function price18(uint160 sqrtPriceX96, bool stockIsCurrency0, uint8 stockDec, uint8 stableDec)\n        internal\n        pure\n        returns (uint256 stockPrice18)\n    {\n        if (sqrtPriceX96 == 0) revert ZeroSqrtPrice();\n        uint256 ratioX128 = FullMath.mulDiv(uint256(sqrtPriceX96), uint256(sqrtPriceX96), 1 << 64);\n        if (stockIsCurrency0) {\n            return FullMath.mulDiv(ratioX128, 1e18 * 10 ** stockDec, Q128 * 10 ** stableDec);\n        } else {\n            return FullMath.mulDiv(Q128 * 1e18, 10 ** stockDec, ratioX128) / 10 ** stableDec;\n        }\n    }\n}\n"},"src/libraries/DepthLib.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.26;\n\nimport {IPoolManager} from \"v4-core/src/interfaces/IPoolManager.sol\";\nimport {PoolKey} from \"v4-core/src/types/PoolKey.sol\";\nimport {PoolId, PoolIdLibrary} from \"v4-core/src/types/PoolId.sol\";\nimport {StateLibrary} from \"v4-core/src/libraries/StateLibrary.sol\";\nimport {SqrtPriceMath} from \"v4-core/src/libraries/SqrtPriceMath.sol\";\nimport {TickMath} from \"v4-core/src/libraries/TickMath.sol\";\nimport {TickBitmap} from \"v4-core/src/libraries/TickBitmap.sol\";\nimport {BitMath} from \"v4-core/src/libraries/BitMath.sol\";\n\nlibrary DepthLib {\n    using StateLibrary for IPoolManager;\n    using PoolIdLibrary for PoolKey;\n\n    uint256 internal constant SQRT_102_NUM = 1_009_950_494;\n    uint256 internal constant SQRT_102_DEN = 1_000_000_000;\n\n    function stableForTwoPercentMove(uint160 sqrtPriceX96, uint128 liquidity, bool stockIsCurrency0)\n        internal\n        pure\n        returns (uint256 stableRaw)\n    {\n        if (liquidity == 0 || sqrtPriceX96 == 0) return 0;\n        if (stockIsCurrency0) {\n            return SqrtPriceMath.getAmount1Delta(sqrtPriceX96, _upperTarget(sqrtPriceX96), liquidity, true);\n        } else {\n            return SqrtPriceMath.getAmount0Delta(_lowerTarget(sqrtPriceX96), sqrtPriceX96, liquidity, true);\n        }\n    }\n\n    function bandDepth(IPoolManager manager, PoolKey memory key, bool stockIsCurrency0)\n        internal\n        view\n        returns (uint256 stableRaw)\n    {\n        Walk memory w;\n        w.id = key.toId();\n        (w.sqrtP, w.tick,,) = manager.getSlot0(w.id);\n        if (w.sqrtP == 0) return 0;\n        w.liquidity = manager.getLiquidity(w.id);\n        w.spacing = key.tickSpacing;\n        return _walk(manager, w, stockIsCurrency0, stockIsCurrency0, true);\n    }\n\n    function bandDepthBoth(IPoolManager manager, PoolKey memory key, bool stockIsCurrency0)\n        internal\n        view\n        returns (uint256 buyStableRaw, uint256 sellStableRaw)\n    {\n        Walk memory buy;\n        buy.id = key.toId();\n        (buy.sqrtP, buy.tick,,) = manager.getSlot0(buy.id);\n        if (buy.sqrtP == 0) return (0, 0);\n        buy.liquidity = manager.getLiquidity(buy.id);\n        buy.spacing = key.tickSpacing;\n        Walk memory sell =\n            Walk({id: buy.id, sqrtP: buy.sqrtP, tick: buy.tick, liquidity: buy.liquidity, spacing: buy.spacing});\n\n        buyStableRaw = _walk(manager, buy, stockIsCurrency0, stockIsCurrency0, true);\n        sellStableRaw = _walk(manager, sell, !stockIsCurrency0, stockIsCurrency0, false);\n    }\n\n    function bandEdges(uint160 priceSqrtX96) internal pure returns (uint160 lo, uint160 hi) {\n        lo = _lowerTarget(priceSqrtX96);\n        hi = _upperTarget(priceSqrtX96);\n    }\n\n    function bandDepthWithin(\n        IPoolManager manager,\n        PoolKey memory key,\n        bool stockIsCurrency0,\n        uint160 lo,\n        uint160 hi,\n        bool buy\n    ) internal view returns (uint256 stableRaw) {\n        Walk memory w;\n        w.id = key.toId();\n        (w.sqrtP, w.tick,,) = manager.getSlot0(w.id);\n        if (w.sqrtP == 0) return 0;\n        if (w.sqrtP < lo || w.sqrtP > hi) return 0;\n\n        bool up = buy == stockIsCurrency0;\n        uint160 target = up ? hi : lo;\n        if (up ? w.sqrtP >= target : w.sqrtP <= target) return 0;\n\n        w.liquidity = manager.getLiquidity(w.id);\n        w.spacing = key.tickSpacing;\n        return _walkTo(manager, w, up, stockIsCurrency0, buy, target);\n    }\n\n\n    struct Walk {\n        PoolId id;\n        uint160 sqrtP;\n        int24 tick;\n        uint128 liquidity;\n        int24 spacing;\n    }\n\n    function _walk(IPoolManager manager, Walk memory w, bool up, bool measure1, bool roundUp)\n        private\n        view\n        returns (uint256 amount)\n    {\n        return _walkTo(manager, w, up, measure1, roundUp, up ? _upperTarget(w.sqrtP) : _lowerTarget(w.sqrtP));\n    }\n\n    function _walkTo(IPoolManager manager, Walk memory w, bool up, bool measure1, bool roundUp, uint160 target)\n        private\n        view\n        returns (uint256 amount)\n    {\n        while (up ? w.sqrtP < target : w.sqrtP > target) {\n            (int24 next, bool initialized) = _nextTick(manager, w.id, w.tick, w.spacing, !up);\n            if (up) {\n                if (next >= TickMath.MAX_TICK) next = TickMath.MAX_TICK;\n            } else {\n                if (next <= TickMath.MIN_TICK) next = TickMath.MIN_TICK;\n            }\n            uint160 nextSqrt = TickMath.getSqrtPriceAtTick(next);\n            uint160 stop = up ? (nextSqrt < target ? nextSqrt : target) : (nextSqrt > target ? nextSqrt : target);\n            if (w.liquidity != 0) {\n                (uint160 lo, uint160 hi) = up ? (w.sqrtP, stop) : (stop, w.sqrtP);\n                amount += measure1\n                    ? SqrtPriceMath.getAmount1Delta(lo, hi, w.liquidity, roundUp)\n                    : SqrtPriceMath.getAmount0Delta(lo, hi, w.liquidity, roundUp);\n            }\n            w.sqrtP = stop;\n            if (stop != nextSqrt) break;\n            if (initialized) w.liquidity = _applyNet(w.liquidity, _net(manager, w.id, next), !up);\n            w.tick = up ? next : next - 1;\n        }\n    }\n\n    function _upperTarget(uint160 sqrtPriceX96) private pure returns (uint160) {\n        uint256 upper = uint256(sqrtPriceX96) * SQRT_102_NUM / SQRT_102_DEN;\n        return upper > TickMath.MAX_SQRT_PRICE ? TickMath.MAX_SQRT_PRICE : uint160(upper);\n    }\n\n    function _lowerTarget(uint160 sqrtPriceX96) private pure returns (uint160) {\n        uint256 lower = uint256(sqrtPriceX96) * SQRT_102_DEN / SQRT_102_NUM;\n        return lower < TickMath.MIN_SQRT_PRICE ? TickMath.MIN_SQRT_PRICE : uint160(lower);\n    }\n\n    function _net(IPoolManager manager, PoolId id, int24 tick) private view returns (int128 liquidityNet) {\n        (, liquidityNet) = manager.getTickLiquidity(id, tick);\n    }\n\n    function _applyNet(uint128 liquidity, int128 net, bool movingDown) private pure returns (uint128) {\n        if (movingDown) net = -net;\n        return net >= 0 ? liquidity + uint128(net) : liquidity - uint128(-net);\n    }\n\n    function _nextTick(IPoolManager manager, PoolId id, int24 tick, int24 spacing, bool lte)\n        private\n        view\n        returns (int24 next, bool initialized)\n    {\n        unchecked {\n            int24 compressed = TickBitmap.compress(tick, spacing);\n            if (lte) {\n                (int16 wordPos, uint8 bitPos) = TickBitmap.position(compressed);\n                uint256 mask = type(uint256).max >> (uint256(type(uint8).max) - bitPos);\n                uint256 masked = manager.getTickBitmap(id, wordPos) & mask;\n                initialized = masked != 0;\n                next = initialized\n                    ? (compressed - int24(uint24(bitPos - BitMath.mostSignificantBit(masked)))) * spacing\n                    : (compressed - int24(uint24(bitPos))) * spacing;\n            } else {\n                (int16 wordPos, uint8 bitPos) = TickBitmap.position(++compressed);\n                uint256 mask = ~((1 << bitPos) - 1);\n                uint256 masked = manager.getTickBitmap(id, wordPos) & mask;\n                initialized = masked != 0;\n                next = initialized\n                    ? (compressed + int24(uint24(BitMath.leastSignificantBit(masked) - bitPos))) * spacing\n                    : (compressed + int24(uint24(type(uint8).max - bitPos))) * spacing;\n            }\n        }\n    }\n}\n"},"src/libraries/BasketLimits.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.26;\n\nlibrary BasketLimits {\n    uint256 internal constant MIN_CONSTITUENTS = 2;\n    uint256 internal constant MAX_CONSTITUENTS = 10;\n}\n"},"src/NavJitSharedStandingManager.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.26;\n\nimport {Ownable, Ownable2Step} from \"@openzeppelin/contracts/access/Ownable2Step.sol\";\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport {ReentrancyGuard} from \"@openzeppelin/contracts/utils/ReentrancyGuard.sol\";\nimport {Math} from \"@openzeppelin/contracts/utils/math/Math.sol\";\nimport {EnumerableSet} from \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\nimport {SqrtPriceMath} from \"v4-core/src/libraries/SqrtPriceMath.sol\";\nimport {IPoolManager} from \"v4-core/src/interfaces/IPoolManager.sol\";\nimport {StateLibrary} from \"v4-core/src/libraries/StateLibrary.sol\";\nimport {TickMath} from \"v4-core/src/libraries/TickMath.sol\";\nimport {PoolKey} from \"v4-core/src/types/PoolKey.sol\";\nimport {PoolId} from \"v4-core/src/types/PoolId.sol\";\nimport {Currency} from \"v4-core/src/types/Currency.sol\";\nimport {NavJitHook} from \"./NavJitHook.sol\";\nimport {INavGuard} from \"./INavGuard.sol\";\n\ninterface INavGuardParams {\n    function getParams()\n        external\n        view\n        returns (uint16 navTolBps, uint16 staleTolBps, uint32 maxFeedAge, uint16 minCoverageBps);\n}\n\ncontract NavJitSharedStandingManager is Ownable2Step, ReentrancyGuard {\n    using SafeERC20 for IERC20;\n    using EnumerableSet for EnumerableSet.AddressSet;\n    using StateLibrary for IPoolManager;\n\n    error VenueNotOpen(address lot);\n    error StandingExists();\n    error NotDepositor();\n    error PositionLocked(address lot);\n    error DepositTooSmall(uint256 valueUsd18);\n    error NothingExtra(address lot);\n    error NothingBase(address lot);\n    error ExtraTooSmall(address lot);\n    error PoolUnpriced(address lot);\n    error ZeroShares();\n    error HookTransferPending();\n    error ActiveLots(uint256 count);\n    error HasDepositors(address lot);\n    error ZeroAddress();\n    error OwnershipCannotBeRenounced();\n    error DepositsPaused();\n    error NoDepositors(address lot);\n\n    event Deposited(\n        address indexed lot,\n        bytes32 indexed poolId,\n        address indexed depositor,\n        uint256 usdgIn,\n        uint256 lotIn,\n        uint256 shares,\n        bool locked\n    );\n    event Withdrawn(\n        address indexed lot,\n        bytes32 indexed poolId,\n        address indexed depositor,\n        uint256 usdgOut,\n        uint256 lotOut,\n        uint256 shares\n    );\n    event PositionReturned(address indexed lot, address indexed depositor);\n    event PositionEscrowed(address indexed lot, address indexed depositor);\n    event UnownedStandingWithdrawn(address indexed lot, bytes32 indexed poolId, address to);\n    event LockAtDepositSet(bool lockAtDeposit);\n    event HookOwnershipTransferStarted(address indexed newOwner);\n    event Swept(address indexed token, address indexed to, uint256 amount);\n    event DepositsPausedSet(bool paused);\n    event Owed(address indexed token, address indexed account, uint256 amount);\n    event OwedPaid(address indexed token, address indexed account, uint256 amount);\n    event ResidualRecovered(address indexed lot, uint256 usdgAmount);\n\n    uint256 public constant minDepositUsd18 = 50e18;\n    int24 public constant HALF_WIDTH = 100;\n    uint256 public constant MIN_NAV_TOL_BPS = 100;\n    uint256 public constant MAX_NAV_TOL_BPS = 2_000;\n\n    address public immutable hook;\n    address public immutable usdg;\n    uint256 internal immutable usdgScale;\n\n    bool public lockAtDeposit;\n    bool public depositsPaused;\n    uint256 public activeLots;\n\n    mapping(address lot => uint256) public totalShares;\n    mapping(address lot => mapping(address account => uint256)) public sharesOf;\n    mapping(address lot => mapping(address account => uint256)) public baseSharesOf;\n    mapping(address lot => mapping(address account => bool)) public lockedOf;\n    mapping(address lot => EnumerableSet.AddressSet) internal _depositors;\n\n    mapping(address lot => uint256) public usdgHeld;\n    mapping(address lot => uint256) public lotHeld;\n    uint256 public totalUsdgHeld;\n    mapping(address lot => uint256) public usdgPlaced;\n    mapping(address token => mapping(address account => uint256)) public owed;\n    mapping(address token => uint256) public totalOwed;\n    mapping(address token => uint256) public strayHeld;\n    mapping(address lot => uint256) public usdgStrayInPosition;\n    mapping(address lot => uint256) public lotStrayInPosition;\n\n    constructor(NavJitHook hook_, address owner_) Ownable(owner_) {\n        if (address(hook_) == address(0)) revert ZeroAddress();\n        hook = address(hook_);\n        usdg = hook_.usdg();\n        usdgScale = 10 ** (18 - hook_.usdgDecimals());\n    }\n\n    function renounceOwnership() public pure override {\n        revert OwnershipCannotBeRenounced();\n    }\n\n\n    function depositorCount(address lot) external view returns (uint256) {\n        return _depositors[lot].length();\n    }\n\n    function depositorsOf(address lot) external view returns (address[] memory) {\n        return _depositors[lot].values();\n    }\n\n    function poolAssets(address lot) public view returns (uint256 usdgAmt, uint256 lotAmt) {\n        (uint256 u, uint256 l) = _inPosition(lot);\n        u -= Math.min(u, usdgStrayInPosition[lot]);\n        l -= Math.min(l, lotStrayInPosition[lot]);\n        uint256 placed = usdgPlaced[lot];\n        if (placed > u) {\n            uint256 free = _unattributed(usdg);\n            u += placed - u < free ? placed - u : free;\n        }\n        if (totalShares[lot] != 0) l += _unattributed(lot);\n        return (usdgHeld[lot] + u, lotHeld[lot] + l);\n    }\n\n    function navTolBps() public view returns (uint256 tol) {\n        try INavGuardParams(address(NavJitHook(hook).navGuard())).getParams() returns (\n            uint16 nav, uint16 stale, uint32, uint16\n        ) {\n            tol = nav > stale ? nav : stale;\n        } catch {\n            return MAX_NAV_TOL_BPS;\n        }\n        if (tol < MIN_NAV_TOL_BPS) return MIN_NAV_TOL_BPS;\n        if (tol > MAX_NAV_TOL_BPS) return MAX_NAV_TOL_BPS;\n    }\n\n    function _inPosition(address lot) internal view returns (uint256 u, uint256 l) {\n        NavJitHook h = NavJitHook(hook);\n        bytes32 id = h.venueOf(lot);\n        if (id == bytes32(0)) return (0, 0);\n        (uint128 liq, int24 lower, int24 upper) = h.standingOf(id);\n        if (liq == 0) return (0, 0);\n        (uint160 cur,,,) = h.poolManager().getSlot0(PoolId.wrap(id));\n        (uint256 a0, uint256 a1) =\n            _amountsFor(cur, TickMath.getSqrtPriceAtTick(lower), TickMath.getSqrtPriceAtTick(upper), liq);\n        return usdg < lot ? (a0, a1) : (a1, a0);\n    }\n\n    function _amountsFor(uint160 cur, uint160 lo, uint160 hi, uint128 liq)\n        internal\n        pure\n        returns (uint256 a0, uint256 a1)\n    {\n        if (cur <= lo) {\n            a0 = SqrtPriceMath.getAmount0Delta(lo, hi, liq, false);\n        } else if (cur < hi) {\n            a0 = SqrtPriceMath.getAmount0Delta(cur, hi, liq, false);\n            a1 = SqrtPriceMath.getAmount1Delta(lo, cur, liq, false);\n        } else {\n            a1 = SqrtPriceMath.getAmount1Delta(lo, hi, liq, false);\n        }\n    }\n\n    function positionOf(address lot, address account)\n        external\n        view\n        returns (uint256 shares, uint256 usdgAmt, uint256 lotAmt)\n    {\n        shares = sharesOf[lot][account];\n        uint256 total = totalShares[lot];\n        if (shares == 0 || total == 0) return (shares, 0, 0);\n        (uint256 u, uint256 l) = poolAssets(lot);\n        return (shares, u * shares / total, l * shares / total);\n    }\n\n    function extraOf(address lot, address account)\n        external\n        view\n        returns (uint256 shares, uint256 usdgAmt, uint256 lotAmt)\n    {\n        shares = sharesOf[lot][account] - baseSharesOf[lot][account];\n        uint256 total = totalShares[lot];\n        if (shares == 0 || total == 0) return (shares, 0, 0);\n        (uint256 u, uint256 l) = poolAssets(lot);\n        return (shares, u * shares / total, l * shares / total);\n    }\n\n\n    function deposit(address lot, uint256 usdgAmt, uint256 lotAmt) external nonReentrant returns (uint256 shares) {\n        if (depositsPaused) revert DepositsPaused();\n        NavJitHook h = NavJitHook(hook);\n        bytes32 id = h.venueOf(lot);\n        if (id == bytes32(0)) revert VenueNotOpen(lot);\n        if (h.pendingOwner() != address(0)) revert HookTransferPending();\n\n        bool had = sharesOf[lot][msg.sender] != 0;\n\n        (uint256 minted, uint256 uIn, uint256 lIn) = _join(h, lot, id, usdgAmt, lotAmt, had);\n        _book(lot, id, minted, uIn, lIn, had);\n        return minted;\n    }\n\n    function _book(address lot, bytes32 id, uint256 minted, uint256 uIn, uint256 lIn, bool had) internal {\n        sharesOf[lot][msg.sender] += minted;\n        if (!had) {\n            _depositors[lot].add(msg.sender);\n            lockedOf[lot][msg.sender] = lockAtDeposit;\n        }\n        emit Deposited(lot, id, msg.sender, uIn, lIn, minted, lockedOf[lot][msg.sender]);\n    }\n\n    function _join(NavJitHook h, address lot, bytes32 id, uint256 usdgAmt, uint256 lotAmt, bool had)\n        internal\n        returns (uint256 shares, uint256 uIn, uint256 lIn)\n    {\n        uint256 total = totalShares[lot];\n        if (total == 0) {\n            if (_liq(id) != 0) revert StandingExists();\n            _sweep(lot);\n        } else {\n            _lift(h, lot, id);\n        }\n\n        uint256 nav = INavGuard(h.navGuard()).checkedNavPerUnit18(lot);\n\n        (uIn, lIn) = _placeCallers(h, lot, usdgAmt, lotAmt);\n        usdgPlaced[lot] = uIn;\n        uint256 value = _value(uIn, lIn, nav);\n        if (_liq(id) == 0 || value == 0 || (!had && value < minDepositUsd18)) revert DepositTooSmall(value);\n\n        if (total == 0) {\n            shares = value;\n            ++activeLots;\n        } else {\n            shares = _sharesFor(lot, uIn, lIn, nav, total);\n            _lift(h, lot, id);\n            _placePool(h, lot);\n        }\n        if (shares == 0) revert ZeroShares();\n        totalShares[lot] = total + shares;\n        if (!had) baseSharesOf[lot][msg.sender] = shares * minDepositUsd18 / value;\n    }\n\n    function withdraw(address lot) external nonReentrant {\n        uint256 shares = sharesOf[lot][msg.sender];\n        if (shares == 0) revert NotDepositor();\n        if (lockedOf[lot][msg.sender]) revert PositionLocked(lot);\n        _take(lot, msg.sender, shares, false);\n    }\n\n    function withdrawBase(address lot) external nonReentrant {\n        uint256 shares = sharesOf[lot][msg.sender];\n        if (shares == 0) revert NotDepositor();\n        if (lockedOf[lot][msg.sender]) revert PositionLocked(lot);\n        uint256 base = baseSharesOf[lot][msg.sender];\n        if (base == 0) revert NothingBase(lot);\n        if (base == shares) {\n            _take(lot, msg.sender, shares, false);\n            return;\n        }\n        if (shares - base < base) revert ExtraTooSmall(lot);\n        baseSharesOf[lot][msg.sender] = 0;\n        _take(lot, msg.sender, base, false);\n    }\n\n    function withdrawExtra(address lot) external nonReentrant {\n        uint256 shares = sharesOf[lot][msg.sender];\n        if (shares == 0) revert NotDepositor();\n        uint256 extra = shares - baseSharesOf[lot][msg.sender];\n        if (extra == 0) revert NothingExtra(lot);\n        _take(lot, msg.sender, extra, false);\n    }\n\n    function payOwed(address token, address account) external nonReentrant {\n        _payOwed(token, account);\n    }\n\n    function reseed(address lot) external nonReentrant {\n        if (sharesOf[lot][msg.sender] == 0 && msg.sender != owner()) revert NotDepositor();\n        if (totalShares[lot] == 0) revert NoDepositors(lot);\n        NavJitHook h = NavJitHook(hook);\n        bytes32 id = h.venueOf(lot);\n        _lift(h, lot, id);\n        _placePool(h, lot);\n    }\n\n    function _take(address lot, address d, uint256 shares, bool escrow) internal {\n        NavJitHook h = NavJitHook(hook);\n        bytes32 id = h.venueOf(lot);\n        _lift(h, lot, id);\n\n        uint256 total = totalShares[lot];\n        uint256 uOut = shares == total ? usdgHeld[lot] : usdgHeld[lot] * shares / total;\n        uint256 lOut = shares == total ? lotHeld[lot] : lotHeld[lot] * shares / total;\n\n        usdgHeld[lot] -= uOut;\n        totalUsdgHeld -= uOut;\n        lotHeld[lot] -= lOut;\n        totalShares[lot] = total - shares;\n        if (shares == sharesOf[lot][d]) {\n            delete sharesOf[lot][d];\n            delete baseSharesOf[lot][d];\n            delete lockedOf[lot][d];\n            _depositors[lot].remove(d);\n        } else {\n            sharesOf[lot][d] -= shares;\n        }\n        if (total == shares) --activeLots;\n\n        if (escrow) {\n            _owe(usdg, d, uOut);\n            _owe(lot, d, lOut);\n            emit PositionEscrowed(lot, d);\n        } else {\n            if (uOut > 0) IERC20(usdg).safeTransfer(d, uOut);\n            if (lOut > 0) IERC20(lot).safeTransfer(d, lOut);\n            _payOwed(usdg, d);\n            _payOwed(lot, d);\n        }\n        emit Withdrawn(lot, id, d, uOut, lOut, shares);\n\n        if (total != shares) _placePool(h, lot);\n    }\n\n\n    function _lift(NavJitHook h, address lot, bytes32 id) internal {\n        uint256 got;\n        if (_liq(id) != 0) {\n            uint256 u0 = IERC20(usdg).balanceOf(address(this));\n            uint256 l0 = IERC20(lot).balanceOf(address(this));\n            h.withdrawStanding(h.venueKey(lot), address(this));\n            got = IERC20(usdg).balanceOf(address(this)) - u0;\n            uint256 su = Math.min(got, usdgStrayInPosition[lot]);\n            got -= su;\n            strayHeld[usdg] += su;\n            strayHeld[lot] += Math.min(IERC20(lot).balanceOf(address(this)) - l0, lotStrayInPosition[lot]);\n        }\n        usdgStrayInPosition[lot] = 0;\n        lotStrayInPosition[lot] = 0;\n        uint256 placed = usdgPlaced[lot];\n        usdgPlaced[lot] = 0;\n        if (placed > got) {\n            uint256 free = _unattributed(usdg) - got;\n            uint256 residual = placed - got < free ? placed - got : free;\n            if (residual > 0) {\n                got += residual;\n                emit ResidualRecovered(lot, residual);\n            }\n        }\n        usdgHeld[lot] += got;\n        totalUsdgHeld += got;\n        lotHeld[lot] += _unattributed(lot);\n    }\n\n    function _placePool(NavJitHook h, address lot) internal {\n        uint256 u = usdgHeld[lot];\n        uint256 l = lotHeld[lot];\n        if (u == 0 || l == 0) return;\n        (uint256 uPlaced, uint256 lPlaced) = _seed(h, lot, u, l, true);\n        usdgHeld[lot] = u - uPlaced;\n        totalUsdgHeld -= uPlaced;\n        lotHeld[lot] = l - lPlaced;\n        usdgPlaced[lot] = uPlaced;\n    }\n\n    function _placeCallers(NavJitHook h, address lot, uint256 usdgAmt, uint256 lotAmt)\n        internal\n        returns (uint256 uIn, uint256 lIn)\n    {\n        IERC20(usdg).safeTransferFrom(msg.sender, address(this), usdgAmt);\n        IERC20(lot).safeTransferFrom(msg.sender, address(this), lotAmt);\n        (uIn, lIn) = _seed(h, lot, usdgAmt, lotAmt, false);\n        if (usdgAmt > uIn) IERC20(usdg).safeTransfer(msg.sender, usdgAmt - uIn);\n        if (lotAmt > lIn) IERC20(lot).safeTransfer(msg.sender, lotAmt - lIn);\n    }\n\n    function _seed(NavJitHook h, address lot, uint256 u, uint256 l, bool mayFail)\n        internal\n        returns (uint256 uPlaced, uint256 lPlaced)\n    {\n        uint256 su = IERC20(usdg).balanceOf(hook);\n        uint256 sl = IERC20(lot).balanceOf(hook);\n        uint256 u0 = IERC20(usdg).balanceOf(address(this)) + su;\n        uint256 l0 = IERC20(lot).balanceOf(address(this)) + sl;\n        IERC20(usdg).forceApprove(hook, u);\n        IERC20(lot).forceApprove(hook, l);\n        if (mayFail) {\n            try h.seedStanding(h.venueKey(lot), u, l, HALF_WIDTH) {} catch {}\n        } else {\n            h.seedStanding(h.venueKey(lot), u, l, HALF_WIDTH);\n        }\n        IERC20(usdg).forceApprove(hook, 0);\n        IERC20(lot).forceApprove(hook, 0);\n        uPlaced = _placed(lot, usdg, u0, su, u);\n        lPlaced = _placed(lot, lot, l0, sl, l);\n    }\n\n    function _placed(address lot, address token, uint256 before, uint256 s, uint256 given)\n        internal\n        returns (uint256 placed)\n    {\n        uint256 left = IERC20(token).balanceOf(hook);\n        uint256 afterwards = IERC20(token).balanceOf(address(this)) + left;\n        uint256 gone = afterwards < before ? before - afterwards : 0;\n        placed = gone < given ? gone : given;\n        uint256 x = gone - placed;\n        if (x > 0) {\n            if (token == usdg) usdgStrayInPosition[lot] += x;\n            else lotStrayInPosition[lot] += x;\n        }\n        strayHeld[token] += _back(s, left, x);\n    }\n\n    function _back(uint256 s, uint256 left, uint256 x) internal pure returns (uint256) {\n        return s > left + x ? s - left - x : 0;\n    }\n\n    function _sharesFor(address lot, uint256 uIn, uint256 lIn, uint256 nav, uint256 total)\n        internal\n        view\n        returns (uint256)\n    {\n        uint256 u = usdgHeld[lot];\n        uint256 l = lotHeld[lot];\n        uint256 tol = navTolBps();\n        uint256 navW;\n        uint256 vc;\n        uint256 poolW;\n        if (uIn != 0 && u * lIn <= l * uIn) {\n            navW = Math.mulDiv(nav, 10_000, 10_000 - tol, Math.Rounding.Ceil);\n            vc = _value(uIn, lIn, navW);\n            poolW = Math.mulDiv(u, vc, uIn) + _value(0, l - Math.mulDiv(u, lIn, uIn), navW);\n        } else {\n            navW = nav * 10_000 / (10_000 + tol);\n            vc = _value(uIn, lIn, navW);\n            poolW = Math.mulDiv(l, vc, lIn) + _value(u - Math.mulDiv(l, uIn, lIn), 0, navW);\n        }\n        if (poolW == 0) revert PoolUnpriced(lot);\n        return Math.mulDiv(vc, total, poolW);\n    }\n\n    function _value(uint256 usdgAmt, uint256 lotAmt, uint256 nav18) internal view returns (uint256) {\n        return usdgAmt * usdgScale + lotAmt * nav18 / 1e18;\n    }\n\n    function _owe(address token, address account, uint256 amt) internal {\n        if (amt == 0) return;\n        owed[token][account] += amt;\n        totalOwed[token] += amt;\n        emit Owed(token, account, amt);\n    }\n\n    function _payOwed(address token, address account) internal {\n        uint256 amt = owed[token][account];\n        if (amt == 0) return;\n        delete owed[token][account];\n        totalOwed[token] -= amt;\n        IERC20(token).safeTransfer(account, amt);\n        emit OwedPaid(token, account, amt);\n    }\n\n    function _unattributed(address token) internal view returns (uint256) {\n        uint256 claimed = totalOwed[token] + strayHeld[token] + (token == usdg ? totalUsdgHeld : lotHeld[token]);\n        return IERC20(token).balanceOf(address(this)) - claimed;\n    }\n\n    function _liq(bytes32 id) internal view returns (uint128 liq) {\n        (liq,,) = NavJitHook(hook).standingOf(id);\n    }\n\n\n    function setHookParams(NavJitHook.Params calldata p) external onlyOwner {\n        NavJitHook(hook).setParams(p);\n    }\n\n    function setHookTreasury(address t) external onlyOwner {\n        NavJitHook(hook).setTreasury(t);\n    }\n\n    function setHookNavGuard(INavGuard g) external onlyOwner {\n        NavJitHook(hook).setNavGuard(g);\n    }\n\n\n    function setLockAtDeposit(bool v) external onlyOwner {\n        lockAtDeposit = v;\n        emit LockAtDepositSet(v);\n    }\n\n    function setDepositsPaused(bool v) external onlyOwner {\n        depositsPaused = v;\n        emit DepositsPausedSet(v);\n    }\n\n\n    function acceptHookOwnership() external {\n        NavJitHook(hook).acceptOwnership();\n    }\n\n    function transferHookOwnership(address newOwner) external onlyOwner {\n        if (newOwner == address(0)) revert ZeroAddress();\n        if (activeLots != 0) revert ActiveLots(activeLots);\n        NavJitHook(hook).transferOwnership(newOwner);\n        emit HookOwnershipTransferStarted(newOwner);\n    }\n\n\n    function returnPosition(address lot, address account) external onlyOwner nonReentrant {\n        uint256 shares = sharesOf[lot][account];\n        if (shares == 0) revert NotDepositor();\n        _take(lot, account, shares, false);\n        emit PositionReturned(lot, account);\n    }\n\n    function escrowPosition(address lot, address account) external onlyOwner nonReentrant {\n        uint256 shares = sharesOf[lot][account];\n        if (shares == 0) revert NotDepositor();\n        _take(lot, account, shares, true);\n    }\n\n    function withdrawUnownedStanding(address lot, address to) external onlyOwner nonReentrant {\n        if (to == address(0)) revert ZeroAddress();\n        if (totalShares[lot] != 0) revert HasDepositors(lot);\n        NavJitHook h = NavJitHook(hook);\n        bytes32 id = h.venueOf(lot);\n        h.withdrawStanding(h.venueKey(lot), to);\n        emit UnownedStandingWithdrawn(lot, id, to);\n    }\n\n    function sweep(address token) external onlyOwner nonReentrant {\n        bool claimable = token == usdg ? activeLots != 0 : totalShares[token] != 0;\n        if (claimable) {\n            uint256 st = strayHeld[token];\n            if (st == 0) {\n                if (token == usdg) revert ActiveLots(activeLots);\n                revert HasDepositors(token);\n            }\n            delete strayHeld[token];\n            IERC20(token).safeTransfer(owner(), st);\n            emit Swept(token, owner(), st);\n            return;\n        }\n        _sweep(token);\n    }\n\n    function _sweep(address token) internal {\n        uint256 bal = _unattributed(token) + strayHeld[token];\n        delete strayHeld[token];\n        if (bal == 0) return;\n        address to = owner();\n        IERC20(token).safeTransfer(to, bal);\n        emit Swept(token, to, bal);\n    }\n}\n"},"lib/uniswap-hooks/lib/v4-core/lib/openzeppelin-contracts/contracts/access/Ownable2Step.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable2Step.sol)\n\npragma solidity ^0.8.20;\n\nimport {Ownable} from \"./Ownable.sol\";\n\n/**\n * @dev Contract module which provides access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * The initial owner is specified at deployment time in the constructor for `Ownable`. This\n * can later be changed with {transferOwnership} and {acceptOwnership}.\n *\n * This module is used through inheritance. It will make available all functions\n * from parent (Ownable).\n */\nabstract contract Ownable2Step is Ownable {\n    address private _pendingOwner;\n\n    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Returns the address of the pending owner.\n     */\n    function pendingOwner() public view virtual returns (address) {\n        return _pendingOwner;\n    }\n\n    /**\n     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.\n     * Can only be called by the current owner.\n     */\n    function transferOwnership(address newOwner) public virtual override onlyOwner {\n        _pendingOwner = newOwner;\n        emit OwnershipTransferStarted(owner(), newOwner);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.\n     * Internal function without access restriction.\n     */\n    function _transferOwnership(address newOwner) internal virtual override {\n        delete _pendingOwner;\n        super._transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev The new owner accepts the ownership transfer.\n     */\n    function acceptOwnership() public virtual {\n        address sender = _msgSender();\n        if (pendingOwner() != sender) {\n            revert OwnableUnauthorizedAccount(sender);\n        }\n        _transferOwnership(sender);\n    }\n}\n"},"lib/uniswap-hooks/lib/v4-core/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n\n    /**\n     * @dev Returns the value of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the value of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves a `value` amount of tokens from the caller's account to `to`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address to, uint256 value) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the\n     * caller's tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender's allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 value) external returns (bool);\n\n    /**\n     * @dev Moves a `value` amount of tokens from `from` to `to` using the\n     * allowance mechanism. `value` is then deducted from the caller's\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(address from, address to, uint256 value) external returns (bool);\n}\n"},"lib/uniswap-hooks/lib/v4-core/lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"../IERC20.sol\";\nimport {IERC20Permit} from \"../extensions/IERC20Permit.sol\";\nimport {Address} from \"../../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n    using Address for address;\n\n    /**\n     * @dev An operation with an ERC20 token failed.\n     */\n    error SafeERC20FailedOperation(address token);\n\n    /**\n     * @dev Indicates a failed `decreaseAllowance` request.\n     */\n    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);\n\n    /**\n     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeTransfer(IERC20 token, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));\n    }\n\n    /**\n     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\n     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\n     */\n    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));\n    }\n\n    /**\n     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n        uint256 oldAllowance = token.allowance(address(this), spender);\n        forceApprove(token, spender, oldAllowance + value);\n    }\n\n    /**\n     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no\n     * value, non-reverting calls are assumed to be successful.\n     */\n    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {\n        unchecked {\n            uint256 currentAllowance = token.allowance(address(this), spender);\n            if (currentAllowance < requestedDecrease) {\n                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);\n            }\n            forceApprove(token, spender, currentAllowance - requestedDecrease);\n        }\n    }\n\n    /**\n     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\n     * to be set to zero before setting it to a non-zero value, such as USDT.\n     */\n    function forceApprove(IERC20 token, address spender, uint256 value) internal {\n        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));\n\n        if (!_callOptionalReturnBool(token, approvalCall)) {\n            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));\n            _callOptionalReturn(token, approvalCall);\n        }\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     */\n    function _callOptionalReturn(IERC20 token, bytes memory data) private {\n        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\n        // the target address contains contract code and also asserts for success in the low-level call.\n\n        bytes memory returndata = address(token).functionCall(data);\n        if (returndata.length != 0 && !abi.decode(returndata, (bool))) {\n            revert SafeERC20FailedOperation(address(token));\n        }\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     *\n     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.\n     */\n    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {\n        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false\n        // and not revert is the subcall reverts.\n\n        (bool success, bytes memory returndata) = address(token).call(data);\n        return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;\n    }\n}\n"},"lib/uniswap-hooks/lib/v4-core/lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuard {\n    // Booleans are more expensive than uint256 or any type that takes up a full\n    // word because each write operation emits an extra SLOAD to first read the\n    // slot's contents, replace the bits taken up by the boolean, and then write\n    // back. This is the compiler's defense against contract upgrades and\n    // pointer aliasing, and it cannot be disabled.\n\n    // The values being non-zero value makes deployment a bit more expensive,\n    // but in exchange the refund on every call to nonReentrant will be lower in\n    // amount. Since refunds are capped to a percentage of the total\n    // transaction's gas, it is best to keep them low in cases like this one, to\n    // increase the likelihood of the full refund coming into effect.\n    uint256 private constant NOT_ENTERED = 1;\n    uint256 private constant ENTERED = 2;\n\n    uint256 private _status;\n\n    /**\n     * @dev Unauthorized reentrant call.\n     */\n    error ReentrancyGuardReentrantCall();\n\n    constructor() {\n        _status = NOT_ENTERED;\n    }\n\n    /**\n     * @dev Prevents a contract from calling itself, directly or indirectly.\n     * Calling a `nonReentrant` function from another `nonReentrant`\n     * function is not supported. It is possible to prevent this from happening\n     * by making the `nonReentrant` function external, and making it call a\n     * `private` function that does the actual work.\n     */\n    modifier nonReentrant() {\n        _nonReentrantBefore();\n        _;\n        _nonReentrantAfter();\n    }\n\n    function _nonReentrantBefore() private {\n        // On the first call to nonReentrant, _status will be NOT_ENTERED\n        if (_status == ENTERED) {\n            revert ReentrancyGuardReentrantCall();\n        }\n\n        // Any calls to nonReentrant after this point will fail\n        _status = ENTERED;\n    }\n\n    function _nonReentrantAfter() private {\n        // By storing the original value once again, a refund is triggered (see\n        // https://eips.ethereum.org/EIPS/eip-2200)\n        _status = NOT_ENTERED;\n    }\n\n    /**\n     * @dev Returns true if the reentrancy guard is currently set to \"entered\", which indicates there is a\n     * `nonReentrant` function in the call stack.\n     */\n    function _reentrancyGuardEntered() internal view returns (bool) {\n        return _status == ENTERED;\n    }\n}\n"},"lib/uniswap-hooks/lib/v4-core/lib/openzeppelin-contracts/contracts/utils/math/Math.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n    /**\n     * @dev Muldiv operation overflow.\n     */\n    error MathOverflowedMulDiv();\n\n    enum Rounding {\n        Floor, // Toward negative infinity\n        Ceil, // Toward positive infinity\n        Trunc, // Toward zero\n        Expand // Away from zero\n    }\n\n    /**\n     * @dev Returns the addition of two unsigned integers, with an overflow flag.\n     */\n    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\n            uint256 c = a + b;\n            if (c < a) return (false, 0);\n            return (true, c);\n        }\n    }\n\n    /**\n     * @dev Returns the subtraction of two unsigned integers, with an overflow flag.\n     */\n    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\n            if (b > a) return (false, 0);\n            return (true, a - b);\n        }\n    }\n\n    /**\n     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.\n     */\n    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\n            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n            // benefit is lost if 'b' is also tested.\n            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n            if (a == 0) return (true, 0);\n            uint256 c = a * b;\n            if (c / a != b) return (false, 0);\n            return (true, c);\n        }\n    }\n\n    /**\n     * @dev Returns the division of two unsigned integers, with a division by zero flag.\n     */\n    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\n            if (b == 0) return (false, 0);\n            return (true, a / b);\n        }\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.\n     */\n    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\n            if (b == 0) return (false, 0);\n            return (true, a % b);\n        }\n    }\n\n    /**\n     * @dev Returns the largest of two numbers.\n     */\n    function max(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a > b ? a : b;\n    }\n\n    /**\n     * @dev Returns the smallest of two numbers.\n     */\n    function min(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a < b ? a : b;\n    }\n\n    /**\n     * @dev Returns the average of two numbers. The result is rounded towards\n     * zero.\n     */\n    function average(uint256 a, uint256 b) internal pure returns (uint256) {\n        // (a + b) / 2 can overflow.\n        return (a & b) + (a ^ b) / 2;\n    }\n\n    /**\n     * @dev Returns the ceiling of the division of two numbers.\n     *\n     * This differs from standard division with `/` in that it rounds towards infinity instead\n     * of rounding towards zero.\n     */\n    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n        if (b == 0) {\n            // Guarantee the same behavior as in a regular Solidity division.\n            return a / b;\n        }\n\n        // (a + b - 1) / b can overflow on addition, so we distribute.\n        return a == 0 ? 0 : (a - 1) / b + 1;\n    }\n\n    /**\n     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or\n     * denominator == 0.\n     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by\n     * Uniswap Labs also under MIT license.\n     */\n    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\n        unchecked {\n            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n            // variables such that product = prod1 * 2^256 + prod0.\n            uint256 prod0 = x * y; // Least significant 256 bits of the product\n            uint256 prod1; // Most significant 256 bits of the product\n            assembly {\n                let mm := mulmod(x, y, not(0))\n                prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n            }\n\n            // Handle non-overflow cases, 256 by 256 division.\n            if (prod1 == 0) {\n                // Solidity will revert if denominator == 0, unlike the div opcode on its own.\n                // The surrounding unchecked block does not change this fact.\n                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\n                return prod0 / denominator;\n            }\n\n            // Make sure the result is less than 2^256. Also prevents denominator == 0.\n            if (denominator <= prod1) {\n                revert MathOverflowedMulDiv();\n            }\n\n            ///////////////////////////////////////////////\n            // 512 by 256 division.\n            ///////////////////////////////////////////////\n\n            // Make division exact by subtracting the remainder from [prod1 prod0].\n            uint256 remainder;\n            assembly {\n                // Compute remainder using mulmod.\n                remainder := mulmod(x, y, denominator)\n\n                // Subtract 256 bit number from 512 bit number.\n                prod1 := sub(prod1, gt(remainder, prod0))\n                prod0 := sub(prod0, remainder)\n            }\n\n            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.\n            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.\n\n            uint256 twos = denominator & (0 - denominator);\n            assembly {\n                // Divide denominator by twos.\n                denominator := div(denominator, twos)\n\n                // Divide [prod1 prod0] by twos.\n                prod0 := div(prod0, twos)\n\n                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n                twos := add(div(sub(0, twos), twos), 1)\n            }\n\n            // Shift in bits from prod1 into prod0.\n            prod0 |= prod1 * twos;\n\n            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n            // four bits. That is, denominator * inv = 1 mod 2^4.\n            uint256 inverse = (3 * denominator) ^ 2;\n\n            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also\n            // works in modular arithmetic, doubling the correct bits in each step.\n            inverse *= 2 - denominator * inverse; // inverse mod 2^8\n            inverse *= 2 - denominator * inverse; // inverse mod 2^16\n            inverse *= 2 - denominator * inverse; // inverse mod 2^32\n            inverse *= 2 - denominator * inverse; // inverse mod 2^64\n            inverse *= 2 - denominator * inverse; // inverse mod 2^128\n            inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n            // is no longer required.\n            result = prod0 * inverse;\n            return result;\n        }\n    }\n\n    /**\n     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n     */\n    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {\n        uint256 result = mulDiv(x, y, denominator);\n        if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {\n            result += 1;\n        }\n        return result;\n    }\n\n    /**\n     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded\n     * towards zero.\n     *\n     * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n     */\n    function sqrt(uint256 a) internal pure returns (uint256) {\n        if (a == 0) {\n            return 0;\n        }\n\n        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n        //\n        // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n        //\n        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n        //\n        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n        uint256 result = 1 << (log2(a) >> 1);\n\n        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n        // into the expected uint128 result.\n        unchecked {\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            return min(result, a / result);\n        }\n    }\n\n    /**\n     * @notice Calculates sqrt(a), following the selected rounding direction.\n     */\n    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = sqrt(a);\n            return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 2 of a positive value rounded towards zero.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >> 128 > 0) {\n                value >>= 128;\n                result += 128;\n            }\n            if (value >> 64 > 0) {\n                value >>= 64;\n                result += 64;\n            }\n            if (value >> 32 > 0) {\n                value >>= 32;\n                result += 32;\n            }\n            if (value >> 16 > 0) {\n                value >>= 16;\n                result += 16;\n            }\n            if (value >> 8 > 0) {\n                value >>= 8;\n                result += 8;\n            }\n            if (value >> 4 > 0) {\n                value >>= 4;\n                result += 4;\n            }\n            if (value >> 2 > 0) {\n                value >>= 2;\n                result += 2;\n            }\n            if (value >> 1 > 0) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log2(value);\n            return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 10 of a positive value rounded towards zero.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >= 10 ** 64) {\n                value /= 10 ** 64;\n                result += 64;\n            }\n            if (value >= 10 ** 32) {\n                value /= 10 ** 32;\n                result += 32;\n            }\n            if (value >= 10 ** 16) {\n                value /= 10 ** 16;\n                result += 16;\n            }\n            if (value >= 10 ** 8) {\n                value /= 10 ** 8;\n                result += 8;\n            }\n            if (value >= 10 ** 4) {\n                value /= 10 ** 4;\n                result += 4;\n            }\n            if (value >= 10 ** 2) {\n                value /= 10 ** 2;\n                result += 2;\n            }\n            if (value >= 10 ** 1) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log10(value);\n            return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 256 of a positive value rounded towards zero.\n     * Returns 0 if given 0.\n     *\n     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n     */\n    function log256(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >> 128 > 0) {\n                value >>= 128;\n                result += 16;\n            }\n            if (value >> 64 > 0) {\n                value >>= 64;\n                result += 8;\n            }\n            if (value >> 32 > 0) {\n                value >>= 32;\n                result += 4;\n            }\n            if (value >> 16 > 0) {\n                value >>= 16;\n                result += 2;\n            }\n            if (value >> 8 > 0) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log256(value);\n            return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.\n     */\n    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {\n        return uint8(rounding) % 2 == 1;\n    }\n}\n"},"lib/uniswap-hooks/lib/v4-core/lib/openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/structs/EnumerableSet.sol)\n// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Library for managing\n * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive\n * types.\n *\n * Sets have the following properties:\n *\n * - Elements are added, removed, and checked for existence in constant time\n * (O(1)).\n * - Elements are enumerated in O(n). No guarantees are made on the ordering.\n *\n * ```solidity\n * contract Example {\n *     // Add the library methods\n *     using EnumerableSet for EnumerableSet.AddressSet;\n *\n *     // Declare a set state variable\n *     EnumerableSet.AddressSet private mySet;\n * }\n * ```\n *\n * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)\n * and `uint256` (`UintSet`) are supported.\n *\n * [WARNING]\n * ====\n * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure\n * unusable.\n * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.\n *\n * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an\n * array of EnumerableSet.\n * ====\n */\nlibrary EnumerableSet {\n    // To implement this library for multiple types with as little code\n    // repetition as possible, we write it in terms of a generic Set type with\n    // bytes32 values.\n    // The Set implementation uses private functions, and user-facing\n    // implementations (such as AddressSet) are just wrappers around the\n    // underlying Set.\n    // This means that we can only create new EnumerableSets for types that fit\n    // in bytes32.\n\n    struct Set {\n        // Storage of set values\n        bytes32[] _values;\n        // Position is the index of the value in the `values` array plus 1.\n        // Position 0 is used to mean a value is not in the set.\n        mapping(bytes32 value => uint256) _positions;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function _add(Set storage set, bytes32 value) private returns (bool) {\n        if (!_contains(set, value)) {\n            set._values.push(value);\n            // The value is stored at length-1, but we add 1 to all indexes\n            // and use 0 as a sentinel value\n            set._positions[value] = set._values.length;\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function _remove(Set storage set, bytes32 value) private returns (bool) {\n        // We cache the value's position to prevent multiple reads from the same storage slot\n        uint256 position = set._positions[value];\n\n        if (position != 0) {\n            // Equivalent to contains(set, value)\n            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in\n            // the array, and then remove the last element (sometimes called as 'swap and pop').\n            // This modifies the order of the array, as noted in {at}.\n\n            uint256 valueIndex = position - 1;\n            uint256 lastIndex = set._values.length - 1;\n\n            if (valueIndex != lastIndex) {\n                bytes32 lastValue = set._values[lastIndex];\n\n                // Move the lastValue to the index where the value to delete is\n                set._values[valueIndex] = lastValue;\n                // Update the tracked position of the lastValue (that was just moved)\n                set._positions[lastValue] = position;\n            }\n\n            // Delete the slot where the moved value was stored\n            set._values.pop();\n\n            // Delete the tracked position for the deleted slot\n            delete set._positions[value];\n\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function _contains(Set storage set, bytes32 value) private view returns (bool) {\n        return set._positions[value] != 0;\n    }\n\n    /**\n     * @dev Returns the number of values on the set. O(1).\n     */\n    function _length(Set storage set) private view returns (uint256) {\n        return set._values.length;\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function _at(Set storage set, uint256 index) private view returns (bytes32) {\n        return set._values[index];\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function _values(Set storage set) private view returns (bytes32[] memory) {\n        return set._values;\n    }\n\n    // Bytes32Set\n\n    struct Bytes32Set {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n        return _add(set._inner, value);\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n        return _remove(set._inner, value);\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {\n        return _contains(set._inner, value);\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(Bytes32Set storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {\n        return _at(set._inner, index);\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {\n        bytes32[] memory store = _values(set._inner);\n        bytes32[] memory result;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            result := store\n        }\n\n        return result;\n    }\n\n    // AddressSet\n\n    struct AddressSet {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(AddressSet storage set, address value) internal returns (bool) {\n        return _add(set._inner, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(AddressSet storage set, address value) internal returns (bool) {\n        return _remove(set._inner, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(AddressSet storage set, address value) internal view returns (bool) {\n        return _contains(set._inner, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(AddressSet storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(AddressSet storage set, uint256 index) internal view returns (address) {\n        return address(uint160(uint256(_at(set._inner, index))));\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(AddressSet storage set) internal view returns (address[] memory) {\n        bytes32[] memory store = _values(set._inner);\n        address[] memory result;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            result := store\n        }\n\n        return result;\n    }\n\n    // UintSet\n\n    struct UintSet {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(UintSet storage set, uint256 value) internal returns (bool) {\n        return _add(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(UintSet storage set, uint256 value) internal returns (bool) {\n        return _remove(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(UintSet storage set, uint256 value) internal view returns (bool) {\n        return _contains(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(UintSet storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(UintSet storage set, uint256 index) internal view returns (uint256) {\n        return uint256(_at(set._inner, index));\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(UintSet storage set) internal view returns (uint256[] memory) {\n        bytes32[] memory store = _values(set._inner);\n        uint256[] memory result;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            result := store\n        }\n\n        return result;\n    }\n}\n"},"lib/uniswap-hooks/lib/v4-core/src/libraries/SqrtPriceMath.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {SafeCast} from \"./SafeCast.sol\";\n\nimport {FullMath} from \"./FullMath.sol\";\nimport {UnsafeMath} from \"./UnsafeMath.sol\";\nimport {FixedPoint96} from \"./FixedPoint96.sol\";\n\n/// @title Functions based on Q64.96 sqrt price and liquidity\n/// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas\nlibrary SqrtPriceMath {\n    using SafeCast for uint256;\n\n    error InvalidPriceOrLiquidity();\n    error InvalidPrice();\n    error NotEnoughLiquidity();\n    error PriceOverflow();\n\n    /// @notice Gets the next sqrt price given a delta of currency0\n    /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least\n    /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the\n    /// price less in order to not send too much output.\n    /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96),\n    /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount).\n    /// @param sqrtPX96 The starting price, i.e. before accounting for the currency0 delta\n    /// @param liquidity The amount of usable liquidity\n    /// @param amount How much of currency0 to add or remove from virtual reserves\n    /// @param add Whether to add or remove the amount of currency0\n    /// @return The price after adding or removing amount, depending on add\n    function getNextSqrtPriceFromAmount0RoundingUp(uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add)\n        internal\n        pure\n        returns (uint160)\n    {\n        // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price\n        if (amount == 0) return sqrtPX96;\n        uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;\n\n        if (add) {\n            unchecked {\n                uint256 product = amount * sqrtPX96;\n                if (product / amount == sqrtPX96) {\n                    uint256 denominator = numerator1 + product;\n                    if (denominator >= numerator1) {\n                        // always fits in 160 bits\n                        return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator));\n                    }\n                }\n            }\n            // denominator is checked for overflow\n            return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96) + amount));\n        } else {\n            unchecked {\n                uint256 product = amount * sqrtPX96;\n                // if the product overflows, we know the denominator underflows\n                // in addition, we must check that the denominator does not underflow\n                // equivalent: if (product / amount != sqrtPX96 || numerator1 <= product) revert PriceOverflow();\n                assembly (\"memory-safe\") {\n                    if iszero(\n                        and(\n                            eq(div(product, amount), and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff)),\n                            gt(numerator1, product)\n                        )\n                    ) {\n                        mstore(0, 0xf5c787f1) // selector for PriceOverflow()\n                        revert(0x1c, 0x04)\n                    }\n                }\n                uint256 denominator = numerator1 - product;\n                return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160();\n            }\n        }\n    }\n\n    /// @notice Gets the next sqrt price given a delta of currency1\n    /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least\n    /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the\n    /// price less in order to not send too much output.\n    /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity\n    /// @param sqrtPX96 The starting price, i.e., before accounting for the currency1 delta\n    /// @param liquidity The amount of usable liquidity\n    /// @param amount How much of currency1 to add, or remove, from virtual reserves\n    /// @param add Whether to add, or remove, the amount of currency1\n    /// @return The price after adding or removing `amount`\n    function getNextSqrtPriceFromAmount1RoundingDown(uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add)\n        internal\n        pure\n        returns (uint160)\n    {\n        // if we're adding (subtracting), rounding down requires rounding the quotient down (up)\n        // in both cases, avoid a mulDiv for most inputs\n        if (add) {\n            uint256 quotient = (\n                amount <= type(uint160).max\n                    ? (amount << FixedPoint96.RESOLUTION) / liquidity\n                    : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity)\n            );\n\n            return (uint256(sqrtPX96) + quotient).toUint160();\n        } else {\n            uint256 quotient = (\n                amount <= type(uint160).max\n                    ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity)\n                    : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity)\n            );\n\n            // equivalent: if (sqrtPX96 <= quotient) revert NotEnoughLiquidity();\n            assembly (\"memory-safe\") {\n                if iszero(gt(and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff), quotient)) {\n                    mstore(0, 0x4323a555) // selector for NotEnoughLiquidity()\n                    revert(0x1c, 0x04)\n                }\n            }\n            // always fits 160 bits\n            unchecked {\n                return uint160(sqrtPX96 - quotient);\n            }\n        }\n    }\n\n    /// @notice Gets the next sqrt price given an input amount of currency0 or currency1\n    /// @dev Throws if price or liquidity are 0, or if the next price is out of bounds\n    /// @param sqrtPX96 The starting price, i.e., before accounting for the input amount\n    /// @param liquidity The amount of usable liquidity\n    /// @param amountIn How much of currency0, or currency1, is being swapped in\n    /// @param zeroForOne Whether the amount in is currency0 or currency1\n    /// @return uint160 The price after adding the input amount to currency0 or currency1\n    function getNextSqrtPriceFromInput(uint160 sqrtPX96, uint128 liquidity, uint256 amountIn, bool zeroForOne)\n        internal\n        pure\n        returns (uint160)\n    {\n        // equivalent: if (sqrtPX96 == 0 || liquidity == 0) revert InvalidPriceOrLiquidity();\n        assembly (\"memory-safe\") {\n            if or(\n                iszero(and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff)),\n                iszero(and(liquidity, 0xffffffffffffffffffffffffffffffff))\n            ) {\n                mstore(0, 0x4f2461b8) // selector for InvalidPriceOrLiquidity()\n                revert(0x1c, 0x04)\n            }\n        }\n\n        // round to make sure that we don't pass the target price\n        return zeroForOne\n            ? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true)\n            : getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true);\n    }\n\n    /// @notice Gets the next sqrt price given an output amount of currency0 or currency1\n    /// @dev Throws if price or liquidity are 0 or the next price is out of bounds\n    /// @param sqrtPX96 The starting price before accounting for the output amount\n    /// @param liquidity The amount of usable liquidity\n    /// @param amountOut How much of currency0, or currency1, is being swapped out\n    /// @param zeroForOne Whether the amount out is currency1 or currency0\n    /// @return uint160 The price after removing the output amount of currency0 or currency1\n    function getNextSqrtPriceFromOutput(uint160 sqrtPX96, uint128 liquidity, uint256 amountOut, bool zeroForOne)\n        internal\n        pure\n        returns (uint160)\n    {\n        // equivalent: if (sqrtPX96 == 0 || liquidity == 0) revert InvalidPriceOrLiquidity();\n        assembly (\"memory-safe\") {\n            if or(\n                iszero(and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff)),\n                iszero(and(liquidity, 0xffffffffffffffffffffffffffffffff))\n            ) {\n                mstore(0, 0x4f2461b8) // selector for InvalidPriceOrLiquidity()\n                revert(0x1c, 0x04)\n            }\n        }\n\n        // round to make sure that we pass the target price\n        return zeroForOne\n            ? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false)\n            : getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false);\n    }\n\n    /// @notice Gets the amount0 delta between two prices\n    /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper),\n    /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))\n    /// @param sqrtPriceAX96 A sqrt price\n    /// @param sqrtPriceBX96 Another sqrt price\n    /// @param liquidity The amount of usable liquidity\n    /// @param roundUp Whether to round the amount up or down\n    /// @return uint256 Amount of currency0 required to cover a position of size liquidity between the two passed prices\n    function getAmount0Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint128 liquidity, bool roundUp)\n        internal\n        pure\n        returns (uint256)\n    {\n        unchecked {\n            if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);\n\n            // equivalent: if (sqrtPriceAX96 == 0) revert InvalidPrice();\n            assembly (\"memory-safe\") {\n                if iszero(and(sqrtPriceAX96, 0xffffffffffffffffffffffffffffffffffffffff)) {\n                    mstore(0, 0x00bfc921) // selector for InvalidPrice()\n                    revert(0x1c, 0x04)\n                }\n            }\n\n            uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;\n            uint256 numerator2 = sqrtPriceBX96 - sqrtPriceAX96;\n\n            return roundUp\n                ? UnsafeMath.divRoundingUp(FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtPriceBX96), sqrtPriceAX96)\n                : FullMath.mulDiv(numerator1, numerator2, sqrtPriceBX96) / sqrtPriceAX96;\n        }\n    }\n\n    /// @notice Equivalent to: `a >= b ? a - b : b - a`\n    function absDiff(uint160 a, uint160 b) internal pure returns (uint256 res) {\n        assembly (\"memory-safe\") {\n            let diff :=\n                sub(and(a, 0xffffffffffffffffffffffffffffffffffffffff), and(b, 0xffffffffffffffffffffffffffffffffffffffff))\n            // mask = 0 if a >= b else -1 (all 1s)\n            let mask := sar(255, diff)\n            // if a >= b, res = a - b = 0 ^ (a - b)\n            // if a < b, res = b - a = ~~(b - a) = ~(-(b - a) - 1) = ~(a - b - 1) = (-1) ^ (a - b - 1)\n            // either way, res = mask ^ (a - b + mask)\n            res := xor(mask, add(mask, diff))\n        }\n    }\n\n    /// @notice Gets the amount1 delta between two prices\n    /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))\n    /// @param sqrtPriceAX96 A sqrt price\n    /// @param sqrtPriceBX96 Another sqrt price\n    /// @param liquidity The amount of usable liquidity\n    /// @param roundUp Whether to round the amount up, or down\n    /// @return amount1 Amount of currency1 required to cover a position of size liquidity between the two passed prices\n    function getAmount1Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint128 liquidity, bool roundUp)\n        internal\n        pure\n        returns (uint256 amount1)\n    {\n        uint256 numerator = absDiff(sqrtPriceAX96, sqrtPriceBX96);\n        uint256 denominator = FixedPoint96.Q96;\n        uint256 _liquidity = uint256(liquidity);\n\n        /**\n         * Equivalent to:\n         *   amount1 = roundUp\n         *       ? FullMath.mulDivRoundingUp(liquidity, sqrtPriceBX96 - sqrtPriceAX96, FixedPoint96.Q96)\n         *       : FullMath.mulDiv(liquidity, sqrtPriceBX96 - sqrtPriceAX96, FixedPoint96.Q96);\n         * Cannot overflow because `type(uint128).max * type(uint160).max >> 96 < (1 << 192)`.\n         */\n        amount1 = FullMath.mulDiv(_liquidity, numerator, denominator);\n        assembly (\"memory-safe\") {\n            amount1 := add(amount1, and(gt(mulmod(_liquidity, numerator, denominator), 0), roundUp))\n        }\n    }\n\n    /// @notice Helper that gets signed currency0 delta\n    /// @param sqrtPriceAX96 A sqrt price\n    /// @param sqrtPriceBX96 Another sqrt price\n    /// @param liquidity The change in liquidity for which to compute the amount0 delta\n    /// @return int256 Amount of currency0 corresponding to the passed liquidityDelta between the two prices\n    function getAmount0Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, int128 liquidity)\n        internal\n        pure\n        returns (int256)\n    {\n        unchecked {\n            return liquidity < 0\n                ? getAmount0Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(-liquidity), false).toInt256()\n                : -getAmount0Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(liquidity), true).toInt256();\n        }\n    }\n\n    /// @notice Helper that gets signed currency1 delta\n    /// @param sqrtPriceAX96 A sqrt price\n    /// @param sqrtPriceBX96 Another sqrt price\n    /// @param liquidity The change in liquidity for which to compute the amount1 delta\n    /// @return int256 Amount of currency1 corresponding to the passed liquidityDelta between the two prices\n    function getAmount1Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, int128 liquidity)\n        internal\n        pure\n        returns (int256)\n    {\n        unchecked {\n            return liquidity < 0\n                ? getAmount1Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(-liquidity), false).toInt256()\n                : -getAmount1Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(liquidity), true).toInt256();\n        }\n    }\n}\n"},"lib/uniswap-hooks/lib/v4-core/src/interfaces/IPoolManager.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\nimport {Currency} from \"../types/Currency.sol\";\nimport {PoolKey} from \"../types/PoolKey.sol\";\nimport {IHooks} from \"./IHooks.sol\";\nimport {IERC6909Claims} from \"./external/IERC6909Claims.sol\";\nimport {IProtocolFees} from \"./IProtocolFees.sol\";\nimport {BalanceDelta} from \"../types/BalanceDelta.sol\";\nimport {PoolId} from \"../types/PoolId.sol\";\nimport {IExtsload} from \"./IExtsload.sol\";\nimport {IExttload} from \"./IExttload.sol\";\nimport {ModifyLiquidityParams, SwapParams} from \"../types/PoolOperation.sol\";\n\n/// @notice Interface for the PoolManager\ninterface IPoolManager is IProtocolFees, IERC6909Claims, IExtsload, IExttload {\n    /// @notice Thrown when a currency is not netted out after the contract is unlocked\n    error CurrencyNotSettled();\n\n    /// @notice Thrown when trying to interact with a non-initialized pool\n    error PoolNotInitialized();\n\n    /// @notice Thrown when unlock is called, but the contract is already unlocked\n    error AlreadyUnlocked();\n\n    /// @notice Thrown when a function is called that requires the contract to be unlocked, but it is not\n    error ManagerLocked();\n\n    /// @notice Pools are limited to type(int16).max tickSpacing in #initialize, to prevent overflow\n    error TickSpacingTooLarge(int24 tickSpacing);\n\n    /// @notice Pools must have a positive non-zero tickSpacing passed to #initialize\n    error TickSpacingTooSmall(int24 tickSpacing);\n\n    /// @notice PoolKey must have currencies where address(currency0) < address(currency1)\n    error CurrenciesOutOfOrderOrEqual(address currency0, address currency1);\n\n    /// @notice Thrown when a call to updateDynamicLPFee is made by an address that is not the hook,\n    /// or on a pool that does not have a dynamic swap fee.\n    error UnauthorizedDynamicLPFeeUpdate();\n\n    /// @notice Thrown when trying to swap amount of 0\n    error SwapAmountCannotBeZero();\n\n    ///@notice Thrown when native currency is passed to a non native settlement\n    error NonzeroNativeValue();\n\n    /// @notice Thrown when `clear` is called with an amount that is not exactly equal to the open currency delta.\n    error MustClearExactPositiveDelta();\n\n    /// @notice Emitted when a new pool is initialized\n    /// @param id The abi encoded hash of the pool key struct for the new pool\n    /// @param currency0 The first currency of the pool by address sort order\n    /// @param currency1 The second currency of the pool by address sort order\n    /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip\n    /// @param tickSpacing The minimum number of ticks between initialized ticks\n    /// @param hooks The hooks contract address for the pool, or address(0) if none\n    /// @param sqrtPriceX96 The price of the pool on initialization\n    /// @param tick The initial tick of the pool corresponding to the initialized price\n    event Initialize(\n        PoolId indexed id,\n        Currency indexed currency0,\n        Currency indexed currency1,\n        uint24 fee,\n        int24 tickSpacing,\n        IHooks hooks,\n        uint160 sqrtPriceX96,\n        int24 tick\n    );\n\n    /// @notice Emitted when a liquidity position is modified\n    /// @param id The abi encoded hash of the pool key struct for the pool that was modified\n    /// @param sender The address that modified the pool\n    /// @param tickLower The lower tick of the position\n    /// @param tickUpper The upper tick of the position\n    /// @param liquidityDelta The amount of liquidity that was added or removed\n    /// @param salt The extra data to make positions unique\n    event ModifyLiquidity(\n        PoolId indexed id, address indexed sender, int24 tickLower, int24 tickUpper, int256 liquidityDelta, bytes32 salt\n    );\n\n    /// @notice Emitted for swaps between currency0 and currency1\n    /// @param id The abi encoded hash of the pool key struct for the pool that was modified\n    /// @param sender The address that initiated the swap call, and that received the callback\n    /// @param amount0 The delta of the currency0 balance of the pool\n    /// @param amount1 The delta of the currency1 balance of the pool\n    /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96\n    /// @param liquidity The liquidity of the pool after the swap\n    /// @param tick The log base 1.0001 of the price of the pool after the swap\n    /// @param fee The swap fee in hundredths of a bip\n    event Swap(\n        PoolId indexed id,\n        address indexed sender,\n        int128 amount0,\n        int128 amount1,\n        uint160 sqrtPriceX96,\n        uint128 liquidity,\n        int24 tick,\n        uint24 fee\n    );\n\n    /// @notice Emitted for donations\n    /// @param id The abi encoded hash of the pool key struct for the pool that was donated to\n    /// @param sender The address that initiated the donate call\n    /// @param amount0 The amount donated in currency0\n    /// @param amount1 The amount donated in currency1\n    event Donate(PoolId indexed id, address indexed sender, uint256 amount0, uint256 amount1);\n\n    /// @notice All interactions on the contract that account deltas require unlocking. A caller that calls `unlock` must implement\n    /// `IUnlockCallback(msg.sender).unlockCallback(data)`, where they interact with the remaining functions on this contract.\n    /// @dev The only functions callable without an unlocking are `initialize` and `updateDynamicLPFee`\n    /// @param data Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)`\n    /// @return The data returned by the call to `IUnlockCallback(msg.sender).unlockCallback(data)`\n    function unlock(bytes calldata data) external returns (bytes memory);\n\n    /// @notice Initialize the state for a given pool ID\n    /// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee\n    /// @param key The pool key for the pool to initialize\n    /// @param sqrtPriceX96 The initial square root price\n    /// @return tick The initial tick of the pool\n    function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick);\n\n    /// @notice Modify the liquidity for the given pool\n    /// @dev Poke by calling with a zero liquidityDelta\n    /// @param key The pool to modify liquidity in\n    /// @param params The parameters for modifying the liquidity\n    /// @param hookData The data to pass through to the add/removeLiquidity hooks\n    /// @return callerDelta The balance delta of the caller of modifyLiquidity. This is the total of both principal, fee deltas, and hook deltas if applicable\n    /// @return feesAccrued The balance delta of the fees generated in the liquidity range. Returned for informational purposes\n    /// @dev Note that feesAccrued can be artificially inflated by a malicious actor and integrators should be careful using the value\n    /// For pools with a single liquidity position, actors can donate to themselves to inflate feeGrowthGlobal (and consequently feesAccrued)\n    /// atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme\n    function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData)\n        external\n        returns (BalanceDelta callerDelta, BalanceDelta feesAccrued);\n\n    /// @notice Swap against the given pool\n    /// @param key The pool to swap in\n    /// @param params The parameters for swapping\n    /// @param hookData The data to pass through to the swap hooks\n    /// @return swapDelta The balance delta of the address swapping\n    /// @dev Swapping on low liquidity pools may cause unexpected swap amounts when liquidity available is less than amountSpecified.\n    /// Additionally note that if interacting with hooks that have the BEFORE_SWAP_RETURNS_DELTA_FLAG or AFTER_SWAP_RETURNS_DELTA_FLAG\n    /// the hook may alter the swap input/output. Integrators should perform checks on the returned swapDelta.\n    function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData)\n        external\n        returns (BalanceDelta swapDelta);\n\n    /// @notice Donate the given currency amounts to the in-range liquidity providers of a pool\n    /// @dev Calls to donate can be frontrun adding just-in-time liquidity, with the aim of receiving a portion donated funds.\n    /// Donors should keep this in mind when designing donation mechanisms.\n    /// @dev This function donates to in-range LPs at slot0.tick. In certain edge-cases of the swap algorithm, the `sqrtPrice` of\n    /// 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\n    /// `donate` would donate to tick `n - 1` (slot0.tick) not tick `n` (getTickAtSqrtPrice(slot0.sqrtPriceX96)).\n    /// Read the comments in `Pool.swap()` for more information about this.\n    /// @param key The key of the pool to donate to\n    /// @param amount0 The amount of currency0 to donate\n    /// @param amount1 The amount of currency1 to donate\n    /// @param hookData The data to pass through to the donate hooks\n    /// @return BalanceDelta The delta of the caller after the donate\n    function donate(PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)\n        external\n        returns (BalanceDelta);\n\n    /// @notice Writes the current ERC20 balance of the specified currency to transient storage\n    /// This is used to checkpoint balances for the manager and derive deltas for the caller.\n    /// @dev This MUST be called before any ERC20 tokens are sent into the contract, but can be skipped\n    /// for native tokens because the amount to settle is determined by the sent value.\n    /// However, if an ERC20 token has been synced and not settled, and the caller instead wants to settle\n    /// native funds, this function can be called with the native currency to then be able to settle the native currency\n    function sync(Currency currency) external;\n\n    /// @notice Called by the user to net out some value owed to the user\n    /// @dev Will revert if the requested amount is not available, consider using `mint` instead\n    /// @dev Can also be used as a mechanism for free flash loans\n    /// @param currency The currency to withdraw from the pool manager\n    /// @param to The address to withdraw to\n    /// @param amount The amount of currency to withdraw\n    function take(Currency currency, address to, uint256 amount) external;\n\n    /// @notice Called by the user to pay what is owed\n    /// @return paid The amount of currency settled\n    function settle() external payable returns (uint256 paid);\n\n    /// @notice Called by the user to pay on behalf of another address\n    /// @param recipient The address to credit for the payment\n    /// @return paid The amount of currency settled\n    function settleFor(address recipient) external payable returns (uint256 paid);\n\n    /// @notice WARNING - Any currency that is cleared, will be non-retrievable, and locked in the contract permanently.\n    /// A call to clear will zero out a positive balance WITHOUT a corresponding transfer.\n    /// @dev This could be used to clear a balance that is considered dust.\n    /// Additionally, the amount must be the exact positive balance. This is to enforce that the caller is aware of the amount being cleared.\n    function clear(Currency currency, uint256 amount) external;\n\n    /// @notice Called by the user to move value into ERC6909 balance\n    /// @param to The address to mint the tokens to\n    /// @param id The currency address to mint to ERC6909s, as a uint256\n    /// @param amount The amount of currency to mint\n    /// @dev The id is converted to a uint160 to correspond to a currency address\n    /// If the upper 12 bytes are not 0, they will be 0-ed out\n    function mint(address to, uint256 id, uint256 amount) external;\n\n    /// @notice Called by the user to move value from ERC6909 balance\n    /// @param from The address to burn the tokens from\n    /// @param id The currency address to burn from ERC6909s, as a uint256\n    /// @param amount The amount of currency to burn\n    /// @dev The id is converted to a uint160 to correspond to a currency address\n    /// If the upper 12 bytes are not 0, they will be 0-ed out\n    function burn(address from, uint256 id, uint256 amount) external;\n\n    /// @notice Updates the pools lp fees for the a pool that has enabled dynamic lp fees.\n    /// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee\n    /// @param key The key of the pool to update dynamic LP fees for\n    /// @param newDynamicLPFee The new dynamic pool LP fee\n    function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external;\n}\n"},"lib/uniswap-hooks/lib/v4-core/src/libraries/StateLibrary.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {PoolId} from \"../types/PoolId.sol\";\nimport {IPoolManager} from \"../interfaces/IPoolManager.sol\";\nimport {Position} from \"./Position.sol\";\n\n/// @notice A helper library to provide state getters that use extsload\nlibrary StateLibrary {\n    /// @notice index of pools mapping in the PoolManager\n    bytes32 public constant POOLS_SLOT = bytes32(uint256(6));\n\n    /// @notice index of feeGrowthGlobal0X128 in Pool.State\n    uint256 public constant FEE_GROWTH_GLOBAL0_OFFSET = 1;\n\n    // feeGrowthGlobal1X128 offset in Pool.State = 2\n\n    /// @notice index of liquidity in Pool.State\n    uint256 public constant LIQUIDITY_OFFSET = 3;\n\n    /// @notice index of TicksInfo mapping in Pool.State: mapping(int24 => TickInfo) ticks;\n    uint256 public constant TICKS_OFFSET = 4;\n\n    /// @notice index of tickBitmap mapping in Pool.State\n    uint256 public constant TICK_BITMAP_OFFSET = 5;\n\n    /// @notice index of Position.State mapping in Pool.State: mapping(bytes32 => Position.State) positions;\n    uint256 public constant POSITIONS_OFFSET = 6;\n\n    /**\n     * @notice Get Slot0 of the pool: sqrtPriceX96, tick, protocolFee, lpFee\n     * @dev Corresponds to pools[poolId].slot0\n     * @param manager The pool manager contract.\n     * @param poolId The ID of the pool.\n     * @return sqrtPriceX96 The square root of the price of the pool, in Q96 precision.\n     * @return tick The current tick of the pool.\n     * @return protocolFee The protocol fee of the pool.\n     * @return lpFee The swap fee of the pool.\n     */\n    function getSlot0(IPoolManager manager, PoolId poolId)\n        internal\n        view\n        returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee)\n    {\n        // slot key of Pool.State value: `pools[poolId]`\n        bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n        bytes32 data = manager.extsload(stateSlot);\n\n        //   24 bits  |24bits|24bits      |24 bits|160 bits\n        // 0x000000   |000bb8|000000      |ffff75 |0000000000000000fe3aa841ba359daa0ea9eff7\n        // ---------- | fee  |protocolfee | tick  | sqrtPriceX96\n        assembly (\"memory-safe\") {\n            // bottom 160 bits of data\n            sqrtPriceX96 := and(data, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n            // next 24 bits of data\n            tick := signextend(2, shr(160, data))\n            // next 24 bits of data\n            protocolFee := and(shr(184, data), 0xFFFFFF)\n            // last 24 bits of data\n            lpFee := and(shr(208, data), 0xFFFFFF)\n        }\n    }\n\n    /**\n     * @notice Retrieves the tick information of a pool at a specific tick.\n     * @dev Corresponds to pools[poolId].ticks[tick]\n     * @param manager The pool manager contract.\n     * @param poolId The ID of the pool.\n     * @param tick The tick to retrieve information for.\n     * @return liquidityGross The total position liquidity that references this tick\n     * @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)\n     * @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n     * @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n     */\n    function getTickInfo(IPoolManager manager, PoolId poolId, int24 tick)\n        internal\n        view\n        returns (\n            uint128 liquidityGross,\n            int128 liquidityNet,\n            uint256 feeGrowthOutside0X128,\n            uint256 feeGrowthOutside1X128\n        )\n    {\n        bytes32 slot = _getTickInfoSlot(poolId, tick);\n\n        // read all 3 words of the TickInfo struct\n        bytes32[] memory data = manager.extsload(slot, 3);\n        assembly (\"memory-safe\") {\n            let firstWord := mload(add(data, 32))\n            liquidityNet := sar(128, firstWord)\n            liquidityGross := and(firstWord, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n            feeGrowthOutside0X128 := mload(add(data, 64))\n            feeGrowthOutside1X128 := mload(add(data, 96))\n        }\n    }\n\n    /**\n     * @notice Retrieves the liquidity information of a pool at a specific tick.\n     * @dev Corresponds to pools[poolId].ticks[tick].liquidityGross and pools[poolId].ticks[tick].liquidityNet. A more gas efficient version of getTickInfo\n     * @param manager The pool manager contract.\n     * @param poolId The ID of the pool.\n     * @param tick The tick to retrieve liquidity for.\n     * @return liquidityGross The total position liquidity that references this tick\n     * @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)\n     */\n    function getTickLiquidity(IPoolManager manager, PoolId poolId, int24 tick)\n        internal\n        view\n        returns (uint128 liquidityGross, int128 liquidityNet)\n    {\n        bytes32 slot = _getTickInfoSlot(poolId, tick);\n\n        bytes32 value = manager.extsload(slot);\n        assembly (\"memory-safe\") {\n            liquidityNet := sar(128, value)\n            liquidityGross := and(value, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n        }\n    }\n\n    /**\n     * @notice Retrieves the fee growth outside a tick range of a pool\n     * @dev Corresponds to pools[poolId].ticks[tick].feeGrowthOutside0X128 and pools[poolId].ticks[tick].feeGrowthOutside1X128. A more gas efficient version of getTickInfo\n     * @param manager The pool manager contract.\n     * @param poolId The ID of the pool.\n     * @param tick The tick to retrieve fee growth for.\n     * @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n     * @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n     */\n    function getTickFeeGrowthOutside(IPoolManager manager, PoolId poolId, int24 tick)\n        internal\n        view\n        returns (uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128)\n    {\n        bytes32 slot = _getTickInfoSlot(poolId, tick);\n\n        // offset by 1 word, since the first word is liquidityGross + liquidityNet\n        bytes32[] memory data = manager.extsload(bytes32(uint256(slot) + 1), 2);\n        assembly (\"memory-safe\") {\n            feeGrowthOutside0X128 := mload(add(data, 32))\n            feeGrowthOutside1X128 := mload(add(data, 64))\n        }\n    }\n\n    /**\n     * @notice Retrieves the global fee growth of a pool.\n     * @dev Corresponds to pools[poolId].feeGrowthGlobal0X128 and pools[poolId].feeGrowthGlobal1X128\n     * @param manager The pool manager contract.\n     * @param poolId The ID of the pool.\n     * @return feeGrowthGlobal0 The global fee growth for token0.\n     * @return feeGrowthGlobal1 The global fee growth for token1.\n     * @dev Note that feeGrowthGlobal can be artificially inflated\n     * For pools with a single liquidity position, actors can donate to themselves to freely inflate feeGrowthGlobal\n     * atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme\n     */\n    function getFeeGrowthGlobals(IPoolManager manager, PoolId poolId)\n        internal\n        view\n        returns (uint256 feeGrowthGlobal0, uint256 feeGrowthGlobal1)\n    {\n        // slot key of Pool.State value: `pools[poolId]`\n        bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n        // Pool.State, `uint256 feeGrowthGlobal0X128`\n        bytes32 slot_feeGrowthGlobal0X128 = bytes32(uint256(stateSlot) + FEE_GROWTH_GLOBAL0_OFFSET);\n\n        // read the 2 words of feeGrowthGlobal\n        bytes32[] memory data = manager.extsload(slot_feeGrowthGlobal0X128, 2);\n        assembly (\"memory-safe\") {\n            feeGrowthGlobal0 := mload(add(data, 32))\n            feeGrowthGlobal1 := mload(add(data, 64))\n        }\n    }\n\n    /**\n     * @notice Retrieves total the liquidity of a pool.\n     * @dev Corresponds to pools[poolId].liquidity\n     * @param manager The pool manager contract.\n     * @param poolId The ID of the pool.\n     * @return liquidity The liquidity of the pool.\n     */\n    function getLiquidity(IPoolManager manager, PoolId poolId) internal view returns (uint128 liquidity) {\n        // slot key of Pool.State value: `pools[poolId]`\n        bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n        // Pool.State: `uint128 liquidity`\n        bytes32 slot = bytes32(uint256(stateSlot) + LIQUIDITY_OFFSET);\n\n        liquidity = uint128(uint256(manager.extsload(slot)));\n    }\n\n    /**\n     * @notice Retrieves the tick bitmap of a pool at a specific tick.\n     * @dev Corresponds to pools[poolId].tickBitmap[tick]\n     * @param manager The pool manager contract.\n     * @param poolId The ID of the pool.\n     * @param tick The tick to retrieve the bitmap for.\n     * @return tickBitmap The bitmap of the tick.\n     */\n    function getTickBitmap(IPoolManager manager, PoolId poolId, int16 tick)\n        internal\n        view\n        returns (uint256 tickBitmap)\n    {\n        // slot key of Pool.State value: `pools[poolId]`\n        bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n        // Pool.State: `mapping(int16 => uint256) tickBitmap;`\n        bytes32 tickBitmapMapping = bytes32(uint256(stateSlot) + TICK_BITMAP_OFFSET);\n\n        // slot id of the mapping key: `pools[poolId].tickBitmap[tick]\n        bytes32 slot = keccak256(abi.encodePacked(int256(tick), tickBitmapMapping));\n\n        tickBitmap = uint256(manager.extsload(slot));\n    }\n\n    /**\n     * @notice Retrieves the position information of a pool without needing to calculate the `positionId`.\n     * @dev Corresponds to pools[poolId].positions[positionId]\n     * @param poolId The ID of the pool.\n     * @param owner The owner of the liquidity position.\n     * @param tickLower The lower tick of the liquidity range.\n     * @param tickUpper The upper tick of the liquidity range.\n     * @param salt The bytes32 randomness to further distinguish position state.\n     * @return liquidity The liquidity of the position.\n     * @return feeGrowthInside0LastX128 The fee growth inside the position for token0.\n     * @return feeGrowthInside1LastX128 The fee growth inside the position for token1.\n     */\n    function getPositionInfo(\n        IPoolManager manager,\n        PoolId poolId,\n        address owner,\n        int24 tickLower,\n        int24 tickUpper,\n        bytes32 salt\n    ) internal view returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128) {\n        // positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt))\n        bytes32 positionKey = Position.calculatePositionKey(owner, tickLower, tickUpper, salt);\n\n        (liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128) = getPositionInfo(manager, poolId, positionKey);\n    }\n\n    /**\n     * @notice Retrieves the position information of a pool at a specific position ID.\n     * @dev Corresponds to pools[poolId].positions[positionId]\n     * @param manager The pool manager contract.\n     * @param poolId The ID of the pool.\n     * @param positionId The ID of the position.\n     * @return liquidity The liquidity of the position.\n     * @return feeGrowthInside0LastX128 The fee growth inside the position for token0.\n     * @return feeGrowthInside1LastX128 The fee growth inside the position for token1.\n     */\n    function getPositionInfo(IPoolManager manager, PoolId poolId, bytes32 positionId)\n        internal\n        view\n        returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128)\n    {\n        bytes32 slot = _getPositionInfoSlot(poolId, positionId);\n\n        // read all 3 words of the Position.State struct\n        bytes32[] memory data = manager.extsload(slot, 3);\n\n        assembly (\"memory-safe\") {\n            liquidity := mload(add(data, 32))\n            feeGrowthInside0LastX128 := mload(add(data, 64))\n            feeGrowthInside1LastX128 := mload(add(data, 96))\n        }\n    }\n\n    /**\n     * @notice Retrieves the liquidity of a position.\n     * @dev Corresponds to pools[poolId].positions[positionId].liquidity. More gas efficient for just retrieiving liquidity as compared to getPositionInfo\n     * @param manager The pool manager contract.\n     * @param poolId The ID of the pool.\n     * @param positionId The ID of the position.\n     * @return liquidity The liquidity of the position.\n     */\n    function getPositionLiquidity(IPoolManager manager, PoolId poolId, bytes32 positionId)\n        internal\n        view\n        returns (uint128 liquidity)\n    {\n        bytes32 slot = _getPositionInfoSlot(poolId, positionId);\n        liquidity = uint128(uint256(manager.extsload(slot)));\n    }\n\n    /**\n     * @notice Calculate the fee growth inside a tick range of a pool\n     * @dev pools[poolId].feeGrowthInside0LastX128 in Position.State is cached and can become stale. This function will calculate the up to date feeGrowthInside\n     * @param manager The pool manager contract.\n     * @param poolId The ID of the pool.\n     * @param tickLower The lower tick of the range.\n     * @param tickUpper The upper tick of the range.\n     * @return feeGrowthInside0X128 The fee growth inside the tick range for token0.\n     * @return feeGrowthInside1X128 The fee growth inside the tick range for token1.\n     */\n    function getFeeGrowthInside(IPoolManager manager, PoolId poolId, int24 tickLower, int24 tickUpper)\n        internal\n        view\n        returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128)\n    {\n        (uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128) = getFeeGrowthGlobals(manager, poolId);\n\n        (uint256 lowerFeeGrowthOutside0X128, uint256 lowerFeeGrowthOutside1X128) =\n            getTickFeeGrowthOutside(manager, poolId, tickLower);\n        (uint256 upperFeeGrowthOutside0X128, uint256 upperFeeGrowthOutside1X128) =\n            getTickFeeGrowthOutside(manager, poolId, tickUpper);\n        (, int24 tickCurrent,,) = getSlot0(manager, poolId);\n        unchecked {\n            if (tickCurrent < tickLower) {\n                feeGrowthInside0X128 = lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;\n                feeGrowthInside1X128 = lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;\n            } else if (tickCurrent >= tickUpper) {\n                feeGrowthInside0X128 = upperFeeGrowthOutside0X128 - lowerFeeGrowthOutside0X128;\n                feeGrowthInside1X128 = upperFeeGrowthOutside1X128 - lowerFeeGrowthOutside1X128;\n            } else {\n                feeGrowthInside0X128 = feeGrowthGlobal0X128 - lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;\n                feeGrowthInside1X128 = feeGrowthGlobal1X128 - lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;\n            }\n        }\n    }\n\n    function _getPoolStateSlot(PoolId poolId) internal pure returns (bytes32) {\n        return keccak256(abi.encodePacked(PoolId.unwrap(poolId), POOLS_SLOT));\n    }\n\n    function _getTickInfoSlot(PoolId poolId, int24 tick) internal pure returns (bytes32) {\n        // slot key of Pool.State value: `pools[poolId]`\n        bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n        // Pool.State: `mapping(int24 => TickInfo) ticks`\n        bytes32 ticksMappingSlot = bytes32(uint256(stateSlot) + TICKS_OFFSET);\n\n        // slot key of the tick key: `pools[poolId].ticks[tick]\n        return keccak256(abi.encodePacked(int256(tick), ticksMappingSlot));\n    }\n\n    function _getPositionInfoSlot(PoolId poolId, bytes32 positionId) internal pure returns (bytes32) {\n        // slot key of Pool.State value: `pools[poolId]`\n        bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n        // Pool.State: `mapping(bytes32 => Position.State) positions;`\n        bytes32 positionMapping = bytes32(uint256(stateSlot) + POSITIONS_OFFSET);\n\n        // slot of the mapping key: `pools[poolId].positions[positionId]\n        return keccak256(abi.encodePacked(positionId, positionMapping));\n    }\n}\n"},"lib/uniswap-hooks/lib/v4-core/src/libraries/TickMath.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {BitMath} from \"./BitMath.sol\";\nimport {CustomRevert} from \"./CustomRevert.sol\";\n\n/// @title Math library for computing sqrt prices from ticks and vice versa\n/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports\n/// prices between 2**-128 and 2**128\nlibrary TickMath {\n    using CustomRevert for bytes4;\n\n    /// @notice Thrown when the tick passed to #getSqrtPriceAtTick is not between MIN_TICK and MAX_TICK\n    error InvalidTick(int24 tick);\n    /// @notice Thrown when the price passed to #getTickAtSqrtPrice does not correspond to a price between MIN_TICK and MAX_TICK\n    error InvalidSqrtPrice(uint160 sqrtPriceX96);\n\n    /// @dev The minimum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**-128\n    /// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used\n    int24 internal constant MIN_TICK = -887272;\n    /// @dev The maximum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**128\n    /// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used\n    int24 internal constant MAX_TICK = 887272;\n\n    /// @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]\n    int24 internal constant MIN_TICK_SPACING = 1;\n    /// @dev The maximum tick spacing value drawn from the range of type int16, i.e. max from the range [1, 32767]\n    int24 internal constant MAX_TICK_SPACING = type(int16).max;\n\n    /// @dev The minimum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MIN_TICK)\n    uint160 internal constant MIN_SQRT_PRICE = 4295128739;\n    /// @dev The maximum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MAX_TICK)\n    uint160 internal constant MAX_SQRT_PRICE = 1461446703485210103287273052203988822378723970342;\n    /// @dev A threshold used for optimized bounds check, equals `MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1`\n    uint160 internal constant MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE =\n        1461446703485210103287273052203988822378723970342 - 4295128739 - 1;\n\n    /// @notice Given a tickSpacing, compute the maximum usable tick\n    function maxUsableTick(int24 tickSpacing) internal pure returns (int24) {\n        unchecked {\n            return (MAX_TICK / tickSpacing) * tickSpacing;\n        }\n    }\n\n    /// @notice Given a tickSpacing, compute the minimum usable tick\n    function minUsableTick(int24 tickSpacing) internal pure returns (int24) {\n        unchecked {\n            return (MIN_TICK / tickSpacing) * tickSpacing;\n        }\n    }\n\n    /// @notice Calculates sqrt(1.0001^tick) * 2^96\n    /// @dev Throws if |tick| > max tick\n    /// @param tick The input tick for the above formula\n    /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the price of the two assets (currency1/currency0)\n    /// at the given tick\n    function getSqrtPriceAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {\n        unchecked {\n            uint256 absTick;\n            assembly (\"memory-safe\") {\n                tick := signextend(2, tick)\n                // mask = 0 if tick >= 0 else -1 (all 1s)\n                let mask := sar(255, tick)\n                // if tick >= 0, |tick| = tick = 0 ^ tick\n                // if tick < 0, |tick| = ~~|tick| = ~(-|tick| - 1) = ~(tick - 1) = (-1) ^ (tick - 1)\n                // either way, |tick| = mask ^ (tick + mask)\n                absTick := xor(mask, add(mask, tick))\n            }\n\n            if (absTick > uint256(int256(MAX_TICK))) InvalidTick.selector.revertWith(tick);\n\n            // 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))\n            // is calculated (using Q128.128). The constants used for this calculation are rounded to the nearest integer\n\n            // Equivalent to:\n            //     price = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;\n            //     or price = int(2**128 / sqrt(1.0001)) if (absTick & 0x1) else 1 << 128\n            uint256 price;\n            assembly (\"memory-safe\") {\n                price := xor(shl(128, 1), mul(xor(shl(128, 1), 0xfffcb933bd6fad37aa2d162d1a594001), and(absTick, 0x1)))\n            }\n            if (absTick & 0x2 != 0) price = (price * 0xfff97272373d413259a46990580e213a) >> 128;\n            if (absTick & 0x4 != 0) price = (price * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;\n            if (absTick & 0x8 != 0) price = (price * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;\n            if (absTick & 0x10 != 0) price = (price * 0xffcb9843d60f6159c9db58835c926644) >> 128;\n            if (absTick & 0x20 != 0) price = (price * 0xff973b41fa98c081472e6896dfb254c0) >> 128;\n            if (absTick & 0x40 != 0) price = (price * 0xff2ea16466c96a3843ec78b326b52861) >> 128;\n            if (absTick & 0x80 != 0) price = (price * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;\n            if (absTick & 0x100 != 0) price = (price * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;\n            if (absTick & 0x200 != 0) price = (price * 0xf987a7253ac413176f2b074cf7815e54) >> 128;\n            if (absTick & 0x400 != 0) price = (price * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;\n            if (absTick & 0x800 != 0) price = (price * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;\n            if (absTick & 0x1000 != 0) price = (price * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;\n            if (absTick & 0x2000 != 0) price = (price * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;\n            if (absTick & 0x4000 != 0) price = (price * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;\n            if (absTick & 0x8000 != 0) price = (price * 0x31be135f97d08fd981231505542fcfa6) >> 128;\n            if (absTick & 0x10000 != 0) price = (price * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;\n            if (absTick & 0x20000 != 0) price = (price * 0x5d6af8dedb81196699c329225ee604) >> 128;\n            if (absTick & 0x40000 != 0) price = (price * 0x2216e584f5fa1ea926041bedfe98) >> 128;\n            if (absTick & 0x80000 != 0) price = (price * 0x48a170391f7dc42444e8fa2) >> 128;\n\n            assembly (\"memory-safe\") {\n                // if (tick > 0) price = type(uint256).max / price;\n                if sgt(tick, 0) { price := div(not(0), price) }\n\n                // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.\n                // we then downcast because we know the result always fits within 160 bits due to our tick input constraint\n                // we round up in the division so getTickAtSqrtPrice of the output price is always consistent\n                // `sub(shl(32, 1), 1)` is `type(uint32).max`\n                // `price + type(uint32).max` will not overflow because `price` fits in 192 bits\n                sqrtPriceX96 := shr(32, add(price, sub(shl(32, 1), 1)))\n            }\n        }\n    }\n\n    /// @notice Calculates the greatest tick value such that getSqrtPriceAtTick(tick) <= sqrtPriceX96\n    /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_PRICE, as MIN_SQRT_PRICE is the lowest value getSqrtPriceAtTick may\n    /// ever return.\n    /// @param sqrtPriceX96 The sqrt price for which to compute the tick as a Q64.96\n    /// @return tick The greatest tick for which the getSqrtPriceAtTick(tick) is less than or equal to the input sqrtPriceX96\n    function getTickAtSqrtPrice(uint160 sqrtPriceX96) internal pure returns (int24 tick) {\n        unchecked {\n            // Equivalent: if (sqrtPriceX96 < MIN_SQRT_PRICE || sqrtPriceX96 >= MAX_SQRT_PRICE) revert InvalidSqrtPrice();\n            // second inequality must be >= because the price can never reach the price at the max tick\n            // if sqrtPriceX96 < MIN_SQRT_PRICE, the `sub` underflows and `gt` is true\n            // if sqrtPriceX96 >= MAX_SQRT_PRICE, sqrtPriceX96 - MIN_SQRT_PRICE > MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1\n            if ((sqrtPriceX96 - MIN_SQRT_PRICE) > MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE) {\n                InvalidSqrtPrice.selector.revertWith(sqrtPriceX96);\n            }\n\n            uint256 price = uint256(sqrtPriceX96) << 32;\n\n            uint256 r = price;\n            uint256 msb = BitMath.mostSignificantBit(r);\n\n            if (msb >= 128) r = price >> (msb - 127);\n            else r = price << (127 - msb);\n\n            int256 log_2 = (int256(msb) - 128) << 64;\n\n            assembly (\"memory-safe\") {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(63, f))\n                r := shr(f, r)\n            }\n            assembly (\"memory-safe\") {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(62, f))\n                r := shr(f, r)\n            }\n            assembly (\"memory-safe\") {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(61, f))\n                r := shr(f, r)\n            }\n            assembly (\"memory-safe\") {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(60, f))\n                r := shr(f, r)\n            }\n            assembly (\"memory-safe\") {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(59, f))\n                r := shr(f, r)\n            }\n            assembly (\"memory-safe\") {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(58, f))\n                r := shr(f, r)\n            }\n            assembly (\"memory-safe\") {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(57, f))\n                r := shr(f, r)\n            }\n            assembly (\"memory-safe\") {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(56, f))\n                r := shr(f, r)\n            }\n            assembly (\"memory-safe\") {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(55, f))\n                r := shr(f, r)\n            }\n            assembly (\"memory-safe\") {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(54, f))\n                r := shr(f, r)\n            }\n            assembly (\"memory-safe\") {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(53, f))\n                r := shr(f, r)\n            }\n            assembly (\"memory-safe\") {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(52, f))\n                r := shr(f, r)\n            }\n            assembly (\"memory-safe\") {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(51, f))\n                r := shr(f, r)\n            }\n            assembly (\"memory-safe\") {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(50, f))\n            }\n\n            int256 log_sqrt10001 = log_2 * 255738958999603826347141; // Q22.128 number\n\n            // Magic number represents the ceiling of the maximum value of the error when approximating log_sqrt10001(x)\n            int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);\n\n            // Magic number represents the minimum value of the error when approximating log_sqrt10001(x), when\n            // 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\n            // is changed, this may need to be changed too\n            int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);\n\n            tick = tickLow == tickHi ? tickLow : getSqrtPriceAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;\n        }\n    }\n}\n"},"lib/uniswap-hooks/lib/v4-core/src/types/PoolKey.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {Currency} from \"./Currency.sol\";\nimport {IHooks} from \"../interfaces/IHooks.sol\";\nimport {PoolIdLibrary} from \"./PoolId.sol\";\n\nusing PoolIdLibrary for PoolKey global;\n\n/// @notice Returns the key for identifying a pool\nstruct PoolKey {\n    /// @notice The lower currency of the pool, sorted numerically\n    Currency currency0;\n    /// @notice The higher currency of the pool, sorted numerically\n    Currency currency1;\n    /// @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\n    uint24 fee;\n    /// @notice Ticks that involve positions must be a multiple of tick spacing\n    int24 tickSpacing;\n    /// @notice The hooks of the pool\n    IHooks hooks;\n}\n"},"lib/uniswap-hooks/lib/v4-core/src/types/PoolId.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {PoolKey} from \"./PoolKey.sol\";\n\ntype PoolId is bytes32;\n\n/// @notice Library for computing the ID of a pool\nlibrary PoolIdLibrary {\n    /// @notice Returns value equal to keccak256(abi.encode(poolKey))\n    function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) {\n        assembly (\"memory-safe\") {\n            // 0xa0 represents the total size of the poolKey struct (5 slots of 32 bytes)\n            poolId := keccak256(poolKey, 0xa0)\n        }\n    }\n}\n"},"lib/uniswap-hooks/lib/v4-core/src/types/Currency.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IERC20Minimal} from \"../interfaces/external/IERC20Minimal.sol\";\nimport {CustomRevert} from \"../libraries/CustomRevert.sol\";\n\ntype Currency is address;\n\nusing {greaterThan as >, lessThan as <, greaterThanOrEqualTo as >=, equals as ==} for Currency global;\nusing CurrencyLibrary for Currency global;\n\nfunction equals(Currency currency, Currency other) pure returns (bool) {\n    return Currency.unwrap(currency) == Currency.unwrap(other);\n}\n\nfunction greaterThan(Currency currency, Currency other) pure returns (bool) {\n    return Currency.unwrap(currency) > Currency.unwrap(other);\n}\n\nfunction lessThan(Currency currency, Currency other) pure returns (bool) {\n    return Currency.unwrap(currency) < Currency.unwrap(other);\n}\n\nfunction greaterThanOrEqualTo(Currency currency, Currency other) pure returns (bool) {\n    return Currency.unwrap(currency) >= Currency.unwrap(other);\n}\n\n/// @title CurrencyLibrary\n/// @dev This library allows for transferring and holding native tokens and ERC20 tokens\nlibrary CurrencyLibrary {\n    /// @notice Additional context for ERC-7751 wrapped error when a native transfer fails\n    error NativeTransferFailed();\n\n    /// @notice Additional context for ERC-7751 wrapped error when an ERC20 transfer fails\n    error ERC20TransferFailed();\n\n    /// @notice A constant to represent the native currency\n    Currency public constant ADDRESS_ZERO = Currency.wrap(address(0));\n\n    function transfer(Currency currency, address to, uint256 amount) internal {\n        // altered from https://github.com/transmissions11/solmate/blob/44a9963d4c78111f77caa0e65d677b8b46d6f2e6/src/utils/SafeTransferLib.sol\n        // modified custom error selectors\n\n        bool success;\n        if (currency.isAddressZero()) {\n            assembly (\"memory-safe\") {\n                // Transfer the ETH and revert if it fails.\n                success := call(gas(), to, amount, 0, 0, 0, 0)\n            }\n            // revert with NativeTransferFailed, containing the bubbled up error as an argument\n            if (!success) {\n                CustomRevert.bubbleUpAndRevertWith(to, bytes4(0), NativeTransferFailed.selector);\n            }\n        } else {\n            assembly (\"memory-safe\") {\n                // Get a pointer to some free memory.\n                let fmp := mload(0x40)\n\n                // Write the abi-encoded calldata into memory, beginning with the function selector.\n                mstore(fmp, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)\n                mstore(add(fmp, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the \"to\" argument.\n                mstore(add(fmp, 36), amount) // Append the \"amount\" argument. Masking not required as it's a full 32 byte type.\n\n                success :=\n                    and(\n                        // Set success to whether the call reverted, if not we check it either\n                        // returned exactly 1 (can't just be non-zero data), or had no return data.\n                        or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),\n                        // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.\n                        // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.\n                        // Counterintuitively, this call must be positioned second to the or() call in the\n                        // surrounding and() call or else returndatasize() will be zero during the computation.\n                        call(gas(), currency, 0, fmp, 68, 0, 32)\n                    )\n\n                // Now clean the memory we used\n                mstore(fmp, 0) // 4 byte `selector` and 28 bytes of `to` were stored here\n                mstore(add(fmp, 0x20), 0) // 4 bytes of `to` and 28 bytes of `amount` were stored here\n                mstore(add(fmp, 0x40), 0) // 4 bytes of `amount` were stored here\n            }\n            // revert with ERC20TransferFailed, containing the bubbled up error as an argument\n            if (!success) {\n                CustomRevert.bubbleUpAndRevertWith(\n                    Currency.unwrap(currency), IERC20Minimal.transfer.selector, ERC20TransferFailed.selector\n                );\n            }\n        }\n    }\n\n    function balanceOfSelf(Currency currency) internal view returns (uint256) {\n        if (currency.isAddressZero()) {\n            return address(this).balance;\n        } else {\n            return IERC20Minimal(Currency.unwrap(currency)).balanceOf(address(this));\n        }\n    }\n\n    function balanceOf(Currency currency, address owner) internal view returns (uint256) {\n        if (currency.isAddressZero()) {\n            return owner.balance;\n        } else {\n            return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner);\n        }\n    }\n\n    function isAddressZero(Currency currency) internal pure returns (bool) {\n        return Currency.unwrap(currency) == Currency.unwrap(ADDRESS_ZERO);\n    }\n\n    function toId(Currency currency) internal pure returns (uint256) {\n        return uint160(Currency.unwrap(currency));\n    }\n\n    // If the upper 12 bytes are non-zero, they will be zero-ed out\n    // Therefore, fromId() and toId() are not inverses of each other\n    function fromId(uint256 id) internal pure returns (Currency) {\n        return Currency.wrap(address(uint160(id)));\n    }\n}\n"},"src/NavJitHook.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.26;\n\nimport {BaseHook} from \"v4-periphery/src/utils/BaseHook.sol\";\nimport {LiquidityAmounts} from \"v4-periphery/src/libraries/LiquidityAmounts.sol\";\nimport {Ownable, Ownable2Step} from \"@openzeppelin/contracts/access/Ownable2Step.sol\";\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {IERC20Metadata} from \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport {Math} from \"@openzeppelin/contracts/utils/math/Math.sol\";\nimport {IPoolManager} from \"v4-core/src/interfaces/IPoolManager.sol\";\nimport {IHooks} from \"v4-core/src/interfaces/IHooks.sol\";\nimport {Hooks} from \"v4-core/src/libraries/Hooks.sol\";\nimport {TickMath} from \"v4-core/src/libraries/TickMath.sol\";\nimport {FullMath} from \"v4-core/src/libraries/FullMath.sol\";\nimport {StateLibrary} from \"v4-core/src/libraries/StateLibrary.sol\";\nimport {TransientStateLibrary} from \"v4-core/src/libraries/TransientStateLibrary.sol\";\nimport {PoolKey} from \"v4-core/src/types/PoolKey.sol\";\nimport {PoolId} from \"v4-core/src/types/PoolId.sol\";\nimport {Currency} from \"v4-core/src/types/Currency.sol\";\nimport {BalanceDelta} from \"v4-core/src/types/BalanceDelta.sol\";\nimport {BeforeSwapDelta, BeforeSwapDeltaLibrary} from \"v4-core/src/types/BeforeSwapDelta.sol\";\nimport {SwapParams, ModifyLiquidityParams} from \"v4-core/src/types/PoolOperation.sol\";\nimport {IUnlockCallback} from \"v4-core/src/interfaces/callback/IUnlockCallback.sol\";\nimport {BasketFactory} from \"./BasketFactory.sol\";\nimport {StockRegistry} from \"./StockRegistry.sol\";\nimport {Basket} from \"./Basket.sol\";\nimport {INavGuard} from \"./INavGuard.sol\";\n\ncontract NavJitHook is BaseHook, Ownable2Step, IUnlockCallback {\n    using SafeERC20 for IERC20;\n    using StateLibrary for IPoolManager;\n    using TransientStateLibrary for IPoolManager;\n\n    error NoThirdPartyLiquidity();\n    error DonationsDisabled();\n    error OnlyOpenVenue();\n    error NotABasket(address lot);\n    error VenueAlreadyOpen(address lot);\n    error VenueNotOpen(address lot);\n    error NotProfitable(int256 usdgDelta);\n    error OutsideBand(uint256 poolUsd18, uint256 nav18);\n    error TradeTooSmall();\n    error StockNotUsdgPriced(address stock);\n    error SellExceedsFloat(uint256 poolManagerLot, uint256 needed);\n    error StandingExists();\n    error NoStanding();\n    error BadParams();\n    error ZeroAddress();\n    error Reentered();\n    error OwnershipCannotBeRenounced();\n\n    event ParamsSet(Params p);\n    event TreasurySet(address treasury);\n    event NavGuardSet(address navGuard);\n    event VenueOpened(address indexed lot, bytes32 indexed poolId, uint256 nav18);\n    event StandingSeeded(bytes32 indexed poolId, uint128 liquidity, int24 lower, int24 upper);\n    event StandingWithdrawn(bytes32 indexed poolId, address to);\n\n    struct Standing {\n        uint128 liq;\n        int24 lower;\n        int24 upper;\n    }\n\n    struct Params {\n        uint16 buySpreadBps;\n        uint16 sellSpreadBps;\n        uint16 bandBps;\n        uint16 sizeBufferBps;\n        int24 widthTicks;\n    }\n\n    uint256 constant BPS = 10_000;\n    uint16 public constant MAX_BAND_BPS = 1_000;\n    uint16 public constant MAX_SIZE_BUFFER_BPS = 2_000;\n    int24 public constant MAX_WIDTH_TICKS = 2_000;\n\n    BasketFactory public immutable factory;\n    StockRegistry public immutable registry;\n    address public immutable usdg;\n    uint8 public immutable usdgDecimals;\n\n    INavGuard public navGuard;\n    address public treasury;\n    Params public params;\n    mapping(address lot => bytes32 poolId) public venueOf;\n    mapping(bytes32 => Standing) internal _standing;\n\n    bytes32 constant STANDING_SALT = bytes32(uint256(1));\n    uint8 constant OP_SEED = 1;\n    uint8 constant OP_WITHDRAW = 2;\n\n    uint256 constant T_LOCK = uint256(keccak256(\"navjit.lock\"));\n    uint256 constant T_LIQ = uint256(keccak256(\"navjit.liq\"));\n    uint256 constant T_LOWER = uint256(keccak256(\"navjit.lower\"));\n    uint256 constant T_UPPER = uint256(keccak256(\"navjit.upper\"));\n    uint256 constant T_NAV = uint256(keccak256(\"navjit.nav\"));\n    uint256 constant T_S0 = uint256(keccak256(\"navjit.standing.amount0\"));\n    uint256 constant T_S1 = uint256(keccak256(\"navjit.standing.amount1\"));\n\n    constructor(\n        IPoolManager manager_,\n        BasketFactory factory_,\n        INavGuard navGuard_,\n        address usdg_,\n        address owner_,\n        address treasury_\n    ) BaseHook(manager_) Ownable(owner_) {\n        if (address(navGuard_) == address(0) || treasury_ == address(0) || usdg_ == address(0)) revert ZeroAddress();\n        factory = factory_;\n        registry = factory_.registry();\n        usdg = usdg_;\n        usdgDecimals = IERC20Metadata(usdg_).decimals();\n        navGuard = navGuard_;\n        treasury = treasury_;\n        _setParams(Params({buySpreadBps: 25, sellSpreadBps: 100, bandBps: 200, sizeBufferBps: 300, widthTicks: 20}));\n    }\n\n\n    function renounceOwnership() public pure override {\n        revert OwnershipCannotBeRenounced();\n    }\n\n    function setParams(Params calldata p) external onlyOwner {\n        _setParams(p);\n    }\n\n    function getParams() external view returns (Params memory) {\n        return params;\n    }\n\n    function setTreasury(address t) external onlyOwner {\n        if (t == address(0)) revert ZeroAddress();\n        treasury = t;\n        emit TreasurySet(t);\n    }\n\n    function setNavGuard(INavGuard g) external onlyOwner {\n        if (address(g) == address(0)) revert ZeroAddress();\n        navGuard = g;\n        emit NavGuardSet(address(g));\n    }\n\n    function _setParams(Params memory p) internal {\n        if (\n            p.bandBps == 0 || p.bandBps > MAX_BAND_BPS || p.buySpreadBps > p.bandBps || p.sellSpreadBps > p.bandBps\n                || p.sizeBufferBps > MAX_SIZE_BUFFER_BPS || p.widthTicks <= 0 || p.widthTicks > MAX_WIDTH_TICKS\n        ) revert BadParams();\n        params = p;\n        emit ParamsSet(p);\n    }\n\n\n    function openVenue(address lot) external returns (bytes32 id) {\n        if (venueOf[lot] != bytes32(0)) revert VenueAlreadyOpen(lot);\n        if (!factory.isBasket(lot)) revert NotABasket(lot);\n        (address[] memory toks,) = Basket(lot).constituents();\n        for (uint256 i; i < toks.length; ++i) {\n            _venue(toks[i]);\n        }\n        uint256 nav = navGuard.checkedNavPerUnit18(lot);\n        PoolKey memory key = venueKey(lot);\n        id = _id(key);\n        venueOf[lot] = id;\n        poolManager.initialize(key, _sqrtPriceForUsd18(nav, Currency.unwrap(key.currency0) == usdg));\n        emit VenueOpened(lot, id, nav);\n    }\n\n    function venueKey(address lot) public view returns (PoolKey memory) {\n        (address c0, address c1) = usdg < lot ? (usdg, lot) : (lot, usdg);\n        return PoolKey({\n            currency0: Currency.wrap(c0),\n            currency1: Currency.wrap(c1),\n            fee: 0,\n            tickSpacing: 1,\n            hooks: IHooks(address(this))\n        });\n    }\n\n\n    function standingOf(bytes32 poolId) external view returns (uint128 liq, int24 lower, int24 upper) {\n        Standing memory st = _standing[poolId];\n        return (st.liq, st.lower, st.upper);\n    }\n\n    function seedStanding(PoolKey calldata key, uint256 usdgAmt, uint256 lotAmt, int24 halfWidth) external onlyOwner {\n        if (_standing[_id(key)].liq != 0) revert StandingExists();\n        if (halfWidth <= 0 || halfWidth > MAX_WIDTH_TICKS) revert BadParams();\n        address lot = _lotOf(key);\n        if (venueOf[lot] != _id(key)) revert VenueNotOpen(lot);\n        IERC20(usdg).safeTransferFrom(msg.sender, address(this), usdgAmt);\n        IERC20(lot).safeTransferFrom(msg.sender, address(this), lotAmt);\n        poolManager.unlock(abi.encode(OP_SEED, key, halfWidth, address(0)));\n        _sweepTo(lot, msg.sender);\n    }\n\n    function withdrawStanding(PoolKey calldata key, address to) external onlyOwner {\n        if (to == address(0)) revert ZeroAddress();\n        if (_standing[_id(key)].liq == 0) revert NoStanding();\n        poolManager.unlock(abi.encode(OP_WITHDRAW, key, int24(0), to));\n    }\n\n    function unlockCallback(bytes calldata data) external onlyPoolManager returns (bytes memory) {\n        (uint8 op, PoolKey memory key, int24 halfWidth, address to) = abi.decode(data, (uint8, PoolKey, int24, address));\n        bytes32 id = _id(key);\n        address lot = _lotOf(key);\n        if (op == OP_SEED) {\n            if (poolManager.getLiquidity(PoolId.wrap(id)) != 0) revert StandingExists();\n            uint256 nav = navGuard.checkedNavPerUnit18(lot);\n            int24 center = TickMath.getTickAtSqrtPrice(_sqrtPriceForUsd18(nav, Currency.unwrap(key.currency0) == usdg));\n            _reposition(key, TickMath.getSqrtPriceAtTick(center));\n            uint256 bal0 = IERC20(Currency.unwrap(key.currency0)).balanceOf(address(this));\n            uint256 bal1 = IERC20(Currency.unwrap(key.currency1)).balanceOf(address(this));\n            _addStanding(key, center - halfWidth, center + halfWidth, bal0, bal1);\n            _settleOwed(key);\n        } else {\n            Standing memory st = _standing[id];\n            poolManager.modifyLiquidity(\n                key,\n                ModifyLiquidityParams({\n                    tickLower: st.lower,\n                    tickUpper: st.upper,\n                    liquidityDelta: -int256(uint256(st.liq)),\n                    salt: STANDING_SALT\n                }),\n                \"\"\n            );\n            delete _standing[id];\n            _takeCredit(key.currency0, to);\n            _takeCredit(key.currency1, to);\n            emit StandingWithdrawn(id, to);\n        }\n        return \"\";\n    }\n\n    function _addStanding(PoolKey memory key, int24 lower, int24 upper, uint256 amt0, uint256 amt1)\n        internal\n        returns (BalanceDelta d)\n    {\n        (uint160 cur,,,) = poolManager.getSlot0(PoolId.wrap(_id(key)));\n        uint128 liq = LiquidityAmounts.getLiquidityForAmounts(\n            cur,\n            TickMath.getSqrtPriceAtTick(lower),\n            TickMath.getSqrtPriceAtTick(upper),\n            amt0 > 0 ? amt0 - 1 : 0,\n            amt1 > 0 ? amt1 - 1 : 0\n        );\n        bytes32 id = _id(key);\n        if (liq == 0) {\n            delete _standing[id];\n            return d;\n        }\n        (d,) = poolManager.modifyLiquidity(\n            key,\n            ModifyLiquidityParams({tickLower: lower, tickUpper: upper, liquidityDelta: int256(uint256(liq)), salt: STANDING_SALT}),\n            \"\"\n        );\n        _standing[id] = Standing({liq: liq, lower: lower, upper: upper});\n        emit StandingSeeded(id, liq, lower, upper);\n    }\n\n    function _liftStanding(PoolKey calldata key) internal {\n        Standing memory st = _standing[_id(key)];\n        if (st.liq == 0) return;\n        (BalanceDelta d,) = poolManager.modifyLiquidity(\n            key,\n            ModifyLiquidityParams({\n                tickLower: st.lower,\n                tickUpper: st.upper,\n                liquidityDelta: -int256(uint256(st.liq)),\n                salt: STANDING_SALT\n            }),\n            \"\"\n        );\n        _tstore(T_S0, uint256(uint128(d.amount0())));\n        _tstore(T_S1, uint256(uint128(d.amount1())));\n    }\n\n    function _restoreStanding(PoolKey calldata key, bool usdgIs0) internal {\n        Standing memory st = _standing[_id(key)];\n        if (st.liq == 0) return;\n        int24 half = (st.upper - st.lower) / 2;\n        int24 center = TickMath.getTickAtSqrtPrice(_sqrtPriceForUsd18(_tload(T_NAV), usdgIs0));\n        _reposition(key, TickMath.getSqrtPriceAtTick(center));\n        BalanceDelta d = _addStanding(key, center - half, center + half, _tload(T_S0), _tload(T_S1));\n        uint256 left0 = _tload(T_S0) - uint256(uint128(-d.amount0()));\n        uint256 left1 = _tload(T_S1) - uint256(uint128(-d.amount1()));\n        if (left0 > 0) poolManager.take(key.currency0, owner(), left0);\n        if (left1 > 0) poolManager.take(key.currency1, owner(), left1);\n        _tstore(T_S0, 0);\n        _tstore(T_S1, 0);\n    }\n\n    function _settleOwed(PoolKey memory key) internal {\n        int256 d0 = poolManager.currencyDelta(address(this), key.currency0);\n        int256 d1 = poolManager.currencyDelta(address(this), key.currency1);\n        if (d0 < 0) _settle(Currency.unwrap(key.currency0), uint256(-d0));\n        if (d1 < 0) _settle(Currency.unwrap(key.currency1), uint256(-d1));\n    }\n\n    function _takeCredit(Currency c, address to) internal {\n        int256 d = poolManager.currencyDelta(address(this), c);\n        if (d > 0) poolManager.take(c, to, uint256(d));\n    }\n\n    function _sweepTo(address lot, address to) internal {\n        uint256 u = IERC20(usdg).balanceOf(address(this));\n        uint256 l = IERC20(lot).balanceOf(address(this));\n        if (u > 0) IERC20(usdg).safeTransfer(to, u);\n        if (l > 0) IERC20(lot).safeTransfer(to, l);\n    }\n\n    function _id(PoolKey memory key) internal pure returns (bytes32) {\n        return PoolId.unwrap(key.toId());\n    }\n\n    function _lotOf(PoolKey memory key) internal view returns (address) {\n        return Currency.unwrap(key.currency0) == usdg ? Currency.unwrap(key.currency1) : Currency.unwrap(key.currency0);\n    }\n\n\n    function getHookPermissions() public pure override returns (Hooks.Permissions memory) {\n        return Hooks.Permissions({\n            beforeInitialize: true,\n            afterInitialize: false,\n            beforeAddLiquidity: true,\n            afterAddLiquidity: false,\n            beforeRemoveLiquidity: true,\n            afterRemoveLiquidity: false,\n            beforeSwap: true,\n            afterSwap: true,\n            beforeDonate: true,\n            afterDonate: false,\n            beforeSwapReturnDelta: false,\n            afterSwapReturnDelta: false,\n            afterAddLiquidityReturnDelta: false,\n            afterRemoveLiquidityReturnDelta: false\n        });\n    }\n\n    function _beforeInitialize(address, PoolKey calldata, uint160) internal pure override returns (bytes4) {\n        revert OnlyOpenVenue();\n    }\n\n    function _beforeAddLiquidity(address, PoolKey calldata, ModifyLiquidityParams calldata, bytes calldata)\n        internal\n        pure\n        override\n        returns (bytes4)\n    {\n        revert NoThirdPartyLiquidity();\n    }\n\n    function _beforeRemoveLiquidity(address, PoolKey calldata, ModifyLiquidityParams calldata, bytes calldata)\n        internal\n        pure\n        override\n        returns (bytes4)\n    {\n        revert NoThirdPartyLiquidity();\n    }\n\n    function _beforeDonate(address, PoolKey calldata, uint256, uint256, bytes calldata)\n        internal\n        pure\n        override\n        returns (bytes4)\n    {\n        revert DonationsDisabled();\n    }\n\n\n    struct Ctx {\n        address lot;\n        bool usdgIs0;\n        bool buyLot;\n        bool priceDown;\n        uint256 price18;\n        uint256 inventory;\n    }\n\n    function _beforeSwap(address, PoolKey calldata key, SwapParams calldata sp, bytes calldata)\n        internal\n        override\n        returns (bytes4, BeforeSwapDelta, uint24)\n    {\n        if (_tload(T_LOCK) != 0) revert Reentered();\n        _tstore(T_LOCK, 1);\n        Ctx memory c;\n        c.usdgIs0 = Currency.unwrap(key.currency0) == usdg;\n        c.lot = c.usdgIs0 ? Currency.unwrap(key.currency1) : Currency.unwrap(key.currency0);\n        c.buyLot = sp.zeroForOne == c.usdgIs0;\n        c.priceDown = sp.zeroForOne;\n        Params memory p = params;\n\n        uint256 nav = navGuard.checkedNavPerUnit18(c.lot);\n        _tstore(T_NAV, nav);\n        _liftStanding(key);\n        _quote(c, sp.amountSpecified, nav, p);\n        _place(key, c, p.widthTicks);\n        return (IHooks.beforeSwap.selector, BeforeSwapDeltaLibrary.ZERO_DELTA, 0);\n    }\n\n    function _quote(Ctx memory c, int256 amountSpecified, uint256 nav, Params memory p) internal {\n        bool exactIn = amountSpecified < 0;\n        uint256 amt = exactIn ? uint256(-amountSpecified) : uint256(amountSpecified);\n        if (c.buyLot) {\n            c.inventory = exactIn\n                ? FullMath.mulDiv(_toUsd18(amt), 1e18, nav) * (BPS + p.sizeBufferBps) / BPS\n                : amt + amt / 1000 + 1;\n            if (c.inventory == 0) revert TradeTooSmall();\n            uint256 cost = _mintLot(c.lot, c.inventory);\n            c.price18 = FullMath.mulDiv(_toUsd18(cost), 1e18, c.inventory) * (BPS + p.buySpreadBps) / BPS;\n        } else {\n            c.price18 = nav * (BPS - p.sellSpreadBps) / BPS;\n            c.inventory = exactIn\n                ? _fromUsd18(FullMath.mulDiv(amt, c.price18, 1e18)) * (BPS + p.sizeBufferBps) / BPS\n                : amt + amt / 1000 + 1;\n            if (c.inventory == 0) revert TradeTooSmall();\n        }\n    }\n\n    function _place(PoolKey calldata key, Ctx memory c, int24 width) internal {\n        (int24 lower, int24 upper, uint160 edge) = _range(c.price18, c.buyLot, c.usdgIs0, c.priceDown, width);\n        _reposition(key, edge);\n\n        uint160 sa = TickMath.getSqrtPriceAtTick(lower);\n        uint160 sb = TickMath.getSqrtPriceAtTick(upper);\n        uint128 liq = c.priceDown\n            ? LiquidityAmounts.getLiquidityForAmount1(sa, sb, c.inventory)\n            : LiquidityAmounts.getLiquidityForAmount0(sa, sb, c.inventory);\n        if (liq == 0) revert TradeTooSmall();\n\n        (BalanceDelta d,) = poolManager.modifyLiquidity(\n            key,\n            ModifyLiquidityParams({tickLower: lower, tickUpper: upper, liquidityDelta: int256(uint256(liq)), salt: 0}),\n            \"\"\n        );\n        if (c.buyLot) {\n            int128 owed = c.usdgIs0 ? d.amount1() : d.amount0();\n            _settle(c.lot, uint256(uint128(-owed)));\n        }\n\n        _tstore(T_LIQ, liq);\n        _tstore(T_LOWER, uint256(int256(lower)));\n        _tstore(T_UPPER, uint256(int256(upper)));\n    }\n\n    function _afterSwap(address, PoolKey calldata key, SwapParams calldata, BalanceDelta, bytes calldata)\n        internal\n        override\n        returns (bytes4, int128)\n    {\n        bool usdgIs0 = Currency.unwrap(key.currency0) == usdg;\n        address lot = usdgIs0 ? Currency.unwrap(key.currency1) : Currency.unwrap(key.currency0);\n        _removeJit(key);\n        _requireInBand(key, usdgIs0);\n        _restoreStanding(key, usdgIs0);\n        _unwind(lot);\n        _tstore(T_LIQ, 0);\n        _tstore(T_LOWER, 0);\n        _tstore(T_UPPER, 0);\n        _tstore(T_NAV, 0);\n        _tstore(T_LOCK, 0);\n        return (IHooks.afterSwap.selector, 0);\n    }\n\n    function _removeJit(PoolKey calldata key) internal {\n        poolManager.modifyLiquidity(\n            key,\n            ModifyLiquidityParams({\n                tickLower: int24(int256(_tload(T_LOWER))),\n                tickUpper: int24(int256(_tload(T_UPPER))),\n                liquidityDelta: -int256(_tload(T_LIQ)),\n                salt: 0\n            }),\n            \"\"\n        );\n    }\n\n    function _unwind(address lot) internal {\n        int256 lotDelta = poolManager.currencyDelta(address(this), Currency.wrap(lot));\n        if (lotDelta > 0) {\n            uint256 floatLot = IERC20(lot).balanceOf(address(poolManager));\n            if (floatLot < uint256(lotDelta)) revert SellExceedsFloat(floatLot, uint256(lotDelta));\n            poolManager.take(Currency.wrap(lot), address(this), uint256(lotDelta));\n        }\n        uint256 lotBal = IERC20(lot).balanceOf(address(this));\n        if (lotBal > 0) _redeemAndSell(lot, lotBal);\n\n        int256 usdgDelta = poolManager.currencyDelta(address(this), Currency.wrap(usdg));\n        if (usdgDelta < 0) revert NotProfitable(usdgDelta);\n        if (usdgDelta > 0) poolManager.take(Currency.wrap(usdg), treasury, uint256(usdgDelta));\n    }\n\n    function _requireInBand(PoolKey calldata key, bool usdgIs0) internal view {\n        uint256 nav = _tload(T_NAV);\n        uint256 px = _poolUsd18(key, usdgIs0);\n        uint256 diff = px > nav ? px - nav : nav - px;\n        if (diff * BPS > nav * params.bandBps) revert OutsideBand(px, nav);\n    }\n\n\n    function _mintLot(address lot, uint256 lotAmt) internal returns (uint256 cost) {\n        (address[] memory toks, uint256[] memory amts) = Basket(lot).amountsFor(lotAmt);\n        for (uint256 i; i < toks.length; ++i) {\n            (PoolKey memory pk, bool stockIs0) = _venue(toks[i]);\n            BalanceDelta d = _pmSwap(pk, !stockIs0, int256(amts[i]));\n            int128 u = stockIs0 ? d.amount1() : d.amount0();\n            cost += uint256(uint128(-u));\n            poolManager.take(Currency.wrap(toks[i]), address(this), amts[i]);\n            IERC20(toks[i]).forceApprove(lot, amts[i]);\n        }\n        Basket(lot).mint(lotAmt, address(this));\n    }\n\n    function _redeemAndSell(address lot, uint256 lotAmt) internal {\n        Basket(lot).redeem(lotAmt, address(this));\n        (address[] memory toks,) = Basket(lot).constituents();\n        for (uint256 i; i < toks.length; ++i) {\n            uint256 bal = IERC20(toks[i]).balanceOf(address(this));\n            if (bal == 0) continue;\n            (PoolKey memory pk, bool stockIs0) = _venue(toks[i]);\n            _pmSwap(pk, stockIs0, -int256(bal));\n            _settle(toks[i], bal);\n        }\n    }\n\n    function _venue(address stock) internal view returns (PoolKey memory pk, bool stockIs0) {\n        StockRegistry.StockInfo memory s = registry.getStock(stock);\n        if (s.stable != usdg) revert StockNotUsdgPriced(stock);\n        pk = s.pools[s.priceIndex];\n        stockIs0 = s.stockIsCurrency0;\n    }\n\n\n    function _pmSwap(PoolKey memory pk, bool zeroForOne, int256 amountSpecified) internal returns (BalanceDelta) {\n        return poolManager.swap(\n            pk,\n            SwapParams({\n                zeroForOne: zeroForOne,\n                amountSpecified: amountSpecified,\n                sqrtPriceLimitX96: zeroForOne ? TickMath.MIN_SQRT_PRICE + 1 : TickMath.MAX_SQRT_PRICE - 1\n            }),\n            \"\"\n        );\n    }\n\n    function _settle(address token, uint256 amount) internal {\n        if (amount == 0) return;\n        poolManager.sync(Currency.wrap(token));\n        IERC20(token).safeTransfer(address(poolManager), amount);\n        poolManager.settle();\n    }\n\n    function _reposition(PoolKey memory key, uint160 target) internal {\n        (uint160 cur,,,) = poolManager.getSlot0(key.toId());\n        if (cur == target) return;\n        poolManager.swap(key, SwapParams({zeroForOne: target < cur, amountSpecified: -1, sqrtPriceLimitX96: target}), \"\");\n    }\n\n    function _range(uint256 price18, bool buyLot, bool usdgIs0, bool priceDown, int24 width)\n        internal\n        view\n        returns (int24 lower, int24 upper, uint160 edge)\n    {\n        int24 t = TickMath.getTickAtSqrtPrice(_sqrtPriceForUsd18(price18, usdgIs0));\n        bool roundUp = buyLot ? !usdgIs0 : usdgIs0;\n        int24 b = roundUp ? t + 1 : t;\n        (lower, upper) = priceDown ? (b - width, b) : (b, b + width);\n        edge = TickMath.getSqrtPriceAtTick(b);\n    }\n\n    function _sqrtPriceForUsd18(uint256 p18, bool usdgIs0) internal view returns (uint160) {\n        uint256 scale = 10 ** (18 + 18 - usdgDecimals);\n        uint256 ratioX192 = usdgIs0 ? FullMath.mulDiv(scale, 1 << 192, p18) : FullMath.mulDiv(p18, 1 << 192, scale);\n        return uint160(Math.sqrt(ratioX192));\n    }\n\n    function _poolUsd18(PoolKey calldata key, bool usdgIs0) internal view returns (uint256) {\n        (uint160 s,,,) = poolManager.getSlot0(key.toId());\n        uint256 scale = 10 ** (18 + 18 - usdgDecimals);\n        uint256 raw18 = FullMath.mulDiv(uint256(s), uint256(s) * 1e18, 1 << 192);\n        return usdgIs0 ? FullMath.mulDiv(scale, 1e36, raw18) / 1e18 : FullMath.mulDiv(raw18, scale, 1e36);\n    }\n\n    function _toUsd18(uint256 usdgRaw) internal view returns (uint256) {\n        return usdgRaw * 10 ** (18 - usdgDecimals);\n    }\n\n    function _fromUsd18(uint256 usd18) internal view returns (uint256) {\n        return usd18 / 10 ** (18 - usdgDecimals);\n    }\n\n    function _tstore(uint256 slot, uint256 v) internal {\n        assembly {\n            tstore(slot, v)\n        }\n    }\n\n    function _tload(uint256 slot) internal view returns (uint256 v) {\n        assembly {\n            v := tload(slot)\n        }\n    }\n}\n"},"src/INavGuard.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.26;\n\ninterface INavGuard {\n    function checkedNavPerUnit18(address lot) external view returns (uint256);\n\n    function checkedPrice18(address stock) external view returns (uint256);\n}\n"},"lib/uniswap-hooks/lib/v4-core/lib/openzeppelin-contracts/contracts/access/Ownable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)\n\npragma solidity ^0.8.20;\n\nimport {Context} from \"../utils/Context.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * The initial owner is set to the address provided by the deployer. This can\n * later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n    address private _owner;\n\n    /**\n     * @dev The caller account is not authorized to perform an operation.\n     */\n    error OwnableUnauthorizedAccount(address account);\n\n    /**\n     * @dev The owner is not a valid owner account. (eg. `address(0)`)\n     */\n    error OwnableInvalidOwner(address owner);\n\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.\n     */\n    constructor(address initialOwner) {\n        if (initialOwner == address(0)) {\n            revert OwnableInvalidOwner(address(0));\n        }\n        _transferOwnership(initialOwner);\n    }\n\n    /**\n     * @dev Throws if called by any account other than the owner.\n     */\n    modifier onlyOwner() {\n        _checkOwner();\n        _;\n    }\n\n    /**\n     * @dev Returns the address of the current owner.\n     */\n    function owner() public view virtual returns (address) {\n        return _owner;\n    }\n\n    /**\n     * @dev Throws if the sender is not the owner.\n     */\n    function _checkOwner() internal view virtual {\n        if (owner() != _msgSender()) {\n            revert OwnableUnauthorizedAccount(_msgSender());\n        }\n    }\n\n    /**\n     * @dev Leaves the contract without owner. It will not be possible to call\n     * `onlyOwner` functions. Can only be called by the current owner.\n     *\n     * NOTE: Renouncing ownership will leave the contract without an owner,\n     * thereby disabling any functionality that is only available to the owner.\n     */\n    function renounceOwnership() public virtual onlyOwner {\n        _transferOwnership(address(0));\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Can only be called by the current owner.\n     */\n    function transferOwnership(address newOwner) public virtual onlyOwner {\n        if (newOwner == address(0)) {\n            revert OwnableInvalidOwner(address(0));\n        }\n        _transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Internal function without access restriction.\n     */\n    function _transferOwnership(address newOwner) internal virtual {\n        address oldOwner = _owner;\n        _owner = newOwner;\n        emit OwnershipTransferred(oldOwner, newOwner);\n    }\n}\n"},"lib/uniswap-hooks/lib/v4-core/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n *\n * ==== Security Considerations\n *\n * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature\n * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be\n * considered as an intention to spend the allowance in any specific way. The second is that because permits have\n * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should\n * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be\n * generally recommended is:\n *\n * ```solidity\n * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {\n *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}\n *     doThing(..., value);\n * }\n *\n * function doThing(..., uint256 value) public {\n *     token.safeTransferFrom(msg.sender, address(this), value);\n *     ...\n * }\n * ```\n *\n * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of\n * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also\n * {SafeERC20-safeTransferFrom}).\n *\n * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so\n * contracts should have entry points that don't rely on permit.\n */\ninterface IERC20Permit {\n    /**\n     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n     * given ``owner``'s signed approval.\n     *\n     * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n     * ordering also apply here.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     * - `deadline` must be a timestamp in the future.\n     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n     * over the EIP712-formatted function arguments.\n     * - the signature must use ``owner``'s current nonce (see {nonces}).\n     *\n     * For more information on the signature format, see the\n     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n     * section].\n     *\n     * CAUTION: See Security Considerations above.\n     */\n    function permit(\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) external;\n\n    /**\n     * @dev Returns the current nonce for `owner`. This value must be\n     * included whenever a signature is generated for {permit}.\n     *\n     * Every successful call to {permit} increases ``owner``'s nonce by one. This\n     * prevents a signature from being used multiple times.\n     */\n    function nonces(address owner) external view returns (uint256);\n\n    /**\n     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n     */\n    // solhint-disable-next-line func-name-mixedcase\n    function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n"},"lib/uniswap-hooks/lib/v4-core/lib/openzeppelin-contracts/contracts/utils/Address.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n    /**\n     * @dev The ETH balance of the account is not enough to perform the operation.\n     */\n    error AddressInsufficientBalance(address account);\n\n    /**\n     * @dev There's no code at `target` (it is not a contract).\n     */\n    error AddressEmptyCode(address target);\n\n    /**\n     * @dev A call to an address target failed. The target may have reverted.\n     */\n    error FailedInnerCall();\n\n    /**\n     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n     * `recipient`, forwarding all available gas and reverting on errors.\n     *\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\n     * imposed by `transfer`, making them unable to receive funds via\n     * `transfer`. {sendValue} removes this limitation.\n     *\n     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n     *\n     * IMPORTANT: because control is transferred to `recipient`, care must be\n     * taken to not create reentrancy vulnerabilities. Consider using\n     * {ReentrancyGuard} or the\n     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        if (address(this).balance < amount) {\n            revert AddressInsufficientBalance(address(this));\n        }\n\n        (bool success, ) = recipient.call{value: amount}(\"\");\n        if (!success) {\n            revert FailedInnerCall();\n        }\n    }\n\n    /**\n     * @dev Performs a Solidity function call using a low level `call`. A\n     * plain `call` is an unsafe replacement for a function call: use this\n     * function instead.\n     *\n     * If `target` reverts with a revert reason or custom error, it is bubbled\n     * up by this function (like regular Solidity function calls). However, if\n     * the call reverted with no returned reason, this function reverts with a\n     * {FailedInnerCall} error.\n     *\n     * Returns the raw returned data. To convert to the expected return value,\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n     *\n     * Requirements:\n     *\n     * - `target` must be a contract.\n     * - calling `target` with `data` must not revert.\n     */\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but also transferring `value` wei to `target`.\n     *\n     * Requirements:\n     *\n     * - the calling contract must have an ETH balance of at least `value`.\n     * - the called Solidity function must be `payable`.\n     */\n    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n        if (address(this).balance < value) {\n            revert AddressInsufficientBalance(address(this));\n        }\n        (bool success, bytes memory returndata) = target.call{value: value}(data);\n        return verifyCallResultFromTarget(target, success, returndata);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResultFromTarget(target, success, returndata);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a delegate call.\n     */\n    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.delegatecall(data);\n        return verifyCallResultFromTarget(target, success, returndata);\n    }\n\n    /**\n     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target\n     * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an\n     * unsuccessful call.\n     */\n    function verifyCallResultFromTarget(\n        address target,\n        bool success,\n        bytes memory returndata\n    ) internal view returns (bytes memory) {\n        if (!success) {\n            _revert(returndata);\n        } else {\n            // only check if target is a contract if the call was successful and the return data is empty\n            // otherwise we already know that it was a contract\n            if (returndata.length == 0 && target.code.length == 0) {\n                revert AddressEmptyCode(target);\n            }\n            return returndata;\n        }\n    }\n\n    /**\n     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the\n     * revert reason or with a default {FailedInnerCall} error.\n     */\n    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {\n        if (!success) {\n            _revert(returndata);\n        } else {\n            return returndata;\n        }\n    }\n\n    /**\n     * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.\n     */\n    function _revert(bytes memory returndata) private pure {\n        // Look for revert reason and bubble it up if present\n        if (returndata.length > 0) {\n            // The easiest way to bubble the revert reason is using memory via assembly\n            /// @solidity memory-safe-assembly\n            assembly {\n                let returndata_size := mload(returndata)\n                revert(add(32, returndata), returndata_size)\n            }\n        } else {\n            revert FailedInnerCall();\n        }\n    }\n}\n"},"lib/uniswap-hooks/lib/v4-core/src/libraries/SafeCast.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {CustomRevert} from \"./CustomRevert.sol\";\n\n/// @title Safe casting methods\n/// @notice Contains methods for safely casting between types\nlibrary SafeCast {\n    using CustomRevert for bytes4;\n\n    error SafeCastOverflow();\n\n    /// @notice Cast a uint256 to a uint160, revert on overflow\n    /// @param x The uint256 to be downcasted\n    /// @return y The downcasted integer, now type uint160\n    function toUint160(uint256 x) internal pure returns (uint160 y) {\n        y = uint160(x);\n        if (y != x) SafeCastOverflow.selector.revertWith();\n    }\n\n    /// @notice Cast a uint256 to a uint128, revert on overflow\n    /// @param x The uint256 to be downcasted\n    /// @return y The downcasted integer, now type uint128\n    function toUint128(uint256 x) internal pure returns (uint128 y) {\n        y = uint128(x);\n        if (x != y) SafeCastOverflow.selector.revertWith();\n    }\n\n    /// @notice Cast a int128 to a uint128, revert on overflow or underflow\n    /// @param x The int128 to be casted\n    /// @return y The casted integer, now type uint128\n    function toUint128(int128 x) internal pure returns (uint128 y) {\n        if (x < 0) SafeCastOverflow.selector.revertWith();\n        y = uint128(x);\n    }\n\n    /// @notice Cast a int256 to a int128, revert on overflow or underflow\n    /// @param x The int256 to be downcasted\n    /// @return y The downcasted integer, now type int128\n    function toInt128(int256 x) internal pure returns (int128 y) {\n        y = int128(x);\n        if (y != x) SafeCastOverflow.selector.revertWith();\n    }\n\n    /// @notice Cast a uint256 to a int256, revert on overflow\n    /// @param x The uint256 to be casted\n    /// @return y The casted integer, now type int256\n    function toInt256(uint256 x) internal pure returns (int256 y) {\n        y = int256(x);\n        if (y < 0) SafeCastOverflow.selector.revertWith();\n    }\n\n    /// @notice Cast a uint256 to a int128, revert on overflow\n    /// @param x The uint256 to be downcasted\n    /// @return The downcasted integer, now type int128\n    function toInt128(uint256 x) internal pure returns (int128) {\n        if (x >= 1 << 127) SafeCastOverflow.selector.revertWith();\n        return int128(int256(x));\n    }\n}\n"},"lib/uniswap-hooks/lib/v4-core/src/libraries/FullMath.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title Contains 512-bit math functions\n/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision\n/// @dev Handles \"phantom overflow\" i.e., allows multiplication and division where an intermediate value overflows 256 bits\nlibrary FullMath {\n    /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n    /// @param a The multiplicand\n    /// @param b The multiplier\n    /// @param denominator The divisor\n    /// @return result The 256-bit result\n    /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv\n    function mulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {\n        unchecked {\n            // 512-bit multiply [prod1 prod0] = a * b\n            // Compute the product mod 2**256 and mod 2**256 - 1\n            // then use the Chinese Remainder Theorem to reconstruct\n            // the 512 bit result. The result is stored in two 256\n            // variables such that product = prod1 * 2**256 + prod0\n            uint256 prod0 = a * b; // Least significant 256 bits of the product\n            uint256 prod1; // Most significant 256 bits of the product\n            assembly (\"memory-safe\") {\n                let mm := mulmod(a, b, not(0))\n                prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n            }\n\n            // Make sure the result is less than 2**256.\n            // Also prevents denominator == 0\n            require(denominator > prod1);\n\n            // Handle non-overflow cases, 256 by 256 division\n            if (prod1 == 0) {\n                assembly (\"memory-safe\") {\n                    result := div(prod0, denominator)\n                }\n                return result;\n            }\n\n            ///////////////////////////////////////////////\n            // 512 by 256 division.\n            ///////////////////////////////////////////////\n\n            // Make division exact by subtracting the remainder from [prod1 prod0]\n            // Compute remainder using mulmod\n            uint256 remainder;\n            assembly (\"memory-safe\") {\n                remainder := mulmod(a, b, denominator)\n            }\n            // Subtract 256 bit number from 512 bit number\n            assembly (\"memory-safe\") {\n                prod1 := sub(prod1, gt(remainder, prod0))\n                prod0 := sub(prod0, remainder)\n            }\n\n            // Factor powers of two out of denominator\n            // Compute largest power of two divisor of denominator.\n            // Always >= 1.\n            uint256 twos = (0 - denominator) & denominator;\n            // Divide denominator by power of two\n            assembly (\"memory-safe\") {\n                denominator := div(denominator, twos)\n            }\n\n            // Divide [prod1 prod0] by the factors of two\n            assembly (\"memory-safe\") {\n                prod0 := div(prod0, twos)\n            }\n            // Shift in bits from prod1 into prod0. For this we need\n            // to flip `twos` such that it is 2**256 / twos.\n            // If twos is zero, then it becomes one\n            assembly (\"memory-safe\") {\n                twos := add(div(sub(0, twos), twos), 1)\n            }\n            prod0 |= prod1 * twos;\n\n            // Invert denominator mod 2**256\n            // Now that denominator is an odd number, it has an inverse\n            // modulo 2**256 such that denominator * inv = 1 mod 2**256.\n            // Compute the inverse by starting with a seed that is correct\n            // correct for four bits. That is, denominator * inv = 1 mod 2**4\n            uint256 inv = (3 * denominator) ^ 2;\n            // Now use Newton-Raphson iteration to improve the precision.\n            // Thanks to Hensel's lifting lemma, this also works in modular\n            // arithmetic, doubling the correct bits in each step.\n            inv *= 2 - denominator * inv; // inverse mod 2**8\n            inv *= 2 - denominator * inv; // inverse mod 2**16\n            inv *= 2 - denominator * inv; // inverse mod 2**32\n            inv *= 2 - denominator * inv; // inverse mod 2**64\n            inv *= 2 - denominator * inv; // inverse mod 2**128\n            inv *= 2 - denominator * inv; // inverse mod 2**256\n\n            // Because the division is now exact we can divide by multiplying\n            // with the modular inverse of denominator. This will give us the\n            // correct result modulo 2**256. Since the preconditions guarantee\n            // that the outcome is less than 2**256, this is the final result.\n            // We don't need to compute the high bits of the result and prod1\n            // is no longer required.\n            result = prod0 * inv;\n            return result;\n        }\n    }\n\n    /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n    /// @param a The multiplicand\n    /// @param b The multiplier\n    /// @param denominator The divisor\n    /// @return result The 256-bit result\n    function mulDivRoundingUp(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {\n        unchecked {\n            result = mulDiv(a, b, denominator);\n            if (mulmod(a, b, denominator) != 0) {\n                require(++result > 0);\n            }\n        }\n    }\n}\n"},"lib/uniswap-hooks/lib/v4-core/src/libraries/UnsafeMath.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title Math functions that do not check inputs or outputs\n/// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks\nlibrary UnsafeMath {\n    /// @notice Returns ceil(x / y)\n    /// @dev division by 0 will return 0, and should be checked externally\n    /// @param x The dividend\n    /// @param y The divisor\n    /// @return z The quotient, ceil(x / y)\n    function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        assembly (\"memory-safe\") {\n            z := add(div(x, y), gt(mod(x, y), 0))\n        }\n    }\n\n    /// @notice Calculates floor(a×b÷denominator)\n    /// @dev division by 0 will return 0, and should be checked externally\n    /// @param a The multiplicand\n    /// @param b The multiplier\n    /// @param denominator The divisor\n    /// @return result The 256-bit result, floor(a×b÷denominator)\n    function simpleMulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {\n        assembly (\"memory-safe\") {\n            result := div(mul(a, b), denominator)\n        }\n    }\n}\n"},"lib/uniswap-hooks/lib/v4-core/src/libraries/FixedPoint96.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title FixedPoint96\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)\n/// @dev Used in SqrtPriceMath.sol\nlibrary FixedPoint96 {\n    uint8 internal constant RESOLUTION = 96;\n    uint256 internal constant Q96 = 0x1000000000000000000000000;\n}\n"},"lib/uniswap-hooks/lib/v4-core/src/interfaces/IHooks.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {PoolKey} from \"../types/PoolKey.sol\";\nimport {BalanceDelta} from \"../types/BalanceDelta.sol\";\nimport {ModifyLiquidityParams, SwapParams} from \"../types/PoolOperation.sol\";\nimport {BeforeSwapDelta} from \"../types/BeforeSwapDelta.sol\";\n\n/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits\n/// of the address that the hooks contract is deployed to.\n/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400\n/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.\n/// See the Hooks library for the full spec.\n/// @dev Should only be callable by the v4 PoolManager.\ninterface IHooks {\n    /// @notice The hook called before the state of a pool is initialized\n    /// @param sender The initial msg.sender for the initialize call\n    /// @param key The key for the pool being initialized\n    /// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96\n    /// @return bytes4 The function selector for the hook\n    function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96) external returns (bytes4);\n\n    /// @notice The hook called after the state of a pool is initialized\n    /// @param sender The initial msg.sender for the initialize call\n    /// @param key The key for the pool being initialized\n    /// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96\n    /// @param tick The current tick after the state of a pool is initialized\n    /// @return bytes4 The function selector for the hook\n    function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)\n        external\n        returns (bytes4);\n\n    /// @notice The hook called before liquidity is added\n    /// @param sender The initial msg.sender for the add liquidity call\n    /// @param key The key for the pool\n    /// @param params The parameters for adding liquidity\n    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook\n    /// @return bytes4 The function selector for the hook\n    function beforeAddLiquidity(\n        address sender,\n        PoolKey calldata key,\n        ModifyLiquidityParams calldata params,\n        bytes calldata hookData\n    ) external returns (bytes4);\n\n    /// @notice The hook called after liquidity is added\n    /// @param sender The initial msg.sender for the add liquidity call\n    /// @param key The key for the pool\n    /// @param params The parameters for adding liquidity\n    /// @param delta The caller's balance delta after adding liquidity; the sum of principal delta, fees accrued, and hook delta\n    /// @param feesAccrued The fees accrued since the last time fees were collected from this position\n    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook\n    /// @return bytes4 The function selector for the hook\n    /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency\n    function afterAddLiquidity(\n        address sender,\n        PoolKey calldata key,\n        ModifyLiquidityParams calldata params,\n        BalanceDelta delta,\n        BalanceDelta feesAccrued,\n        bytes calldata hookData\n    ) external returns (bytes4, BalanceDelta);\n\n    /// @notice The hook called before liquidity is removed\n    /// @param sender The initial msg.sender for the remove liquidity call\n    /// @param key The key for the pool\n    /// @param params The parameters for removing liquidity\n    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook\n    /// @return bytes4 The function selector for the hook\n    function beforeRemoveLiquidity(\n        address sender,\n        PoolKey calldata key,\n        ModifyLiquidityParams calldata params,\n        bytes calldata hookData\n    ) external returns (bytes4);\n\n    /// @notice The hook called after liquidity is removed\n    /// @param sender The initial msg.sender for the remove liquidity call\n    /// @param key The key for the pool\n    /// @param params The parameters for removing liquidity\n    /// @param delta The caller's balance delta after removing liquidity; the sum of principal delta, fees accrued, and hook delta\n    /// @param feesAccrued The fees accrued since the last time fees were collected from this position\n    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook\n    /// @return bytes4 The function selector for the hook\n    /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency\n    function afterRemoveLiquidity(\n        address sender,\n        PoolKey calldata key,\n        ModifyLiquidityParams calldata params,\n        BalanceDelta delta,\n        BalanceDelta feesAccrued,\n        bytes calldata hookData\n    ) external returns (bytes4, BalanceDelta);\n\n    /// @notice The hook called before a swap\n    /// @param sender The initial msg.sender for the swap call\n    /// @param key The key for the pool\n    /// @param params The parameters for the swap\n    /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook\n    /// @return bytes4 The function selector for the hook\n    /// @return BeforeSwapDelta The hook's delta in specified and unspecified currencies. Positive: the hook is owed/took currency, negative: the hook owes/sent currency\n    /// @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)\n    function beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata hookData)\n        external\n        returns (bytes4, BeforeSwapDelta, uint24);\n\n    /// @notice The hook called after a swap\n    /// @param sender The initial msg.sender for the swap call\n    /// @param key The key for the pool\n    /// @param params The parameters for the swap\n    /// @param delta The amount owed to the caller (positive) or owed to the pool (negative)\n    /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook\n    /// @return bytes4 The function selector for the hook\n    /// @return int128 The hook's delta in unspecified currency. Positive: the hook is owed/took currency, negative: the hook owes/sent currency\n    function afterSwap(\n        address sender,\n        PoolKey calldata key,\n        SwapParams calldata params,\n        BalanceDelta delta,\n        bytes calldata hookData\n    ) external returns (bytes4, int128);\n\n    /// @notice The hook called before donate\n    /// @param sender The initial msg.sender for the donate call\n    /// @param key The key for the pool\n    /// @param amount0 The amount of token0 being donated\n    /// @param amount1 The amount of token1 being donated\n    /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook\n    /// @return bytes4 The function selector for the hook\n    function beforeDonate(\n        address sender,\n        PoolKey calldata key,\n        uint256 amount0,\n        uint256 amount1,\n        bytes calldata hookData\n    ) external returns (bytes4);\n\n    /// @notice The hook called after donate\n    /// @param sender The initial msg.sender for the donate call\n    /// @param key The key for the pool\n    /// @param amount0 The amount of token0 being donated\n    /// @param amount1 The amount of token1 being donated\n    /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook\n    /// @return bytes4 The function selector for the hook\n    function afterDonate(\n        address sender,\n        PoolKey calldata key,\n        uint256 amount0,\n        uint256 amount1,\n        bytes calldata hookData\n    ) external returns (bytes4);\n}\n"},"lib/uniswap-hooks/lib/v4-core/src/interfaces/external/IERC6909Claims.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @notice Interface for claims over a contract balance, wrapped as a ERC6909\ninterface IERC6909Claims {\n    /*//////////////////////////////////////////////////////////////\n                                 EVENTS\n    //////////////////////////////////////////////////////////////*/\n\n    event OperatorSet(address indexed owner, address indexed operator, bool approved);\n\n    event Approval(address indexed owner, address indexed spender, uint256 indexed id, uint256 amount);\n\n    event Transfer(address caller, address indexed from, address indexed to, uint256 indexed id, uint256 amount);\n\n    /*//////////////////////////////////////////////////////////////\n                                 FUNCTIONS\n    //////////////////////////////////////////////////////////////*/\n\n    /// @notice Owner balance of an id.\n    /// @param owner The address of the owner.\n    /// @param id The id of the token.\n    /// @return amount The balance of the token.\n    function balanceOf(address owner, uint256 id) external view returns (uint256 amount);\n\n    /// @notice Spender allowance of an id.\n    /// @param owner The address of the owner.\n    /// @param spender The address of the spender.\n    /// @param id The id of the token.\n    /// @return amount The allowance of the token.\n    function allowance(address owner, address spender, uint256 id) external view returns (uint256 amount);\n\n    /// @notice Checks if a spender is approved by an owner as an operator\n    /// @param owner The address of the owner.\n    /// @param spender The address of the spender.\n    /// @return approved The approval status.\n    function isOperator(address owner, address spender) external view returns (bool approved);\n\n    /// @notice Transfers an amount of an id from the caller to a receiver.\n    /// @param receiver The address of the receiver.\n    /// @param id The id of the token.\n    /// @param amount The amount of the token.\n    /// @return bool True, always, unless the function reverts\n    function transfer(address receiver, uint256 id, uint256 amount) external returns (bool);\n\n    /// @notice Transfers an amount of an id from a sender to a receiver.\n    /// @param sender The address of the sender.\n    /// @param receiver The address of the receiver.\n    /// @param id The id of the token.\n    /// @param amount The amount of the token.\n    /// @return bool True, always, unless the function reverts\n    function transferFrom(address sender, address receiver, uint256 id, uint256 amount) external returns (bool);\n\n    /// @notice Approves an amount of an id to a spender.\n    /// @param spender The address of the spender.\n    /// @param id The id of the token.\n    /// @param amount The amount of the token.\n    /// @return bool True, always\n    function approve(address spender, uint256 id, uint256 amount) external returns (bool);\n\n    /// @notice Sets or removes an operator for the caller.\n    /// @param operator The address of the operator.\n    /// @param approved The approval status.\n    /// @return bool True, always\n    function setOperator(address operator, bool approved) external returns (bool);\n}\n"},"lib/uniswap-hooks/lib/v4-core/src/interfaces/IProtocolFees.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {Currency} from \"../types/Currency.sol\";\nimport {PoolId} from \"../types/PoolId.sol\";\nimport {PoolKey} from \"../types/PoolKey.sol\";\n\n/// @notice Interface for all protocol-fee related functions in the pool manager\ninterface IProtocolFees {\n    /// @notice Thrown when protocol fee is set too high\n    error ProtocolFeeTooLarge(uint24 fee);\n\n    /// @notice Thrown when collectProtocolFees or setProtocolFee is not called by the controller.\n    error InvalidCaller();\n\n    /// @notice Thrown when collectProtocolFees is attempted on a token that is synced.\n    error ProtocolFeeCurrencySynced();\n\n    /// @notice Emitted when the protocol fee controller address is updated in setProtocolFeeController.\n    event ProtocolFeeControllerUpdated(address indexed protocolFeeController);\n\n    /// @notice Emitted when the protocol fee is updated for a pool.\n    event ProtocolFeeUpdated(PoolId indexed id, uint24 protocolFee);\n\n    /// @notice Given a currency address, returns the protocol fees accrued in that currency\n    /// @param currency The currency to check\n    /// @return amount The amount of protocol fees accrued in the currency\n    function protocolFeesAccrued(Currency currency) external view returns (uint256 amount);\n\n    /// @notice Sets the protocol fee for the given pool\n    /// @param key The key of the pool to set a protocol fee for\n    /// @param newProtocolFee The fee to set\n    function setProtocolFee(PoolKey memory key, uint24 newProtocolFee) external;\n\n    /// @notice Sets the protocol fee controller\n    /// @param controller The new protocol fee controller\n    function setProtocolFeeController(address controller) external;\n\n    /// @notice Collects the protocol fees for a given recipient and currency, returning the amount collected\n    /// @dev This will revert if the contract is unlocked\n    /// @param recipient The address to receive the protocol fees\n    /// @param currency The currency to withdraw\n    /// @param amount The amount of currency to withdraw\n    /// @return amountCollected The amount of currency successfully withdrawn\n    function collectProtocolFees(address recipient, Currency currency, uint256 amount)\n        external\n        returns (uint256 amountCollected);\n\n    /// @notice Returns the current protocol fee controller address\n    /// @return address The current protocol fee controller address\n    function protocolFeeController() external view returns (address);\n}\n"},"lib/uniswap-hooks/lib/v4-core/src/types/BalanceDelta.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {SafeCast} from \"../libraries/SafeCast.sol\";\n\n/// @dev Two `int128` values packed into a single `int256` where the upper 128 bits represent the amount0\n/// and the lower 128 bits represent the amount1.\ntype BalanceDelta is int256;\n\nusing {add as +, sub as -, eq as ==, neq as !=} for BalanceDelta global;\nusing BalanceDeltaLibrary for BalanceDelta global;\nusing SafeCast for int256;\n\nfunction toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) {\n    assembly (\"memory-safe\") {\n        balanceDelta := or(shl(128, _amount0), and(sub(shl(128, 1), 1), _amount1))\n    }\n}\n\nfunction add(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {\n    int256 res0;\n    int256 res1;\n    assembly (\"memory-safe\") {\n        let a0 := sar(128, a)\n        let a1 := signextend(15, a)\n        let b0 := sar(128, b)\n        let b1 := signextend(15, b)\n        res0 := add(a0, b0)\n        res1 := add(a1, b1)\n    }\n    return toBalanceDelta(res0.toInt128(), res1.toInt128());\n}\n\nfunction sub(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {\n    int256 res0;\n    int256 res1;\n    assembly (\"memory-safe\") {\n        let a0 := sar(128, a)\n        let a1 := signextend(15, a)\n        let b0 := sar(128, b)\n        let b1 := signextend(15, b)\n        res0 := sub(a0, b0)\n        res1 := sub(a1, b1)\n    }\n    return toBalanceDelta(res0.toInt128(), res1.toInt128());\n}\n\nfunction eq(BalanceDelta a, BalanceDelta b) pure returns (bool) {\n    return BalanceDelta.unwrap(a) == BalanceDelta.unwrap(b);\n}\n\nfunction neq(BalanceDelta a, BalanceDelta b) pure returns (bool) {\n    return BalanceDelta.unwrap(a) != BalanceDelta.unwrap(b);\n}\n\n/// @notice Library for getting the amount0 and amount1 deltas from the BalanceDelta type\nlibrary BalanceDeltaLibrary {\n    /// @notice A BalanceDelta of 0\n    BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0);\n\n    function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) {\n        assembly (\"memory-safe\") {\n            _amount0 := sar(128, balanceDelta)\n        }\n    }\n\n    function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) {\n        assembly (\"memory-safe\") {\n            _amount1 := signextend(15, balanceDelta)\n        }\n    }\n}\n"},"lib/uniswap-hooks/lib/v4-core/src/interfaces/IExtsload.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @notice Interface for functions to access any storage slot in a contract\ninterface IExtsload {\n    /// @notice Called by external contracts to access granular pool state\n    /// @param slot Key of slot to sload\n    /// @return value The value of the slot as bytes32\n    function extsload(bytes32 slot) external view returns (bytes32 value);\n\n    /// @notice Called by external contracts to access granular pool state\n    /// @param startSlot Key of slot to start sloading from\n    /// @param nSlots Number of slots to load into return value\n    /// @return values List of loaded values.\n    function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes32[] memory values);\n\n    /// @notice Called by external contracts to access sparse pool state\n    /// @param slots List of slots to SLOAD from.\n    /// @return values List of loaded values.\n    function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory values);\n}\n"},"lib/uniswap-hooks/lib/v4-core/src/interfaces/IExttload.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\n/// @notice Interface for functions to access any transient storage slot in a contract\ninterface IExttload {\n    /// @notice Called by external contracts to access transient storage of the contract\n    /// @param slot Key of slot to tload\n    /// @return value The value of the slot as bytes32\n    function exttload(bytes32 slot) external view returns (bytes32 value);\n\n    /// @notice Called by external contracts to access sparse transient pool state\n    /// @param slots List of slots to tload\n    /// @return values List of loaded values\n    function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory values);\n}\n"},"lib/uniswap-hooks/lib/v4-core/src/types/PoolOperation.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\nimport {PoolKey} from \"../types/PoolKey.sol\";\nimport {BalanceDelta} from \"../types/BalanceDelta.sol\";\n\n/// @notice Parameter struct for `ModifyLiquidity` pool operations\nstruct ModifyLiquidityParams {\n    // the lower and upper tick of the position\n    int24 tickLower;\n    int24 tickUpper;\n    // how to modify the liquidity\n    int256 liquidityDelta;\n    // a value to set if you want unique liquidity positions at the same range\n    bytes32 salt;\n}\n\n/// @notice Parameter struct for `Swap` pool operations\nstruct SwapParams {\n    /// Whether to swap token0 for token1 or vice versa\n    bool zeroForOne;\n    /// The desired input amount if negative (exactIn), or the desired output amount if positive (exactOut)\n    int256 amountSpecified;\n    /// The sqrt price at which, if reached, the swap will stop executing\n    uint160 sqrtPriceLimitX96;\n}\n"},"lib/uniswap-hooks/lib/v4-core/src/libraries/Position.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport {FullMath} from \"./FullMath.sol\";\nimport {FixedPoint128} from \"./FixedPoint128.sol\";\nimport {LiquidityMath} from \"./LiquidityMath.sol\";\nimport {CustomRevert} from \"./CustomRevert.sol\";\n\n/// @title Position\n/// @notice Positions represent an owner address' liquidity between a lower and upper tick boundary\n/// @dev Positions store additional state for tracking fees owed to the position\nlibrary Position {\n    using CustomRevert for bytes4;\n\n    /// @notice Cannot update a position with no liquidity\n    error CannotUpdateEmptyPosition();\n\n    // info stored for each user's position\n    struct State {\n        // the amount of liquidity owned by this position\n        uint128 liquidity;\n        // fee growth per unit of liquidity as of the last update to liquidity or fees owed\n        uint256 feeGrowthInside0LastX128;\n        uint256 feeGrowthInside1LastX128;\n    }\n\n    /// @notice Returns the State struct of a position, given an owner and position boundaries\n    /// @param self The mapping containing all user positions\n    /// @param owner The address of the position owner\n    /// @param tickLower The lower tick boundary of the position\n    /// @param tickUpper The upper tick boundary of the position\n    /// @param salt A unique value to differentiate between multiple positions in the same range\n    /// @return position The position info struct of the given owners' position\n    function get(mapping(bytes32 => State) storage self, address owner, int24 tickLower, int24 tickUpper, bytes32 salt)\n        internal\n        view\n        returns (State storage position)\n    {\n        bytes32 positionKey = calculatePositionKey(owner, tickLower, tickUpper, salt);\n        position = self[positionKey];\n    }\n\n    /// @notice A helper function to calculate the position key\n    /// @param owner The address of the position owner\n    /// @param tickLower the lower tick boundary of the position\n    /// @param tickUpper the upper tick boundary of the position\n    /// @param salt A unique value to differentiate between multiple positions in the same range, by the same owner. Passed in by the caller.\n    function calculatePositionKey(address owner, int24 tickLower, int24 tickUpper, bytes32 salt)\n        internal\n        pure\n        returns (bytes32 positionKey)\n    {\n        // positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt))\n        assembly (\"memory-safe\") {\n            let fmp := mload(0x40)\n            mstore(add(fmp, 0x26), salt) // [0x26, 0x46)\n            mstore(add(fmp, 0x06), tickUpper) // [0x23, 0x26)\n            mstore(add(fmp, 0x03), tickLower) // [0x20, 0x23)\n            mstore(fmp, owner) // [0x0c, 0x20)\n            positionKey := keccak256(add(fmp, 0x0c), 0x3a) // len is 58 bytes\n\n            // now clean the memory we used\n            mstore(add(fmp, 0x40), 0) // fmp+0x40 held salt\n            mstore(add(fmp, 0x20), 0) // fmp+0x20 held tickLower, tickUpper, salt\n            mstore(fmp, 0) // fmp held owner\n        }\n    }\n\n    /// @notice Credits accumulated fees to a user's position\n    /// @param self The individual position to update\n    /// @param liquidityDelta The change in pool liquidity as a result of the position update\n    /// @param feeGrowthInside0X128 The all-time fee growth in currency0, per unit of liquidity, inside the position's tick boundaries\n    /// @param feeGrowthInside1X128 The all-time fee growth in currency1, per unit of liquidity, inside the position's tick boundaries\n    /// @return feesOwed0 The amount of currency0 owed to the position owner\n    /// @return feesOwed1 The amount of currency1 owed to the position owner\n    function update(\n        State storage self,\n        int128 liquidityDelta,\n        uint256 feeGrowthInside0X128,\n        uint256 feeGrowthInside1X128\n    ) internal returns (uint256 feesOwed0, uint256 feesOwed1) {\n        uint128 liquidity = self.liquidity;\n\n        if (liquidityDelta == 0) {\n            // disallow pokes for 0 liquidity positions\n            if (liquidity == 0) CannotUpdateEmptyPosition.selector.revertWith();\n        } else {\n            self.liquidity = LiquidityMath.addDelta(liquidity, liquidityDelta);\n        }\n\n        // calculate accumulated fees. overflow in the subtraction of fee growth is expected\n        unchecked {\n            feesOwed0 =\n                FullMath.mulDiv(feeGrowthInside0X128 - self.feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128);\n            feesOwed1 =\n                FullMath.mulDiv(feeGrowthInside1X128 - self.feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128);\n        }\n\n        // update the position\n        self.feeGrowthInside0LastX128 = feeGrowthInside0X128;\n        self.feeGrowthInside1LastX128 = feeGrowthInside1X128;\n    }\n}\n"},"lib/uniswap-hooks/lib/v4-core/src/libraries/BitMath.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title BitMath\n/// @dev This library provides functionality for computing bit properties of an unsigned integer\n/// @author Solady (https://github.com/Vectorized/solady/blob/8200a70e8dc2a77ecb074fc2e99a2a0d36547522/src/utils/LibBit.sol)\nlibrary BitMath {\n    /// @notice Returns the index of the most significant bit of the number,\n    ///     where the least significant bit is at index 0 and the most significant bit is at index 255\n    /// @param x the value for which to compute the most significant bit, must be greater than 0\n    /// @return r the index of the most significant bit\n    function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {\n        require(x > 0);\n\n        assembly (\"memory-safe\") {\n            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))\n            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))\n            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))\n            r := or(r, shl(4, lt(0xffff, shr(r, x))))\n            r := or(r, shl(3, lt(0xff, shr(r, x))))\n            // forgefmt: disable-next-item\n            r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),\n                0x0706060506020500060203020504000106050205030304010505030400000000))\n        }\n    }\n\n    /// @notice Returns the index of the least significant bit of the number,\n    ///     where the least significant bit is at index 0 and the most significant bit is at index 255\n    /// @param x the value for which to compute the least significant bit, must be greater than 0\n    /// @return r the index of the least significant bit\n    function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {\n        require(x > 0);\n\n        assembly (\"memory-safe\") {\n            // Isolate the least significant bit.\n            x := and(x, sub(0, x))\n            // For the upper 3 bits of the result, use a De Bruijn-like lookup.\n            // Credit to adhusson: https://blog.adhusson.com/cheap-find-first-set-evm/\n            // forgefmt: disable-next-item\n            r := shl(5, shr(252, shl(shl(2, shr(250, mul(x,\n                0xb6db6db6ddddddddd34d34d349249249210842108c6318c639ce739cffffffff))),\n                0x8040405543005266443200005020610674053026020000107506200176117077)))\n            // For the lower 5 bits of the result, use a De Bruijn lookup.\n            // forgefmt: disable-next-item\n            r := or(r, byte(and(div(0xd76453e0, shr(r, x)), 0x1f),\n                0x001f0d1e100c1d070f090b19131c1706010e11080a1a141802121b1503160405))\n        }\n    }\n}\n"},"lib/uniswap-hooks/lib/v4-core/src/libraries/CustomRevert.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title Library for reverting with custom errors efficiently\n/// @notice Contains functions for reverting with custom errors with different argument types efficiently\n/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with\n/// `CustomError.selector.revertWith()`\n/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately\nlibrary CustomRevert {\n    /// @dev ERC-7751 error for wrapping bubbled up reverts\n    error WrappedError(address target, bytes4 selector, bytes reason, bytes details);\n\n    /// @dev Reverts with the selector of a custom error in the scratch space\n    function revertWith(bytes4 selector) internal pure {\n        assembly (\"memory-safe\") {\n            mstore(0, selector)\n            revert(0, 0x04)\n        }\n    }\n\n    /// @dev Reverts with a custom error with an address argument in the scratch space\n    function revertWith(bytes4 selector, address addr) internal pure {\n        assembly (\"memory-safe\") {\n            mstore(0, selector)\n            mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))\n            revert(0, 0x24)\n        }\n    }\n\n    /// @dev Reverts with a custom error with an int24 argument in the scratch space\n    function revertWith(bytes4 selector, int24 value) internal pure {\n        assembly (\"memory-safe\") {\n            mstore(0, selector)\n            mstore(0x04, signextend(2, value))\n            revert(0, 0x24)\n        }\n    }\n\n    /// @dev Reverts with a custom error with a uint160 argument in the scratch space\n    function revertWith(bytes4 selector, uint160 value) internal pure {\n        assembly (\"memory-safe\") {\n            mstore(0, selector)\n            mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))\n            revert(0, 0x24)\n        }\n    }\n\n    /// @dev Reverts with a custom error with two int24 arguments\n    function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {\n        assembly (\"memory-safe\") {\n            let fmp := mload(0x40)\n            mstore(fmp, selector)\n            mstore(add(fmp, 0x04), signextend(2, value1))\n            mstore(add(fmp, 0x24), signextend(2, value2))\n            revert(fmp, 0x44)\n        }\n    }\n\n    /// @dev Reverts with a custom error with two uint160 arguments\n    function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {\n        assembly (\"memory-safe\") {\n            let fmp := mload(0x40)\n            mstore(fmp, selector)\n            mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))\n            mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))\n            revert(fmp, 0x44)\n        }\n    }\n\n    /// @dev Reverts with a custom error with two address arguments\n    function revertWith(bytes4 selector, address value1, address value2) internal pure {\n        assembly (\"memory-safe\") {\n            let fmp := mload(0x40)\n            mstore(fmp, selector)\n            mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))\n            mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))\n            revert(fmp, 0x44)\n        }\n    }\n\n    /// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error\n    /// @dev this method can be vulnerable to revert data bombs\n    function bubbleUpAndRevertWith(\n        address revertingContract,\n        bytes4 revertingFunctionSelector,\n        bytes4 additionalContext\n    ) internal pure {\n        bytes4 wrappedErrorSelector = WrappedError.selector;\n        assembly (\"memory-safe\") {\n            // Ensure the size of the revert data is a multiple of 32 bytes\n            let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)\n\n            let fmp := mload(0x40)\n\n            // Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason\n            mstore(fmp, wrappedErrorSelector)\n            mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))\n            mstore(\n                add(fmp, 0x24),\n                and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)\n            )\n            // offset revert reason\n            mstore(add(fmp, 0x44), 0x80)\n            // offset additional context\n            mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))\n            // size revert reason\n            mstore(add(fmp, 0x84), returndatasize())\n            // revert reason\n            returndatacopy(add(fmp, 0xa4), 0, returndatasize())\n            // size additional context\n            mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)\n            // additional context\n            mstore(\n                add(fmp, add(0xc4, encodedDataSize)),\n                and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)\n            )\n            revert(fmp, add(0xe4, encodedDataSize))\n        }\n    }\n}\n"},"lib/uniswap-hooks/lib/v4-core/src/interfaces/external/IERC20Minimal.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title Minimal ERC20 interface for Uniswap\n/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3\ninterface IERC20Minimal {\n    /// @notice Returns an account's balance in the token\n    /// @param account The account for which to look up the number of tokens it has, i.e. its balance\n    /// @return The number of tokens held by the account\n    function balanceOf(address account) external view returns (uint256);\n\n    /// @notice Transfers the amount of token from the `msg.sender` to the recipient\n    /// @param recipient The account that will receive the amount transferred\n    /// @param amount The number of tokens to send from the sender to the recipient\n    /// @return Returns true for a successful transfer, false for an unsuccessful transfer\n    function transfer(address recipient, uint256 amount) external returns (bool);\n\n    /// @notice Returns the current allowance given to a spender by an owner\n    /// @param owner The account of the token owner\n    /// @param spender The account of the token spender\n    /// @return The current allowance granted by `owner` to `spender`\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`\n    /// @param spender The account which will be allowed to spend a given amount of the owners tokens\n    /// @param amount The amount of tokens allowed to be used by `spender`\n    /// @return Returns true for a successful approval, false for unsuccessful\n    function approve(address spender, uint256 amount) external returns (bool);\n\n    /// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`\n    /// @param sender The account from which the transfer will be initiated\n    /// @param recipient The recipient of the transfer\n    /// @param amount The amount of the transfer\n    /// @return Returns true for a successful transfer, false for unsuccessful\n    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n\n    /// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.\n    /// @param from The account from which the tokens were sent, i.e. the balance decreased\n    /// @param to The account to which the tokens were sent, i.e. the balance increased\n    /// @param value The amount of tokens that were transferred\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.\n    /// @param owner The account that approved spending of its tokens\n    /// @param spender The account for which the spending allowance was modified\n    /// @param value The new allowance from the owner to the spender\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n"},"lib/uniswap-hooks/lib/v4-periphery/src/utils/BaseHook.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {Hooks} from \"@uniswap/v4-core/src/libraries/Hooks.sol\";\nimport {IPoolManager} from \"@uniswap/v4-core/src/interfaces/IPoolManager.sol\";\nimport {IHooks} from \"@uniswap/v4-core/src/interfaces/IHooks.sol\";\nimport {BalanceDelta} from \"@uniswap/v4-core/src/types/BalanceDelta.sol\";\nimport {PoolKey} from \"@uniswap/v4-core/src/types/PoolKey.sol\";\nimport {BeforeSwapDelta} from \"@uniswap/v4-core/src/types/BeforeSwapDelta.sol\";\nimport {ImmutableState} from \"../base/ImmutableState.sol\";\nimport {ModifyLiquidityParams, SwapParams} from \"@uniswap/v4-core/src/types/PoolOperation.sol\";\n\n/// @title Base Hook\n/// @notice abstract contract for hook implementations\nabstract contract BaseHook is IHooks, ImmutableState {\n    error HookNotImplemented();\n\n    constructor(IPoolManager _manager) ImmutableState(_manager) {\n        validateHookAddress(this);\n    }\n\n    /// @notice Returns a struct of permissions to signal which hook functions are to be implemented\n    /// @dev Used at deployment to validate the address correctly represents the expected permissions\n    /// @return Permissions struct\n    function getHookPermissions() public pure virtual returns (Hooks.Permissions memory);\n\n    /// @notice Validates the deployed hook address agrees with the expected permissions of the hook\n    /// @dev this function is virtual so that we can override it during testing,\n    /// which allows us to deploy an implementation to any address\n    /// and then etch the bytecode into the correct address\n    function validateHookAddress(BaseHook _this) internal pure virtual {\n        Hooks.validateHookPermissions(_this, getHookPermissions());\n    }\n\n    /// @inheritdoc IHooks\n    function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96)\n        external\n        onlyPoolManager\n        returns (bytes4)\n    {\n        return _beforeInitialize(sender, key, sqrtPriceX96);\n    }\n\n    function _beforeInitialize(address, PoolKey calldata, uint160) internal virtual returns (bytes4) {\n        revert HookNotImplemented();\n    }\n\n    /// @inheritdoc IHooks\n    function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)\n        external\n        onlyPoolManager\n        returns (bytes4)\n    {\n        return _afterInitialize(sender, key, sqrtPriceX96, tick);\n    }\n\n    function _afterInitialize(address, PoolKey calldata, uint160, int24) internal virtual returns (bytes4) {\n        revert HookNotImplemented();\n    }\n\n    /// @inheritdoc IHooks\n    function beforeAddLiquidity(\n        address sender,\n        PoolKey calldata key,\n        ModifyLiquidityParams calldata params,\n        bytes calldata hookData\n    ) external onlyPoolManager returns (bytes4) {\n        return _beforeAddLiquidity(sender, key, params, hookData);\n    }\n\n    function _beforeAddLiquidity(address, PoolKey calldata, ModifyLiquidityParams calldata, bytes calldata)\n        internal\n        virtual\n        returns (bytes4)\n    {\n        revert HookNotImplemented();\n    }\n\n    /// @inheritdoc IHooks\n    function beforeRemoveLiquidity(\n        address sender,\n        PoolKey calldata key,\n        ModifyLiquidityParams calldata params,\n        bytes calldata hookData\n    ) external onlyPoolManager returns (bytes4) {\n        return _beforeRemoveLiquidity(sender, key, params, hookData);\n    }\n\n    function _beforeRemoveLiquidity(address, PoolKey calldata, ModifyLiquidityParams calldata, bytes calldata)\n        internal\n        virtual\n        returns (bytes4)\n    {\n        revert HookNotImplemented();\n    }\n\n    /// @inheritdoc IHooks\n    function afterAddLiquidity(\n        address sender,\n        PoolKey calldata key,\n        ModifyLiquidityParams calldata params,\n        BalanceDelta delta,\n        BalanceDelta feesAccrued,\n        bytes calldata hookData\n    ) external onlyPoolManager returns (bytes4, BalanceDelta) {\n        return _afterAddLiquidity(sender, key, params, delta, feesAccrued, hookData);\n    }\n\n    function _afterAddLiquidity(\n        address,\n        PoolKey calldata,\n        ModifyLiquidityParams calldata,\n        BalanceDelta,\n        BalanceDelta,\n        bytes calldata\n    ) internal virtual returns (bytes4, BalanceDelta) {\n        revert HookNotImplemented();\n    }\n\n    /// @inheritdoc IHooks\n    function afterRemoveLiquidity(\n        address sender,\n        PoolKey calldata key,\n        ModifyLiquidityParams calldata params,\n        BalanceDelta delta,\n        BalanceDelta feesAccrued,\n        bytes calldata hookData\n    ) external onlyPoolManager returns (bytes4, BalanceDelta) {\n        return _afterRemoveLiquidity(sender, key, params, delta, feesAccrued, hookData);\n    }\n\n    function _afterRemoveLiquidity(\n        address,\n        PoolKey calldata,\n        ModifyLiquidityParams calldata,\n        BalanceDelta,\n        BalanceDelta,\n        bytes calldata\n    ) internal virtual returns (bytes4, BalanceDelta) {\n        revert HookNotImplemented();\n    }\n\n    /// @inheritdoc IHooks\n    function beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata hookData)\n        external\n        onlyPoolManager\n        returns (bytes4, BeforeSwapDelta, uint24)\n    {\n        return _beforeSwap(sender, key, params, hookData);\n    }\n\n    function _beforeSwap(address, PoolKey calldata, SwapParams calldata, bytes calldata)\n        internal\n        virtual\n        returns (bytes4, BeforeSwapDelta, uint24)\n    {\n        revert HookNotImplemented();\n    }\n\n    /// @inheritdoc IHooks\n    function afterSwap(\n        address sender,\n        PoolKey calldata key,\n        SwapParams calldata params,\n        BalanceDelta delta,\n        bytes calldata hookData\n    ) external onlyPoolManager returns (bytes4, int128) {\n        return _afterSwap(sender, key, params, delta, hookData);\n    }\n\n    function _afterSwap(address, PoolKey calldata, SwapParams calldata, BalanceDelta, bytes calldata)\n        internal\n        virtual\n        returns (bytes4, int128)\n    {\n        revert HookNotImplemented();\n    }\n\n    /// @inheritdoc IHooks\n    function beforeDonate(\n        address sender,\n        PoolKey calldata key,\n        uint256 amount0,\n        uint256 amount1,\n        bytes calldata hookData\n    ) external onlyPoolManager returns (bytes4) {\n        return _beforeDonate(sender, key, amount0, amount1, hookData);\n    }\n\n    function _beforeDonate(address, PoolKey calldata, uint256, uint256, bytes calldata)\n        internal\n        virtual\n        returns (bytes4)\n    {\n        revert HookNotImplemented();\n    }\n\n    /// @inheritdoc IHooks\n    function afterDonate(\n        address sender,\n        PoolKey calldata key,\n        uint256 amount0,\n        uint256 amount1,\n        bytes calldata hookData\n    ) external onlyPoolManager returns (bytes4) {\n        return _afterDonate(sender, key, amount0, amount1, hookData);\n    }\n\n    function _afterDonate(address, PoolKey calldata, uint256, uint256, bytes calldata)\n        internal\n        virtual\n        returns (bytes4)\n    {\n        revert HookNotImplemented();\n    }\n}\n"},"lib/uniswap-hooks/lib/v4-periphery/src/libraries/LiquidityAmounts.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {FullMath} from \"@uniswap/v4-core/src/libraries/FullMath.sol\";\nimport {FixedPoint96} from \"@uniswap/v4-core/src/libraries/FixedPoint96.sol\";\nimport {SafeCast} from \"@uniswap/v4-core/src/libraries/SafeCast.sol\";\n\n/// @notice Provides functions for computing liquidity amounts from token amounts and prices\nlibrary LiquidityAmounts {\n    using SafeCast for uint256;\n\n    /// @notice Computes the amount of liquidity received for a given amount of token0 and price range\n    /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))\n    /// @param sqrtPriceAX96 A sqrt price representing the first tick boundary\n    /// @param sqrtPriceBX96 A sqrt price representing the second tick boundary\n    /// @param amount0 The amount0 being sent in\n    /// @return liquidity The amount of returned liquidity\n    function getLiquidityForAmount0(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint256 amount0)\n        internal\n        pure\n        returns (uint128 liquidity)\n    {\n        unchecked {\n            if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);\n            uint256 intermediate = FullMath.mulDiv(sqrtPriceAX96, sqrtPriceBX96, FixedPoint96.Q96);\n            return FullMath.mulDiv(amount0, intermediate, sqrtPriceBX96 - sqrtPriceAX96).toUint128();\n        }\n    }\n\n    /// @notice Computes the amount of liquidity received for a given amount of token1 and price range\n    /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).\n    /// @param sqrtPriceAX96 A sqrt price representing the first tick boundary\n    /// @param sqrtPriceBX96 A sqrt price representing the second tick boundary\n    /// @param amount1 The amount1 being sent in\n    /// @return liquidity The amount of returned liquidity\n    function getLiquidityForAmount1(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint256 amount1)\n        internal\n        pure\n        returns (uint128 liquidity)\n    {\n        unchecked {\n            if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);\n            return FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtPriceBX96 - sqrtPriceAX96).toUint128();\n        }\n    }\n\n    /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current\n    /// pool prices and the prices at the tick boundaries\n    /// @param sqrtPriceX96 A sqrt price representing the current pool prices\n    /// @param sqrtPriceAX96 A sqrt price representing the first tick boundary\n    /// @param sqrtPriceBX96 A sqrt price representing the second tick boundary\n    /// @param amount0 The amount of token0 being sent in\n    /// @param amount1 The amount of token1 being sent in\n    /// @return liquidity The maximum amount of liquidity received\n    function getLiquidityForAmounts(\n        uint160 sqrtPriceX96,\n        uint160 sqrtPriceAX96,\n        uint160 sqrtPriceBX96,\n        uint256 amount0,\n        uint256 amount1\n    ) internal pure returns (uint128 liquidity) {\n        if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);\n\n        if (sqrtPriceX96 <= sqrtPriceAX96) {\n            liquidity = getLiquidityForAmount0(sqrtPriceAX96, sqrtPriceBX96, amount0);\n        } else if (sqrtPriceX96 < sqrtPriceBX96) {\n            uint128 liquidity0 = getLiquidityForAmount0(sqrtPriceX96, sqrtPriceBX96, amount0);\n            uint128 liquidity1 = getLiquidityForAmount1(sqrtPriceAX96, sqrtPriceX96, amount1);\n\n            liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;\n        } else {\n            liquidity = getLiquidityForAmount1(sqrtPriceAX96, sqrtPriceBX96, amount1);\n        }\n    }\n}\n"},"lib/uniswap-hooks/lib/v4-core/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n */\ninterface IERC20Metadata is IERC20 {\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() external view returns (string memory);\n\n    /**\n     * @dev Returns the symbol of the token.\n     */\n    function symbol() external view returns (string memory);\n\n    /**\n     * @dev Returns the decimals places of the token.\n     */\n    function decimals() external view returns (uint8);\n}\n"},"lib/uniswap-hooks/lib/v4-core/src/libraries/Hooks.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {PoolKey} from \"../types/PoolKey.sol\";\nimport {IHooks} from \"../interfaces/IHooks.sol\";\nimport {SafeCast} from \"./SafeCast.sol\";\nimport {LPFeeLibrary} from \"./LPFeeLibrary.sol\";\nimport {BalanceDelta, toBalanceDelta, BalanceDeltaLibrary} from \"../types/BalanceDelta.sol\";\nimport {BeforeSwapDelta, BeforeSwapDeltaLibrary} from \"../types/BeforeSwapDelta.sol\";\nimport {IPoolManager} from \"../interfaces/IPoolManager.sol\";\nimport {ModifyLiquidityParams, SwapParams} from \"../types/PoolOperation.sol\";\nimport {ParseBytes} from \"./ParseBytes.sol\";\nimport {CustomRevert} from \"./CustomRevert.sol\";\n\n/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits\n/// of the address that the hooks contract is deployed to.\n/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400\n/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.\nlibrary Hooks {\n    using LPFeeLibrary for uint24;\n    using Hooks for IHooks;\n    using SafeCast for int256;\n    using BeforeSwapDeltaLibrary for BeforeSwapDelta;\n    using ParseBytes for bytes;\n    using CustomRevert for bytes4;\n\n    uint160 internal constant ALL_HOOK_MASK = uint160((1 << 14) - 1);\n\n    uint160 internal constant BEFORE_INITIALIZE_FLAG = 1 << 13;\n    uint160 internal constant AFTER_INITIALIZE_FLAG = 1 << 12;\n\n    uint160 internal constant BEFORE_ADD_LIQUIDITY_FLAG = 1 << 11;\n    uint160 internal constant AFTER_ADD_LIQUIDITY_FLAG = 1 << 10;\n\n    uint160 internal constant BEFORE_REMOVE_LIQUIDITY_FLAG = 1 << 9;\n    uint160 internal constant AFTER_REMOVE_LIQUIDITY_FLAG = 1 << 8;\n\n    uint160 internal constant BEFORE_SWAP_FLAG = 1 << 7;\n    uint160 internal constant AFTER_SWAP_FLAG = 1 << 6;\n\n    uint160 internal constant BEFORE_DONATE_FLAG = 1 << 5;\n    uint160 internal constant AFTER_DONATE_FLAG = 1 << 4;\n\n    uint160 internal constant BEFORE_SWAP_RETURNS_DELTA_FLAG = 1 << 3;\n    uint160 internal constant AFTER_SWAP_RETURNS_DELTA_FLAG = 1 << 2;\n    uint160 internal constant AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 1;\n    uint160 internal constant AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 0;\n\n    struct Permissions {\n        bool beforeInitialize;\n        bool afterInitialize;\n        bool beforeAddLiquidity;\n        bool afterAddLiquidity;\n        bool beforeRemoveLiquidity;\n        bool afterRemoveLiquidity;\n        bool beforeSwap;\n        bool afterSwap;\n        bool beforeDonate;\n        bool afterDonate;\n        bool beforeSwapReturnDelta;\n        bool afterSwapReturnDelta;\n        bool afterAddLiquidityReturnDelta;\n        bool afterRemoveLiquidityReturnDelta;\n    }\n\n    /// @notice Thrown if the address will not lead to the specified hook calls being called\n    /// @param hooks The address of the hooks contract\n    error HookAddressNotValid(address hooks);\n\n    /// @notice Hook did not return its selector\n    error InvalidHookResponse();\n\n    /// @notice Additional context for ERC-7751 wrapped error when a hook call fails\n    error HookCallFailed();\n\n    /// @notice The hook's delta changed the swap from exactIn to exactOut or vice versa\n    error HookDeltaExceedsSwapAmount();\n\n    /// @notice Utility function intended to be used in hook constructors to ensure\n    /// the deployed hooks address causes the intended hooks to be called\n    /// @param permissions The hooks that are intended to be called\n    /// @dev permissions param is memory as the function will be called from constructors\n    function validateHookPermissions(IHooks self, Permissions memory permissions) internal pure {\n        if (\n            permissions.beforeInitialize != self.hasPermission(BEFORE_INITIALIZE_FLAG)\n                || permissions.afterInitialize != self.hasPermission(AFTER_INITIALIZE_FLAG)\n                || permissions.beforeAddLiquidity != self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG)\n                || permissions.afterAddLiquidity != self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG)\n                || permissions.beforeRemoveLiquidity != self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG)\n                || permissions.afterRemoveLiquidity != self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)\n                || permissions.beforeSwap != self.hasPermission(BEFORE_SWAP_FLAG)\n                || permissions.afterSwap != self.hasPermission(AFTER_SWAP_FLAG)\n                || permissions.beforeDonate != self.hasPermission(BEFORE_DONATE_FLAG)\n                || permissions.afterDonate != self.hasPermission(AFTER_DONATE_FLAG)\n                || permissions.beforeSwapReturnDelta != self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)\n                || permissions.afterSwapReturnDelta != self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)\n                || permissions.afterAddLiquidityReturnDelta != self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG)\n                || permissions.afterRemoveLiquidityReturnDelta\n                    != self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)\n        ) {\n            HookAddressNotValid.selector.revertWith(address(self));\n        }\n    }\n\n    /// @notice Ensures that the hook address includes at least one hook flag or dynamic fees, or is the 0 address\n    /// @param self The hook to verify\n    /// @param fee The fee of the pool the hook is used with\n    /// @return bool True if the hook address is valid\n    function isValidHookAddress(IHooks self, uint24 fee) internal pure returns (bool) {\n        // The hook can only have a flag to return a hook delta on an action if it also has the corresponding action flag\n        if (!self.hasPermission(BEFORE_SWAP_FLAG) && self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) return false;\n        if (!self.hasPermission(AFTER_SWAP_FLAG) && self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)) return false;\n        if (!self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG) && self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG))\n        {\n            return false;\n        }\n        if (\n            !self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)\n                && self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)\n        ) return false;\n\n        // If there is no hook contract set, then fee cannot be dynamic\n        // If a hook contract is set, it must have at least 1 flag set, or have a dynamic fee\n        return address(self) == address(0)\n            ? !fee.isDynamicFee()\n            : (uint160(address(self)) & ALL_HOOK_MASK > 0 || fee.isDynamicFee());\n    }\n\n    /// @notice performs a hook call using the given calldata on the given hook that doesn't return a delta\n    /// @return result The complete data returned by the hook\n    function callHook(IHooks self, bytes memory data) internal returns (bytes memory result) {\n        bool success;\n        assembly (\"memory-safe\") {\n            success := call(gas(), self, 0, add(data, 0x20), mload(data), 0, 0)\n        }\n        // Revert with FailedHookCall, containing any error message to bubble up\n        if (!success) CustomRevert.bubbleUpAndRevertWith(address(self), bytes4(data), HookCallFailed.selector);\n\n        // The call was successful, fetch the returned data\n        assembly (\"memory-safe\") {\n            // allocate result byte array from the free memory pointer\n            result := mload(0x40)\n            // store new free memory pointer at the end of the array padded to 32 bytes\n            mstore(0x40, add(result, and(add(returndatasize(), 0x3f), not(0x1f))))\n            // store length in memory\n            mstore(result, returndatasize())\n            // copy return data to result\n            returndatacopy(add(result, 0x20), 0, returndatasize())\n        }\n\n        // Length must be at least 32 to contain the selector. Check expected selector and returned selector match.\n        if (result.length < 32 || result.parseSelector() != data.parseSelector()) {\n            InvalidHookResponse.selector.revertWith();\n        }\n    }\n\n    /// @notice performs a hook call using the given calldata on the given hook\n    /// @return int256 The delta returned by the hook\n    function callHookWithReturnDelta(IHooks self, bytes memory data, bool parseReturn) internal returns (int256) {\n        bytes memory result = callHook(self, data);\n\n        // If this hook wasn't meant to return something, default to 0 delta\n        if (!parseReturn) return 0;\n\n        // A length of 64 bytes is required to return a bytes4, and a 32 byte delta\n        if (result.length != 64) InvalidHookResponse.selector.revertWith();\n        return result.parseReturnDelta();\n    }\n\n    /// @notice modifier to prevent calling a hook if they initiated the action\n    modifier noSelfCall(IHooks self) {\n        if (msg.sender != address(self)) {\n            _;\n        }\n    }\n\n    /// @notice calls beforeInitialize hook if permissioned and validates return value\n    function beforeInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96) internal noSelfCall(self) {\n        if (self.hasPermission(BEFORE_INITIALIZE_FLAG)) {\n            self.callHook(abi.encodeCall(IHooks.beforeInitialize, (msg.sender, key, sqrtPriceX96)));\n        }\n    }\n\n    /// @notice calls afterInitialize hook if permissioned and validates return value\n    function afterInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96, int24 tick)\n        internal\n        noSelfCall(self)\n    {\n        if (self.hasPermission(AFTER_INITIALIZE_FLAG)) {\n            self.callHook(abi.encodeCall(IHooks.afterInitialize, (msg.sender, key, sqrtPriceX96, tick)));\n        }\n    }\n\n    /// @notice calls beforeModifyLiquidity hook if permissioned and validates return value\n    function beforeModifyLiquidity(\n        IHooks self,\n        PoolKey memory key,\n        ModifyLiquidityParams memory params,\n        bytes calldata hookData\n    ) internal noSelfCall(self) {\n        if (params.liquidityDelta > 0 && self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG)) {\n            self.callHook(abi.encodeCall(IHooks.beforeAddLiquidity, (msg.sender, key, params, hookData)));\n        } else if (params.liquidityDelta <= 0 && self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG)) {\n            self.callHook(abi.encodeCall(IHooks.beforeRemoveLiquidity, (msg.sender, key, params, hookData)));\n        }\n    }\n\n    /// @notice calls afterModifyLiquidity hook if permissioned and validates return value\n    function afterModifyLiquidity(\n        IHooks self,\n        PoolKey memory key,\n        ModifyLiquidityParams memory params,\n        BalanceDelta delta,\n        BalanceDelta feesAccrued,\n        bytes calldata hookData\n    ) internal returns (BalanceDelta callerDelta, BalanceDelta hookDelta) {\n        if (msg.sender == address(self)) return (delta, BalanceDeltaLibrary.ZERO_DELTA);\n\n        callerDelta = delta;\n        if (params.liquidityDelta > 0) {\n            if (self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG)) {\n                hookDelta = BalanceDelta.wrap(\n                    self.callHookWithReturnDelta(\n                        abi.encodeCall(\n                            IHooks.afterAddLiquidity, (msg.sender, key, params, delta, feesAccrued, hookData)\n                        ),\n                        self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG)\n                    )\n                );\n                callerDelta = callerDelta - hookDelta;\n            }\n        } else {\n            if (self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)) {\n                hookDelta = BalanceDelta.wrap(\n                    self.callHookWithReturnDelta(\n                        abi.encodeCall(\n                            IHooks.afterRemoveLiquidity, (msg.sender, key, params, delta, feesAccrued, hookData)\n                        ),\n                        self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)\n                    )\n                );\n                callerDelta = callerDelta - hookDelta;\n            }\n        }\n    }\n\n    /// @notice calls beforeSwap hook if permissioned and validates return value\n    function beforeSwap(IHooks self, PoolKey memory key, SwapParams memory params, bytes calldata hookData)\n        internal\n        returns (int256 amountToSwap, BeforeSwapDelta hookReturn, uint24 lpFeeOverride)\n    {\n        amountToSwap = params.amountSpecified;\n        if (msg.sender == address(self)) return (amountToSwap, BeforeSwapDeltaLibrary.ZERO_DELTA, lpFeeOverride);\n\n        if (self.hasPermission(BEFORE_SWAP_FLAG)) {\n            bytes memory result = callHook(self, abi.encodeCall(IHooks.beforeSwap, (msg.sender, key, params, hookData)));\n\n            // A length of 96 bytes is required to return a bytes4, a 32 byte delta, and an LP fee\n            if (result.length != 96) InvalidHookResponse.selector.revertWith();\n\n            // dynamic fee pools that want to override the cache fee, return a valid fee with the override flag. If override flag\n            // is set but an invalid fee is returned, the transaction will revert. Otherwise the current LP fee will be used\n            if (key.fee.isDynamicFee()) lpFeeOverride = result.parseFee();\n\n            // skip this logic for the case where the hook return is 0\n            if (self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) {\n                hookReturn = BeforeSwapDelta.wrap(result.parseReturnDelta());\n\n                // any return in unspecified is passed to the afterSwap hook for handling\n                int128 hookDeltaSpecified = hookReturn.getSpecifiedDelta();\n\n                // Update the swap amount according to the hook's return, and check that the swap type doesn't change (exact input/output)\n                if (hookDeltaSpecified != 0) {\n                    bool exactInput = amountToSwap < 0;\n                    amountToSwap += hookDeltaSpecified;\n                    if (exactInput ? amountToSwap > 0 : amountToSwap < 0) {\n                        HookDeltaExceedsSwapAmount.selector.revertWith();\n                    }\n                }\n            }\n        }\n    }\n\n    /// @notice calls afterSwap hook if permissioned and validates return value\n    function afterSwap(\n        IHooks self,\n        PoolKey memory key,\n        SwapParams memory params,\n        BalanceDelta swapDelta,\n        bytes calldata hookData,\n        BeforeSwapDelta beforeSwapHookReturn\n    ) internal returns (BalanceDelta, BalanceDelta) {\n        if (msg.sender == address(self)) return (swapDelta, BalanceDeltaLibrary.ZERO_DELTA);\n\n        int128 hookDeltaSpecified = beforeSwapHookReturn.getSpecifiedDelta();\n        int128 hookDeltaUnspecified = beforeSwapHookReturn.getUnspecifiedDelta();\n\n        if (self.hasPermission(AFTER_SWAP_FLAG)) {\n            hookDeltaUnspecified += self.callHookWithReturnDelta(\n                abi.encodeCall(IHooks.afterSwap, (msg.sender, key, params, swapDelta, hookData)),\n                self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)\n            ).toInt128();\n        }\n\n        BalanceDelta hookDelta;\n        if (hookDeltaUnspecified != 0 || hookDeltaSpecified != 0) {\n            hookDelta = (params.amountSpecified < 0 == params.zeroForOne)\n                ? toBalanceDelta(hookDeltaSpecified, hookDeltaUnspecified)\n                : toBalanceDelta(hookDeltaUnspecified, hookDeltaSpecified);\n\n            // the caller has to pay for (or receive) the hook's delta\n            swapDelta = swapDelta - hookDelta;\n        }\n        return (swapDelta, hookDelta);\n    }\n\n    /// @notice calls beforeDonate hook if permissioned and validates return value\n    function beforeDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)\n        internal\n        noSelfCall(self)\n    {\n        if (self.hasPermission(BEFORE_DONATE_FLAG)) {\n            self.callHook(abi.encodeCall(IHooks.beforeDonate, (msg.sender, key, amount0, amount1, hookData)));\n        }\n    }\n\n    /// @notice calls afterDonate hook if permissioned and validates return value\n    function afterDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)\n        internal\n        noSelfCall(self)\n    {\n        if (self.hasPermission(AFTER_DONATE_FLAG)) {\n            self.callHook(abi.encodeCall(IHooks.afterDonate, (msg.sender, key, amount0, amount1, hookData)));\n        }\n    }\n\n    function hasPermission(IHooks self, uint160 flag) internal pure returns (bool) {\n        return uint160(address(self)) & flag != 0;\n    }\n}\n"},"lib/uniswap-hooks/lib/v4-core/src/libraries/TransientStateLibrary.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\nimport {IPoolManager} from \"../interfaces/IPoolManager.sol\";\nimport {Currency} from \"../types/Currency.sol\";\nimport {CurrencyReserves} from \"./CurrencyReserves.sol\";\nimport {NonzeroDeltaCount} from \"./NonzeroDeltaCount.sol\";\nimport {Lock} from \"./Lock.sol\";\n\n/// @notice A helper library to provide state getters that use exttload\nlibrary TransientStateLibrary {\n    /// @notice returns the reserves for the synced currency\n    /// @param manager The pool manager contract.\n\n    /// @return uint256 The reserves of the currency.\n    /// @dev returns 0 if the reserves are not synced or value is 0.\n    /// Checks the synced currency to only return valid reserve values (after a sync and before a settle).\n    function getSyncedReserves(IPoolManager manager) internal view returns (uint256) {\n        if (getSyncedCurrency(manager).isAddressZero()) return 0;\n        return uint256(manager.exttload(CurrencyReserves.RESERVES_OF_SLOT));\n    }\n\n    function getSyncedCurrency(IPoolManager manager) internal view returns (Currency) {\n        return Currency.wrap(address(uint160(uint256(manager.exttload(CurrencyReserves.CURRENCY_SLOT)))));\n    }\n\n    /// @notice Returns the number of nonzero deltas open on the PoolManager that must be zeroed out before the contract is locked\n    function getNonzeroDeltaCount(IPoolManager manager) internal view returns (uint256) {\n        return uint256(manager.exttload(NonzeroDeltaCount.NONZERO_DELTA_COUNT_SLOT));\n    }\n\n    /// @notice Get the current delta for a caller in the given currency\n    /// @param target The credited account address\n    /// @param currency The currency for which to lookup the delta\n    function currencyDelta(IPoolManager manager, address target, Currency currency) internal view returns (int256) {\n        bytes32 key;\n        assembly (\"memory-safe\") {\n            mstore(0, and(target, 0xffffffffffffffffffffffffffffffffffffffff))\n            mstore(32, and(currency, 0xffffffffffffffffffffffffffffffffffffffff))\n            key := keccak256(0, 64)\n        }\n        return int256(uint256(manager.exttload(key)));\n    }\n\n    /// @notice Returns whether the contract is unlocked or not\n    function isUnlocked(IPoolManager manager) internal view returns (bool) {\n        return manager.exttload(Lock.IS_UNLOCKED_SLOT) != 0x0;\n    }\n}\n"},"lib/uniswap-hooks/lib/v4-core/src/types/BeforeSwapDelta.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Return type of the beforeSwap hook.\n// Upper 128 bits is the delta in specified tokens. Lower 128 bits is delta in unspecified tokens (to match the afterSwap hook)\ntype BeforeSwapDelta is int256;\n\n// Creates a BeforeSwapDelta from specified and unspecified\nfunction toBeforeSwapDelta(int128 deltaSpecified, int128 deltaUnspecified)\n    pure\n    returns (BeforeSwapDelta beforeSwapDelta)\n{\n    assembly (\"memory-safe\") {\n        beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified))\n    }\n}\n\n/// @notice Library for getting the specified and unspecified deltas from the BeforeSwapDelta type\nlibrary BeforeSwapDeltaLibrary {\n    /// @notice A BeforeSwapDelta of 0\n    BeforeSwapDelta public constant ZERO_DELTA = BeforeSwapDelta.wrap(0);\n\n    /// extracts int128 from the upper 128 bits of the BeforeSwapDelta\n    /// returned by beforeSwap\n    function getSpecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaSpecified) {\n        assembly (\"memory-safe\") {\n            deltaSpecified := sar(128, delta)\n        }\n    }\n\n    /// extracts int128 from the lower 128 bits of the BeforeSwapDelta\n    /// returned by beforeSwap and afterSwap\n    function getUnspecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaUnspecified) {\n        assembly (\"memory-safe\") {\n            deltaUnspecified := signextend(15, delta)\n        }\n    }\n}\n"},"lib/uniswap-hooks/lib/v4-core/src/interfaces/callback/IUnlockCallback.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @notice Interface for the callback executed when an address unlocks the pool manager\ninterface IUnlockCallback {\n    /// @notice Called by the pool manager on `msg.sender` when the manager is unlocked\n    /// @param data The data that was passed to the call to unlock\n    /// @return Any data that you want to be returned from the unlock call\n    function unlockCallback(bytes calldata data) external returns (bytes memory);\n}\n"},"src/BasketFactory.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.26;\n\nimport {Ownable, Ownable2Step} from \"@openzeppelin/contracts/access/Ownable2Step.sol\";\nimport {IERC20Metadata} from \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport {IPoolManager} from \"v4-core/src/interfaces/IPoolManager.sol\";\nimport {PoolKey} from \"v4-core/src/types/PoolKey.sol\";\nimport {PoolIdLibrary} from \"v4-core/src/types/PoolId.sol\";\nimport {StateLibrary} from \"v4-core/src/libraries/StateLibrary.sol\";\nimport {FullMath} from \"v4-core/src/libraries/FullMath.sol\";\nimport {StockRegistry} from \"./StockRegistry.sol\";\nimport {Basket} from \"./Basket.sol\";\nimport {INavGuard} from \"./INavGuard.sol\";\nimport {SpotLib} from \"./libraries/SpotLib.sol\";\nimport {DepthLib} from \"./libraries/DepthLib.sol\";\nimport {BasketLimits} from \"./libraries/BasketLimits.sol\";\n\ncontract BasketFactory is Ownable2Step {\n    using StateLibrary for IPoolManager;\n    using PoolIdLibrary for PoolKey;\n\n    uint256 public constant MIN_CONSTITUENTS = BasketLimits.MIN_CONSTITUENTS;\n    uint256 public constant MAX_CONSTITUENTS = BasketLimits.MAX_CONSTITUENTS;\n    uint256 public constant BPS = 10_000;\n\n    string public constant LOT_PREFIX = \"LOT-\";\n    uint256 public constant MAX_LOT_NAME_BYTES = 32;\n\n    uint160 public constant ADDRESS_FLOOR = uint160(1) << 159;\n\n    uint256 private constant MAX_SALT_BUMPS = 256;\n\n    StockRegistry public immutable registry;\n    IPoolManager public immutable poolManager;\n\n    uint256 public minDepthUsd18 = 25_000e18;\n    uint256 public minPriceDepthUsd18 = 25_000e18;\n\n    mapping(bytes32 => address) public basketByHash;\n    mapping(address => bool) public isBasket;\n    address[] public baskets;\n    uint256 private _basketSalt;\n\n    INavGuard public navGuard;\n\n    error BadCount();\n    error NotSorted();\n    error WeightsNot10000();\n    error ZeroWeight();\n    error InsufficientDepth(address stock);\n    error InsufficientPriceDepth(address stock);\n    error NotRegistered(address stock);\n    error ZeroUnit(address stock);\n\n    error LotNameTooLong(uint256 length);\n    error LotNameInvalidChar(uint256 index);\n    error LotNameEdgeWhitespace();\n    error LotNameHasPrefix();\n    error LotAlreadyExists(address basket);\n    error NoBasketSaltFound();\n    error BasketAddressMismatch(address predicted, address deployed);\n    error ZeroNavGuard();\n\n    event BasketCreated(\n        address indexed basket,\n        bytes32 indexed hash,\n        address indexed creator,\n        address[] tokens,\n        uint16[] weightBps,\n        uint256[] units,\n        string name\n    );\n    event MinDepthSet(uint256 minDepthUsd18);\n    event MinPriceDepthSet(uint256 minPriceDepthUsd18);\n    event BasketLedgerSet(address indexed basket, address indexed ledger);\n    event NavGuardSet(address indexed navGuard);\n\n    error NotOurBasket(address basket);\n\n    constructor(address owner_, StockRegistry registry_, IPoolManager poolManager_) Ownable(owner_) {\n        registry = registry_;\n        poolManager = poolManager_;\n    }\n\n    error OwnershipCannotBeRenounced();\n\n    function renounceOwnership() public pure override {\n        revert OwnershipCannotBeRenounced();\n    }\n\n    function setMinDepthUsd18(uint256 v) external onlyOwner {\n        minDepthUsd18 = v;\n        emit MinDepthSet(v);\n    }\n\n    function setMinPriceDepthUsd18(uint256 v) external onlyOwner {\n        minPriceDepthUsd18 = v;\n        emit MinPriceDepthSet(v);\n    }\n\n    function setNavGuard(address g) external onlyOwner {\n        if (g == address(0)) revert ZeroNavGuard();\n        navGuard = INavGuard(g);\n        emit NavGuardSet(g);\n    }\n\n    function quoteUsd18(address quote, bool checked) external view returns (uint256 usd18, uint8 dec) {\n        INavGuard g = navGuard;\n        bool guarded = checked && address(g) != address(0);\n        if (isBasket[quote]) return (guarded ? g.checkedNavPerUnit18(quote) : navPerUnit18(quote), 18);\n        dec = _info(quote).stockDecimals;\n        usd18 = guarded ? g.checkedPrice18(quote) : spotUsd18(quote);\n    }\n\n    function setBasketLedger(address basket, address ledger) external onlyOwner {\n        if (!isBasket[basket]) revert NotOurBasket(basket);\n        Basket(basket).setRecoveryLedger(ledger);\n        emit BasketLedgerSet(basket, ledger);\n    }\n\n    function basketCount() external view returns (uint256) {\n        return baskets.length;\n    }\n\n    function createBasket(address[] calldata tokens, uint16[] calldata weightBps) external returns (address basket) {\n        return _createBasket(tokens, weightBps, \"\");\n    }\n\n    function createBasket(address[] calldata tokens, uint16[] calldata weightBps, string calldata lotName)\n        public\n        returns (address basket)\n    {\n        return _createBasket(tokens, weightBps, lotName);\n    }\n\n    function _createBasket(address[] calldata tokens, uint16[] calldata weightBps, string memory lotName)\n        internal\n        returns (address basket)\n    {\n        uint256 n = tokens.length;\n        if (n < MIN_CONSTITUENTS || n > MAX_CONSTITUENTS || weightBps.length != n) revert BadCount();\n\n        uint256 sum;\n        for (uint256 i; i < n; ++i) {\n            if (i > 0 && tokens[i] <= tokens[i - 1]) revert NotSorted();\n            if (weightBps[i] == 0) revert ZeroWeight();\n            sum += weightBps[i];\n        }\n        if (sum != BPS) revert WeightsNot10000();\n\n        if (bytes(lotName).length != 0) _requireValidLotName(lotName);\n\n        bytes32 hash = keccak256(abi.encode(tokens, weightBps));\n        basket = basketByHash[hash];\n        if (basket != address(0)) {\n            if (bytes(lotName).length != 0) revert LotAlreadyExists(basket);\n            return basket;\n        }\n\n        uint256[] memory units = new uint256[](n);\n        for (uint256 i; i < n; ++i) {\n            StockRegistry.StockInfo memory s = registry.requireStock(tokens[i]);\n            requireDepth(tokens[i]);\n            uint256 price = spotUsd18(tokens[i]);\n            units[i] = FullMath.mulDiv(uint256(weightBps[i]) * (10 ** s.stockDecimals), 1e18, BPS * price);\n            if (units[i] == 0) revert ZeroUnit(tokens[i]);\n        }\n\n        (string memory name, string memory symbol) = _names(tokens, lotName);\n\n        basket = _deployAboveFloor(name, symbol, tokens, units);\n        basketByHash[hash] = basket;\n        isBasket[basket] = true;\n        baskets.push(basket);\n        if (address(navGuard) != address(0)) navGuard.checkedNavPerUnit18(basket);\n        emit BasketCreated(basket, hash, msg.sender, tokens, weightBps, units, name);\n    }\n\n    function _deployAboveFloor(\n        string memory name,\n        string memory symbol,\n        address[] calldata tokens,\n        uint256[] memory units\n    ) internal returns (address basket) {\n        bytes32 initHash =\n            keccak256(abi.encodePacked(type(Basket).creationCode, abi.encode(name, symbol, tokens, units, msg.sender)));\n        (bytes32 salt, address predicted) = _saltAboveFloor(initHash);\n        basket = address(new Basket{salt: salt}(name, symbol, tokens, units, msg.sender));\n        if (basket != predicted) revert BasketAddressMismatch(predicted, basket);\n    }\n\n    function _saltAboveFloor(bytes32 initHash) internal returns (bytes32 salt, address predicted) {\n        uint256 id = ++_basketSalt;\n        for (uint256 bump; bump < MAX_SALT_BUMPS; ++bump) {\n            salt = keccak256(abi.encode(id, bump));\n            predicted =\n                address(uint160(uint256(keccak256(abi.encodePacked(bytes1(0xff), address(this), salt, initHash)))));\n            if (uint160(predicted) >= ADDRESS_FLOOR) return (salt, predicted);\n        }\n        revert NoBasketSaltFound();\n    }\n\n    function _info(address stock) internal view returns (StockRegistry.StockInfo memory s) {\n        s = registry.getStock(stock);\n        if (s.stable == address(0)) revert NotRegistered(stock);\n    }\n\n    function spotUsd18(address stock) public view returns (uint256) {\n        StockRegistry.StockInfo memory s = _info(stock);\n        (uint160 sqrtP,,,) = poolManager.getSlot0(s.pools[s.priceIndex].toId());\n        return SpotLib.price18(sqrtP, s.stockIsCurrency0, s.stockDecimals, s.stableDecimals);\n    }\n\n    function depthUsd18(address stock) public view returns (uint256) {\n        StockRegistry.StockInfo memory s = _info(stock);\n        uint256 stableRaw = _bandAcrossVenues(s, true);\n        return stableRaw * 1e18 / (10 ** s.stableDecimals);\n    }\n\n    function priceVenueDepthUsd18(address stock) public view returns (uint256) {\n        StockRegistry.StockInfo memory s = _info(stock);\n        uint256 stableRaw = DepthLib.bandDepth(poolManager, s.pools[s.priceIndex], s.stockIsCurrency0);\n        return stableRaw * 1e18 / (10 ** s.stableDecimals);\n    }\n\n    function _bandAcrossVenues(StockRegistry.StockInfo memory s, bool buy) internal view returns (uint256 sum) {\n        (uint160 priceSqrtP,,,) = poolManager.getSlot0(s.pools[s.priceIndex].toId());\n        if (priceSqrtP == 0) return 0;\n        (uint160 lo, uint160 hi) = DepthLib.bandEdges(priceSqrtP);\n        uint256 n = s.pools.length;\n        for (uint256 i; i < n; ++i) {\n            sum += DepthLib.bandDepthWithin(poolManager, s.pools[i], s.stockIsCurrency0, lo, hi, buy);\n        }\n    }\n\n    function depthUsd18Both(address stock) external view returns (uint256 buyUsd18, uint256 sellUsd18) {\n        StockRegistry.StockInfo memory s = _info(stock);\n        uint256 scale = 10 ** s.stableDecimals;\n        uint256 buyRaw = _bandAcrossVenues(s, true);\n        uint256 sellRaw = _bandAcrossVenues(s, false);\n        return (buyRaw * 1e18 / scale, sellRaw * 1e18 / scale);\n    }\n\n    function requireDepth(address stock) public view {\n        if (depthUsd18(stock) < minDepthUsd18) revert InsufficientDepth(stock);\n        if (priceVenueDepthUsd18(stock) < minPriceDepthUsd18) revert InsufficientPriceDepth(stock);\n    }\n\n    function requireEligibleAll(address basket) external view {\n        (address[] memory toks,) = Basket(basket).constituents();\n        for (uint256 i; i < toks.length; ++i) {\n            registry.requireStock(toks[i]);\n        }\n    }\n\n    function requireDepthAll(address basket) external view {\n        (address[] memory toks,) = Basket(basket).constituents();\n        for (uint256 i; i < toks.length; ++i) {\n            requireDepth(toks[i]);\n        }\n    }\n\n    function navPerUnit18(address basket) public view returns (uint256 nav) {\n        (address[] memory toks, uint256[] memory units) = Basket(basket).constituents();\n        for (uint256 i; i < toks.length; ++i) {\n            StockRegistry.StockInfo memory s = _info(toks[i]);\n            (uint160 sqrtP,,,) = poolManager.getSlot0(s.pools[s.priceIndex].toId());\n            uint256 price = SpotLib.price18(sqrtP, s.stockIsCurrency0, s.stockDecimals, s.stableDecimals);\n            nav += FullMath.mulDiv(units[i], price, 10 ** s.stockDecimals);\n        }\n    }\n\n    function _names(address[] calldata tokens, string memory lotName)\n        internal\n        view\n        returns (string memory name, string memory symbol)\n    {\n        if (bytes(lotName).length != 0) {\n            name = string.concat(LOT_PREFIX, lotName);\n            return (name, name);\n        }\n\n        symbol = \"b\";\n        name = LOT_PREFIX;\n        for (uint256 i; i < tokens.length; ++i) {\n            string memory ticker = IERC20Metadata(tokens[i]).symbol();\n            symbol = string.concat(symbol, ticker);\n            name = string.concat(name, i == 0 ? \"\" : \"/\", ticker);\n        }\n    }\n\n    function _requireValidLotName(string memory lotName) internal pure {\n        bytes memory b = bytes(lotName);\n        if (b.length > MAX_LOT_NAME_BYTES) revert LotNameTooLong(b.length);\n\n        if (b[0] == 0x20 || b[b.length - 1] == 0x20) revert LotNameEdgeWhitespace();\n\n        for (uint256 i; i < b.length; ++i) {\n            uint8 c = uint8(b[i]);\n            if (c < 0x20 || c > 0x7E) revert LotNameInvalidChar(i);\n            if (c == 0x2F) revert LotNameInvalidChar(i);\n        }\n\n        _requireNoPrefix(b);\n    }\n\n    function _requireNoPrefix(bytes memory b) internal pure {\n        if (b.length < 4) return;\n        if (_lower(b[0]) == \"l\" && _lower(b[1]) == \"o\" && _lower(b[2]) == \"t\" && b[3] == \"-\") {\n            revert LotNameHasPrefix();\n        }\n    }\n\n    function _lower(bytes1 c) private pure returns (bytes1) {\n        return (c >= 0x41 && c <= 0x5A) ? bytes1(uint8(c) + 32) : c;\n    }\n}\n"},"src/StockRegistry.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.26;\n\nimport {Ownable, Ownable2Step} from \"@openzeppelin/contracts/access/Ownable2Step.sol\";\nimport {IERC20Metadata} from \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport {PoolKey} from \"v4-core/src/types/PoolKey.sol\";\nimport {PoolId, PoolIdLibrary} from \"v4-core/src/types/PoolId.sol\";\nimport {Currency} from \"v4-core/src/types/Currency.sol\";\nimport {Hooks} from \"v4-core/src/libraries/Hooks.sol\";\n\ncontract StockRegistry is Ownable2Step {\n    using PoolIdLibrary for PoolKey;\n\n    struct StockInfo {\n        PoolKey[] pools;\n        uint8 priceIndex;\n        address stable;\n        bool stockIsCurrency0;\n        uint8 stockDecimals;\n        uint8 stableDecimals;\n        bool enabled;\n    }\n\n    error PoolMissingStock();\n    error NotEligible(address stock);\n    error NotStable(address token);\n    error TickSpacingTooFine(int24 tickSpacing);\n    error HookUsesCustomAccounting(address hooks);\n    error UnsortedKey();\n    error NotEthPool();\n    error KeyMismatch();\n    error NoVenues();\n    error TooManyVenues();\n    error BadPriceIndex(uint8 priceIndex, uint8 venueCount);\n    error StableMismatch(address expected, address got);\n    error DuplicateVenue(PoolId id);\n    error HookedVenueNotAllowed(uint8 index, address hooks);\n\n    int24 public constant MIN_TICK_SPACING = 10;\n\n    uint256 public constant MAX_VENUES = 6;\n\n    event StockVenuesSet(\n        address indexed stock,\n        address indexed stable,\n        PoolKey[] pools,\n        uint8 priceIndex,\n        bool stockIsCurrency0,\n        uint8 stockDecimals,\n        uint8 stableDecimals\n    );\n    event StockRemoved(address indexed stock);\n    event StableSet(address indexed stable, bool enabled);\n    event EthStablePoolSet(address indexed stable, PoolKey pool);\n    event StablePoolSet(address indexed a, address indexed b, PoolKey pool);\n\n    mapping(address => bool) public isStable;\n\n    mapping(address => StockInfo) private _stocks;\n    PoolKey private _ethStablePool;\n    mapping(bytes32 => PoolKey) private _stablePools;\n\n    error OwnershipCannotBeRenounced();\n\n    constructor(address owner_) Ownable(owner_) {}\n\n    function renounceOwnership() public pure override {\n        revert OwnershipCannotBeRenounced();\n    }\n\n\n    function setStable(address stable, bool enabled) external onlyOwner {\n        isStable[stable] = enabled;\n        emit StableSet(stable, enabled);\n    }\n\n    function setStock(address stock, PoolKey calldata pool) external onlyOwner {\n        PoolKey[] memory one = new PoolKey[](1);\n        one[0] = pool;\n        _setStockVenues(stock, one, 0);\n    }\n\n    function setStockVenues(address stock, PoolKey[] calldata pools, uint8 priceIndex) external onlyOwner {\n        _setStockVenues(stock, pools, priceIndex);\n    }\n\n    function _setStockVenues(address stock, PoolKey[] memory pools, uint8 priceIndex) private {\n        uint256 n = pools.length;\n        if (n == 0) revert NoVenues();\n        if (n > MAX_VENUES) revert TooManyVenues();\n        if (priceIndex >= n) revert BadPriceIndex(priceIndex, uint8(n));\n\n        address stable;\n        bool is0;\n        for (uint256 i; i < n; ++i) {\n            PoolKey memory k = pools[i];\n            address c0 = Currency.unwrap(k.currency0);\n            address c1 = Currency.unwrap(k.currency1);\n            if (c0 >= c1) revert UnsortedKey();\n            if (k.tickSpacing < MIN_TICK_SPACING) revert TickSpacingTooFine(k.tickSpacing);\n\n            if (i != priceIndex && address(k.hooks) != address(0)) {\n                revert HookedVenueNotAllowed(uint8(i), address(k.hooks));\n            }\n            _requirePlainAccounting(k);\n\n            address venueStable;\n            bool venueIs0;\n            if (c0 == stock) {\n                venueIs0 = true;\n                venueStable = c1;\n            } else if (c1 == stock) {\n                venueIs0 = false;\n                venueStable = c0;\n            } else {\n                revert PoolMissingStock();\n            }\n            if (!isStable[venueStable]) revert NotStable(venueStable);\n\n            if (i == 0) {\n                stable = venueStable;\n                is0 = venueIs0;\n            } else if (venueStable != stable) {\n                revert StableMismatch(stable, venueStable);\n            }\n\n            for (uint256 j; j < i; ++j) {\n                if (PoolId.unwrap(pools[j].toId()) == PoolId.unwrap(k.toId())) revert DuplicateVenue(k.toId());\n            }\n        }\n\n        uint8 stockDec = IERC20Metadata(stock).decimals();\n        uint8 stableDec = IERC20Metadata(stable).decimals();\n\n        delete _stocks[stock];\n        StockInfo storage s = _stocks[stock];\n        for (uint256 i; i < n; ++i) {\n            s.pools.push(pools[i]);\n        }\n        s.priceIndex = priceIndex;\n        s.stable = stable;\n        s.stockIsCurrency0 = is0;\n        s.stockDecimals = stockDec;\n        s.stableDecimals = stableDec;\n        s.enabled = true;\n\n        emit StockVenuesSet(stock, stable, pools, priceIndex, is0, stockDec, stableDec);\n    }\n\n    function removeStock(address stock) external onlyOwner {\n        if (!_stocks[stock].enabled) revert NotEligible(stock);\n        _stocks[stock].enabled = false;\n        emit StockRemoved(stock);\n    }\n\n    function setEthStablePool(PoolKey calldata pool) external onlyOwner {\n        address c0 = Currency.unwrap(pool.currency0);\n        address c1 = Currency.unwrap(pool.currency1);\n        if (c0 >= c1) revert UnsortedKey();\n        if (c0 != address(0)) revert NotEthPool();\n        if (!isStable[c1]) revert NotStable(c1);\n        _requirePlainAccounting(pool);\n        _ethStablePool = pool;\n        emit EthStablePoolSet(c1, pool);\n    }\n\n    function setStablePool(address a, address b, PoolKey calldata pool) external onlyOwner {\n        address c0 = Currency.unwrap(pool.currency0);\n        address c1 = Currency.unwrap(pool.currency1);\n        if (c0 >= c1) revert UnsortedKey();\n        (address lo, address hi) = a < b ? (a, b) : (b, a);\n        if (c0 != lo || c1 != hi) revert KeyMismatch();\n        if (!isStable[c0]) revert NotStable(c0);\n        if (!isStable[c1]) revert NotStable(c1);\n        _requirePlainAccounting(pool);\n        _stablePools[_pairId(a, b)] = pool;\n        emit StablePoolSet(a, b, pool);\n    }\n\n    function _requirePlainAccounting(PoolKey memory pool) private pure {\n        uint160 h = uint160(address(pool.hooks));\n        if (h & (Hooks.BEFORE_SWAP_RETURNS_DELTA_FLAG | Hooks.AFTER_SWAP_RETURNS_DELTA_FLAG) != 0) {\n            revert HookUsesCustomAccounting(address(pool.hooks));\n        }\n    }\n\n\n    function isEligible(address stock) public view returns (bool) {\n        return _stocks[stock].enabled;\n    }\n\n    function getStock(address stock) external view returns (StockInfo memory) {\n        return _stocks[stock];\n    }\n\n    function requireStock(address stock) external view returns (StockInfo memory s) {\n        s = _stocks[stock];\n        if (!s.enabled) revert NotEligible(stock);\n    }\n\n    function ethStablePool() external view returns (PoolKey memory) {\n        return _ethStablePool;\n    }\n\n    function stablePool(address a, address b) external view returns (PoolKey memory) {\n        return _stablePools[_pairId(a, b)];\n    }\n\n    function _pairId(address a, address b) internal pure returns (bytes32) {\n        return a < b ? keccak256(abi.encode(a, b)) : keccak256(abi.encode(b, a));\n    }\n}\n"},"src/Basket.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.26;\n\nimport {ERC20} from \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport {Math} from \"@openzeppelin/contracts/utils/math/Math.sol\";\nimport {IRecoveryLedger} from \"./IRecoveryLedger.sol\";\nimport {BasketLimits} from \"./libraries/BasketLimits.sol\";\n\ncontract Basket is ERC20 {\n    using SafeERC20 for IERC20;\n\n    uint256 public constant UNIT = 1e18;\n    uint256 public constant MAX_CONSTITUENTS = BasketLimits.MAX_CONSTITUENTS;\n    uint256 public constant LEDGER_HEALTH_GAS = 100_000;\n    uint256 private constant LEDGER_HEALTH_HEADROOM = 40_000;\n\n    error BadLengths();\n    error ZeroUnit(uint256 i);\n    error UnsortedTokens();\n    error TooManyConstituents();\n    error ZeroAmount();\n    error NotFactory();\n    error LedgerLocked(address ledger);\n    error InsufficientGasForHealthCheck();\n    error IssuanceHalted();\n    error LedgerUnanswerable(address ledger);\n\n    enum LedgerAnswer {\n        Incident,\n        Healthy,\n        Unanswerable\n    }\n\n    address public immutable creator;\n    address public immutable factory;\n    IRecoveryLedger public recoveryLedger;\n    address[] private _tokens;\n    uint256[] private _units;\n\n    event Minted(address indexed by, address indexed to, uint256 amount);\n    event Redeemed(address indexed by, address indexed to, uint256 amount, uint256 skipMask);\n    event RecoveryLedgerSet(address indexed ledger);\n\n    constructor(\n        string memory name_,\n        string memory symbol_,\n        address[] memory tokens_,\n        uint256[] memory units_,\n        address creator_\n    ) ERC20(name_, symbol_) {\n        uint256 n = tokens_.length;\n        if (n != units_.length || n < BasketLimits.MIN_CONSTITUENTS) revert BadLengths();\n        if (n > MAX_CONSTITUENTS) revert TooManyConstituents();\n        for (uint256 i; i < n; ++i) {\n            if (units_[i] == 0) revert ZeroUnit(i);\n            if (i != 0 && tokens_[i] <= tokens_[i - 1]) revert UnsortedTokens();\n        }\n        _tokens = tokens_;\n        _units = units_;\n        creator = creator_;\n        factory = msg.sender;\n    }\n\n    function setRecoveryLedger(address ledger) external {\n        if (msg.sender != factory) revert NotFactory();\n        address current = address(recoveryLedger);\n        if (current != address(0) && _askCurrentLedger(current) == LedgerAnswer.Incident) {\n            revert LedgerLocked(current);\n        }\n        recoveryLedger = IRecoveryLedger(ledger);\n        emit RecoveryLedgerSet(ledger);\n    }\n\n    function _askCurrentLedger(address ledger) private view returns (LedgerAnswer) {\n        if (ledger.code.length == 0) return LedgerAnswer.Unanswerable;\n        if (gasleft() < LEDGER_HEALTH_GAS * 64 / 63 + LEDGER_HEALTH_HEADROOM) {\n            revert InsufficientGasForHealthCheck();\n        }\n        return _askLedger(ledger);\n    }\n\n    function _askLedger(address ledger) private view returns (LedgerAnswer) {\n        bytes4 sel = IRecoveryLedger.issuanceAllowed.selector;\n        address self = address(this);\n        uint256 budget = LEDGER_HEALTH_GAS;\n        bool ok;\n        uint256 len;\n        uint256 word;\n        assembly (\"memory-safe\") {\n            let p := mload(0x40)\n            mstore(p, sel)\n            mstore(add(p, 4), self)\n            ok := staticcall(budget, ledger, p, 36, 0, 0)\n            len := returndatasize()\n            if gt(len, 31) {\n                returndatacopy(p, 0, 32)\n                word := mload(p)\n            }\n        }\n\n        if (!ok || len != 32) return LedgerAnswer.Unanswerable;\n        if (word == 0) return LedgerAnswer.Incident;\n        if (word == 1) return LedgerAnswer.Healthy;\n        return LedgerAnswer.Unanswerable;\n    }\n\n    function constituents() external view returns (address[] memory, uint256[] memory) {\n        return (_tokens, _units);\n    }\n\n    function count() external view returns (uint256) {\n        return _tokens.length;\n    }\n\n    function amountsFor(uint256 amount) public view returns (address[] memory toks, uint256[] memory amts) {\n        toks = _tokens;\n        amts = new uint256[](toks.length);\n        for (uint256 i; i < toks.length; ++i) {\n            amts[i] = Math.mulDiv(_units[i], amount, UNIT, Math.Rounding.Ceil);\n        }\n    }\n\n    function solvency()\n        external\n        view\n        returns (\n            address[] memory toks,\n            uint256[] memory held,\n            uint256[] memory required,\n            uint256[] memory shortfall,\n            bool solvent\n        )\n    {\n        toks = _tokens;\n        uint256 n = toks.length;\n        held = new uint256[](n);\n        required = new uint256[](n);\n        shortfall = new uint256[](n);\n        solvent = true;\n        uint256 supply = totalSupply();\n        for (uint256 i; i < n; ++i) {\n            held[i] = IERC20(toks[i]).balanceOf(address(this));\n            required[i] = Math.mulDiv(_units[i], supply, UNIT, Math.Rounding.Floor);\n            if (held[i] < required[i]) {\n                shortfall[i] = required[i] - held[i];\n                solvent = false;\n            }\n        }\n    }\n\n    function mint(uint256 amount, address to) external {\n        if (amount == 0) revert ZeroAmount();\n        address ledger = address(recoveryLedger);\n        if (ledger != address(0)) {\n            LedgerAnswer answer = _askLedger(ledger);\n            if (answer == LedgerAnswer.Incident) revert IssuanceHalted();\n            if (answer == LedgerAnswer.Unanswerable) revert LedgerUnanswerable(ledger);\n        }\n        (address[] memory toks, uint256[] memory amts) = amountsFor(amount);\n        for (uint256 i; i < toks.length; ++i) {\n            IERC20(toks[i]).safeTransferFrom(msg.sender, address(this), amts[i]);\n        }\n        _mint(to, amount);\n        emit Minted(msg.sender, to, amount);\n    }\n\n    function redeem(uint256 amount, address to) external {\n        _redeem(amount, to, 0);\n    }\n\n    function redeemSkipping(uint256 amount, address to, uint256 skipMask) external {\n        _redeem(amount, to, skipMask);\n    }\n\n    function _redeem(uint256 amount, address to, uint256 skipMask) internal {\n        if (amount == 0) revert ZeroAmount();\n        _burn(msg.sender, amount);\n        uint256 n = _tokens.length;\n        for (uint256 i; i < n; ++i) {\n            if (skipMask & (1 << i) != 0) continue;\n            uint256 amt = Math.mulDiv(_units[i], amount, UNIT);\n            IERC20(_tokens[i]).safeTransfer(to, amt);\n        }\n        emit Redeemed(msg.sender, to, amount, skipMask);\n    }\n}\n"},"lib/uniswap-hooks/lib/v4-core/lib/openzeppelin-contracts/contracts/utils/Context.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n    function _msgSender() internal view virtual returns (address) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        return msg.data;\n    }\n\n    function _contextSuffixLength() internal view virtual returns (uint256) {\n        return 0;\n    }\n}\n"},"lib/uniswap-hooks/lib/v4-core/src/libraries/FixedPoint128.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title FixedPoint128\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)\nlibrary FixedPoint128 {\n    uint256 internal constant Q128 = 0x100000000000000000000000000000000;\n}\n"},"lib/uniswap-hooks/lib/v4-core/src/libraries/LiquidityMath.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title Math library for liquidity\nlibrary LiquidityMath {\n    /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows\n    /// @param x The liquidity before change\n    /// @param y The delta by which liquidity should be changed\n    /// @return z The liquidity delta\n    function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {\n        assembly (\"memory-safe\") {\n            z := add(and(x, 0xffffffffffffffffffffffffffffffff), signextend(15, y))\n            if shr(128, z) {\n                // revert SafeCastOverflow()\n                mstore(0, 0x93dafdf1)\n                revert(0x1c, 0x04)\n            }\n        }\n    }\n}\n"},"lib/uniswap-hooks/lib/v4-periphery/src/base/ImmutableState.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IPoolManager} from \"@uniswap/v4-core/src/interfaces/IPoolManager.sol\";\nimport {IImmutableState} from \"../interfaces/IImmutableState.sol\";\n\n/// @title Immutable State\n/// @notice A collection of immutable state variables, commonly used across multiple contracts\ncontract ImmutableState is IImmutableState {\n    /// @inheritdoc IImmutableState\n    IPoolManager public immutable poolManager;\n\n    /// @notice Thrown when the caller is not PoolManager\n    error NotPoolManager();\n\n    /// @notice Only allow calls from the PoolManager contract\n    modifier onlyPoolManager() {\n        if (msg.sender != address(poolManager)) revert NotPoolManager();\n        _;\n    }\n\n    constructor(IPoolManager _poolManager) {\n        poolManager = _poolManager;\n    }\n}\n"},"lib/uniswap-hooks/lib/v4-core/src/libraries/LPFeeLibrary.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {CustomRevert} from \"./CustomRevert.sol\";\n\n/// @notice Library of helper functions for a pools LP fee\nlibrary LPFeeLibrary {\n    using LPFeeLibrary for uint24;\n    using CustomRevert for bytes4;\n\n    /// @notice Thrown when the static or dynamic fee on a pool exceeds 100%.\n    error LPFeeTooLarge(uint24 fee);\n\n    /// @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\n    uint24 public constant DYNAMIC_FEE_FLAG = 0x800000;\n\n    /// @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\n    // only dynamic-fee pools can return a fee via the beforeSwap hook\n    uint24 public constant OVERRIDE_FEE_FLAG = 0x400000;\n\n    /// @notice mask to remove the override fee flag from a fee returned by the beforeSwaphook\n    uint24 public constant REMOVE_OVERRIDE_MASK = 0xBFFFFF;\n\n    /// @notice the lp fee is represented in hundredths of a bip, so the max is 100%\n    uint24 public constant MAX_LP_FEE = 1000000;\n\n    /// @notice returns true if a pool's LP fee signals that the pool has a dynamic fee\n    /// @param self The fee to check\n    /// @return bool True of the fee is dynamic\n    function isDynamicFee(uint24 self) internal pure returns (bool) {\n        return self == DYNAMIC_FEE_FLAG;\n    }\n\n    /// @notice returns true if an LP fee is valid, aka not above the maximum permitted fee\n    /// @param self The fee to check\n    /// @return bool True of the fee is valid\n    function isValid(uint24 self) internal pure returns (bool) {\n        return self <= MAX_LP_FEE;\n    }\n\n    /// @notice validates whether an LP fee is larger than the maximum, and reverts if invalid\n    /// @param self The fee to validate\n    function validate(uint24 self) internal pure {\n        if (!self.isValid()) LPFeeTooLarge.selector.revertWith(self);\n    }\n\n    /// @notice gets and validates the initial LP fee for a pool. Dynamic fee pools have an initial fee of 0.\n    /// @dev if a dynamic fee pool wants a non-0 initial fee, it should call `updateDynamicLPFee` in the afterInitialize hook\n    /// @param self The fee to get the initial LP from\n    /// @return initialFee 0 if the fee is dynamic, otherwise the fee (if valid)\n    function getInitialLPFee(uint24 self) internal pure returns (uint24) {\n        // the initial fee for a dynamic fee pool is 0\n        if (self.isDynamicFee()) return 0;\n        self.validate();\n        return self;\n    }\n\n    /// @notice returns true if the fee has the override flag set (2nd highest bit of the uint24)\n    /// @param self The fee to check\n    /// @return bool True of the fee has the override flag set\n    function isOverride(uint24 self) internal pure returns (bool) {\n        return self & OVERRIDE_FEE_FLAG != 0;\n    }\n\n    /// @notice returns a fee with the override flag removed\n    /// @param self The fee to remove the override flag from\n    /// @return fee The fee without the override flag set\n    function removeOverrideFlag(uint24 self) internal pure returns (uint24) {\n        return self & REMOVE_OVERRIDE_MASK;\n    }\n\n    /// @notice Removes the override flag and validates the fee (reverts if the fee is too large)\n    /// @param self The fee to remove the override flag from, and then validate\n    /// @return fee The fee without the override flag set (if valid)\n    function removeOverrideFlagAndValidate(uint24 self) internal pure returns (uint24 fee) {\n        fee = self.removeOverrideFlag();\n        fee.validate();\n    }\n}\n"},"lib/uniswap-hooks/lib/v4-core/src/libraries/ParseBytes.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n/// @notice Parses bytes returned from hooks and the byte selector used to check return selectors from hooks.\n/// @dev parseSelector also is used to parse the expected selector\n/// For parsing hook returns, note that all hooks return either bytes4 or (bytes4, 32-byte-delta) or (bytes4, 32-byte-delta, uint24).\nlibrary ParseBytes {\n    function parseSelector(bytes memory result) internal pure returns (bytes4 selector) {\n        // equivalent: (selector,) = abi.decode(result, (bytes4, int256));\n        assembly (\"memory-safe\") {\n            selector := mload(add(result, 0x20))\n        }\n    }\n\n    function parseFee(bytes memory result) internal pure returns (uint24 lpFee) {\n        // equivalent: (,, lpFee) = abi.decode(result, (bytes4, int256, uint24));\n        assembly (\"memory-safe\") {\n            lpFee := mload(add(result, 0x60))\n        }\n    }\n\n    function parseReturnDelta(bytes memory result) internal pure returns (int256 hookReturn) {\n        // equivalent: (, hookReturnDelta) = abi.decode(result, (bytes4, int256));\n        assembly (\"memory-safe\") {\n            hookReturn := mload(add(result, 0x40))\n        }\n    }\n}\n"},"lib/uniswap-hooks/lib/v4-core/src/libraries/CurrencyReserves.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.24;\n\nimport {Currency} from \"../types/Currency.sol\";\nimport {CustomRevert} from \"./CustomRevert.sol\";\n\nlibrary CurrencyReserves {\n    using CustomRevert for bytes4;\n\n    /// bytes32(uint256(keccak256(\"ReservesOf\")) - 1)\n    bytes32 constant RESERVES_OF_SLOT = 0x1e0745a7db1623981f0b2a5d4232364c00787266eb75ad546f190e6cebe9bd95;\n    /// bytes32(uint256(keccak256(\"Currency\")) - 1)\n    bytes32 constant CURRENCY_SLOT = 0x27e098c505d44ec3574004bca052aabf76bd35004c182099d8c575fb238593b9;\n\n    function getSyncedCurrency() internal view returns (Currency currency) {\n        assembly (\"memory-safe\") {\n            currency := tload(CURRENCY_SLOT)\n        }\n    }\n\n    function resetCurrency() internal {\n        assembly (\"memory-safe\") {\n            tstore(CURRENCY_SLOT, 0)\n        }\n    }\n\n    function syncCurrencyAndReserves(Currency currency, uint256 value) internal {\n        assembly (\"memory-safe\") {\n            tstore(CURRENCY_SLOT, and(currency, 0xffffffffffffffffffffffffffffffffffffffff))\n            tstore(RESERVES_OF_SLOT, value)\n        }\n    }\n\n    function getSyncedReserves() internal view returns (uint256 value) {\n        assembly (\"memory-safe\") {\n            value := tload(RESERVES_OF_SLOT)\n        }\n    }\n}\n"},"lib/uniswap-hooks/lib/v4-core/src/libraries/NonzeroDeltaCount.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.24;\n\n/// @notice This is a temporary library that allows us to use transient storage (tstore/tload)\n/// for the nonzero delta count.\n/// TODO: This library can be deleted when we have the transient keyword support in solidity.\nlibrary NonzeroDeltaCount {\n    // The slot holding the number of nonzero deltas. bytes32(uint256(keccak256(\"NonzeroDeltaCount\")) - 1)\n    bytes32 internal constant NONZERO_DELTA_COUNT_SLOT =\n        0x7d4b3164c6e45b97e7d87b7125a44c5828d005af88f9d751cfd78729c5d99a0b;\n\n    function read() internal view returns (uint256 count) {\n        assembly (\"memory-safe\") {\n            count := tload(NONZERO_DELTA_COUNT_SLOT)\n        }\n    }\n\n    function increment() internal {\n        assembly (\"memory-safe\") {\n            let count := tload(NONZERO_DELTA_COUNT_SLOT)\n            count := add(count, 1)\n            tstore(NONZERO_DELTA_COUNT_SLOT, count)\n        }\n    }\n\n    /// @notice Potential to underflow. Ensure checks are performed by integrating contracts to ensure this does not happen.\n    /// Current usage ensures this will not happen because we call decrement with known boundaries (only up to the number of times we call increment).\n    function decrement() internal {\n        assembly (\"memory-safe\") {\n            let count := tload(NONZERO_DELTA_COUNT_SLOT)\n            count := sub(count, 1)\n            tstore(NONZERO_DELTA_COUNT_SLOT, count)\n        }\n    }\n}\n"},"lib/uniswap-hooks/lib/v4-core/src/libraries/Lock.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.24;\n\n/// @notice This is a temporary library that allows us to use transient storage (tstore/tload)\n/// TODO: This library can be deleted when we have the transient keyword support in solidity.\nlibrary Lock {\n    // The slot holding the unlocked state, transiently. bytes32(uint256(keccak256(\"Unlocked\")) - 1)\n    bytes32 internal constant IS_UNLOCKED_SLOT = 0xc090fc4683624cfc3884e9d8de5eca132f2d0ec062aff75d43c0465d5ceeab23;\n\n    function unlock() internal {\n        assembly (\"memory-safe\") {\n            // unlock\n            tstore(IS_UNLOCKED_SLOT, true)\n        }\n    }\n\n    function lock() internal {\n        assembly (\"memory-safe\") {\n            tstore(IS_UNLOCKED_SLOT, false)\n        }\n    }\n\n    function isUnlocked() internal view returns (bool unlocked) {\n        assembly (\"memory-safe\") {\n            unlocked := tload(IS_UNLOCKED_SLOT)\n        }\n    }\n}\n"},"lib/uniswap-hooks/lib/v4-core/lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"./IERC20.sol\";\nimport {IERC20Metadata} from \"./extensions/IERC20Metadata.sol\";\nimport {Context} from \"../../utils/Context.sol\";\nimport {IERC20Errors} from \"../../interfaces/draft-IERC6093.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * The default value of {decimals} is 18. To change this, you should override\n * this function so it returns a different value.\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n */\nabstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {\n    mapping(address account => uint256) private _balances;\n\n    mapping(address account => mapping(address spender => uint256)) private _allowances;\n\n    uint256 private _totalSupply;\n\n    string private _name;\n    string private _symbol;\n\n    /**\n     * @dev Sets the values for {name} and {symbol}.\n     *\n     * All two of these values are immutable: they can only be set once during\n     * construction.\n     */\n    constructor(string memory name_, string memory symbol_) {\n        _name = name_;\n        _symbol = symbol_;\n    }\n\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() public view virtual returns (string memory) {\n        return _name;\n    }\n\n    /**\n     * @dev Returns the symbol of the token, usually a shorter version of the\n     * name.\n     */\n    function symbol() public view virtual returns (string memory) {\n        return _symbol;\n    }\n\n    /**\n     * @dev Returns the number of decimals used to get its user representation.\n     * For example, if `decimals` equals `2`, a balance of `505` tokens should\n     * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n     *\n     * Tokens usually opt for a value of 18, imitating the relationship between\n     * Ether and Wei. This is the default value returned by this function, unless\n     * it's overridden.\n     *\n     * NOTE: This information is only used for _display_ purposes: it in\n     * no way affects any of the arithmetic of the contract, including\n     * {IERC20-balanceOf} and {IERC20-transfer}.\n     */\n    function decimals() public view virtual returns (uint8) {\n        return 18;\n    }\n\n    /**\n     * @dev See {IERC20-totalSupply}.\n     */\n    function totalSupply() public view virtual returns (uint256) {\n        return _totalSupply;\n    }\n\n    /**\n     * @dev See {IERC20-balanceOf}.\n     */\n    function balanceOf(address account) public view virtual returns (uint256) {\n        return _balances[account];\n    }\n\n    /**\n     * @dev See {IERC20-transfer}.\n     *\n     * Requirements:\n     *\n     * - `to` cannot be the zero address.\n     * - the caller must have a balance of at least `value`.\n     */\n    function transfer(address to, uint256 value) public virtual returns (bool) {\n        address owner = _msgSender();\n        _transfer(owner, to, value);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-allowance}.\n     */\n    function allowance(address owner, address spender) public view virtual returns (uint256) {\n        return _allowances[owner][spender];\n    }\n\n    /**\n     * @dev See {IERC20-approve}.\n     *\n     * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on\n     * `transferFrom`. This is semantically equivalent to an infinite approval.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     */\n    function approve(address spender, uint256 value) public virtual returns (bool) {\n        address owner = _msgSender();\n        _approve(owner, spender, value);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-transferFrom}.\n     *\n     * Emits an {Approval} event indicating the updated allowance. This is not\n     * required by the EIP. See the note at the beginning of {ERC20}.\n     *\n     * NOTE: Does not update the allowance if the current allowance\n     * is the maximum `uint256`.\n     *\n     * Requirements:\n     *\n     * - `from` and `to` cannot be the zero address.\n     * - `from` must have a balance of at least `value`.\n     * - the caller must have allowance for ``from``'s tokens of at least\n     * `value`.\n     */\n    function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {\n        address spender = _msgSender();\n        _spendAllowance(from, spender, value);\n        _transfer(from, to, value);\n        return true;\n    }\n\n    /**\n     * @dev Moves a `value` amount of tokens from `from` to `to`.\n     *\n     * This internal function is equivalent to {transfer}, and can be used to\n     * e.g. implement automatic token fees, slashing mechanisms, etc.\n     *\n     * Emits a {Transfer} event.\n     *\n     * NOTE: This function is not virtual, {_update} should be overridden instead.\n     */\n    function _transfer(address from, address to, uint256 value) internal {\n        if (from == address(0)) {\n            revert ERC20InvalidSender(address(0));\n        }\n        if (to == address(0)) {\n            revert ERC20InvalidReceiver(address(0));\n        }\n        _update(from, to, value);\n    }\n\n    /**\n     * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`\n     * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding\n     * this function.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _update(address from, address to, uint256 value) internal virtual {\n        if (from == address(0)) {\n            // Overflow check required: The rest of the code assumes that totalSupply never overflows\n            _totalSupply += value;\n        } else {\n            uint256 fromBalance = _balances[from];\n            if (fromBalance < value) {\n                revert ERC20InsufficientBalance(from, fromBalance, value);\n            }\n            unchecked {\n                // Overflow not possible: value <= fromBalance <= totalSupply.\n                _balances[from] = fromBalance - value;\n            }\n        }\n\n        if (to == address(0)) {\n            unchecked {\n                // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.\n                _totalSupply -= value;\n            }\n        } else {\n            unchecked {\n                // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.\n                _balances[to] += value;\n            }\n        }\n\n        emit Transfer(from, to, value);\n    }\n\n    /**\n     * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).\n     * Relies on the `_update` mechanism\n     *\n     * Emits a {Transfer} event with `from` set to the zero address.\n     *\n     * NOTE: This function is not virtual, {_update} should be overridden instead.\n     */\n    function _mint(address account, uint256 value) internal {\n        if (account == address(0)) {\n            revert ERC20InvalidReceiver(address(0));\n        }\n        _update(address(0), account, value);\n    }\n\n    /**\n     * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.\n     * Relies on the `_update` mechanism.\n     *\n     * Emits a {Transfer} event with `to` set to the zero address.\n     *\n     * NOTE: This function is not virtual, {_update} should be overridden instead\n     */\n    function _burn(address account, uint256 value) internal {\n        if (account == address(0)) {\n            revert ERC20InvalidSender(address(0));\n        }\n        _update(account, address(0), value);\n    }\n\n    /**\n     * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.\n     *\n     * This internal function is equivalent to `approve`, and can be used to\n     * e.g. set automatic allowances for certain subsystems, etc.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `owner` cannot be the zero address.\n     * - `spender` cannot be the zero address.\n     *\n     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.\n     */\n    function _approve(address owner, address spender, uint256 value) internal {\n        _approve(owner, spender, value, true);\n    }\n\n    /**\n     * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.\n     *\n     * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by\n     * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any\n     * `Approval` event during `transferFrom` operations.\n     *\n     * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to\n     * true using the following override:\n     * ```\n     * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {\n     *     super._approve(owner, spender, value, true);\n     * }\n     * ```\n     *\n     * Requirements are the same as {_approve}.\n     */\n    function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {\n        if (owner == address(0)) {\n            revert ERC20InvalidApprover(address(0));\n        }\n        if (spender == address(0)) {\n            revert ERC20InvalidSpender(address(0));\n        }\n        _allowances[owner][spender] = value;\n        if (emitEvent) {\n            emit Approval(owner, spender, value);\n        }\n    }\n\n    /**\n     * @dev Updates `owner` s allowance for `spender` based on spent `value`.\n     *\n     * Does not update the allowance value in case of infinite allowance.\n     * Revert if not enough allowance is available.\n     *\n     * Does not emit an {Approval} event.\n     */\n    function _spendAllowance(address owner, address spender, uint256 value) internal virtual {\n        uint256 currentAllowance = allowance(owner, spender);\n        if (currentAllowance != type(uint256).max) {\n            if (currentAllowance < value) {\n                revert ERC20InsufficientAllowance(spender, currentAllowance, value);\n            }\n            unchecked {\n                _approve(owner, spender, currentAllowance - value, false);\n            }\n        }\n    }\n}\n"},"src/IRecoveryLedger.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.26;\n\ninterface IRecoveryLedger {\n    enum Phase {\n        Healthy,\n        Impaired,\n        Recovery\n    }\n\n    function phaseOf(address basket) external view returns (Phase);\n\n    function issuanceAllowed(address basket) external view returns (bool);\n\n    function impairedMask(address basket) external view returns (uint256);\n}\n"},"lib/uniswap-hooks/lib/v4-periphery/src/interfaces/IImmutableState.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IPoolManager} from \"@uniswap/v4-core/src/interfaces/IPoolManager.sol\";\n\n/// @title IImmutableState\n/// @notice Interface for the ImmutableState contract\ninterface IImmutableState {\n    /// @notice The Uniswap v4 PoolManager contract\n    function poolManager() external view returns (IPoolManager);\n}\n"},"lib/uniswap-hooks/lib/v4-core/src/libraries/TickBitmap.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {BitMath} from \"./BitMath.sol\";\n\n/// @title Packed tick initialized state library\n/// @notice Stores a packed mapping of tick index to its initialized state\n/// @dev The mapping uses int16 for keys since ticks are represented as int24 and there are 256 (2^8) values per word.\nlibrary TickBitmap {\n    /// @notice Thrown when the tick is not enumerated by the tick spacing\n    /// @param tick the invalid tick\n    /// @param tickSpacing The tick spacing of the pool\n    error TickMisaligned(int24 tick, int24 tickSpacing);\n\n    /// @dev round towards negative infinity\n    function compress(int24 tick, int24 tickSpacing) internal pure returns (int24 compressed) {\n        // compressed = tick / tickSpacing;\n        // if (tick < 0 && tick % tickSpacing != 0) compressed--;\n        assembly (\"memory-safe\") {\n            tick := signextend(2, tick)\n            tickSpacing := signextend(2, tickSpacing)\n            compressed :=\n                sub(\n                    sdiv(tick, tickSpacing),\n                    // if (tick < 0 && tick % tickSpacing != 0) then tick % tickSpacing < 0, vice versa\n                    slt(smod(tick, tickSpacing), 0)\n                )\n        }\n    }\n\n    /// @notice Computes the position in the mapping where the initialized bit for a tick lives\n    /// @param tick The tick for which to compute the position\n    /// @return wordPos The key in the mapping containing the word in which the bit is stored\n    /// @return bitPos The bit position in the word where the flag is stored\n    function position(int24 tick) internal pure returns (int16 wordPos, uint8 bitPos) {\n        assembly (\"memory-safe\") {\n            // signed arithmetic shift right\n            wordPos := sar(8, signextend(2, tick))\n            bitPos := and(tick, 0xff)\n        }\n    }\n\n    /// @notice Flips the initialized state for a given tick from false to true, or vice versa\n    /// @param self The mapping in which to flip the tick\n    /// @param tick The tick to flip\n    /// @param tickSpacing The spacing between usable ticks\n    function flipTick(mapping(int16 => uint256) storage self, int24 tick, int24 tickSpacing) internal {\n        // Equivalent to the following Solidity:\n        //     if (tick % tickSpacing != 0) revert TickMisaligned(tick, tickSpacing);\n        //     (int16 wordPos, uint8 bitPos) = position(tick / tickSpacing);\n        //     uint256 mask = 1 << bitPos;\n        //     self[wordPos] ^= mask;\n        assembly (\"memory-safe\") {\n            tick := signextend(2, tick)\n            tickSpacing := signextend(2, tickSpacing)\n            // ensure that the tick is spaced\n            if smod(tick, tickSpacing) {\n                let fmp := mload(0x40)\n                mstore(fmp, 0xd4d8f3e6) // selector for TickMisaligned(int24,int24)\n                mstore(add(fmp, 0x20), tick)\n                mstore(add(fmp, 0x40), tickSpacing)\n                revert(add(fmp, 0x1c), 0x44)\n            }\n            tick := sdiv(tick, tickSpacing)\n            // calculate the storage slot corresponding to the tick\n            // wordPos = tick >> 8\n            mstore(0, sar(8, tick))\n            mstore(0x20, self.slot)\n            // the slot of self[wordPos] is keccak256(abi.encode(wordPos, self.slot))\n            let slot := keccak256(0, 0x40)\n            // mask = 1 << bitPos = 1 << (tick % 256)\n            // self[wordPos] ^= mask\n            sstore(slot, xor(sload(slot), shl(and(tick, 0xff), 1)))\n        }\n    }\n\n    /// @notice Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is either\n    /// to the left (less than or equal to) or right (greater than) of the given tick\n    /// @param self The mapping in which to compute the next initialized tick\n    /// @param tick The starting tick\n    /// @param tickSpacing The spacing between usable ticks\n    /// @param lte Whether to search for the next initialized tick to the left (less than or equal to the starting tick)\n    /// @return next The next initialized or uninitialized tick up to 256 ticks away from the current tick\n    /// @return initialized Whether the next tick is initialized, as the function only searches within up to 256 ticks\n    function nextInitializedTickWithinOneWord(\n        mapping(int16 => uint256) storage self,\n        int24 tick,\n        int24 tickSpacing,\n        bool lte\n    ) internal view returns (int24 next, bool initialized) {\n        unchecked {\n            int24 compressed = compress(tick, tickSpacing);\n\n            if (lte) {\n                (int16 wordPos, uint8 bitPos) = position(compressed);\n                // all the 1s at or to the right of the current bitPos\n                uint256 mask = type(uint256).max >> (uint256(type(uint8).max) - bitPos);\n                uint256 masked = self[wordPos] & mask;\n\n                // if there are no initialized ticks to the right of or at the current tick, return rightmost in the word\n                initialized = masked != 0;\n                // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick\n                next = initialized\n                    ? (compressed - int24(uint24(bitPos - BitMath.mostSignificantBit(masked)))) * tickSpacing\n                    : (compressed - int24(uint24(bitPos))) * tickSpacing;\n            } else {\n                // start from the word of the next tick, since the current tick state doesn't matter\n                (int16 wordPos, uint8 bitPos) = position(++compressed);\n                // all the 1s at or to the left of the bitPos\n                uint256 mask = ~((1 << bitPos) - 1);\n                uint256 masked = self[wordPos] & mask;\n\n                // if there are no initialized ticks to the left of the current tick, return leftmost in the word\n                initialized = masked != 0;\n                // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick\n                next = initialized\n                    ? (compressed + int24(uint24(BitMath.leastSignificantBit(masked) - bitPos))) * tickSpacing\n                    : (compressed + int24(uint24(type(uint8).max - bitPos))) * tickSpacing;\n            }\n        }\n    }\n}\n"},"lib/uniswap-hooks/lib/v4-core/lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)\npragma solidity ^0.8.20;\n\n/**\n * @dev Standard ERC20 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.\n */\ninterface IERC20Errors {\n    /**\n     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     * @param balance Current balance for the interacting account.\n     * @param needed Minimum amount required to perform a transfer.\n     */\n    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);\n\n    /**\n     * @dev Indicates a failure with the token `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     */\n    error ERC20InvalidSender(address sender);\n\n    /**\n     * @dev Indicates a failure with the token `receiver`. Used in transfers.\n     * @param receiver Address to which tokens are being transferred.\n     */\n    error ERC20InvalidReceiver(address receiver);\n\n    /**\n     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.\n     * @param spender Address that may be allowed to operate on tokens without being their owner.\n     * @param allowance Amount of tokens a `spender` is allowed to operate with.\n     * @param needed Minimum amount required to perform a transfer.\n     */\n    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);\n\n    /**\n     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n     * @param approver Address initiating an approval operation.\n     */\n    error ERC20InvalidApprover(address approver);\n\n    /**\n     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.\n     * @param spender Address that may be allowed to operate on tokens without being their owner.\n     */\n    error ERC20InvalidSpender(address spender);\n}\n\n/**\n * @dev Standard ERC721 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.\n */\ninterface IERC721Errors {\n    /**\n     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.\n     * Used in balance queries.\n     * @param owner Address of the current owner of a token.\n     */\n    error ERC721InvalidOwner(address owner);\n\n    /**\n     * @dev Indicates a `tokenId` whose `owner` is the zero address.\n     * @param tokenId Identifier number of a token.\n     */\n    error ERC721NonexistentToken(uint256 tokenId);\n\n    /**\n     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     * @param tokenId Identifier number of a token.\n     * @param owner Address of the current owner of a token.\n     */\n    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);\n\n    /**\n     * @dev Indicates a failure with the token `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     */\n    error ERC721InvalidSender(address sender);\n\n    /**\n     * @dev Indicates a failure with the token `receiver`. Used in transfers.\n     * @param receiver Address to which tokens are being transferred.\n     */\n    error ERC721InvalidReceiver(address receiver);\n\n    /**\n     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     * @param tokenId Identifier number of a token.\n     */\n    error ERC721InsufficientApproval(address operator, uint256 tokenId);\n\n    /**\n     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n     * @param approver Address initiating an approval operation.\n     */\n    error ERC721InvalidApprover(address approver);\n\n    /**\n     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     */\n    error ERC721InvalidOperator(address operator);\n}\n\n/**\n * @dev Standard ERC1155 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.\n */\ninterface IERC1155Errors {\n    /**\n     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     * @param balance Current balance for the interacting account.\n     * @param needed Minimum amount required to perform a transfer.\n     * @param tokenId Identifier number of a token.\n     */\n    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);\n\n    /**\n     * @dev Indicates a failure with the token `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     */\n    error ERC1155InvalidSender(address sender);\n\n    /**\n     * @dev Indicates a failure with the token `receiver`. Used in transfers.\n     * @param receiver Address to which tokens are being transferred.\n     */\n    error ERC1155InvalidReceiver(address receiver);\n\n    /**\n     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     * @param owner Address of the current owner of a token.\n     */\n    error ERC1155MissingApprovalForAll(address operator, address owner);\n\n    /**\n     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n     * @param approver Address initiating an approval operation.\n     */\n    error ERC1155InvalidApprover(address approver);\n\n    /**\n     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     */\n    error ERC1155InvalidOperator(address operator);\n\n    /**\n     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.\n     * Used in batch transfers.\n     * @param idsLength Length of the array of token identifiers\n     * @param valuesLength Length of the array of token amounts\n     */\n    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);\n}\n"}},"compilation":{"language":"Solidity","compiler":"solc","compilerVersion":"0.8.26+commit.8a97fa7a","compilerSettings":{"viaIR":false,"metadata":{"appendCBOR":true,"bytecodeHash":"ipfs","useLiteralContent":false},"libraries":{},"optimizer":{"runs":200,"enabled":true},"evmVersion":"cancun","remappings":["forge-std/=lib/forge-std/src/","@uniswap/v4-core/=lib/uniswap-hooks/lib/v4-core/","@uniswap/v4-periphery/=lib/uniswap-hooks/lib/v4-periphery/","v4-core/=lib/uniswap-hooks/lib/v4-core/","v4-periphery/=lib/uniswap-hooks/lib/v4-periphery/","@openzeppelin/uniswap-hooks/=lib/uniswap-hooks/","@openzeppelin/contracts/=lib/uniswap-hooks/lib/v4-core/lib/openzeppelin-contracts/contracts/","hookmate/=lib/hookmate/src/","permit2/=lib/uniswap-hooks/lib/v4-periphery/lib/permit2/","solmate/=lib/uniswap-hooks/lib/v4-core/lib/solmate/"]},"name":"NavJitSharedStandingManager","fullyQualifiedName":"src/NavJitSharedStandingManager.sol:NavJitSharedStandingManager"},"matchId":"55948484","creationMatch":"exact_match","runtimeMatch":"exact_match","verifiedAt":"2026-10-11T22:45:55Z","match":"exact_match","chainId":"4663","address":"0xb2c17EE01563Af795e2494952f6C8f2b1D3d1b51"}