Перейти к содержимому
Проверенный контрактЧастичноеBUSL-1.1

V3Vault

Адрес0xfecf287390838fbe1b5449ab2ff50087f68fd2d4
Баланс

0 ETH

 

Транзакций

1

 

Компилятор

solc 0.8.28

 

Тот же код

Только этот контракт

 

Подробности

Компилятор
solc 0.8.28+commit.7893614a
Язык
solidity
Оптимизация
Да, 1 прогонов
Версия EVM
cancun
Через IR
да
Лицензия
BUSL-1.1
Совпадение
Частичноекод создания: да, код в сети: да
Проверен на Sourcify
Создан в блоке
26 423 240
Транзакция создания
0x89536c4996…7493ac62a6
Библиотеки
project/contracts/vaults/libraries/ShapeMath.sol:ShapeMath0x9b33…619edbproject/contracts/vaults/libraries/V3SwapLogic.sol:V3SwapLogic0x8b97…0c21edproject/contracts/vaults/libraries/BaseLimitMath.sol:BaseLimitMath0xb120…91b7e7project/contracts/vaults/libraries/VaultExitLogic.sol:VaultExitLogic0xd1ae…eb6b71project/contracts/vaults/libraries/V3PositionLogic.sol:V3PositionLogic0xabfa…dc004d

42 файла

project/contracts/vaults/V3Vault.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;

import "./VaultCore.sol";
import "../interfaces/IUniswapV3Minimal.sol";
import "./interfaces/IV3Vault.sol";
import "./libraries/LiquidityAmounts.sol";
import "./libraries/BaseLimitMath.sol";
import "./libraries/V3PositionLogic.sol";
import "./libraries/V3SwapLogic.sol";

/// @title V3Vault (pool-direct base+limit)
/// @notice An active liquidity manager over one Uniswap V3 pool, holding a two-sided `base` straddling spot.
contract V3Vault is VaultCore, IV3Vault {
    using SafeERC20 for IERC20;

    /// @dev At most three positions ever exist: base + limit + the full-range floor.
    uint256 public constant MAX_RANGES = 3;

    /// @dev A freshly created V3 pool holds ONE oracle observation - too shallow for ClearingV3's TWAP deviation gate
    ///      to read.
    uint16 internal immutable INITIAL_OBSERVATION_CARDINALITY;
    /// @dev The most observation slots vault creation grows (see `INITIAL_OBSERVATION_CARDINALITY`).
    uint256 internal constant MAX_CREATION_OBSERVATIONS = 256;

    /// @dev Trailing window the fresh-limit placement centers on (30 min).
    uint32 internal constant LIMIT_TWAP_WINDOW = 1800;

    address public pool;
    uint24 public fee;

    /// @notice The base+limit width dials, in ticks (multiples of the pool's tick spacing).
    int24 public baseThreshold;
    int24 public limitThreshold;

    bool public swapToRatioOff;
    uint16 internal _swapCapBps;      // 0 = DEFAULT_SWAP_CAP_BPS
    uint16 internal _swapSlippageBps; // 0 = DEFAULT_SWAP_SLIPPAGE_BPS; the per-vault override
    /// The full-range floor's share of value (packs beside `_swapSlippageBps`); 0 = DEFAULT_FULL_RANGE_BPS.
    uint16 internal _fullRangeBps;
    uint16 internal constant DEFAULT_SWAP_CAP_BPS = 2_500;
    /// The floor on the cap is the library's MIN_SWAP_BPS: a cap under it could never plan a swap the
    /// minimum would then skip, disabling the swap silently.
    uint16 internal constant MIN_SWAP_CAP_BPS = 200;
    uint16 internal constant MAX_SWAP_CAP_BPS = 5_000;
    uint16 internal constant DEFAULT_SWAP_SLIPPAGE_BPS = 150;
    uint16 internal constant MIN_SWAP_SLIPPAGE_BPS = 25;
    uint16 internal constant MAX_SWAP_SLIPPAGE_BPS = 300;
    uint16 internal constant DEFAULT_FULL_RANGE_BPS = 300;
    uint16 internal constant MIN_FULL_RANGE_BPS = 100;
    uint16 internal constant MAX_FULL_RANGE_BPS = 500;

    event SwapToRatioSet(bool enabled, uint16 capBps, uint16 slippageBps);
    event FullRangeBpsSet(uint16 bps);
    error BadSwapToRatioConfig();
    error BadFullRangeBps();

    /// @dev Two-layer `uniswapV3MintCallback` guard.
    bool transient _mintCalled;
    /// Rebalance-swap state for the guard, this transaction only: the recentre's swap (1 swap-to-ratio, 2 a fold
    /// slice), and whether a planned swap-to-ratio failed.
    uint8 transient _swapMode;
    bool transient _swapPlannedFailed;

    error NotPool();
    error UnexpectedMintCallback();
    error NotSelf();
    error PoolNotInitialized();
    error CenterNearTickBound();
    error DuplicateRange();
    error BadFloorRange();

    /// @custom:oz-upgrades-unsafe-allow constructor state-variable-immutable
    constructor(uint32 secondsPerBlock_) {
        if (secondsPerBlock_ == 0 || secondsPerBlock_ > 15) revert BadSecondsPerBlock();
        uint256 need = (DEFAULT_TWAP_WINDOW + secondsPerBlock_ - 1) / secondsPerBlock_ + 1;
        INITIAL_OBSERVATION_CARDINALITY = uint16(need < MAX_CREATION_OBSERVATIONS ? need : MAX_CREATION_OBSERVATIONS);
        _disableInitializers();
    }

    /// @param baseThreshold_ base half-width in ticks (multiple of tickSpacing, > 0)
    /// @param limitThreshold_ limit width in ticks (multiple of tickSpacing, > 0)
    function initialize(
        address pool_,
        address genesis_,
        int24 baseThreshold_,
        int24 limitThreshold_,
        string memory name_,
        string memory symbol_
    ) external initializer {
        if (pool_ == address(0)) revert ZeroAddress();
        pool = pool_;
        fee = IUniswapV3PoolState(pool_).fee();
        _setBaseLimit(baseThreshold_, limitThreshold_);

        // Seed the initial base+limit around the pool's CURRENT spot tick.
        (uint160 sqrtPriceX96, int24 tick,,,,,) = IUniswapV3PoolState(pool_).slot0();
        if (sqrtPriceX96 == 0) revert PoolNotInitialized();
        IUniswapV3PoolState(pool_).increaseObservationCardinalityNext(INITIAL_OBSERVATION_CARDINALITY);

        __VaultCore_init(
            IUniswapV3PoolState(pool_).token0(),
            IUniswapV3PoolState(pool_).token1(),
            genesis_,
            _baseLimitRanges(tick),
            name_,
            symbol_
        );
    }

    function _maxRanges() internal pure override returns (uint256) {
        return MAX_RANGES;
    }

    /// @dev Re-declared to resolve the IV3Vault/VaultCore diamond at this level, forwarding upward.
    function totalSupply() public view override(IVaultCore, VaultCore) returns (uint256) {
        return super.totalSupply();
    }

    /// @dev Pool-direct positions are the state (read live off `pool.positions`), so there is no parallel per-range
    ///      array to reset.
    function _onRangesReset() internal override {
        uint8 bad = V3PositionLogic.validateRanges(_ranges);
        if (bad == 1) revert DuplicateRange();
        if (bad == 2) revert BadFloorRange();
    }

    /// @notice Set the base and limit widths (riskAdmin; narrowing either needs genesis); applied at the next recenter.
    function setBaseLimitConfig(int24 baseThreshold_, int24 limitThreshold_) external onlyRiskAdmin {
        // A narrower limit also narrows the idle signal's band, which can open recentres: genesis only.
        if ((baseThreshold_ < baseThreshold || limitThreshold_ < limitThreshold) && msg.sender != genesis) {
            revert NotGenesis();
        }
        _setBaseLimit(baseThreshold_, limitThreshold_);
    }

    function _setBaseLimit(int24 baseThreshold_, int24 limitThreshold_) internal {
        int24 spacing = IUniswapV3PoolState(pool).tickSpacing();
        if (
            baseThreshold_ <= 0 || limitThreshold_ <= 0 || baseThreshold_ % spacing != 0
                || limitThreshold_ % spacing != 0
        ) revert BaseLimitMath.BadThreshold();
        baseThreshold = baseThreshold_;
        limitThreshold = limitThreshold_;
    }

    /// @dev The base+limit ranges centered on `centerTick`: `[base, provisional-ask]`.
    function _baseLimitRanges(int24 centerTick) internal view returns (Range[] memory) {
        return BaseLimitMath.baseLimitRanges(centerTick, _tickSpacing(), baseThreshold, limitThreshold);
    }

    /// @notice The full-range floor's share of value, bps. Default 3%, bounded [1%, 5%].
    function fullRangeBps() public view returns (uint16) {
        return _fullRangeBps == 0 ? DEFAULT_FULL_RANGE_BPS : _fullRangeBps;
    }

    /// @notice Set the floor's share.
    function setFullRangeBps(uint16 bps) external onlyRiskAdmin {
        if (bps < MIN_FULL_RANGE_BPS || bps > MAX_FULL_RANGE_BPS) revert BadFullRangeBps();
        if (bps < fullRangeBps() && msg.sender != genesis) revert NotGenesis();
        _fullRangeBps = bps;
        emit FullRangeBpsSet(bps);
    }

    /// @dev A centre within one base-width (plus a spacing) of the tick bound is REFUSED, by name.
    function _buildOptimalRanges(int24 centerTick) internal view override returns (Range[] memory) {
        if (baseThreshold == 0) revert NoShapeConfigured();
        // The margin is "one base-width" CAPPED at 100 spacings, in int256: a full-range base (baseThreshold ~ 2x the
        // band) would otherwise trip this at every centre, and the sum could leave int24.
        if (V3PositionLogic.centerNearBound(centerTick, baseThreshold, _tickSpacing())) revert CenterNearTickBound();
        return _baseLimitRanges(centerTick);
    }

    /// @notice The rebalance-swap dials: enabled, the cap (bps of vault value) and the slippage beyond the pool fee.
    function swapToRatioConfig() public view returns (bool enabled, uint16 capBps, uint16 slippageBps) {
        enabled = !swapToRatioOff;
        capBps = _swapCapBps == 0 ? DEFAULT_SWAP_CAP_BPS : _swapCapBps;
        slippageBps = _swapSlippageBps == 0 ? DEFAULT_SWAP_SLIPPAGE_BPS : _swapSlippageBps;
    }

    /// @notice Set the rebalance-swap dials (riskAdmin, within bounds; loosening any of them needs genesis).
    function setSwapToRatio(bool enabled, uint16 capBps, uint16 slippageBps) external onlyRiskAdmin {
        if (
            capBps < MIN_SWAP_CAP_BPS || capBps > MAX_SWAP_CAP_BPS || slippageBps < MIN_SWAP_SLIPPAGE_BPS
                || slippageBps > MAX_SWAP_SLIPPAGE_BPS
        ) revert BadSwapToRatioConfig();
        (bool wasOn, uint16 oldCap, uint16 oldSlip) = swapToRatioConfig();
        if (msg.sender != genesis && ((enabled && !wasOn) || capBps > oldCap || slippageBps > oldSlip)) {
            revert NotGenesis();
        }
        swapToRatioOff = !enabled;
        _swapCapBps = capBps;
        _swapSlippageBps = slippageBps;
        emit SwapToRatioSet(enabled, capBps, slippageBps);
    }

    /// @notice Set the fold slice (bps of value, 0 = off), the target limit share and the balanced-zap budget per hour.
    function setSlices(uint16 foldSliceBps, uint16 foldTargetBps, uint16 zapBalanceBps) external onlyRiskAdmin {
        V3SwapLogic.setSlices(foldSliceBps, foldTargetBps, zapBalanceBps, msg.sender == genesis);
    }

    /// @notice Share (bps) of vault value in productive liquidity at the TWAP - the idle-value signal
    ///         `RebalanceGuard` and the keeper trigger a recenter on. See the library body.
    function productiveShareBps() external view returns (uint256) {
        return V3PositionLogic.productiveShareBps(_ranges, pool, clearing, limitThreshold);
    }

    /// @notice True, within the transaction of a rebalance, when a swap was planned and did not execute (the router
    ///         could not fill the TWAP floor, answered with nothing, or filled short of it).
    function lastSwapFailed() external view returns (bool) {
        return _swapPlannedFailed;
    }

    /// @dev Before the fresh base+limit deploy, sell a capped slice of the surplus token toward the base's ratio so the
    ///      base is FUNDED after a one-way move.
    function _swapToRatioBeforeDeploy(bool optimal) internal override {
        if (!optimal || _swapMode != 1) return;
        (bool enabled, uint16 capBps, uint16 slippageBps) = swapToRatioConfig();
        if (!enabled || swapRouter == address(0)) return;
        (uint256 amountIn,, bool planned) =
            V3SwapLogic.swapToRatio(_ranges, capBps, slippageBps);
        if (planned && amountIn == 0) _swapPlannedFailed = true;
    }

    /// @notice Everything a share is a claim on: each position's liquidity valued at spot plus its
    ///         last-poked `tokensOwed`, read straight off the pool, plus idle and parked inventory.
    function getTotalAmounts() public view override(IVaultCore, VaultCore) returns (uint256 amount0, uint256 amount1) {
        return _totalAmountsAt(_sqrtPriceX96()); // at spot
    }

    function _depositQuote(uint160 sqrtTwap) internal override returns (uint256, uint256, uint256) {
        return V3PositionLogic.depositQuote(_ranges, pool, _token0, _token1, lendingPool, sqrtTwap);
    }

    function _quotedShares(uint256 amount0, uint256 amount1, uint256 supply, uint256 virtualAssets) internal view override returns (uint256) {
        return V3PositionLogic.quotedShares(amount0, amount1, supply, virtualAssets);
    }

    /// @dev Ranges valued at `sqrtPriceX96` (spot for getTotalAmounts, TWAP for _twapNav's floor); uncollected fees,
    ///      idle balances and parked inventory are price-independent.
    function _totalAmountsAt(uint160 sqrtPriceX96) internal view override returns (uint256 amount0, uint256 amount1) {
        return V3PositionLogic.totalAmountsAt(_ranges, pool, _token0, _token1, lendingPool, sqrtPriceX96);
    }

    function _checkRehypo(address newPool, bool enabled, uint16 floorBps, uint16 capBps) internal view override {
        V3PositionLogic.checkRehypo(lendingPool, newPool, enabled, floorBps, capBps, _token0, _token1);
    }

    function _checkFactories(address fm, address ledger) internal view override {
        V3PositionLogic.checkFactories(fm, ledger);
    }

    function _requirePausedRealiser(address ledger, address caller) internal view override {
        V3PositionLogic.requirePausedRealiser(ledger, caller);
    }

    /// @notice `VaultCore`'s `unrealisedFees` (see its note there).
    function unrealisedFees() external view returns (uint256, uint256, uint256, uint256) {
        return V3PositionLogic.unrealisedFees(_ranges, pool);
    }

    function _beforeShareUpdate(address accountant, address ledger, address from, address to, uint256 value) internal override {
        V3PositionLogic.beforeShareUpdate(accountant, ledger, from, to, value);
    }

    function _reclaimAllInventory() internal override {
        if (lendingPool != address(0)) V3PositionLogic.reclaimAll(lendingPool, _token0, _token1);
    }

    function _parkExcessInventory() internal override {
        if (rehypoEnabled) V3PositionLogic.parkExcess(lendingPool, _token0, _token1, rehypoFloorBps, rehypoCapBps);
    }

    function _spotPrice() internal view override returns (uint256) {
        return PriceLib.priceFromSqrt(_sqrtPriceX96());
    }

    function _sqrtPriceX96() internal view returns (uint160 sqrtPriceX96) {
        (sqrtPriceX96,,,,,,) = IUniswapV3PoolState(pool).slot0();
    }

    function _tickSpacing() internal view override returns (int24) {
        return IUniswapV3PoolState(pool).tickSpacing();
    }

    function _spotAndTwapTick(uint32 window) internal view override returns (int24, int24, bool) {
        return V3PositionLogic.spotAndTwapTick(pool, window);
    }

    /// @notice Single-token deposit: swaps part of `tokenIn` toward the vault's mix, then deposits both sides.
    function zapDeposit(address tokenIn, uint256 amountIn, uint256 slippageBps, address to, uint256 minShares)
        external
        nonReentrant
        returns (uint256 shares)
    {
        if (depositsPaused || globalPause) revert DepositsArePaused();
        if (amountIn == 0) revert ZeroAmounts();
        if (clearing == address(0)) revert NoClearing();
        if (swapRouter == address(0)) revert NoSwapRouter();
        bool tokenInIsToken0 = tokenIn == address(_token0);
        if (!tokenInIsToken0 && tokenIn != address(_token1)) revert InvalidZapToken();

        _realiseFeesAndRoute();

        // The vault, the deposit, the swap sizing and its slippage floor are all valued at the TWAP.
        (uint256 twapPrice, uint256 existing0, uint256 existing1) = _snapshotExistingValue();
        bool untraded = _untradedNow(); // before the zap's own swap stamps the block

        // The pull, the sizing, the swap (the depositor's TWAP floor, re-checked on the delivered amount) and the
        // measured, saturating deltas: all in V3SwapLogic for bytecode.
        (uint256 amount0, uint256 amount1) = V3SwapLogic.zapIn(
            _ranges, tokenInIsToken0, amountIn, existing0, existing1, twapPrice, slippageBps, untraded
        );

        _clearZap(untraded, amount0, amount1);

        shares = _creditDeposit(amount0, amount1, to, minShares);
        emit Deposit(msg.sender, to, shares, amount0, amount1);
    }

    /// @dev Pokes every position (zero-liquidity `burn`) to realise its fees, then collects them into a real balance.
    function _realiseAndCollectAll() internal override returns (uint256 fee0, uint256 fee1) {
        return V3PositionLogic.realiseAndCollectAll(_ranges, pool);
    }

    /// @dev Deploys the vault's entire idle balance as base + limit.
    function _deployIdleCapital() internal override {
        V3PositionLogic.deployIdleCapital(
            _ranges, pool, _token0, _token1, baseThreshold, limitThreshold, LIMIT_TWAP_WINDOW, fullRangeBps()
        );
    }

    /// @dev Burns a pro-rata slice of every position, pays the principal and the idle share to `to`, and returns the
    ///      fees the burn realised.
    function _withdrawProRata(uint256 shares, uint256 supply, address to)
        internal
        override
        returns (uint256 amount0, uint256 amount1, uint256 fee0, uint256 fee1)
    {
        return V3PositionLogic.withdrawProRata(_ranges, pool, _token0, _token1, shares, supply, to);
    }

    /// @dev Full unwind of every position (used by `rebalance` only).
    function _unwindAll() internal override returns (uint256 fee0, uint256 fee1) {
        uint8 mode;
        // A fold slice runs on the optimal path only, with the base still in the pool.
        (mode, fee0, fee1) = V3SwapLogic.unwind(
            _ranges,
            V3PositionLogic.recenterNeeded(_ranges, pool, clearing, limitThreshold, rebalanceGuard),
            msg.sig == this.rebalanceOptimal.selector
        );
        _swapMode = mode;
        _swapPlannedFailed = false;
    }

    /// @notice Mint a position, arming the transient callback guard.
    function mintPosition(int24 tickLower, int24 tickUpper, uint128 liquidity) external {
        if (msg.sender != address(this)) revert NotSelf();
        // Arm the transient guard, then mint.
        _mintCalled = true;
        IUniswapV3PoolActions(pool).mint(address(this), tickLower, tickUpper, liquidity, "");
    }

    /// @notice Uniswap V3 mint callback - the pool calls this during `pool.mint` to pull the owed tokens.
    function uniswapV3MintCallback(uint256 amount0Owed, uint256 amount1Owed, bytes calldata) external {
        if (msg.sender != pool) revert NotPool();
        if (!_mintCalled) revert UnexpectedMintCallback();
        _mintCalled = false;
        if (amount0Owed > 0) _token0.safeTransfer(pool, amount0Owed);
        if (amount1Owed > 0) _token1.safeTransfer(pool, amount1Owed);
    }

    /// Reserved storage slots for future upgrades - same convention every other upgradeable contract in this codebase
    /// uses. 49 = 50 minus the slot `_swapSlippageBps` occupies.
    uint256[49] private __gap;
}

npm/@openzeppelin/[email protected]/proxy/utils/Initializable.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";

npm/@openzeppelin/[email protected]/token/ERC20/ERC20Upgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {ContextUpgradeable} from "../../utils/ContextUpgradeable.sol";
import {IERC20Errors} from "@openzeppelin/contracts/interfaces/draft-IERC6093.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC-20
 * applications.
 */
abstract contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20, IERC20Metadata, IERC20Errors {
    /// @custom:storage-location erc7201:openzeppelin.storage.ERC20
    struct ERC20Storage {
        mapping(address account => uint256) _balances;

        mapping(address account => mapping(address spender => uint256)) _allowances;

        uint256 _totalSupply;

        string _name;
        string _symbol;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC20")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant ERC20StorageLocation = 0x52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00;

    function _getERC20Storage() private pure returns (ERC20Storage storage $) {
        assembly {
            $.slot := ERC20StorageLocation
        }
    }

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * Both values are immutable: they can only be set once during construction.
     */
    function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
        __ERC20_init_unchained(name_, symbol_);
    }

    function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
        ERC20Storage storage $ = _getERC20Storage();
        $._name = name_;
        $._symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual returns (string memory) {
        ERC20Storage storage $ = _getERC20Storage();
        return $._name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual returns (string memory) {
        ERC20Storage storage $ = _getERC20Storage();
        return $._symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the default value returned by this function, unless
     * it's overridden.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual returns (uint8) {
        return 18;
    }

    /// @inheritdoc IERC20
    function totalSupply() public view virtual returns (uint256) {
        ERC20Storage storage $ = _getERC20Storage();
        return $._totalSupply;
    }

    /// @inheritdoc IERC20
    function balanceOf(address account) public view virtual returns (uint256) {
        ERC20Storage storage $ = _getERC20Storage();
        return $._balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `value`.
     */
    function transfer(address to, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, value);
        return true;
    }

    /// @inheritdoc IERC20
    function allowance(address owner, address spender) public view virtual returns (uint256) {
        ERC20Storage storage $ = _getERC20Storage();
        return $._allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, value);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Skips emitting an {Approval} event indicating an allowance update. This is not
     * required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `value`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `value`.
     */
    function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, value);
        _transfer(from, to, value);
        return true;
    }

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _transfer(address from, address to, uint256 value) internal {
        if (from == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        if (to == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(from, to, value);
    }

    /**
     * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
     * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
     * this function.
     *
     * Emits a {Transfer} event.
     */
    function _update(address from, address to, uint256 value) internal virtual {
        ERC20Storage storage $ = _getERC20Storage();
        if (from == address(0)) {
            // Overflow check required: The rest of the code assumes that totalSupply never overflows
            $._totalSupply += value;
        } else {
            uint256 fromBalance = $._balances[from];
            if (fromBalance < value) {
                revert ERC20InsufficientBalance(from, fromBalance, value);
            }
            unchecked {
                // Overflow not possible: value <= fromBalance <= totalSupply.
                $._balances[from] = fromBalance - value;
            }
        }

        if (to == address(0)) {
            unchecked {
                // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
                $._totalSupply -= value;
            }
        } else {
            unchecked {
                // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
                $._balances[to] += value;
            }
        }

        emit Transfer(from, to, value);
    }

    /**
     * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
     * Relies on the `_update` mechanism
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _mint(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(address(0), account, value);
    }

    /**
     * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
     * Relies on the `_update` mechanism.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead
     */
    function _burn(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        _update(account, address(0), value);
    }

    /**
     * @dev Sets `value` as the allowance of `spender` over the `owner`'s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     *
     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
     */
    function _approve(address owner, address spender, uint256 value) internal {
        _approve(owner, spender, value, true);
    }

    /**
     * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
     *
     * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
     * `_spendAllowance` during the `transferFrom` operation sets the flag to false. This saves gas by not emitting any
     * `Approval` event during `transferFrom` operations.
     *
     * Anyone who wishes to continue emitting `Approval` events on the `transferFrom` operation can force the flag to
     * true using the following override:
     *
     * ```solidity
     * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
     *     super._approve(owner, spender, value, true);
     * }
     * ```
     *
     * Requirements are the same as {_approve}.
     */
    function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
        ERC20Storage storage $ = _getERC20Storage();
        if (owner == address(0)) {
            revert ERC20InvalidApprover(address(0));
        }
        if (spender == address(0)) {
            revert ERC20InvalidSpender(address(0));
        }
        $._allowances[owner][spender] = value;
        if (emitEvent) {
            emit Approval(owner, spender, value);
        }
    }

    /**
     * @dev Updates `owner`'s allowance for `spender` based on spent `value`.
     *
     * Does not update the allowance value in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Does not emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance < type(uint256).max) {
            if (currentAllowance < value) {
                revert ERC20InsufficientAllowance(spender, currentAllowance, value);
            }
            unchecked {
                _approve(owner, spender, currentAllowance - value, false);
            }
        }
    }
}

npm/@openzeppelin/[email protected]/utils/ContextUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract ContextUpgradeable is Initializable {
    function __Context_init() internal onlyInitializing {
    }

    function __Context_init_unchained() internal onlyInitializing {
    }
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

npm/@openzeppelin/[email protected]/interfaces/IERC1363.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)

pragma solidity >=0.6.2;

import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

npm/@openzeppelin/[email protected]/interfaces/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)

pragma solidity >=0.4.16;

import {IERC165} from "../utils/introspection/IERC165.sol";

npm/@openzeppelin/[email protected]/interfaces/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)

pragma solidity >=0.4.16;

import {IERC20} from "../token/ERC20/IERC20.sol";

npm/@openzeppelin/[email protected]/interfaces/draft-IERC6093.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (interfaces/draft-IERC6093.sol)

pragma solidity >=0.8.4;

/**
 * @dev Standard ERC-20 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
 */
interface IERC20Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC20InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC20InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     * @param allowance Amount of tokens a `spender` is allowed to operate with.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC20InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC20InvalidSpender(address spender);
}

/**
 * @dev Standard ERC-721 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
 */
interface IERC721Errors {
    /**
     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-721.
     * Used in balance queries.
     * @param owner Address of the current owner of a token.
     */
    error ERC721InvalidOwner(address owner);

    /**
     * @dev Indicates a `tokenId` whose `owner` is the zero address.
     * @param tokenId Identifier number of a token.
     */
    error ERC721NonexistentToken(uint256 tokenId);

    /**
     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param tokenId Identifier number of a token.
     * @param owner Address of the current owner of a token.
     */
    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC721InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC721InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param tokenId Identifier number of a token.
     */
    error ERC721InsufficientApproval(address operator, uint256 tokenId);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC721InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC721InvalidOperator(address operator);
}

/**
 * @dev Standard ERC-1155 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
 */
interface IERC1155Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     * @param tokenId Identifier number of a token.
     */
    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC1155InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC1155InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param owner Address of the current owner of a token.
     */
    error ERC1155MissingApprovalForAll(address operator, address owner);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC1155InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC1155InvalidOperator(address operator);

    /**
     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
     * Used in batch transfers.
     * @param idsLength Length of the array of token identifiers
     * @param valuesLength Length of the array of token amounts
     */
    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}

npm/@openzeppelin/[email protected]/proxy/utils/Initializable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Storage of the initializable contract.
     *
     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
     * when using with upgradeable contracts.
     *
     * @custom:storage-location erc7201:openzeppelin.storage.Initializable
     */
    struct InitializableStorage {
        /**
         * @dev Indicates that the contract has been initialized.
         */
        uint64 _initialized;
        /**
         * @dev Indicates that the contract is in the process of being initialized.
         */
        bool _initializing;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

    /**
     * @dev The contract is already initialized.
     */
    error InvalidInitialization();

    /**
     * @dev The contract is not initializing.
     */
    error NotInitializing();

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint64 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
     * production.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        // Cache values to avoid duplicated sloads
        bool isTopLevelCall = !$._initializing;
        uint64 initialized = $._initialized;

        // Allowed calls:
        // - initialSetup: the contract is not in the initializing state and no previous version was
        //                 initialized
        // - construction: the contract is initialized at version 1 (no reinitialization) and the
        //                 current contract is just being deployed
        bool initialSetup = initialized == 0 && isTopLevelCall;
        bool construction = initialized == 1 && address(this).code.length == 0;

        if (!initialSetup && !construction) {
            revert InvalidInitialization();
        }
        $._initialized = 1;
        if (isTopLevelCall) {
            $._initializing = true;
        }
        _;
        if (isTopLevelCall) {
            $._initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint64 version) {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing || $._initialized >= version) {
            revert InvalidInitialization();
        }
        $._initialized = version;
        $._initializing = true;
        _;
        $._initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        _checkInitializing();
        _;
    }

    /**
     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
     */
    function _checkInitializing() internal view virtual {
        if (!_isInitializing()) {
            revert NotInitializing();
        }
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing) {
            revert InvalidInitialization();
        }
        if ($._initialized != type(uint64).max) {
            $._initialized = type(uint64).max;
            emit Initialized(type(uint64).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint64) {
        return _getInitializableStorage()._initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _getInitializableStorage()._initializing;
    }

    /**
     * @dev Pointer to storage slot. Allows integrators to override it with a custom storage location.
     *
     * NOTE: Consider following the ERC-7201 formula to derive storage locations.
     */
    function _initializableStorageSlot() internal pure virtual returns (bytes32) {
        return INITIALIZABLE_STORAGE;
    }

    /**
     * @dev Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        bytes32 slot = _initializableStorageSlot();
        assembly {
            $.slot := slot
        }
    }
}

npm/@openzeppelin/[email protected]/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}

npm/@openzeppelin/[email protected]/token/ERC20/extensions/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity >=0.6.2;

import {IERC20} from "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC-20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

npm/@openzeppelin/[email protected]/token/ERC20/utils/SafeERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        if (!_safeTransfer(token, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        if (!_safeTransferFrom(token, from, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _safeTransfer(token, to, value, false);
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _safeTransferFrom(token, from, to, value, false);
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        if (!_safeApprove(token, spender, value, false)) {
            if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
            if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Oppositely, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity `token.transfer(to, value)` call, relaxing the requirement on the return value: the
     * return value is optional (but if data is returned, it must not be false).
     *
     * @param token The token targeted by the call.
     * @param to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.transfer.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(to, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }

    /**
     * @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, relaxing the requirement on the return
     * value: the return value is optional (but if data is returned, it must not be false).
     *
     * @param token The token targeted by the call.
     * @param from The sender of the tokens
     * @param to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value,
        bool bubble
    ) private returns (bool success) {
        bytes4 selector = IERC20.transferFrom.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(from, shr(96, not(0))))
            mstore(0x24, and(to, shr(96, not(0))))
            mstore(0x44, value)
            success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
            mstore(0x60, 0)
        }
    }

    /**
     * @dev Imitates a Solidity `token.approve(spender, value)` call, relaxing the requirement on the return value:
     * the return value is optional (but if data is returned, it must not be false).
     *
     * @param token The token targeted by the call.
     * @param spender The spender of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.approve.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(spender, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }
}

npm/@openzeppelin/[email protected]/utils/Panic.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)

pragma solidity ^0.8.20;

/**
 * @dev Helper library for emitting standardized panic codes.
 *
 * ```solidity
 * contract Example {
 *      using Panic for uint256;
 *
 *      // Use any of the declared internal constants
 *      function foo() { Panic.GENERIC.panic(); }
 *
 *      // Alternatively
 *      function foo() { Panic.panic(Panic.GENERIC); }
 * }
 * ```
 *
 * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
 *
 * _Available since v5.1._
 */
// slither-disable-next-line unused-state
library Panic {
    /// @dev generic / unspecified error
    uint256 internal constant GENERIC = 0x00;
    /// @dev used by the assert() builtin
    uint256 internal constant ASSERT = 0x01;
    /// @dev arithmetic underflow or overflow
    uint256 internal constant UNDER_OVERFLOW = 0x11;
    /// @dev division or modulo by zero
    uint256 internal constant DIVISION_BY_ZERO = 0x12;
    /// @dev enum conversion error
    uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
    /// @dev invalid encoding in storage
    uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
    /// @dev empty array pop
    uint256 internal constant EMPTY_ARRAY_POP = 0x31;
    /// @dev array out of bounds access
    uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
    /// @dev resource error (too large allocation or too large array)
    uint256 internal constant RESOURCE_ERROR = 0x41;
    /// @dev calling invalid internal function
    uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;

    /// @dev Reverts with a panic code. Recommended to use with
    /// the internal constants with predefined codes.
    function panic(uint256 code) internal pure {
        assembly ("memory-safe") {
            mstore(0x00, 0x4e487b71)
            mstore(0x20, code)
            revert(0x1c, 0x24)
        }
    }
}

npm/@openzeppelin/[email protected]/utils/ReentrancyGuardTransient.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/ReentrancyGuardTransient.sol)

pragma solidity ^0.8.24;

import {TransientSlot} from "./TransientSlot.sol";

/**
 * @dev Variant of {ReentrancyGuard} that uses transient storage.
 *
 * NOTE: This variant only works on networks where EIP-1153 is available.
 *
 * _Available since v5.1._
 *
 * @custom:stateless
 */
abstract contract ReentrancyGuardTransient {
    using TransientSlot for *;

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant REENTRANCY_GUARD_STORAGE =
        0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    /**
     * @dev A `view` only version of {nonReentrant}. Use to block view functions
     * from being called, preventing reading from inconsistent contract state.
     *
     * CAUTION: This is a "view" modifier and does not change the reentrancy
     * status. Use it only on view functions. For payable or non-payable functions,
     * use the standard {nonReentrant} modifier instead.
     */
    modifier nonReentrantView() {
        _nonReentrantBeforeView();
        _;
    }

    function _nonReentrantBeforeView() private view {
        if (_reentrancyGuardEntered()) {
            revert ReentrancyGuardReentrantCall();
        }
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, REENTRANCY_GUARD_STORAGE.asBoolean().tload() will be false
        _nonReentrantBeforeView();

        // Any calls to nonReentrant after this point will fail
        _reentrancyGuardStorageSlot().asBoolean().tstore(true);
    }

    function _nonReentrantAfter() private {
        _reentrancyGuardStorageSlot().asBoolean().tstore(false);
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _reentrancyGuardStorageSlot().asBoolean().tload();
    }

    function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
        return REENTRANCY_GUARD_STORAGE;
    }
}

npm/@openzeppelin/[email protected]/utils/TransientSlot.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/TransientSlot.sol)
// This file was procedurally generated from scripts/generate/templates/TransientSlot.js.

pragma solidity ^0.8.24;

/**
 * @dev Library for reading and writing value-types to specific transient storage slots.
 *
 * Transient slots are often used to store temporary values that are removed after the current transaction.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 *  * Example reading and writing values using transient storage:
 * ```solidity
 * contract Lock {
 *     using TransientSlot for *;
 *
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
 *
 *     modifier locked() {
 *         require(!_LOCK_SLOT.asBoolean().tload());
 *
 *         _LOCK_SLOT.asBoolean().tstore(true);
 *         _;
 *         _LOCK_SLOT.asBoolean().tstore(false);
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library TransientSlot {
    /**
     * @dev UDVT that represents a slot holding an address.
     */
    type AddressSlot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a AddressSlot.
     */
    function asAddress(bytes32 slot) internal pure returns (AddressSlot) {
        return AddressSlot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a bool.
     */
    type BooleanSlot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a BooleanSlot.
     */
    function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {
        return BooleanSlot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a bytes32.
     */
    type Bytes32Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Bytes32Slot.
     */
    function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {
        return Bytes32Slot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a uint256.
     */
    type Uint256Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Uint256Slot.
     */
    function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {
        return Uint256Slot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a int256.
     */
    type Int256Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Int256Slot.
     */
    function asInt256(bytes32 slot) internal pure returns (Int256Slot) {
        return Int256Slot.wrap(slot);
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(AddressSlot slot) internal view returns (address value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(AddressSlot slot, address value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(BooleanSlot slot) internal view returns (bool value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(BooleanSlot slot, bool value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Bytes32Slot slot) internal view returns (bytes32 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Bytes32Slot slot, bytes32 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Uint256Slot slot) internal view returns (uint256 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Uint256Slot slot, uint256 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Int256Slot slot) internal view returns (int256 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Int256Slot slot, int256 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }
}

npm/@openzeppelin/[email protected]/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

npm/@openzeppelin/[email protected]/utils/math/Math.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Return the 512-bit addition of two uint256.
     *
     * The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
     */
    function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        assembly ("memory-safe") {
            low := add(a, b)
            high := lt(low, a)
        }
    }

    /**
     * @dev Return the 512-bit multiplication of two uint256.
     *
     * The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
     */
    function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        // 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
        // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
        // variables such that product = high * 2²⁵⁶ + low.
        assembly ("memory-safe") {
            let mm := mulmod(a, b, not(0))
            low := mul(a, b)
            high := sub(sub(mm, low), lt(mm, low))
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a + b;
            success = c >= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a - b;
            success = c <= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a * b;
            assembly ("memory-safe") {
                // Only true when the multiplication doesn't overflow
                // (c / a == b) || (a == 0)
                success := or(eq(div(c, a), b), iszero(a))
            }
            // equivalent to: success ? c : 0
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `DIV` opcode returns zero when the denominator is 0.
                result := div(a, b)
            }
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `MOD` opcode returns zero when the denominator is 0.
                result := mod(a, b)
            }
        }
    }

    /**
     * @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryAdd(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
     */
    function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
        (, uint256 result) = trySub(a, b);
        return result;
    }

    /**
     * @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryMul(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Branchless ternary evaluation for `condition ? a : b`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `condition ? a : b`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * SafeCast.toUint(condition));
        }
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a > b, a, b);
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a < b, a, b);
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            // (a + b) / 2 can overflow.
            return (a & b) + (a ^ b) / 2;
        }
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }

        // The following calculation ensures accurate ceiling division without overflow.
        // Since a is non-zero, (a - 1) / b will not overflow.
        // The largest possible result occurs when (a - 1) / b is type(uint256).max,
        // but the largest value we can obtain is type(uint256).max - 1, which happens
        // when a = type(uint256).max and b = 1.
        unchecked {
            return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
        }
    }

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);

            // Handle non-overflow cases, 256 by 256 division.
            if (high == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return low / denominator;
            }

            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
            if (denominator <= high) {
                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
            }

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [high low].
            uint256 remainder;
            assembly ("memory-safe") {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                high := sub(high, gt(remainder, low))
                low := sub(low, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.

            uint256 twos = denominator & (0 - denominator);
            assembly ("memory-safe") {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [high low] by twos.
                low := div(low, twos)

                // Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from high into low.
            low |= high * twos;

            // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
            // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv ≡ 1 mod 2⁴.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
            // works in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
            inverse *= 2 - denominator * inverse; // inverse mod 2³²
            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
            // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
            // is no longer required.
            result = low * inverse;
            return result;
        }
    }

    /**
     * @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
    }

    /**
     * @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
     */
    function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);
            if (high >= 1 << n) {
                Panic.panic(Panic.UNDER_OVERFLOW);
            }
            return (high << (256 - n)) | (low >> n);
        }
    }

    /**
     * @dev Calculates x * y >> n with full precision, following the selected rounding direction.
     */
    function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
        return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
    }

    /**
     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
     *
     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
     *
     * If the input value is not inversible, 0 is returned.
     *
     * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
     */
    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
        unchecked {
            if (n == 0) return 0;

            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
            // Used to compute integers x and y such that: ax + ny = gcd(a, n).
            // When the gcd is 1, then the inverse of a modulo n exists and it's x.
            // ax + ny = 1
            // ax = 1 + (-y)n
            // ax ≡ 1 (mod n) # x is the inverse of a modulo n

            // If the remainder is 0 the gcd is n right away.
            uint256 remainder = a % n;
            uint256 gcd = n;

            // Therefore the initial coefficients are:
            // ax + ny = gcd(a, n) = n
            // 0a + 1n = n
            int256 x = 0;
            int256 y = 1;

            while (remainder != 0) {
                uint256 quotient = gcd / remainder;

                (gcd, remainder) = (
                    // The old remainder is the next gcd to try.
                    remainder,
                    // Compute the next remainder.
                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
                    // where gcd is at most n (capped to type(uint256).max)
                    gcd - remainder * quotient
                );

                (x, y) = (
                    // Increment the coefficient of a.
                    y,
                    // Decrement the coefficient of n.
                    // Can overflow, but the result is casted to uint256 so that the
                    // next value of y is "wrapped around" to a value between 0 and n - 1.
                    x - y * int256(quotient)
                );
            }

            if (gcd != 1) return 0; // No inverse exists.
            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
        }
    }

    /**
     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
     *
     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
     * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.
     *
     * NOTE: this function does NOT check that `p` is a prime greater than `2`.
     */
    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
        unchecked {
            return Math.modExp(a, p - 2, p);
        }
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
     *
     * Requirements:
     * - modulus can't be zero
     * - underlying staticcall to precompile must succeed
     *
     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
     * sure the chain you're using it on supports the precompiled contract for modular exponentiation
     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly
     * interpreted as 0.
     */
    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
        (bool success, uint256 result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
     * to operate modulo 0 or if the underlying precompile reverted.
     *
     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
     * of a revert, but the result may be incorrectly interpreted as 0.
     */
    function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
        if (m == 0) return (false, 0);
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            // | Offset    | Content    | Content (Hex)                                                      |
            // |-----------|------------|--------------------------------------------------------------------|
            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x60:0x7f | value of b | 0x<.............................................................b> |
            // | 0x80:0x9f | value of e | 0x<.............................................................e> |
            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |
            mstore(ptr, 0x20)
            mstore(add(ptr, 0x20), 0x20)
            mstore(add(ptr, 0x40), 0x20)
            mstore(add(ptr, 0x60), b)
            mstore(add(ptr, 0x80), e)
            mstore(add(ptr, 0xa0), m)

            // Given the result < m, it's guaranteed to fit in 32 bytes,
            // so we can use the memory scratch space located at offset 0.
            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
            result := mload(0x00)
        }
    }

    /**
     * @dev Variant of {modExp} that supports inputs of arbitrary length.
     */
    function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
        (bool success, bytes memory result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Variant of {tryModExp} that supports inputs of arbitrary length.
     */
    function tryModExp(
        bytes memory b,
        bytes memory e,
        bytes memory m
    ) internal view returns (bool success, bytes memory result) {
        if (_zeroBytes(m)) return (false, new bytes(0));

        uint256 mLen = m.length;

        // Encode call args in result and move the free memory pointer
        result = abi.encodePacked(b.length, e.length, mLen, b, e, m);

        assembly ("memory-safe") {
            let dataPtr := add(result, 0x20)
            // Write result on top of args to avoid allocating extra memory.
            success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
            // Overwrite the length.
            // result.length > returndatasize() is guaranteed because returndatasize() == m.length
            mstore(result, mLen)
            // Set the memory pointer after the returned data.
            mstore(0x40, add(dataPtr, mLen))
        }
    }

    /**
     * @dev Returns whether the provided byte array is zero.
     */
    function _zeroBytes(bytes memory buffer) private pure returns (bool) {
        uint256 chunk;
        for (uint256 i = 0; i < buffer.length; i += 0x20) {
            // See _unsafeReadBytesOffset from utils/Bytes.sol
            assembly ("memory-safe") {
                chunk := mload(add(add(buffer, 0x20), i))
            }
            if (chunk >> (8 * saturatingSub(i + 0x20, buffer.length)) != 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * This method is based on Newton's method for computing square roots; the algorithm is restricted to only
     * using integer operations.
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        unchecked {
            // Take care of easy edge cases when a == 0 or a == 1
            if (a <= 1) {
                return a;
            }

            // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
            // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
            // the current value as `ε_n = | x_n - sqrt(a) |`.
            //
            // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
            // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
            // bigger than any uint256.
            //
            // By noticing that
            // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
            // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
            // to the msb function.
            uint256 aa = a;
            uint256 xn = 1;

            if (aa >= (1 << 128)) {
                aa >>= 128;
                xn <<= 64;
            }
            if (aa >= (1 << 64)) {
                aa >>= 64;
                xn <<= 32;
            }
            if (aa >= (1 << 32)) {
                aa >>= 32;
                xn <<= 16;
            }
            if (aa >= (1 << 16)) {
                aa >>= 16;
                xn <<= 8;
            }
            if (aa >= (1 << 8)) {
                aa >>= 8;
                xn <<= 4;
            }
            if (aa >= (1 << 4)) {
                aa >>= 4;
                xn <<= 2;
            }
            if (aa >= (1 << 2)) {
                xn <<= 1;
            }

            // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
            //
            // We can refine our estimation by noticing that the middle of that interval minimizes the error.
            // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
            // This is going to be our x_0 (and ε_0)
            xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)

            // From here, Newton's method give us:
            // x_{n+1} = (x_n + a / x_n) / 2
            //
            // One should note that:
            // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
            //              = ((x_n² + a) / (2 * x_n))² - a
            //              = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
            //              = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
            //              = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
            //              = (x_n² - a)² / (2 * x_n)²
            //              = ((x_n² - a) / (2 * x_n))²
            //              ≥ 0
            // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
            //
            // This gives us the proof of quadratic convergence of the sequence:
            // ε_{n+1} = | x_{n+1} - sqrt(a) |
            //         = | (x_n + a / x_n) / 2 - sqrt(a) |
            //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
            //         = | (x_n - sqrt(a))² / (2 * x_n) |
            //         = | ε_n² / (2 * x_n) |
            //         = ε_n² / | (2 * x_n) |
            //
            // For the first iteration, we have a special case where x_0 is known:
            // ε_1 = ε_0² / | (2 * x_0) |
            //     ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
            //     ≤ 2**(2*e-4) / (3 * 2**(e-1))
            //     ≤ 2**(e-3) / 3
            //     ≤ 2**(e-3-log2(3))
            //     ≤ 2**(e-4.5)
            //
            // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
            // ε_{n+1} = ε_n² / | (2 * x_n) |
            //         ≤ (2**(e-k))² / (2 * 2**(e-1))
            //         ≤ 2**(2*e-2*k) / 2**e
            //         ≤ 2**(e-2*k)
            xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5)  -- special case, see above
            xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9)    -- general case with k = 4.5
            xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18)   -- general case with k = 9
            xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36)   -- general case with k = 18
            xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72)   -- general case with k = 36
            xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144)  -- general case with k = 72

            // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
            // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
            // sqrt(a) or sqrt(a) + 1.
            return xn - SafeCast.toUint(xn > a / xn);
        }
    }

    /**
     * @dev Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // If upper 8 bits of 16-bit half set, add 8 to result
        r |= SafeCast.toUint((x >> r) > 0xff) << 3;
        // If upper 4 bits of 8-bit half set, add 4 to result
        r |= SafeCast.toUint((x >> r) > 0xf) << 2;

        // Shifts value right by the current result and use it as an index into this lookup table:
        //
        // | x (4 bits) |  index  | table[index] = MSB position |
        // |------------|---------|-----------------------------|
        // |    0000    |    0    |        table[0] = 0         |
        // |    0001    |    1    |        table[1] = 0         |
        // |    0010    |    2    |        table[2] = 1         |
        // |    0011    |    3    |        table[3] = 1         |
        // |    0100    |    4    |        table[4] = 2         |
        // |    0101    |    5    |        table[5] = 2         |
        // |    0110    |    6    |        table[6] = 2         |
        // |    0111    |    7    |        table[7] = 2         |
        // |    1000    |    8    |        table[8] = 3         |
        // |    1001    |    9    |        table[9] = 3         |
        // |    1010    |   10    |        table[10] = 3        |
        // |    1011    |   11    |        table[11] = 3        |
        // |    1100    |   12    |        table[12] = 3        |
        // |    1101    |   13    |        table[13] = 3        |
        // |    1110    |   14    |        table[14] = 3        |
        // |    1111    |   15    |        table[15] = 3        |
        //
        // The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the first 16 bytes (most significant half).
        assembly ("memory-safe") {
            r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
        }
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
        }
    }

    /**
     * @dev Return the log in base 10 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
        }
    }

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
        return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
        }
    }

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }

    /**
     * @dev Counts the number of leading zero bits in a uint256.
     */
    function clz(uint256 x) internal pure returns (uint256) {
        return ternary(x == 0, 256, 255 - log2(x));
    }
}

npm/@openzeppelin/[email protected]/utils/math/SafeCast.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.

pragma solidity ^0.8.20;

/**
 * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeCast {
    /**
     * @dev Value doesn't fit in a uint of `bits` size.
     */
    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);

    /**
     * @dev An int value doesn't fit in a uint of `bits` size.
     */
    error SafeCastOverflowedIntToUint(int256 value);

    /**
     * @dev Value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);

    /**
     * @dev A uint value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedUintToInt(uint256 value);

    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        if (value > type(uint248).max) {
            revert SafeCastOverflowedUintDowncast(248, value);
        }
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        if (value > type(uint240).max) {
            revert SafeCastOverflowedUintDowncast(240, value);
        }
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        if (value > type(uint232).max) {
            revert SafeCastOverflowedUintDowncast(232, value);
        }
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        if (value > type(uint224).max) {
            revert SafeCastOverflowedUintDowncast(224, value);
        }
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        if (value > type(uint216).max) {
            revert SafeCastOverflowedUintDowncast(216, value);
        }
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        if (value > type(uint208).max) {
            revert SafeCastOverflowedUintDowncast(208, value);
        }
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        if (value > type(uint200).max) {
            revert SafeCastOverflowedUintDowncast(200, value);
        }
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        if (value > type(uint192).max) {
            revert SafeCastOverflowedUintDowncast(192, value);
        }
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        if (value > type(uint184).max) {
            revert SafeCastOverflowedUintDowncast(184, value);
        }
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        if (value > type(uint176).max) {
            revert SafeCastOverflowedUintDowncast(176, value);
        }
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        if (value > type(uint168).max) {
            revert SafeCastOverflowedUintDowncast(168, value);
        }
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        if (value > type(uint160).max) {
            revert SafeCastOverflowedUintDowncast(160, value);
        }
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        if (value > type(uint152).max) {
            revert SafeCastOverflowedUintDowncast(152, value);
        }
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        if (value > type(uint144).max) {
            revert SafeCastOverflowedUintDowncast(144, value);
        }
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        if (value > type(uint136).max) {
            revert SafeCastOverflowedUintDowncast(136, value);
        }
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        if (value > type(uint128).max) {
            revert SafeCastOverflowedUintDowncast(128, value);
        }
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        if (value > type(uint120).max) {
            revert SafeCastOverflowedUintDowncast(120, value);
        }
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        if (value > type(uint112).max) {
            revert SafeCastOverflowedUintDowncast(112, value);
        }
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        if (value > type(uint104).max) {
            revert SafeCastOverflowedUintDowncast(104, value);
        }
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        if (value > type(uint96).max) {
            revert SafeCastOverflowedUintDowncast(96, value);
        }
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        if (value > type(uint88).max) {
            revert SafeCastOverflowedUintDowncast(88, value);
        }
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        if (value > type(uint80).max) {
            revert SafeCastOverflowedUintDowncast(80, value);
        }
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        if (value > type(uint72).max) {
            revert SafeCastOverflowedUintDowncast(72, value);
        }
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        if (value > type(uint64).max) {
            revert SafeCastOverflowedUintDowncast(64, value);
        }
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        if (value > type(uint56).max) {
            revert SafeCastOverflowedUintDowncast(56, value);
        }
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        if (value > type(uint48).max) {
            revert SafeCastOverflowedUintDowncast(48, value);
        }
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        if (value > type(uint40).max) {
            revert SafeCastOverflowedUintDowncast(40, value);
        }
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        if (value > type(uint32).max) {
            revert SafeCastOverflowedUintDowncast(32, value);
        }
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        if (value > type(uint24).max) {
            revert SafeCastOverflowedUintDowncast(24, value);
        }
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        if (value > type(uint16).max) {
            revert SafeCastOverflowedUintDowncast(16, value);
        }
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        if (value > type(uint8).max) {
            revert SafeCastOverflowedUintDowncast(8, value);
        }
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        if (value < 0) {
            revert SafeCastOverflowedIntToUint(value);
        }
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(248, value);
        }
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(240, value);
        }
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(232, value);
        }
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(224, value);
        }
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(216, value);
        }
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(208, value);
        }
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(200, value);
        }
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(192, value);
        }
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(184, value);
        }
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(176, value);
        }
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(168, value);
        }
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(160, value);
        }
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(152, value);
        }
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(144, value);
        }
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(136, value);
        }
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(128, value);
        }
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(120, value);
        }
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(112, value);
        }
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(104, value);
        }
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(96, value);
        }
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(88, value);
        }
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(80, value);
        }
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(72, value);
        }
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(64, value);
        }
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(56, value);
        }
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(48, value);
        }
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(40, value);
        }
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(32, value);
        }
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(24, value);
        }
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(16, value);
        }
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(8, value);
        }
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        if (value > uint256(type(int256).max)) {
            revert SafeCastOverflowedUintToInt(value);
        }
        return int256(value);
    }

    /**
     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
     */
    function toUint(bool b) internal pure returns (uint256 u) {
        assembly ("memory-safe") {
            u := iszero(iszero(b))
        }
    }
}

project/contracts/interfaces/IAggregatorV3.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

/// @notice Minimal Chainlink AggregatorV3 interface: `decimals` and `latestRoundData`.
interface IAggregatorV3 {
    function decimals() external view returns (uint8);

    function latestRoundData() external view returns (
        uint80 roundId,
        int256 answer,
        uint256 startedAt,
        uint256 updatedAt,
        uint80 answeredInRound
    );
}

project/contracts/interfaces/IHorizonMintable.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

/// @notice HorizonToken interface for allowlisted minters: ERC20 plus mint.
interface IHorizonMintable is IERC20 {
    function mint(address to, uint256 amount) external;
}

project/contracts/interfaces/IUniswapV3Minimal.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

/// Minimal Uniswap SwapRouter02 interface.
/// @dev SwapRouter02 params carry no `deadline`; a SwapRouter01-shaped call has a different selector and reverts.
interface IV3SwapRouter {
    struct ExactInputSingleParams {
        address tokenIn;
        address tokenOut;
        uint24  fee;
        address recipient;
        uint256 amountIn;
        uint256 amountOutMinimum;
        uint160 sqrtPriceLimitX96;
    }
    function exactInputSingle(ExactInputSingleParams calldata) external payable returns (uint256);

    /// SwapRouter02's exact-output single hop, with no deadline.
    struct ExactOutputSingleParams {
        address tokenIn;
        address tokenOut;
        uint24  fee;
        address recipient;
        uint256 amountOut;
        uint256 amountInMaximum;
        uint160 sqrtPriceLimitX96;
    }
    function exactOutputSingle(ExactOutputSingleParams calldata) external payable returns (uint256 amountIn);
}

/// Minimal Uniswap V3 factory interface.
interface IUniswapV3Factory {
    function getPool(address tokenA, address tokenB, uint24 fee) external view returns (address);
}

/// Minimal Uniswap V3 pool state interface.
interface IUniswapV3PoolState {
    function slot0() external view returns (
        uint160 sqrtPriceX96, int24 tick, uint16, uint16, uint16, uint8, bool
    );
    function observe(uint32[] calldata secondsAgos) external view returns (
        int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s
    );
    function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
    function tickSpacing() external view returns (int24);
    /// Pool-immutable identity, read to verify a supplied pool's tokens and fee.
    function token0() external view returns (address);
    function token1() external view returns (address);
    function fee() external view returns (uint24);
}

/// The pool's in-range liquidity.
interface IUniswapV3PoolLiquidity {
    function liquidity() external view returns (uint128);
}

/// Minimal Uniswap V3 NonfungiblePositionManager interface.
interface IUniswapV3NPM {
    struct MintParams {
        address token0;
        address token1;
        uint24  fee;
        int24   tickLower;
        int24   tickUpper;
        uint256 amount0Desired;
        uint256 amount1Desired;
        uint256 amount0Min;
        uint256 amount1Min;
        address recipient;
        uint256 deadline;
    }
    struct IncreaseLiquidityParams {
        uint256 tokenId;
        uint256 amount0Desired;
        uint256 amount1Desired;
        uint256 amount0Min;
        uint256 amount1Min;
        uint256 deadline;
    }
    struct DecreaseLiquidityParams {
        uint256 tokenId;
        uint128 liquidity;
        uint256 amount0Min;
        uint256 amount1Min;
        uint256 deadline;
    }
    struct CollectParams {
        uint256 tokenId;
        address recipient;
        uint128 amount0Max;
        uint128 amount1Max;
    }
    function mint(MintParams calldata p)
        external payable returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
    function increaseLiquidity(IncreaseLiquidityParams calldata p)
        external payable returns (uint128 liquidity, uint256 amount0, uint256 amount1);
    function decreaseLiquidity(DecreaseLiquidityParams calldata p)
        external returns (uint256 amount0, uint256 amount1);
    function collect(CollectParams calldata p)
        external returns (uint256 amount0, uint256 amount1);
    function positions(uint256 tokenId) external view returns (
        uint96 nonce, address operator, address token0, address token1,
        uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity,
        uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128,
        uint128 tokensOwed0, uint128 tokensOwed1
    );
    /// @notice The Uniswap V3 factory this position manager's pools are created through.
    function factory() external view returns (address);
}

/// Uniswap V3 pool liquidity actions for pool-direct positions, keyed on
/// `keccak256(abi.encodePacked(owner, tickLower, tickUpper))`.
interface IUniswapV3PoolActions {
    /// Adds `amount` liquidity to the position owned by `recipient` over [tickLower, tickUpper]; the
    /// caller must pay the returned owed tokens inside `uniswapV3MintCallback` before this returns.
    function mint(address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data)
        external returns (uint256 amount0, uint256 amount1);
    /// Removes `amount` liquidity from the caller's position, crediting principal and fees to `tokensOwed`.
    function burn(int24 tickLower, int24 tickUpper, uint128 amount)
        external returns (uint256 amount0, uint256 amount1);
    /// Transfers up to the requested amounts of the caller's position's `tokensOwed` to `recipient`.
    function collect(
        address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested
    ) external returns (uint128 amount0, uint128 amount1);
    function positions(bytes32 key) external view returns (
        uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128,
        uint128 tokensOwed0, uint128 tokensOwed1
    );
}

/// Mint callback a pool-direct minter implements to pay owed tokens; it must accept only the pool, during its own
/// mint.
interface IUniswapV3MintCallback {
    function uniswapV3MintCallback(uint256 amount0Owed, uint256 amount1Owed, bytes calldata data) external;
}

project/contracts/libraries/KeeperBounty.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;

/// @notice Keeper bounty split: (amount * bountyBps / BPS, amount - bounty).
library KeeperBounty {
    uint256 internal constant BPS = 10_000;

    function split(uint256 amount, uint256 bountyBps) internal pure returns (uint256 bounty, uint256 remainder) {
        bounty = (amount * bountyBps) / BPS;
        remainder = amount - bounty;
    }
}

project/contracts/libraries/PoolLastGood.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;

import "./PoolMath.sol";

/// @title PoolLastGood - the lending pool's own last-good liquidation price, per price feed
/// @notice Per price feed, the last healthy long-median answer a pool action read, as a liquidation fallback.
/// @dev ERC-7201 slot in the pool's storage, keyed by feed; at most one write per feed per block, newer only.
library PoolLastGood {
    /// ERC-7201: keccak256(abi.encode(uint256(keccak256("horizon.pool.lastGood")) - 1)) & ~0xff.
    bytes32 internal constant SLOT = 0x83530c3fafbf76ea81752cb3c03a9a31e81528eda7015e4f1f0bea8ef73b1c00;

    /// The word for `feed`: `mapping(address => uint256)` rooted at SLOT.
    function slotOf(address feed) internal pure returns (bytes32 s) {
        assembly ("memory-safe") {
            mstore(0x00, feed)
            mstore(0x20, SLOT)
            s := keccak256(0x00, 0x40)
        }
    }

    /// The stored record (answer in the feed's own units and decimals, and the block time of the read); (0, 0) = none.
    function load(address feed) internal view returns (uint256 answer, uint256 at) {
        bytes32 s = slotOf(feed);
        uint256 w;
        assembly ("memory-safe") { w := sload(s) }
        return (w >> 64, uint64(w));
    }

    /// Pack a healthy live read into an observation, or 0 when it does not qualify (see the header).
    function observe(int256 answer, uint256 updatedAt) internal view returns (uint256) {
        if (answer <= 0 || uint256(answer) > type(uint128).max || updatedAt != block.timestamp) return 0;
        return (uint256(answer) << 64) | updatedAt;
    }

    /// Store `obs` for `feed` unless it is empty or no newer than what is stored (at most one write per feed per block).
    function record(address feed, uint256 obs) internal {
        if (obs == 0) return;
        bytes32 s = slotOf(feed);
        uint256 cur;
        assembly ("memory-safe") { cur := sload(s) }
        if (uint64(cur) >= uint64(obs)) return;
        assembly ("memory-safe") { sstore(s, obs) }
    }

    /// Store each reserve's observation from an account walk (`obs[i]` belongs to `reservesList[i]`; 0 = none).
    function recordAll(
        mapping(address => PoolMath.ReserveConfig) storage reserveConfig,
        address[] storage reservesList,
        uint256[] memory obs
    ) internal {
        for (uint256 i = 0; i < obs.length; i++) {
            if (obs[i] != 0) record(reserveConfig[reservesList[i]].priceFeed, obs[i]);
        }
    }
}

project/contracts/libraries/PoolMath.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../interfaces/IHorizonMintable.sol";

/// @title PoolMath
/// @notice Internal helpers shared by HorizonLendingPool and its logic libraries: decimals, userConfig bits, payouts.
library PoolMath {
    using SafeERC20 for IERC20;

    error ReserveNotRegistered();

    /// Mirrors HorizonLendingPool.ReserveConfig field for field; storage layout is positional, so field order and
    /// sizes must match exactly and new fields are appended only.
    struct ReserveConfig {
        address sTokenAddress;
        bool    isActive;
        uint16  collateralFactorBps;
        uint16  liquidationThresholdBps;
        uint16  liquidationBonusBps;
        address priceFeed;
        uint16  baseRateBps;
        uint16  slope1Bps;
        uint16  slope2Bps;
        uint16  kinkBps;
        uint16  reserveFactorBps;
        uint16  liquidationFeeBps;
        uint8   decimals;
        uint128 supplyCap;
        uint128 borrowCap;
        /// Oracle freshness bounds in seconds: `priceStaleAfter` for supply/withdraw/borrow/repay, the lenient
        /// `maxPriceAge` for health and liquidation; `maxPriceAge >= priceStaleAfter`.
        uint32  priceStaleAfter;
        uint32  maxPriceAge;
        /// Upside price cap (1e18 USD), 0 = off; collateral reads use `min(feedPrice, priceCapUsd)`, debt reads uncapped.
        uint128 priceCapUsd;
        /// Non-zero marks the reserve as isolated collateral and is its USD debt ceiling; zero means not isolated.
        uint128 isolationDebtCeilingUsd;
        /// Whether this asset may be borrowed by an account in isolation mode.
        bool    borrowableInIsolation;
        /// Extra origination fee in bps when this asset backs a borrow, on top of the pool's `borrowFeeBps`.
        uint16  liquidityPremiumBps;
        /// Facilitator reserve (e.g. hUSD): `payOut` mints instead of transferring, supply is refused, and
        /// `borrowCap` is the mint cap.
        bool    isFacilitator;
        /// Genesis kill switch: blocks supply, withdraw, borrow, repay and liquidation on this reserve as either leg.
        bool    paused;
        /// Collateral-only: the asset can be supplied, used as collateral, withdrawn and seized, but not borrowed.
        /// `IHorizonLendingPool` declares the same tuple, so a field order mismatch is a compile error.
        bool    borrowingDisabled;
        /// Non-zero marks membership of that correlated group; a position opted into the same id values this collateral
        /// at the constellation factors below, each at least its standard one.
        uint8   constellationId;
        bool    constellationBorrowable;
        uint16  constellationCollateralFactorBps;
        uint16  constellationLiquidationThresholdBps;
        uint16  constellationLiquidationBonusBps;
    }

    /// The opted-in constellation id lives in the top byte of `userConfig[account]` (0 = none); reserve bits stop at
    /// bit 199 (`MAX_RESERVES` = 100) and `setUserBit` flips single bits, so the byte is never disturbed.
    uint256 internal constant CID_SHIFT = 248;

    function constellationIdOf(mapping(address => uint256) storage userConfig, address account) internal view returns (uint8) {
        return uint8(userConfig[account] >> CID_SHIFT);
    }

    function writeConstellationId(mapping(address => uint256) storage userConfig, address account, uint8 id) internal {
        userConfig[account] = (userConfig[account] & ~(uint256(0xFF) << CID_SHIFT)) | (uint256(id) << CID_SHIFT);
    }

    function requireRegistered(mapping(address => ReserveConfig) storage reserveConfig, address asset) internal view {
        if (reserveConfig[asset].sTokenAddress == address(0)) revert ReserveNotRegistered();
    }

    function payOut(mapping(address => ReserveConfig) storage reserveConfig, address asset, address to, uint256 amount) internal {
        if (reserveConfig[asset].isFacilitator) {
            // A facilitator reserve holds no liquidity, so every payout from it is a mint.
            IHorizonMintable(asset).mint(to, amount);
        } else {
            IERC20(asset).safeTransfer(to, amount);
        }
    }

    /// @dev Normalizes `amount` (in `asset`'s own decimals) up to the canonical 18-decimal basis
    ///      every internal computation uses.
    function toCanonical(mapping(address => ReserveConfig) storage reserveConfig, address asset, uint256 amount) internal view returns (uint256) {
        uint8 dec = reserveConfig[asset].decimals;
        return dec == 18 ? amount : amount * (10 ** (18 - dec));
    }

    function fromCanonical(mapping(address => ReserveConfig) storage reserveConfig, address asset, uint256 canonicalAmount) internal view returns (uint256) {
        uint8 dec = reserveConfig[asset].decimals;
        return dec == 18 ? canonicalAmount : canonicalAmount / (10 ** (18 - dec));
    }

    /// @notice Weighted collateral cost of one dollar repaid, in bps: LT x (1 + bonus), scaled by cap / uncapped price
    ///         when the collateral trades above `priceCapUsd`. A partial repay lowers health exactly when HF < this / BPS.
    function seizeCostBps(uint256 ltBps, uint256 bonusBps, uint256 priceCapUsd, uint256 uncapped) internal pure returns (uint256 s) {
        s = ((10_000 + bonusBps) * ltBps) / 10_000;
        if (priceCapUsd != 0 && uncapped > priceCapUsd) s = (s * priceCapUsd) / uncapped;
    }

    /// @dev Canonical (18-decimal) to native for a bare `decimals`, scaling in both directions.
    function canonicalToNative(uint256 canonical, uint8 dec) internal pure returns (uint256) {
        if (dec == 18) return canonical;
        return dec < 18 ? canonical / 10 ** (18 - dec) : canonical * 10 ** (dec - 18);
    }

    /// @dev Native -> canonical for a bare `decimals`, the inverse of `canonicalToNative`.
    function nativeToCanonical(uint256 amount, uint8 dec) internal pure returns (uint256) {
        if (dec == 18) return amount;
        return dec < 18 ? amount * 10 ** (18 - dec) : amount / 10 ** (dec - 18);
    }

    function setUserBit(
        mapping(address => uint256) storage userConfig,
        mapping(address => uint256) storage reserveIndex1,
        address user, address asset, uint256 offset, bool value
    ) internal {
        uint256 id1 = reserveIndex1[asset]; // 1-indexed
        uint256 bitPos = 2 * (id1 - 1) + offset;
        if (value) {
            userConfig[user] |= (1 << bitPos);
        } else {
            userConfig[user] &= ~(1 << bitPos);
        }
    }

    /// @dev This reserve's real, currently-held ERC20 balance, in its own decimals.
    function liquidBalance(address asset) internal view returns (uint256) {
        return IERC20(asset).balanceOf(address(this));
    }
}

project/contracts/libraries/PriceOracle.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;

import "../interfaces/IAggregatorV3.sol";
import "./PoolLastGood.sol";

/// @title PriceOracle
/// @notice The lending pool's price-reading logic, as an external library so it deploys outside the pool's bytecode.
/// @notice The standard feed's last-good surface (`HorizonDexPriceFeed.lastGoodRoundData`), liquidation reads only.
interface ILastGoodFeed {
    function lastGoodRoundData() external view returns (uint80, int256, uint256, uint256, uint80);
    function lastGoodWindow() external view returns (uint32);
}

/// The lending pool's own last-good record (`HorizonLendingPool.lastGoodRecordOf`), for readers outside it.
interface ILastGoodPool {
    function lastGoodRecordOf(address feed) external view returns (uint256 answer, uint256 recordedAt);
}

library PriceOracle {
    error BadPrice();
    error StalePrice();
    /// The standard feed's own error (`HorizonDexPriceFeed.InsufficientGas()`), re-raised by every lenient read.
    error InsufficientGas();
    bytes4 internal constant INSUFFICIENT_GAS = bytes4(keccak256("InsufficientGas()"));

    /// @dev Strict read: reverts on a non-positive answer or one older than `maxAge`; returns
    ///      `min(price, priceCapUsd)` (0 = no cap), so a fall always passes through.
    function readStrict(address priceFeed, uint256 maxAge, uint256 scale, uint256 priceCapUsd) external view returns (uint256) {
        (, int256 answer, , uint256 updatedAt, ) = IAggregatorV3(priceFeed).latestRoundData();
        if (answer <= 0) revert BadPrice();
        // A future `updatedAt` raises StalePrice instead of an underflow panic.
        if (updatedAt > block.timestamp || block.timestamp - updatedAt > maxAge) revert StalePrice();
        uint8 dec = IAggregatorV3(priceFeed).decimals();
        uint256 p = (uint256(answer) * scale) / (10 ** dec);
        return (priceCapUsd != 0 && p > priceCapUsd) ? priceCapUsd : p;
    }

    /// @dev `readStrict` plus the raw observation (before the cap) for `PoolLastGood.observe`; same returned price.
    function readStrictObs(address priceFeed, uint256 maxAge, uint256 scale, uint256 priceCapUsd) external view returns (uint256 p, uint256 obs) {
        (, int256 answer, , uint256 updatedAt, ) = IAggregatorV3(priceFeed).latestRoundData();
        if (answer <= 0) revert BadPrice();
        if (updatedAt > block.timestamp || block.timestamp - updatedAt > maxAge) revert StalePrice();
        uint8 dec = IAggregatorV3(priceFeed).decimals();
        p = (uint256(answer) * scale) / (10 ** dec);
        if (priceCapUsd != 0 && p > priceCapUsd) p = priceCapUsd;
        obs = PoolLastGood.observe(answer, updatedAt);
    }

    /// @dev Non-reverting read: returns 0 on a bad, stale or unreadable feed (the call is wrapped in try/catch).
    function readOrZero(address priceFeed, uint256 maxAge, uint256 scale, uint256 priceCapUsd) external view returns (uint256) {
        (bool ok, int256 answer, uint256 updatedAt, uint256 dec) = rawRound(priceFeed);
        if (!ok || answer <= 0) return 0;
        // A future `updatedAt` returns 0 instead of underflowing, so this never reverts.
        if (updatedAt > block.timestamp || block.timestamp - updatedAt > maxAge) return 0;
        uint256 p = (uint256(answer) * scale) / (10 ** dec);
        return (priceCapUsd != 0 && p > priceCapUsd) ? priceCapUsd : p; // asymmetric upside cap
    }

    /// @dev `readOrZero` plus the raw observation (before the cap) for `PoolLastGood.observe`; same returned price.
    function readOrZeroObs(address priceFeed, uint256 maxAge, uint256 scale, uint256 priceCapUsd) external view returns (uint256 p, uint256 obs) {
        (bool ok, int256 answer, uint256 updatedAt, uint256 dec) = rawRound(priceFeed);
        if (!ok || answer <= 0) return (0, 0);
        if (updatedAt > block.timestamp || block.timestamp - updatedAt > maxAge) return (0, 0);
        p = (uint256(answer) * scale) / (10 ** dec);
        if (priceCapUsd != 0 && p > priceCapUsd) p = priceCapUsd;
        obs = PoolLastGood.observe(answer, updatedAt);
    }

    /// @notice Liquidation strict read: `readStrict`, but a dark feed answers the fresher of its own and the pool's
    ///         last-good record inside the feed's window; pool context only, and `InsufficientGas` re-raises.
    function readLiqStrict(address priceFeed, uint256 maxAge, uint256 scale, uint256 priceCapUsd) external view returns (uint256 p) {
        (p, ) = _liqStrict(address(this), priceFeed, maxAge, scale, priceCapUsd);
    }

    /// @notice `readLiqStrict` for code outside the pool: the pool's record is read through `lastGoodRecordOf`.
    function readLiqStrictOf(address pool, address priceFeed, uint256 maxAge, uint256 scale, uint256 priceCapUsd) external view returns (uint256 p) {
        (p, ) = _liqStrict(pool, priceFeed, maxAge, scale, priceCapUsd);
    }

    /// @notice Liquidation lenient read: `readOrZero` over `readLiqStrict`'s answer; `InsufficientGas` re-raises.
    function readLiqOrZero(address priceFeed, uint256 maxAge, uint256 scale, uint256 priceCapUsd) external view returns (uint256 p) {
        (p, ) = _liqOrZero(address(this), priceFeed, maxAge, scale, priceCapUsd);
    }

    /// @notice `readLiqOrZero` for code outside the pool (the liquidation views).
    function readLiqOrZeroOf(address pool, address priceFeed, uint256 maxAge, uint256 scale, uint256 priceCapUsd) external view returns (uint256 p) {
        (p, ) = _liqOrZero(pool, priceFeed, maxAge, scale, priceCapUsd);
    }

    /// @notice The pool's liquidation reads plus the observation it may record (only a healthy live answer, uncapped).
    ///         `strict` picks `readLiqStrict` (debt) or `readLiqOrZero` (collateral).
    function readLiqObs(address priceFeed, uint256 maxAge, uint256 scale, uint256 priceCapUsd, bool strict)
        external view returns (uint256 p, uint256 obs)
    {
        return strict ? _liqStrict(address(this), priceFeed, maxAge, scale, priceCapUsd)
            : _liqOrZero(address(this), priceFeed, maxAge, scale, priceCapUsd);
    }

    function _liqStrict(address pool, address priceFeed, uint256 maxAge, uint256 scale, uint256 priceCapUsd)
        private view returns (uint256 p, uint256 obs)
    {
        (bool ok, bool live, int256 answer, uint256 updatedAt, uint256 dec, bytes memory err) = _liqRound(pool, priceFeed);
        if (!ok) {
            // No answer: the latest read's own refusal when it reverted (as with no fallback), BadPrice otherwise.
            if (err.length != 0) assembly ("memory-safe") { revert(add(err, 0x20), mload(err)) }
            revert BadPrice();
        }
        if (answer <= 0) revert BadPrice();
        if (updatedAt > block.timestamp || block.timestamp - updatedAt > maxAge) revert StalePrice();
        p = (uint256(answer) * scale) / (10 ** dec);
        if (priceCapUsd != 0 && p > priceCapUsd) p = priceCapUsd;
        if (live) obs = PoolLastGood.observe(answer, updatedAt);
    }

    function _liqOrZero(address pool, address priceFeed, uint256 maxAge, uint256 scale, uint256 priceCapUsd)
        private view returns (uint256 p, uint256 obs)
    {
        (bool ok, bool live, int256 answer, uint256 updatedAt, uint256 dec, ) = _liqRound(pool, priceFeed);
        if (!ok || answer <= 0) return (0, 0);
        if (updatedAt > block.timestamp || block.timestamp - updatedAt > maxAge) return (0, 0);
        p = (uint256(answer) * scale) / (10 ** dec);
        if (priceCapUsd != 0 && p > priceCapUsd) p = priceCapUsd;
        if (live) obs = PoolLastGood.observe(answer, updatedAt);
    }

    /// @notice `rawRound`, falling back to the fresher last-good answer when the latest round cannot be read.
    ///         For liquidation-side readers outside the pool; `InsufficientGas` re-raises first.
    function rawRoundLiq(address feed, address pool) internal view returns (bool ok, int256 answer, uint256 updatedAt, uint256 dec) {
        (ok, , answer, updatedAt, dec, ) = _liqRound(pool, feed);
    }

    /// @notice The liquidation-grade round shared by the reads above; reverts only on `InsufficientGas`.
    ///         `live`: `latestRoundData` answered; else the fresher last-good record, or `err` holding the revert data.
    function _liqRound(address pool, address feed)
        internal view returns (bool ok, bool live, int256 answer, uint256 updatedAt, uint256 dec, bytes memory err)
    {
        (bool s, bytes memory r) = feed.staticcall(abi.encodeWithSelector(IAggregatorV3.latestRoundData.selector));
        if (s) {
            if (r.length < 160) return (false, false, 0, 0, 0, err);
            (, answer, , updatedAt, ) = abi.decode(r, (uint256, int256, uint256, uint256, uint256));
            ok = true;
            live = true;
        } else {
            bubbleInsufficientGas(r);
            err = r;
            (s, r) = feed.staticcall(abi.encodeWithSelector(ILastGoodFeed.lastGoodRoundData.selector));
            if (s && r.length >= 160) {
                (, answer, , updatedAt, ) = abi.decode(r, (uint256, int256, uint256, uint256, uint256));
                ok = true;
            }
            (bool pOk, uint256 pAnswer, uint256 pAt) = _poolRecord(pool, feed);
            if (pOk && (!ok || pAt > updatedAt)) {
                answer = int256(pAnswer);
                updatedAt = pAt;
                ok = true;
            }
            if (!ok) return (false, false, 0, 0, 0, err);
        }
        (s, r) = feed.staticcall(abi.encodeWithSelector(IAggregatorV3.decimals.selector));
        if (!s || r.length < 32) return (false, false, 0, 0, 0, err);
        dec = abi.decode(r, (uint256));
        if (dec > 77) return (false, false, 0, 0, 0, err);
    }

    /// The pool's own record for `feed`, used only inside the feed's `lastGoodWindow()` (0 = 1 hour, max 6 hours).
    function _poolRecord(address pool, address feed) private view returns (bool ok, uint256 answer, uint256 at) {
        (bool s, bytes memory r) = feed.staticcall(abi.encodeWithSelector(ILastGoodFeed.lastGoodWindow.selector));
        if (!s || r.length < 32) return (false, 0, 0);
        uint256 w = abi.decode(r, (uint256));
        if (w == 0) w = 1 hours;
        else if (w > 6 hours) w = 6 hours;
        if (pool == address(this)) {
            (answer, at) = PoolLastGood.load(feed);
        } else {
            (s, r) = pool.staticcall(abi.encodeWithSelector(ILastGoodPool.lastGoodRecordOf.selector, feed));
            if (!s || r.length < 64) return (false, 0, 0);
            (answer, at) = abi.decode(r, (uint256, uint256));
        }
        if (answer == 0 || answer > type(uint128).max || at == 0 || at > block.timestamp || block.timestamp - at > w) return (false, 0, 0);
        ok = true;
    }

    /// @notice A feed's latest answer, update time and decimals that never reverts: raw staticcalls with length checks.
    ///         Decimals above 77 count as unreadable.
    function rawRound(address feed) internal view returns (bool ok, int256 answer, uint256 updatedAt, uint256 dec) {
        bytes memory r;
        (ok, r) = feed.staticcall(abi.encodeWithSelector(IAggregatorV3.latestRoundData.selector));
        if (!ok) bubbleInsufficientGas(r);
        if (!ok || r.length < 160) return (false, 0, 0, 0);
        (, answer, , updatedAt, ) = abi.decode(r, (uint256, int256, uint256, uint256, uint256));
        (ok, r) = feed.staticcall(abi.encodeWithSelector(IAggregatorV3.decimals.selector));
        if (!ok || r.length < 32) return (false, 0, 0, 0);
        dec = abi.decode(r, (uint256));
        if (dec > 77) return (false, 0, 0, 0);
    }

    /// @notice Re-raises a standard feed's `InsufficientGas()`, so a caller cannot turn a gas limit into "no price".
    function bubbleInsufficientGas(bytes memory r) internal pure {
        if (r.length == 4 && bytes4(r) == INSUFFICIENT_GAS) revert InsufficientGas();
    }
}

project/contracts/libraries/TickMath.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.20;

/// @title Math library for computing sqrt prices from ticks
/// @dev Adapted from Uniswap v3-core libraries/TickMath.sol (GPL-2.0-or-later).
/// @notice `getSqrtRatioAtTick` only; it cannot overflow uint256 for any tick within `MAX_TICK`.
library TickMath {
    /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick, exactly -MAX_TICK.
    int24 internal constant MIN_TICK = -887272;
    /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick
    int24 internal constant MAX_TICK = 887272;

    /// @notice Calculates sqrt(1.0001^tick) * 2^96
    /// @dev Throws if |tick| > max tick
    /// @param tick The input tick for the above formula
    /// @return sqrtPriceX96 The sqrt of token1/token0 at the given tick, as a Q64.96 number
    function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
        uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
        require(absTick <= uint256(int256(MAX_TICK)), 'T');

        uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
        if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
        if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
        if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
        if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
        if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
        if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
        if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
        if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
        if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
        if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
        if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
        if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
        if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
        if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
        if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
        if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
        if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
        if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
        if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;

        if (tick > 0) ratio = type(uint256).max / ratio;

        // Divide by 1<<32 rounding up (Q128.128 to Q128.96); the result fits in 160 bits for any valid tick.
        // Rounding up keeps getTickAtSqrtRatio of the output price consistent.
        sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
    }
}

project/contracts/utils/GenesisOwned.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;

/// @title GenesisOwned
/// @notice Admin roles: `genesis` (root, two-step transfer), `riskAdmin` (economic dials) and `guardian` (pause).
/// @dev Inheriting this adds storage slots ahead of the child's; adopting it in a deployed contract needs a migration.
abstract contract GenesisOwned {
    /// @notice The root admin role; satisfies every gate.
    address public genesis;
    /// @notice The nominated next genesis, cleared on accept or re-nomination.
    address public pendingGenesis;

    /// @notice The pause key; it cannot unpause, which is genesis's.
    address public guardian;

    /// @notice The key for economic dials (caps, factors, fees, bounties, rates, cooldowns); no oracle, router,
    ///         upgrade, treasury or wiring powers.
    address public riskAdmin;

    error NotGenesis();
    error NotPendingGenesis();
    error NotRiskAdmin();
    error NotGuardian();
    error ZeroGenesis();

    event GenesisTransferStarted(address indexed from, address indexed to);
    event GenesisTransferred(address indexed from, address indexed to);
    event GuardianSet(address indexed guardian);
    event RiskAdminSet(address indexed riskAdmin);

    // The checks are internal functions so each modifier use inlines only a call. `genesis` passes every gate.

    function _requireGenesis() internal view {
        if (msg.sender != genesis) revert NotGenesis();
    }

    function _requireRiskAdmin() internal view {
        if (msg.sender != riskAdmin && msg.sender != genesis) revert NotRiskAdmin();
    }

    function _requireGuardian() internal view {
        if (msg.sender != guardian && msg.sender != genesis) revert NotGuardian();
    }

    modifier onlyGenesis() {
        _requireGenesis();
        _;
    }

    /// @dev Genesis or riskAdmin.
    modifier onlyRiskAdmin() {
        _requireRiskAdmin();
        _;
    }

    /// @dev Genesis or guardian.
    modifier onlyGuardian() {
        _requireGuardian();
        _;
    }

    /// @notice Appoint the guardian; `address(0)` revokes.
    function setGuardian(address guardian_) external onlyGenesis {
        guardian = guardian_;
        emit GuardianSet(guardian_);
    }

    /// @notice Appoint or revoke the risk admin. `address(0)` revokes.
    function setRiskAdmin(address riskAdmin_) external onlyGenesis {
        riskAdmin = riskAdmin_;
        emit RiskAdminSet(riskAdmin_);
    }

    /// @dev Call from a constructor or an `initialize`.
    function _initGenesis(address genesis_) internal {
        if (genesis_ == address(0)) revert ZeroGenesis();
        genesis = genesis_;
        emit GenesisTransferred(address(0), genesis_);
    }

    /// @notice Step 1 of 2: nominate `newGenesis`; `address(0)` cancels a pending transfer.
    function transferGenesis(address newGenesis) external onlyGenesis {
        pendingGenesis = newGenesis;
        emit GenesisTransferStarted(genesis, newGenesis);
    }

    /// @notice Step 2 of 2: the nominated address claims the role, proving it can transact.
    function acceptGenesis() external {
        if (msg.sender != pendingGenesis) revert NotPendingGenesis();
        address old = genesis;
        genesis = msg.sender;
        pendingGenesis = address(0);
        emit GenesisTransferred(old, msg.sender);
    }
}

project/contracts/vaults/VaultCore.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;

import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
import "./interfaces/IVaultCore.sol";
import "./interfaces/IClearing.sol";
import "./interfaces/IRehypoLendingPool.sol";
import "./libraries/Range.sol";
import "./libraries/PriceLib.sol";
import "./libraries/ShapeMath.sol";
import {ShareHookDispatch} from "./libraries/ShareHookDispatch.sol";
import {VaultExitLogic} from "./libraries/VaultExitLogic.sol";
import "../libraries/KeeperBounty.sol";
import "../utils/GenesisOwned.sol";

interface IVaultFeeManager {
    function computeAndRoute(address vault, address strategist, uint256 fee0, uint256 fee1)
        external
        returns (uint256 remainder0, uint256 remainder1);
}


/// @notice HORIZON-emissions accountant for vault shares.
interface IVaultShareIncentives {
    function handleShareMove(
        address from, address to, uint256 value, uint256 totalSupplyBefore, uint256 fromBalanceBefore, uint256 toBalanceBefore
    ) external;
}

/// @title VaultCore
/// @notice AMM-version-agnostic core shared by `V3Vault` and `V4Vault`: ERC20 share accounting.
abstract contract VaultCore is Initializable, ERC20Upgradeable, ReentrancyGuardTransient, IVaultCore, GenesisOwned {
    using SafeERC20 for IERC20;

    uint256 internal constant BPS = 10_000;
    uint256 internal constant VIRTUAL_SHARES = 1e3;
    uint256 internal constant VIRTUAL_ASSETS = 1;
    /// @dev The clearing's fallback TWAP window, which sizes the pool's initial observation buffer.
    uint256 internal constant DEFAULT_TWAP_WINDOW = 15 minutes;
    /// @dev `compound`'s NAV floor: value at TWAP may not fall more than 3% across the deploy and park.
    uint256 internal constant COMPOUND_MAX_SLIPPAGE_BPS = 300;
    /// @dev The highest caller bounty that can be set: 20% of realised fees.
    uint256 internal constant MAX_CALLER_BOUNTY_BPS = 2_000;
    IERC20  internal _token0;
    IERC20  internal _token1;

    Range[] internal _ranges;

    address public rebalanceGuard;
    address public feeManager;
    address public clearing;
    address public strategist;
    bool public depositsPaused;
    bool public rebalancingPaused;
    bool public globalPause;
    /// @dev Packs into the slot of the three bools above.
    int24 public shapeHalfWidth;
    uint8 public shapePositionCount;
    /// @notice Bps of realised fees paid to the caller of `rebalanceOptimal`.
    uint256 public callerBountyBps;
    /// @notice `zapDeposit`'s swap venue.
    address public swapRouter;

    /// @notice Emissions accountant for this vault's shares, or `address(0)` for none.
    address public shareIncentives;

    address public lendingPool;
    bool public rehypoEnabled;
    uint16 public rehypoFloorBps; // fraction of idle kept raw as a working buffer, never lent
    // Max share of the reserve's liquid depth this vault may park; packs into the slot above.
    uint16 public rehypoCapBps;

    event RehypoConfigSet(address indexed lendingPool, bool enabled, uint16 floorBps);

    event Deposit(address indexed sender, address indexed to, uint256 shares, uint256 amount0, uint256 amount1);
    event Withdraw(address indexed sender, address indexed to, uint256 shares, uint256 amount0, uint256 amount1);
    event EmergencyWithdraw(address indexed sender, address indexed to, uint256 shares, uint256 amount0, uint256 amount1);
    event Rebalance(address indexed caller, uint256 rangeCount, uint256 fee0, uint256 fee1);
    event Compounded(address indexed caller, uint256 fee0, uint256 fee1);
    event RangesUpdated(Range[] ranges);
    event RebalanceGuardSet(address indexed rebalanceGuard);
    event FeeManagerSet(address indexed feeManager);
    event ClearingSet(address indexed clearing);
    event StrategistSet(address indexed strategist);
    event PauseSet(bool depositsPaused, bool rebalancingPaused, bool globalPause);
    event ShapeConfigSet(int24 halfWidth, uint8 positionCount);
    event CallerBountyBpsSet(uint256 callerBountyBps);
    event SwapRouterSet(address indexed swapRouter);
    event ShareIncentivesSet(address indexed shareIncentives);
    event RebalancedOptimal(address indexed caller, uint256 rangeCount, uint256 bounty0, uint256 bounty1);
    error ZeroAddress();
    error ZeroShares();
    error ZeroAmounts();
    error InsufficientShares();
    error SlippageExceeded();
    error DepositsArePaused();
    error RebalancingIsPaused();
    error NotGloballyPaused();
    error NotRebalanceGuard();
    error BadRehypoConfig();
    error RehypoOldPoolNotDrained();
    error RehypoVaultNotRegistered();
    error InvalidTickRange();
    error NoRanges();
    error TooManyRanges();
    error WeightsMustSumToBps();
    error NoShapeConfigured();
    error BountyTooHigh();
    error NoSwapRouter();
    error NoClearing();
    error InvalidZapToken();
    error NotDepositOwner();
    error PriceNotStable();
    error CompoundSlippageExceeded();
    /// @notice A plain deposit with no part in the vault's token composition.
    error TryLater();
    error BadSecondsPerBlock();
    modifier onlyRebalanceGuard() {
        if (msg.sender != rebalanceGuard) revert NotRebalanceGuard();
        _;
    }

    /// @dev Called by each venue's `initialize` once it has resolved the two tokens.
    function __VaultCore_init(
        address token0_, address token1_, address genesis_,
        Range[] memory ranges_, string memory name_, string memory symbol_
    ) internal onlyInitializing {
        if (token0_ == address(0) || token1_ == address(0) || genesis_ == address(0)) revert ZeroAddress();
        __ERC20_init(name_, symbol_);
        _token0 = IERC20(token0_);
        _token1 = IERC20(token1_);
        _initGenesis(genesis_);
        // Genesis can drive rebalances until the real RebalanceGuard is wired.
        rebalanceGuard = genesis_;

        _setRanges(ranges_);
    }

    function _maxRanges() internal pure virtual returns (uint256);

    /// @dev Only called with no live positions: `rebalance` unwinds every position before writing new ranges.
    function _setRanges(Range[] memory newRanges) internal {
        uint256 count = newRanges.length;
        if (count == 0) revert NoRanges();
        if (count > _maxRanges()) revert TooManyRanges();

        uint256 totalWeight;
        delete _ranges;
        for (uint256 i = 0; i < count; i++) {
            Range memory r = newRanges[i];
            if (r.tickLower >= r.tickUpper) revert InvalidTickRange();
            totalWeight += r.weightBps;
            _ranges.push(r);
        }
        if (totalWeight != BPS) revert WeightsMustSumToBps();

        _onRangesReset();
        emit RangesUpdated(newRanges);
    }

    /// @dev Venue hook run after `_ranges` is overwritten.
    function _onRangesReset() internal virtual;

    function ranges() external view returns (Range[] memory) {
        return _ranges;
    }

    function rangeCount() external view returns (uint256) {
        return _ranges.length;
    }

    function token0() external view returns (address) { return address(_token0); }
    function token1() external view returns (address) { return address(_token1); }

    /// @notice Total share supply.
    function totalSupply() public view virtual override(ERC20Upgradeable, IVaultCore) returns (uint256) {
        return super.totalSupply();
    }

    /// @notice Everything the shares claim, at spot.
    function getTotalAmounts() public view virtual returns (uint256 amount0, uint256 amount1);

    /// @dev Venue hook: total amounts with the range legs valued at `sqrtPriceX96`.
    function _totalAmountsAt(uint160 sqrtPriceX96) internal view virtual returns (uint256 amount0, uint256 amount1);

    /// @notice Total vault value in token1 terms at spot.
    function nav() public view returns (uint256) {
        (uint256 amount0, uint256 amount1) = getTotalAmounts();
        return PriceLib.valueInToken1(amount0, amount1, _spotPrice());
    }

    function _spotPrice() internal view virtual returns (uint256);

    /// @dev The pool's tick spacing.
    function _tickSpacing() internal view virtual returns (int24);

    function setRebalanceGuard(address rebalanceGuard_) external onlyGenesis {
        if (rebalanceGuard_ == address(0)) revert ZeroAddress();
        rebalanceGuard = rebalanceGuard_;
        emit RebalanceGuardSet(rebalanceGuard_);
    }

    function setFeeManager(address feeManager_) external onlyGenesis {
        _checkFactories(feeManager_, feeLedger);
        feeManager = feeManager_;
        emit FeeManagerSet(feeManager_);
    }

    /// @dev Non-zero, one-way.
    function setClearing(address clearing_) external onlyGenesis {
        if (clearing_ == address(0)) revert ZeroAddress();
        clearing = clearing_;
        emit ClearingSet(clearing_);
    }

    function setStrategist(address strategist_) external onlyGenesis {
        strategist = strategist_;
        emit StrategistSet(strategist_);
    }

    /// @notice Set the pause flags: the guardian may raise any at once; lowering one needs genesis.
    function setPauseState(bool depositsPaused_, bool rebalancingPaused_, bool globalPause_) external onlyGuardian {
        if (depositsPaused && !depositsPaused_ || rebalancingPaused && !rebalancingPaused_ || globalPause && !globalPause_) _requireGenesis();
        depositsPaused = depositsPaused_;
        rebalancingPaused = rebalancingPaused_;
        globalPause = globalPause_;
        emit PauseSet(depositsPaused_, rebalancingPaused_, globalPause_);
    }

    /// @notice Set the Gaussian shape `rebalanceOptimal` builds around the TWAP tick; a non-genesis caller may only widen.
    function setShapeConfig(int24 halfWidth_, uint8 positionCount_) external onlyRiskAdmin {
        _checkGeometry(halfWidth_, positionCount_, widthConfig);
        shapeHalfWidth = halfWidth_;
        shapePositionCount = positionCount_;
        emit ShapeConfigSet(halfWidth_, positionCount_);
    }

    struct WidthConfig {
        bool enabled;
        int24 minHalfWidth;
        int24 maxHalfWidth;
        uint32 volWindow;          // seconds of TWAP the spot deviation is measured against
        uint32 volSaturationTicks; // deviation mapping to maxHalfWidth
    }

    WidthConfig public widthConfig;

    address public feeLedger;
    bool public feeLedgerSevered;

    event FeeLedgerSet(address indexed feeLedger);
    error FeeLedgerLocked();
    error FactoryMismatch();

    event WidthConfigSet(bool enabled, int24 minHalfWidth, int24 maxHalfWidth, uint32 volWindow, uint32 volSaturationTicks);

    /// @notice Set the volatility-adaptive width; bounds and the loosening rule as `setShapeConfig`.
    function setWidthConfig(WidthConfig calldata cfg) external onlyRiskAdmin {
        _checkGeometry(shapeHalfWidth, shapePositionCount, cfg);
        widthConfig = cfg;
        emit WidthConfigSet(cfg.enabled, cfg.minHalfWidth, cfg.maxHalfWidth, cfg.volWindow, cfg.volSaturationTicks);
    }

    error BadWidthConfig();

    /// @dev Spot tick and trailing-TWAP tick over `window`, venue-specific.
    function _spotAndTwapTick(uint32 window) internal view virtual returns (int24 spot, int24 twap, bool ok);

    /// @dev The half-width `rebalanceOptimal` should use right now.
    function _effectiveHalfWidth() internal view returns (int24) {
        WidthConfig memory wc = widthConfig;
        if (!wc.enabled) return shapeHalfWidth;
        (int24 spot, int24 twap, bool ok) = _spotAndTwapTick(wc.volWindow);
        if (!ok) return shapeHalfWidth;
        uint256 volTicks = spot > twap ? uint256(int256(spot - twap)) : uint256(int256(twap - spot));
        return ShapeMath.adaptiveHalfWidth(volTicks, wc.minHalfWidth, wc.maxHalfWidth, wc.volSaturationTicks);
    }

    /// @notice Set the caller bounty for `rebalanceOptimal`, bps of realised fees.
    function setCallerBountyBps(uint256 callerBountyBps_) external onlyRiskAdmin {
        if (callerBountyBps_ > MAX_CALLER_BOUNTY_BPS) revert BountyTooHigh();
        if (callerBountyBps_ > callerBountyBps && msg.sender != genesis) revert NotGenesis();
        callerBountyBps = callerBountyBps_;
        emit CallerBountyBpsSet(callerBountyBps_);
    }

    /// @notice Set `zapDeposit`'s swap venue.
    function setSwapRouter(address swapRouter_) external onlyGenesis {
        if (swapRouter_ == address(0)) revert ZeroAddress();
        swapRouter = swapRouter_;
        emit SwapRouterSet(swapRouter_);
    }

    /// @notice Point this vault's shares at a HORIZON-emissions accountant, or `address(0)` to earn none.
    function setShareIncentives(address shareIncentives_) external onlyGenesis {
        address old = shareIncentives;
        if (old != address(0)) _beforeShareUpdate(old, address(0), address(0), address(0), 0);
        shareIncentives = shareIncentives_;
        unchecked { ++shareIncentivesEpoch; } // a count of genesis calls: cannot overflow
        emit ShareIncentivesSet(shareIncentives_);
    }

    /// @notice Wire the holder-fee ledger once, or sever it for good with `address(0)`; it is never re-pointed.
    function setFeeLedger(address feeLedger_) external onlyGenesis {
        // Allowed: unset -> set (once), and set -> 0 (sever, once). Everything else is locked.
        if (feeLedgerSevered || (feeLedger_ != address(0)) == (feeLedger != address(0))) revert FeeLedgerLocked();
        if (feeLedger_ == address(0)) feeLedgerSevered = true;
        _checkFactories(feeManager, feeLedger_);
        feeLedger = feeLedger_;
        emit FeeLedgerSet(feeLedger_);
    }

    /// @dev FeeManager and the ledger must share a vault registry, or every holder credit reverts.
    function _checkFactories(address fm, address ledger) internal view virtual;

    /// @notice Point the vault at a lending pool and turn rehypothecation on/off.
    function setRehypo(address lendingPool_, bool enabled_, uint16 floorBps_, uint16 capBps_)
        external
        onlyGenesis
    {
        _checkRehypo(lendingPool_, enabled_, floorBps_, capBps_);
        lendingPool = lendingPool_;
        rehypoEnabled = enabled_;
        rehypoFloorBps = floorBps_;
        rehypoCapBps = capBps_;
        emit RehypoConfigSet(lendingPool_, enabled_, floorBps_);
    }

    /// @dev Reclaim all parked inventory for both legs to raw tokens.
    function _reclaimAllInventory() internal virtual;
    /// @dev Venue hooks for the config validation (VaultConfigChecks).
    function _checkRehypo(address newPool, bool enabled, uint16 floorBps, uint16 capBps) internal view virtual;
    /// @dev Checks the would-be shape and width: bounds, then the widen-only rule for a non-genesis caller.
    function _checkGeometry(int24 hw, uint8 n, WidthConfig memory c) internal view {
        ShapeMath.checkGeometry(hw, n, c.enabled, c.minHalfWidth, c.maxHalfWidth, c.volWindow, c.volSaturationTicks, _tickSpacing());
    }

    // `unrealisedFees() returns (fee0, fee1, inTotals0, inTotals1)`, declared by each venue (`V3Vault`, `V4Vault`)
    // straight from its position-logic library: the trading fees the next realise would collect, per token.

    /// @dev Venue hook: run `ShareHookDispatch.dispatch` through the venue's position-logic library.
    function _beforeShareUpdate(address accountant, address ledger, address from, address to, uint256 value) internal virtual;
    function _parkExcessInventory() internal virtual;

    /// @dev Settles both sides of every balance change, mints and burns included, before the balance moves.
    function _update(address from, address to, uint256 value) internal virtual override {
        address accountant = shareIncentives;
        address ledger = feeLedger;
        if (from == address(0)) VaultExitLogic.recordMint(); // the vault-wide last mint block (RebalanceGuard's floor check)
        // Called on every update; the venue library skips the dispatch when neither is wired.
        _beforeShareUpdate(accountant, ledger, from, to, value);
        super._update(from, to, value);
    }

    /// @notice One raw storage word of this vault (Uniswap V4's `IExtsload`).
    function extsload(bytes32 slot) external view returns (bytes32 value) {
        assembly { value := sload(slot) }
    }

    /// @dev Transient: 1 while a zap's deposit is cleared and the pool had not traded this block when the zap began.
    bytes32 internal constant ZAP_UNTRADED_SLOT = 0x6d039ff8d6e878fa37ccdb1278059f4f7126e3d2ffe72e4ca5987084496d3d7d;

    /// @notice Whether the zap being cleared began in a block the pool had not traded in; false outside a zap.
    function zapUntradedBlock() external view returns (bool u) {
        assembly { u := tload(ZAP_UNTRADED_SLOT) }
    }

    /// @dev Whether the pool is untraded this block; a clearing that cannot answer reads as traded.
    function _untradedNow() internal view returns (bool) {
        (bool ok, bytes memory r) = clearing.staticcall(abi.encodeWithSignature("tradedThisBlock(address)", address(this)));
        return ok && r.length == 32 && abi.decode(r, (uint256)) == 0;
    }

    /// @dev Clears a zap with the block state from before its own swap, which would otherwise mark the block traded.
    function _clearZap(bool untraded, uint256 amount0, uint256 amount1) internal {
        if (untraded) assembly { tstore(ZAP_UNTRADED_SLOT, 1) }
        IClearing(clearing).clearDeposit(address(this), amount0, amount1, msg.sender);
        if (untraded) assembly { tstore(ZAP_UNTRADED_SLOT, 0) }
    }

    /// @notice Deposit both tokens, fitted to the vault's composition, for `to`; `from` must be the caller.
    function deposit(uint256 amount0Desired, uint256 amount1Desired, address to, address from, uint256 minShares)
        external
        nonReentrant
        returns (uint256 shares)
    {
        if (from != msg.sender) revert NotDepositOwner();
        if (depositsPaused || globalPause) revert DepositsArePaused();
        if (amount0Desired == 0 && amount1Desired == 0) revert ZeroAmounts();
        // The clearing gate is required; fail closed.
        if (clearing == address(0)) revert NoClearing();
        // Fits the deposit to the vault's composition and clears it; only the fitted amounts are pulled.
        (amount0Desired, amount1Desired) = VaultExitLogic.clearPlainDeposit(clearing, amount0Desired, amount1Desired);

        // Realise pending fees before pricing shares, or a deposit-then-withdraw captures them.
        _realiseFeesAndRoute();

        _snapshotExistingValue();

        // Price off what the vault actually received (fee-on-transfer safe).
        uint256 amount0;
        uint256 amount1;
        if (amount0Desired > 0) {
            uint256 before0 = _token0.balanceOf(address(this));
            _token0.safeTransferFrom(from, address(this), amount0Desired);
            amount0 = _token0.balanceOf(address(this)) - before0;
        }
        if (amount1Desired > 0) {
            uint256 before1 = _token1.balanceOf(address(this));
            _token1.safeTransferFrom(from, address(this), amount1Desired);
            amount1 = _token1.balanceOf(address(this)) - before1;
        }

        shares = _creditDeposit(amount0, amount1, to, minShares);
        emit Deposit(from, to, shares, amount0, amount1);
    }

    /// @dev Snapshot of the vault's value before new funds arrive.
    function _snapshotExistingValue() internal returns (uint256 twapPrice, uint256 existing0, uint256 existing1) {
        return _depositQuote(_twapSqrt());
    }

    /// @dev Venue hook for `_creditDeposit`: the lowest share count over the stored quote.
    function _quotedShares(uint256 amount0, uint256 amount1, uint256 supply, uint256 virtualAssets) internal view virtual returns (uint256);

    /// @dev Venue hook for `_snapshotExistingValue`.
    function _depositQuote(uint160 sqrtTwap) internal virtual returns (uint256 twapPrice, uint256 existing0, uint256 existing1);

    /// @dev The clearing's TWAP tick as a sqrt price, shared by every manipulation-guarded read.
    function _twapSqrt() internal view returns (uint160) {
        return ShapeMath.sqrtRatioAtTick(IClearing(clearing).twapTick(address(this)));
    }

    /// @dev Shared tail for `deposit` and `zapDeposit`: prices the value added against the snapshot and mints shares.
    function _creditDeposit(uint256 amount0, uint256 amount1, address to, uint256 minShares)
        internal
        returns (uint256 shares)
    {
        // The lowest of the counts, one per valuation point; see _snapshotExistingValue.
        shares = _quotedShares(amount0, amount1, totalSupply() + VIRTUAL_SHARES, VIRTUAL_ASSETS);
        if (shares == 0 || shares < minShares) revert SlippageExceeded();

        _mint(to, shares);
        // No deploy here: the deposit waits idle for `compound` or a rebalance.
    }

    /// @dev Hook: swap the idle balance to the new ranges' ratio just before `_deployIdleCapital`.
    function _swapToRatioBeforeDeploy(bool optimal) internal virtual {}

    function withdraw(uint256 shares, address to, uint256 amount0Min, uint256 amount1Min)
        external
        nonReentrant
        returns (uint256 amount0, uint256 amount1)
    {
        // During `globalPause` a withdraw neither routes fees nor re-parks.
        (amount0, amount1) = _exit(shares, to, !globalPause);
        if (amount0 < amount0Min || amount1 < amount1Min) revert SlippageExceeded();
        if (!globalPause) _parkExcessInventory();
        emit Withdraw(msg.sender, to, shares, amount0, amount1);
        // Not checkpointed: a withdraw leaves NAV per share unchanged.
    }

    /// @notice Exit during `globalPause`; fees are not routed and stay in the vault for remaining shares.
    function emergencyWithdraw(uint256 shares, address to, uint256 amount0Min, uint256 amount1Min)
        external
        nonReentrant
        returns (uint256 amount0, uint256 amount1)
    {
        if (!globalPause) revert NotGloballyPaused();
        (amount0, amount1) = _exit(shares, to, false);
        // A best-effort reclaim can under-deliver from an illiquid reserve, so slippage is checked here too.
        if (amount0 < amount0Min || amount1 < amount1Min) revert SlippageExceeded();
        emit EmergencyWithdraw(msg.sender, to, shares, amount0, amount1);
    }

    function _exit(uint256 shares, address to, bool routeFees) internal returns (uint256 amount0, uint256 amount1) {
        if (shares == 0) revert ZeroShares();
        if (shares > balanceOf(msg.sender)) revert InsufficientShares();

        // Realise and route pending fees before pricing the exit, so the withdrawer gets a pro-rata slice.
        if (routeFees) _realiseFeesAndRoute();

        // Reclaim parked inventory first, so the pro-rata payout runs on the full raw balance.
        _reclaimAllInventory();

        uint256 supply = totalSupply();
        _burn(msg.sender, shares);

        uint256 fee0;
        uint256 fee1;
        (amount0, amount1, fee0, fee1) = _withdrawProRata(shares, supply, to);

        if (routeFees && (fee0 > 0 || fee1 > 0)) _routeFees(fee0, fee1);
    }

    /// @dev Burns a pro-rata slice of every position's principal (plus idle balance) and pays `to`.
    function _withdrawProRata(uint256 shares, uint256 supply, address to)
        internal
        virtual
        returns (uint256 amount0, uint256 amount1, uint256 fee0, uint256 fee1);

    /// @notice Unwinds every position, routes the cut from fees only, writes the new ranges and redeploys.
    function rebalance(Range[] calldata newRanges)
        external
        onlyRebalanceGuard
        nonReentrant
        returns (uint256 amount0Before, uint256 amount1Before, uint256 amount0After, uint256 amount1After)
    {
        if (rebalancingPaused || globalPause) revert RebalancingIsPaused();
        // No caller bounty on the manual path.
        uint256 fee0;
        uint256 fee1;
        (amount0Before, amount1Before, amount0After, amount1After, fee0, fee1) =
            _executeRebalance(newRanges, address(0), 0);
        emit Rebalance(msg.sender, newRanges.length, fee0, fee1);
    }

    /// @notice Deterministic, permissionless recenter: no caller-supplied ranges at all.
    function rebalanceOptimal(address caller, uint256 bountyBps)
        external
        onlyRebalanceGuard
        nonReentrant
        returns (uint256 amount0Before, uint256 amount1Before, uint256 amount0After, uint256 amount1After)
    {
        if (rebalancingPaused || globalPause) revert RebalancingIsPaused();

        int24 centerTick = IClearing(clearing).twapTick(address(this));
        Range[] memory newRanges = _buildOptimalRanges(centerTick);

        uint256 fee0;
        uint256 fee1;
        (amount0Before, amount1Before, amount0After, amount1After, fee0, fee1) =
            _executeRebalance(newRanges, caller, bountyBps);
        emit Rebalance(caller, newRanges.length, fee0, fee1);
    }

    /// @dev The range shape `rebalanceOptimal` deploys, centred on `centerTick`.
    function _buildOptimalRanges(int24 centerTick) internal view virtual returns (Range[] memory) {
        if (shapePositionCount == 0) revert NoShapeConfigured();
        return ShapeMath.buildRanges(
            ShapeMath.Shape.Gaussian, centerTick, _tickSpacing(), _effectiveHalfWidth(), shapePositionCount
        );
    }

    /// @dev Shared body of `rebalance` and `rebalanceOptimal`; a bounty is paid when `caller` is set.
    function _executeRebalance(Range[] memory newRanges, address caller, uint256 bountyBps)
        internal
        returns (
            uint256 amount0Before, uint256 amount1Before, uint256 amount0After, uint256 amount1After,
            uint256 fee0, uint256 fee1
        )
    {
        // Reclaim parked inventory so the unwind/redeploy below works on raw balances.
        _reclaimAllInventory();

        (amount0Before, amount1Before) = _rebalanceFloorAmounts();

        (fee0, fee1) = _unwindAll();
        ShareHookDispatch.markRealised();

        // The RebalanceGuard supplies the bounty rate, capped here.
        uint256 effBps = bountyBps > MAX_CALLER_BOUNTY_BPS ? MAX_CALLER_BOUNTY_BPS : bountyBps;
        if (caller != address(0) && effBps > 0) {
            (uint256 bounty0, uint256 remainder0) = KeeperBounty.split(fee0, effBps);
            (uint256 bounty1, uint256 remainder1) = KeeperBounty.split(fee1, effBps);
            if (bounty0 > 0) _token0.safeTransfer(caller, bounty0);
            if (bounty1 > 0) _token1.safeTransfer(caller, bounty1);
            fee0 = remainder0;
            fee1 = remainder1;
            emit RebalancedOptimal(caller, newRanges.length, bounty0, bounty1);
        }

        _routeFees(fee0, fee1);
        _setRanges(newRanges);
        // Swap the unwound balance to the new ranges' ratio before deploying.
        _swapToRatioBeforeDeploy(caller != address(0));
        _deployIdleCapital();
        // Park the out-of-ratio leftover; no-op when rehypo is disabled.
        _parkExcessInventory();

        (amount0After, amount1After) = _rebalanceFloorAmounts();
        _checkpointNav();
    }

    /// @dev Amounts at TWAP (not spot) that RebalanceGuard's NAV floor compares before and after.
    function _rebalanceFloorAmounts() private view returns (uint256, uint256) {
        return clearing != address(0) ? _totalAmountsAt(_twapSqrt()) : getTotalAmounts();
    }

    /// @dev Removes every position entirely, reporting the fees collected.
    function _unwindAll() internal virtual returns (uint256 fee0, uint256 fee1);

    /// @notice Realises accrued fees on every range and routes them; during a pause, compounding accounts only.
    function realiseFees() external nonReentrant {
        if (globalPause) _requirePausedRealiser(feeLedger, msg.sender);
        _realiseFeesAndRoute();
    }

    /// @dev Reverts `RebalancingIsPaused` unless `caller` is a compounding account of this vault on `ledger`.
    function _requirePausedRealiser(address ledger, address caller) internal view virtual;

    /// @notice Deploy idle capital and route realised fees; the guard, genesis or a guard-listed keeper.
    function compound() external nonReentrant returns (uint256 fee0, uint256 fee1) {
        _requireCompounder();
        // Refused while rebalancing is paused too: compound moves liquidity.
        if (rebalancingPaused || globalPause) revert RebalancingIsPaused();
        bool floorOn = clearing != address(0);
        if (floorOn) {
            (int24 spot, int24 blockStart, bool ok) = _spotAndTwapTick(1);
            if (!VaultExitLogic.deployStable(clearing, spot, blockStart, ok)) revert PriceNotStable();
        }
        _reclaimAllInventory();
        (fee0, fee1) = _realiseFeesAndRoute();
        // NAV floor over the deploy and park only; snapshot after fee routing so the cut is not read as slippage.
        uint256 navBefore = floorOn ? _twapNav() : 0;
        _deployIdleCapital();
        _parkExcessInventory();
        if (floorOn && _twapNav() < navBefore * (BPS - COMPOUND_MAX_SLIPPAGE_BPS) / BPS) {
            revert CompoundSlippageExceeded();
        }
        emit Compounded(msg.sender, fee0, fee1);
    }

    /// @dev The `compound` gate.
    function _requireCompounder() private view {
        address g = rebalanceGuard;
        if (msg.sender == g || msg.sender == genesis) return;
        assembly ("memory-safe") {
            mstore(0, shl(224, 0x6ba42aaa))
            mstore(4, caller())
            let ok := staticcall(gas(), g, 0, 0x24, 0, 0x20)
            if iszero(and(ok, and(gt(returndatasize(), 31), eq(mload(0), 1)))) {
                mstore(0, shl(224, 0xc8802d22))
                revert(0, 4)
            }
        }
    }

    /// @dev The vault's value in token1 terms at TWAP, for `compound`'s floor.
    function _twapNav() internal view returns (uint256) {
        (uint256 amount0, uint256 amount1) = _totalAmountsAt(_twapSqrt());
        return IClearing(clearing).twapValue(address(this), amount0, amount1);
    }

    /// @dev Realises pending fees on every range without changing liquidity, then routes the cut.
    function _realiseFeesAndRoute() internal returns (uint256 fee0, uint256 fee1) {
        (fee0, fee1) = _realiseAndCollectAll();
        ShareHookDispatch.markRealised();
        if (!globalPause && (fee0 > 0 || fee1 > 0)) _routeFees(fee0, fee1);
        _checkpointNav();
    }

    function _realiseAndCollectAll() internal virtual returns (uint256 fee0, uint256 fee1);

    /// @dev Fees leave only as real tokens: `feeManager.computeAndRoute` takes the cut and returns the remainder.
    function _routeFees(uint256 fee0, uint256 fee1) internal {
        if (feeManager == address(0) || (fee0 == 0 && fee1 == 0)) return;
        if (fee0 > 0) _token0.forceApprove(feeManager, fee0);
        if (fee1 > 0) _token1.forceApprove(feeManager, fee1);
        IVaultFeeManager(feeManager).computeAndRoute(address(this), strategist, fee0, fee1);
    }

    /// @dev Distributes the vault's entire idle balance across ranges by weight.
    function _deployIdleCapital() internal virtual;

    event NavCheckpoint(uint256 navPerShare);

    function _checkpointNav() internal {
        uint256 supply = totalSupply();
        if (supply == 0) return;
        emit NavCheckpoint((nav() * 1e18) / supply);
    }

    /// @notice How many times `shareIncentives` has been set (`setShareIncentives`).
    uint256 public shareIncentivesEpoch;

    /// @dev Storage gap: 50 minus the 8 slots appended (`callerBountyBps` .. `shareIncentivesEpoch`).
    uint256[42] private __gap;
}

project/contracts/vaults/interfaces/IClearing.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;

/// @notice Deposit gate implemented by `ClearingV3` and `ClearingV4`.
interface IClearing {
    function clearDeposit(address vault, uint256 amount0, uint256 amount1, address from) external view;

    /// @notice Spot-vs-TWAP deviation check only, without the deposit range and cap checks.
    function isPriceStable(address vault) external view returns (bool);

    /// @notice TWAP-anchored token1 value of (amount0, amount1).
    function twapValue(address vault, uint256 amount0, uint256 amount1) external view returns (uint256);

    /// @notice The TWAP tick, which `VaultCore.rebalanceOptimal` centers its range plan on.
    function twapTick(address vault) external view returns (int24);
}

project/contracts/vaults/interfaces/IRehypoLendingPool.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;

/// @notice The HorizonLendingPool functions a vault uses to park idle inventory and reclaim it.
/// @dev A nonzero `sTokenAddressOf` marks a token as a listed reserve the vault can park in.
interface IRehypoLendingPool {
    function supply(address asset, uint256 amount) external returns (uint256 sTokensOut);
    function withdraw(address asset, uint256 amount) external returns (uint256 withdrawn);
    function supplyBalanceOf(address asset, address user) external view returns (uint256);
    /// @notice Reserve-wide accounted supplied underlying (native decimals), donation-proof.
    function totalSuppliedOf(address asset) external view returns (uint256);
    function sTokenAddressOf(address asset) external view returns (address);
}

project/contracts/vaults/interfaces/IV3Vault.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;

import "./IVaultCore.sol";

/// @notice `IVaultCore` plus the V3 pool address and fee tier, read by `ClearingV3` for spot and TWAP.
interface IV3Vault is IVaultCore {
    function pool() external view returns (address);
    function fee() external view returns (uint24);
}

project/contracts/vaults/interfaces/IVaultCore.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;

import "../libraries/Range.sol";

/// @notice Venue-independent vault surface used by `RebalanceGuard`, `FeeManager`, `VaultFactory` and the frontend.
interface IVaultCore {
    function token0() external view returns (address);
    function token1() external view returns (address);

    /// @notice The vault's current position plan: tick ranges with weights.
    function ranges() external view returns (Range[] memory);
    function rangeCount() external view returns (uint256);

    function getTotalAmounts() external view returns (uint256 amount0, uint256 amount1);
    /// @notice Total vault value in token1 (`PriceLib.valueInToken1`), which share pricing uses.
    function nav() external view returns (uint256 navToken1);
    function totalSupply() external view returns (uint256);

    function depositsPaused() external view returns (bool);
    function rebalancingPaused() external view returns (bool);

    /// @notice The Clearing the vault trusts; `RebalanceGuard` refuses any other oracle.
    function clearing() external view returns (address);

    function deposit(uint256 amount0Desired, uint256 amount1Desired, address to, address from, uint256 minShares)
        external
        returns (uint256 shares);

    function withdraw(uint256 shares, address to, uint256 amount0Min, uint256 amount1Min)
        external
        returns (uint256 amount0, uint256 amount1);

    function rebalance(Range[] calldata newRanges)
        external
        returns (uint256 amount0Before, uint256 amount1Before, uint256 amount0After, uint256 amount1After);

    /// @notice Permissionless deterministic recenter; `caller` gets `bountyBps` (clamped to `MAX_CALLER_BOUNTY_BPS`)
    ///         of the realised fees, `address(0)` for none.
    function rebalanceOptimal(address caller, uint256 bountyBps)
        external
        returns (uint256 amount0Before, uint256 amount1Before, uint256 amount0After, uint256 amount1After);

    /// @notice The vault's flat caller-bounty rate, the RebalanceGuard's fallback when no bounty curve is set.
    function callerBountyBps() external view returns (uint256);

    /// @notice Realises and routes pending fees without changing ranges.
    function compound() external returns (uint256 fee0, uint256 fee1);
}

project/contracts/vaults/libraries/BaseLimitMath.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;

import "./Range.sol";

/// @title BaseLimitMath
/// @notice Tick math for the base + limit shape: a base around the TWAP center tick and a one-sided bid or ask limit.
/// @dev Thresholds are in ticks and must be positive multiples of `tickSpacing`.
library BaseLimitMath {
    error BadThreshold();

    /// Uniswap V3's absolute tick bounds; every emitted edge is clamped strictly inside the aligned band.
    int256 private constant _MIN_TICK = -887272;
    int256 private constant _MAX_TICK = 887272;
    /// The same bounds as int24, for callers checking whether a centre can host the shape.
    int24 internal constant MIN_TICK = -887272;
    int24 internal constant MAX_TICK = 887272;

    function _clamp(int256 v, int256 lo, int256 hi) private pure returns (int24) {
        if (v < lo) return int24(lo);
        if (v > hi) return int24(hi);
        return int24(v);
    }

    /// @notice The full-range floor's ticks: the usable band, aligned to `tickSpacing` and strictly interior.
    function fullRange(int24 tickSpacing) internal pure returns (int24 lower, int24 upper) {
        lower = int24((_MIN_TICK / int256(tickSpacing)) * int256(tickSpacing));
        upper = int24((_MAX_TICK / int256(tickSpacing)) * int256(tickSpacing));
    }

    /// @notice True for a range spanning the whole usable band (the full-range floor).
    /// @dev Fixed bounds; matches `fullRange(s)` when `887272 mod s <= 272`, which initialise enforces.
    function isFullBand(int24 tickLower, int24 tickUpper) internal pure returns (bool) {
        return tickLower <= -887000 && tickUpper >= 887000;
    }

    /// @notice Rounds `tick` down to a multiple of `tickSpacing` (toward negative infinity).
    function floorTick(int24 tick, int24 tickSpacing) internal pure returns (int24) {
        int24 compressed = tick / tickSpacing;
        if (tick < 0 && tick % tickSpacing != 0) compressed--;
        return compressed * tickSpacing;
    }

    /// Base range and both candidate limits around `centerTick`: `base` two-sided, `bid` below spot (token1) and
    /// `ask` above spot (token0); the vault deploys the limit side its leftover balances back with more liquidity.
    function ranges(int24 centerTick, int24 tickSpacing, int24 baseThreshold, int24 limitThreshold)
        public
        pure
        returns (
            int24 baseLower,
            int24 baseUpper,
            int24 bidLower,
            int24 bidUpper,
            int24 askLower,
            int24 askUpper
        )
    {
        if (
            baseThreshold <= 0 || limitThreshold <= 0 || baseThreshold % tickSpacing != 0
                || limitThreshold % tickSpacing != 0
        ) revert BadThreshold();

        int24 tickFloor = floorTick(centerTick, tickSpacing);
        int24 tickCeil = tickFloor + tickSpacing;

        // Usable band, strictly interior; every edge is clamped into it, so near-extreme ticks cannot revert and a
        // huge `baseThreshold` gives a full-range base.
        int256 lo = (_MIN_TICK / int256(tickSpacing)) * int256(tickSpacing);
        int256 hi = (_MAX_TICK / int256(tickSpacing)) * int256(tickSpacing);

        // Base straddles spot: [floor - baseThreshold, ceil + baseThreshold].
        baseLower = _clamp(int256(tickFloor) - int256(baseThreshold), lo, hi);
        baseUpper = _clamp(int256(tickCeil) + int256(baseThreshold), lo, hi);

        // Bid: entirely below spot, token1 only. Both edges clamped so a range near the minimum cannot invert.
        bidLower = _clamp(int256(tickFloor) - int256(limitThreshold), lo, hi);
        bidUpper = _clamp(int256(tickFloor), lo, hi);

        // Ask: entirely above spot, token0 only.
        askLower = _clamp(int256(tickCeil), lo, hi);
        askUpper = _clamp(int256(tickCeil) + int256(limitThreshold), lo, hi);

        // A range clamped onto a point at the band's edge opens one spacing inward, so lower < upper always holds.
        (baseLower, baseUpper) = _widen(baseLower, baseUpper, tickSpacing, lo, hi);
        (bidLower, bidUpper) = _widen(bidLower, bidUpper, tickSpacing, lo, hi);
        (askLower, askUpper) = _widen(askLower, askUpper, tickSpacing, lo, hi);
    }

    /// @dev A range collapsed onto one edge of the band opens one spacing toward the inside.
    function _widen(int24 lower, int24 upper, int24 tickSpacing, int256 lo, int256 hi)
        private
        pure
        returns (int24, int24)
    {
        if (lower < upper) return (lower, upper);
        if (int256(upper) + int256(tickSpacing) <= hi) return (lower, upper + tickSpacing);
        return (_clamp(int256(lower) - int256(tickSpacing), lo, hi), upper);
    }

    /// @notice The base, provisional ask and full-range floor centred on `centerTick`; a full-range base is the floor,
    ///         giving two ranges. The base carries 10,000 `weightBps`.
    function baseLimitRanges(int24 centerTick, int24 tickSpacing, int24 baseThreshold, int24 limitThreshold)
        public
        pure
        returns (Range[] memory r)
    {
        (int24 bl, int24 bu,,, int24 al, int24 au) = ranges(centerTick, tickSpacing, baseThreshold, limitThreshold);
        bool baseIsFull = isFullBand(bl, bu);
        r = new Range[](baseIsFull ? 2 : 3);
        r[0] = Range({tickLower: bl, tickUpper: bu, weightBps: 10_000});
        r[1] = Range({tickLower: al, tickUpper: au, weightBps: 0});
        if (!baseIsFull) {
            (int24 fl, int24 fu) = fullRange(tickSpacing);
            r[2] = Range({tickLower: fl, tickUpper: fu, weightBps: 0});
        }
    }
}

project/contracts/vaults/libraries/LiquidityAmounts.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.28;

import "@openzeppelin/contracts/utils/math/Math.sol";

/// @title Liquidity amount functions
/// @dev Adapted from Uniswap v3-periphery libraries/LiquidityAmounts.sol (GPL-2.0-or-later).
/// @notice Computes liquidity amounts from token amounts and prices, with full-precision `Math.mulDiv`.
library LiquidityAmounts {
    uint256 internal constant Q96 = 1 << 96;
    uint8 internal constant RESOLUTION = 96;

    /// @notice Downcasts uint256 to uint128
    function toUint128(uint256 x) private pure returns (uint128 y) {
        require((y = uint128(x)) == x);
    }

    /// @notice Computes the amount of liquidity received for a given amount of token0 and price range
    /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
    function getLiquidityForAmount0(
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint256 amount0
    ) internal pure returns (uint128 liquidity) {
        if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
        uint256 intermediate = Math.mulDiv(sqrtRatioAX96, sqrtRatioBX96, Q96);
        return toUint128(Math.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));
    }

    /// @notice Computes the amount of liquidity received for a given amount of token1 and price range
    /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
    function getLiquidityForAmount1(
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint256 amount1
    ) internal pure returns (uint128 liquidity) {
        if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
        return toUint128(Math.mulDiv(amount1, Q96, sqrtRatioBX96 - sqrtRatioAX96));
    }

    /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
    /// pool prices and the prices at the tick boundaries
    function getLiquidityForAmounts(
        uint160 sqrtRatioX96,
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint256 amount0,
        uint256 amount1
    ) internal pure returns (uint128 liquidity) {
        if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);

        if (sqrtRatioX96 <= sqrtRatioAX96) {
            liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
        } else if (sqrtRatioX96 < sqrtRatioBX96) {
            // Compute each leg at full width and cast the minimum once, so the larger leg cannot overflow uint128.
            uint256 liquidity0 = Math.mulDiv(amount0, Math.mulDiv(sqrtRatioX96, sqrtRatioBX96, Q96), sqrtRatioBX96 - sqrtRatioX96);
            uint256 liquidity1 = Math.mulDiv(amount1, Q96, sqrtRatioX96 - sqrtRatioAX96);

            liquidity = toUint128(liquidity0 < liquidity1 ? liquidity0 : liquidity1);
        } else {
            liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
        }
    }

    /// @notice Computes the amount of token0 for a given amount of liquidity and a price range
    function getAmount0ForLiquidity(
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint128 liquidity
    ) internal pure returns (uint256 amount0) {
        if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);

        return
            Math.mulDiv(
                uint256(liquidity) << RESOLUTION,
                sqrtRatioBX96 - sqrtRatioAX96,
                sqrtRatioBX96
            ) / sqrtRatioAX96;
    }

    /// @notice Computes the amount of token1 for a given amount of liquidity and a price range
    function getAmount1ForLiquidity(
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint128 liquidity
    ) internal pure returns (uint256 amount1) {
        if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);

        return Math.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, Q96);
    }

    /// @notice Computes the token0 and token1 value for a given liquidity, current price and range bounds
    /// @dev Internal, so importers need no library linking; vaults reach it through `ShapeMath.amountsForLiquidity`.
    function getAmountsForLiquidity(
        uint160 sqrtRatioX96,
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint128 liquidity
    ) internal pure returns (uint256 amount0, uint256 amount1) {
        if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);

        if (sqrtRatioX96 <= sqrtRatioAX96) {
            amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
        } else if (sqrtRatioX96 < sqrtRatioBX96) {
            amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);
            amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);
        } else {
            amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
        }
    }
}

project/contracts/vaults/libraries/PriceLib.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;

import "@openzeppelin/contracts/utils/math/Math.sol";

/// @notice `sqrtPriceX96` to PRECISION-scaled token1-per-token0 conversion and value helpers for vaults and clearing.
library PriceLib {
    uint256 internal constant PRECISION = 1e36;

    /// @dev Transient deposit quote: (price, value) per valuation point, written by `depositQuote` and read by
    ///      `VaultCore._creditDeposit` in the same call. keccak256("horizon.vault.depositQuote") - 1.
    uint256 internal constant QUOTE_SLOT = 0x42c10b870062e3e0d34b791d9952e4b9bb6e0cc428f91560e4f8d0b121f3fa45;
    /// @dev Valuation points: range liquidity at the TWAP, block-start and spot prices, then the spot composition at
    ///      the TWAP and block-start prices (so a pushed spot's impermanent loss is priced).
    uint256 internal constant QUOTE_POINTS = 5;

    function storeQuote(uint256 i, uint256 price, uint256 value) internal {
        assembly ("memory-safe") {
            let s := add(QUOTE_SLOT, mul(2, i))
            tstore(s, price)
            tstore(add(s, 1), value)
        }
    }

    /// @dev The lowest share count over the stored valuation points: `amount0`/`amount1` priced at each point's
    ///      price against the vault's value at that same price, `supply` and `virtualAssets` the vault's offsets.
    function quotedShares(uint256 amount0, uint256 amount1, uint256 supply, uint256 virtualAssets) internal view returns (uint256 shares) {
        shares = type(uint256).max;
        for (uint256 i; i < QUOTE_POINTS; ++i) {
            uint256 price;
            uint256 value;
            assembly ("memory-safe") {
                let s := add(QUOTE_SLOT, mul(2, i))
                price := tload(s)
                value := tload(add(s, 1))
            }
            uint256 n = Math.mulDiv(valueInToken1(amount0, amount1, price), supply, value + virtualAssets);
            if (n < shares) shares = n;
        }
    }

    /// @dev Two chained `Math.mulDiv` calls, since the full product can exceed 256 bits.
    function priceFromSqrt(uint160 sqrtPriceX96) internal pure returns (uint256) {
        uint256 intermediate = Math.mulDiv(uint256(sqrtPriceX96), PRECISION, 1 << 96);
        return Math.mulDiv(intermediate, uint256(sqrtPriceX96), 1 << 96);
    }

    /// @notice `amount1 + amount0 * price`: total value in token1 at a PRECISION-scaled price.
    function valueInToken1(uint256 amount0, uint256 amount1, uint256 priceX) internal pure returns (uint256) {
        return amount1 + Math.mulDiv(amount0, priceX, PRECISION);
    }

    /// @notice The share of a one-sided `amountIn` to swap: the other side's share of the target's value at `priceX`;
    ///         a zero-value target splits in half.
    function valueWeightedSplit(bool tokenInIsToken0, uint256 amountIn, uint256 target0, uint256 target1, uint256 priceX)
        internal
        pure
        returns (uint256 swapAmount)
    {
        if (target0 == 0 && target1 == 0) return amountIn / 2;
        uint256 target0Value = valueInToken1(target0, 0, priceX);
        // Dust token0 that values to zero with target1 zero would divide 0/0; fall back to the even split.
        if (target0Value + target1 == 0) return amountIn / 2;
        swapAmount = tokenInIsToken0
            ? Math.mulDiv(amountIn, target1, target0Value + target1)
            : Math.mulDiv(amountIn, target0Value, target1 + target0Value);
    }

    /// @notice TWAP-anchored minimum output, net of the pool fee `feePips` (1e6 base) and `slippageBps`.
    /// @dev Dynamic-fee venues pass `feePips = 0`.
    function minOutNetOfFee(bool tokenInIsToken0, uint256 swapAmount, uint256 priceX, uint256 slippageBps, uint256 feePips)
        internal
        pure
        returns (uint256 minOut)
    {
        uint256 expectedOut = tokenInIsToken0
            ? Math.mulDiv(swapAmount, priceX, PRECISION)
            : Math.mulDiv(swapAmount, PRECISION, priceX);
        expectedOut = Math.mulDiv(expectedOut, 1_000_000 - feePips, 1_000_000);
        minOut = Math.mulDiv(expectedOut, 10_000 - slippageBps, 10_000);
    }
}

project/contracts/vaults/libraries/Range.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;

/// @notice One concentrated position: a tick range plus the share of deployable capital it takes.
/// @dev `weightBps` across a plan must sum to 10,000.
struct Range {
    int24 tickLower;
    int24 tickUpper;
    uint16 weightBps;
}

project/contracts/vaults/libraries/ShapeMath.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;

import "../../libraries/TickMath.sol";
import "./LiquidityAmounts.sol";
import "./Range.sol";
import {VaultConfigChecks} from "./VaultConfigChecks.sol";

/// @title ShapeMath
/// @notice Builds a `Range` plan from a named shape: N equal-width, spacing-aligned buckets around a center tick.
/// @dev Gaussian weight tables are offline constants summing to exactly 10,000 bps; N is one of 3, 4, 5, 7, 9.
library ShapeMath {
    enum Shape {
        Gaussian
    }

    error UnsupportedShape();
    error UnsupportedPositionCount();
    error HalfWidthTooSmallForPositionCount();

    /// @notice `VaultCore.setShapeConfig` / `setWidthConfig` geometry checks (`VaultConfigChecks.checkGeometry`).
    function checkGeometry(
        int24 halfWidth, uint8 count, bool enabled, int24 minHW, int24 maxHW, uint32 volWindow, uint32 volSat, int24 spacing
    ) public view {
        VaultConfigChecks.checkGeometry(halfWidth, count, enabled, minHW, maxHW, volWindow, volSat, spacing);
    }

    /// @notice `n`-bucket Gaussian weight table, bps, always summing to exactly 10,000.
    /// @dev Odd counts put a bucket on the center tick; even counts straddle it symmetrically.
    function gaussianWeights(uint256 n) internal pure returns (uint16[] memory bps) {
        if (n == 3) {
            bps = new uint16[](3);
            (bps[0], bps[1], bps[2]) = (2420, 5160, 2420);
        } else if (n == 4) {
            bps = new uint16[](4);
            (bps[0], bps[1], bps[2], bps[3]) = (1500, 3500, 3500, 1500);
        } else if (n == 5) {
            bps = new uint16[](5);
            (bps[0], bps[1], bps[2], bps[3], bps[4]) = (856, 2427, 3434, 2427, 856);
        } else if (n == 7) {
            bps = new uint16[](7);
            (bps[0], bps[1], bps[2], bps[3], bps[4], bps[5], bps[6]) = (366, 1113, 2167, 2708, 2167, 1113, 366);
        } else if (n == 9) {
            bps = new uint16[](9);
            (bps[0], bps[1], bps[2], bps[3], bps[4], bps[5], bps[6], bps[7], bps[8]) =
                (190, 559, 1209, 1921, 2242, 1921, 1209, 559, 190);
        } else {
            revert UnsupportedPositionCount();
        }
    }

    function weightsFor(Shape shape, uint256 n) internal pure returns (uint16[] memory) {
        if (shape != Shape.Gaussian) revert UnsupportedShape();
        return gaussianWeights(n);
    }

    /// @notice Builds an `n`-bucket plan for `shape` spanning `centerTick +/- totalHalfWidth`, aligned and clamped.
    /// @dev Contiguous equal-width buckets; weight carries the shape. Public, so callers must link ShapeMath.
    function buildRanges(Shape shape, int24 centerTick, int24 tickSpacing, int24 totalHalfWidth, uint256 n)
        public
        pure
        returns (Range[] memory ranges)
    {
        uint16[] memory weights = weightsFor(shape, n);

        // Layout math in int256, narrowed to int24 only after clamping, so wide many-bucket plans cannot overflow.
        int256 rawBucketWidth = (int256(totalHalfWidth) * 2) / int256(n);
        int256 bucketWidth = (rawBucketWidth / int256(tickSpacing)) * int256(tickSpacing);
        if (bucketWidth < int256(tickSpacing)) revert HalfWidthTooSmallForPositionCount();

        int256 alignedCenter = (int256(centerTick) / int256(tickSpacing)) * int256(tickSpacing);
        // Re-snap the half span to the grid: with odd `k * n` the ladder would land half a spacing off-grid,
        // which the pool rejects on mint.
        int256 halfSpan = ((bucketWidth * int256(n)) / 2 / int256(tickSpacing)) * int256(tickSpacing);
        int256 start = alignedCenter - halfSpan;

        int256 minUsableTick = (int256(TickMath.MIN_TICK) / int256(tickSpacing)) * int256(tickSpacing);
        int256 maxUsableTick = (int256(TickMath.MAX_TICK) / int256(tickSpacing)) * int256(tickSpacing);

        ranges = new Range[](n);
        for (uint256 i = 0; i < n; i++) {
            int256 lower = start + int256(i) * bucketWidth;
            int256 upper = lower + bucketWidth;
            if (lower < minUsableTick) lower = minUsableTick;
            if (upper > maxUsableTick) upper = maxUsableTick;
            // Independent clamping can invert a bucket outside the usable band; collapse it onto the boundary as a
            // minimal valid range so `_setRanges` does not reject the whole plan.
            if (upper <= lower) {
                if (lower <= minUsableTick) {
                    lower = minUsableTick;
                    upper = minUsableTick + int256(tickSpacing);
                } else {
                    upper = maxUsableTick;
                    lower = maxUsableTick - int256(tickSpacing);
                }
            }
            ranges[i] = Range({tickLower: int24(lower), tickUpper: int24(upper), weightBps: weights[i]});
        }
    }

    /// @notice `TickMath.getSqrtRatioAtTick` behind this library's delegatecall boundary, out of vault bytecode.
    function sqrtRatioAtTick(int24 tick) public pure returns (uint160) {
        return TickMath.getSqrtRatioAtTick(tick);
    }

    /// @notice `LiquidityAmounts.getAmountsForLiquidity` behind this library's delegatecall boundary.
    function amountsForLiquidity(uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity)
        public
        pure
        returns (uint256 amount0, uint256 amount1)
    {
        return LiquidityAmounts.getAmountsForLiquidity(sqrtRatioX96, sqrtRatioAX96, sqrtRatioBX96, liquidity);
    }

    /// @notice Volatility-adaptive half-width: linear from `minHalfWidth` at zero volatility to `maxHalfWidth` at
    ///         saturation, clamped.
    function adaptiveHalfWidth(uint256 volTicks, int24 minHalfWidth, int24 maxHalfWidth, uint32 volSaturationTicks)
        public
        pure
        returns (int24)
    {
        if (volTicks >= volSaturationTicks) return maxHalfWidth;
        int256 span = int256(maxHalfWidth) - int256(minHalfWidth);
        return int24(int256(minHalfWidth) + (span * int256(volTicks)) / int256(uint256(volSaturationTicks)));
    }
}

project/contracts/vaults/libraries/ShareHookDispatch.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

/// @notice Emissions accountant for vault shares, called on every mint, burn and transfer before balances move.
/// @dev `from`/`to` is `address(0)` on mint/burn; the implementation skips those.
interface IShareIncentivesHook {
    function handleShareMove(
        address from, address to, uint256 value, uint256 totalSupplyBefore, uint256 fromBalanceBefore, uint256 toBalanceBefore
    ) external;
}

/// @notice Trading-fee ledger for unstaked vault shares, called on every balance change before balances move.
interface IVaultHolderFeeHook {
    function onShareUpdate(
        address from, uint256 fromBalanceBefore, address to, uint256 toBalanceBefore, uint256 value, bool realised
    ) external;
    /// @notice Whether `account` is a compounding account of `vault`.
    function isCompounding(address vault, address account) external view returns (bool);
}

/// @title ShareHookDispatch
/// @notice Pre-change share settlement for `VaultCore._update`: notifies the emissions accountant and fee ledger.
/// @dev Runs by delegatecall from the vault and must run before the ERC-20 balance update.
library ShareHookDispatch {
    /// @dev Transient flag in the vault's storage, set when the vault realised and routed fees earlier in this tx.
    bytes32 internal constant REALISED_SLOT = keccak256("horizon.vault.realisedThisTx");

    function markRealised() internal {
        bytes32 slot = REALISED_SLOT;
        assembly { tstore(slot, 1) }
    }

    function realisedThisTx() internal view returns (bool r) {
        bytes32 slot = REALISED_SLOT;
        assembly { r := tload(slot) }
    }

    /// @dev Gas given to the outgoing accountant's accrual before a change of wiring.
    uint256 internal constant FLUSH_GAS = 300_000;

    /// @notice Thrown when too little gas is left to give the flush its full budget.
    error FlushGasShort();

    function dispatch(address accountant, address ledger, address from, address to, uint256 value) internal {
        IERC20 self = IERC20(address(this));
        // No party: the outgoing accountant accrues before a rewire; best effort, so a broken one cannot block it.
        if (from == address(0) && to == address(0)) {
            bytes memory data =
                abi.encodeCall(IShareIncentivesHook.handleShareMove, (address(0), address(0), 0, self.totalSupply(), 0, 0));
            // Requires the full budget plus the 1/64 the EVM keeps back, so the call always gets `FLUSH_GAS`.
            if (gasleft() < FLUSH_GAS + FLUSH_GAS / 63 + 10_000) revert FlushGasShort();
            // Gas-capped, result ignored, no returndata copied: a faulty accountant costs at most `FLUSH_GAS`.
            assembly ("memory-safe") {
                pop(call(FLUSH_GAS, accountant, 0, add(data, 0x20), mload(data), 0, 0))
            }
            return;
        }
        uint256 fromBal = from == address(0) ? 0 : self.balanceOf(from);
        uint256 toBal = to == address(0) ? 0 : self.balanceOf(to);
        if (accountant != address(0)) {
            IShareIncentivesHook(accountant).handleShareMove(from, to, value, self.totalSupply(), fromBal, toBal);
        }
        if (ledger != address(0)) {
            IVaultHolderFeeHook(ledger).onShareUpdate(from, fromBal, to, toBal, value, realisedThisTx());
        }
    }
}

project/contracts/vaults/libraries/V3PositionLogic.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;

import "../../libraries/PriceOracle.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "../../interfaces/IUniswapV3Minimal.sol";
import "./Range.sol";
import "./LiquidityAmounts.sol";
import "./ShapeMath.sol";
import "./BaseLimitMath.sol";
import "./PriceLib.sol";
import "../interfaces/IRehypoLendingPool.sol";
import {ShareHookDispatch, IVaultHolderFeeHook} from "./ShareHookDispatch.sol";
import {VaultConfigChecks} from "./VaultConfigChecks.sol";
import "../interfaces/IClearing.sol";

/// @dev The vault's self-only mint entrypoint, kept on the vault so the mint callback guard sits with `pool.mint`.
interface IV3VaultMint {
    function mintPosition(int24 tickLower, int24 tickUpper, uint128 liquidity) external;
}

/// @notice The guard's idle trigger, so the vault's swap rule and the guard's signal share one dial.
interface IGuardIdleTrigger {
    function idleTriggerBps(address vault) external view returns (uint256);
}

/// @notice Vault state the idle signal reads through a self-call.
interface IVaultState {
    function totalSupply() external view returns (uint256);
    function token0() external view returns (address);
    function token1() external view returns (address);
    function lendingPool() external view returns (address);
}

/// @title V3PositionLogic
/// @notice `V3Vault`'s position, deploy, swap, rehypothecation and oracle bodies, linked as an external library.
/// @dev Runs by delegatecall, so storage and `address(this)` are the vault's.
library V3PositionLogic {
    using SafeERC20 for IERC20;

    uint128 internal constant MAX_U128 = type(uint128).max;

    /// @notice A fee-growth read failed for a position holding liquidity.
    error FeeGrowthUnreadable();
    /// @notice Same signature as `VaultCore.RebalancingIsPaused`.
    error RebalancingIsPaused();

    /// @notice During `globalPause`, reverts unless `caller` is a compounding account of this vault on `ledger`.
    function requirePausedRealiser(address ledger, address caller) external view {
        if (ledger == address(0) || !IVaultHolderFeeHook(ledger).isCompounding(address(this), caller)) {
            revert RebalancingIsPaused();
        }
    }

    /// @notice Poke every position (zero-liquidity burn realises its fees) and collect them.
    function realiseAndCollectAll(Range[] storage ranges, address pool)
        external
        returns (uint256 fee0, uint256 fee1)
    {
        uint256 count = ranges.length;
        for (uint256 i = 0; i < count; i++) {
            if (_dup(ranges, i)) continue;
            Range storage r = ranges[i];
            // burn(0) on a never-minted position reverts "NP", so only poke live liquidity;
            // `collect` has no NP check, so owed fees are still collected.
            if (_liquidityOf(pool, r.tickLower, r.tickUpper) != 0) IUniswapV3PoolActions(pool).burn(r.tickLower, r.tickUpper, 0);
            (uint128 c0, uint128 c1) =
                IUniswapV3PoolActions(pool).collect(address(this), r.tickLower, r.tickUpper, MAX_U128, MAX_U128);
            fee0 += c0;
            fee1 += c1;
        }
    }

    /// @notice Burn a pro-rata slice of every position plus idle, pay `to`, and report fees apart from principal.
    /// @dev A touch realises all of a position's fees, so they are routed, not paid to the withdrawer.
    function withdrawProRata(
        Range[] storage ranges,
        address pool,
        IERC20 token0,
        IERC20 token1,
        uint256 shares,
        uint256 supply,
        address to
    ) external returns (uint256 amount0, uint256 amount1, uint256 fee0, uint256 fee1) {
        // Idle measured before burning, so this withdrawal's proceeds are not paid twice.
        uint256 idle0 = Math.mulDiv(token0.balanceOf(address(this)), shares, supply);
        uint256 idle1 = Math.mulDiv(token1.balanceOf(address(this)), shares, supply);

        uint256 count = ranges.length;
        for (uint256 i = 0; i < count; i++) {
            if (_dup(ranges, i)) continue;
            Range storage r = ranges[i];
            uint128 liquidity = _liquidityOf(pool, r.tickLower, r.tickUpper);
            uint128 outLiquidity = uint128(Math.mulDiv(liquidity, shares, supply));
            // A zero slice burns nothing but still collects what the position owes.
            uint256 principal0;
            uint256 principal1;
            if (outLiquidity != 0) {
                (principal0, principal1) = IUniswapV3PoolActions(pool).burn(r.tickLower, r.tickUpper, outLiquidity);
            }
            (uint128 collected0, uint128 collected1) =
                IUniswapV3PoolActions(pool).collect(address(this), r.tickLower, r.tickUpper, MAX_U128, MAX_U128);
            fee0 += collected0 - principal0;
            fee1 += collected1 - principal1;
            amount0 += principal0;
            amount1 += principal1;
        }

        amount0 += idle0;
        amount1 += idle1;
        // A whole-supply exit also takes the collected fees; unrouted on the paused path, they would
        // otherwise go to the next depositor.
        if (shares == supply) {
            (amount0, amount1, fee0, fee1) = (amount0 + fee0, amount1 + fee1, 0, 0);
        }
        if (amount0 > 0) token0.safeTransfer(to, amount0);
        if (amount1 > 0) token1.safeTransfer(to, amount1);
    }

    /// @notice Deploys the idle balance as floor, base and limit; the limit side is forced by the leftover inventory.
    /// @dev Each leftover read after a mint is exact, since the callback has already pulled the tokens.
    function deployIdleCapital(
        Range[] storage ranges,
        address pool,
        IERC20 token0,
        IERC20 token1,
        int24 baseThreshold,
        int24 limitThreshold,
        uint32 twapWindow,
        uint16 fullRangeBps
    ) external {
        uint256 budget0 = token0.balanceOf(address(this));
        uint256 budget1 = token1.balanceOf(address(this));
        if (budget0 == 0 && budget1 == 0) return;

        (uint160 sqrtP,,,,,,) = IUniswapV3PoolState(pool).slot0();

        // The full-range floor first: `fullRangeBps` of the budget in both tokens, at `ranges[2]` when listed.
        if (ranges.length >= 3 && fullRangeBps > 0) {
            Range storage full = ranges[2];
            uint128 fullL = LiquidityAmounts.getLiquidityForAmounts(
                sqrtP, ShapeMath.sqrtRatioAtTick(full.tickLower), ShapeMath.sqrtRatioAtTick(full.tickUpper),
                (budget0 * fullRangeBps) / BPS, (budget1 * fullRangeBps) / BPS
            );
            if (fullL > 0) {
                IV3VaultMint(address(this)).mintPosition(full.tickLower, full.tickUpper, fullL);
                budget0 = token0.balanceOf(address(this));
                budget1 = token1.balanceOf(address(this));
            }
        }

        Range storage base = ranges[0];
        uint128 baseL = LiquidityAmounts.getLiquidityForAmounts(
            sqrtP, ShapeMath.sqrtRatioAtTick(base.tickLower), ShapeMath.sqrtRatioAtTick(base.tickUpper), budget0, budget1
        );
        if (baseL > 0) IV3VaultMint(address(this)).mintPosition(base.tickLower, base.tickUpper, baseL);

        if (ranges.length < 2) return;
        Range storage limit = ranges[1];

        uint256 left0 = token0.balanceOf(address(this));
        uint256 left1 = token1.balanceOf(address(this));

        if (_liquidityOf(pool, limit.tickLower, limit.tickUpper) > 0) {
            // Top-up the existing limit side. Single-sided, so only its one relevant token is used.
            uint128 addL = LiquidityAmounts.getLiquidityForAmounts(
                sqrtP, ShapeMath.sqrtRatioAtTick(limit.tickLower), ShapeMath.sqrtRatioAtTick(limit.tickUpper), left0, left1
            );
            if (addL > 0) IV3VaultMint(address(this)).mintPosition(limit.tickLower, limit.tickUpper, addL);
            return;
        }

        // Fresh limit: bid below both spot and TWAP, ask above both, so it never straddles spot and a spot nudge
        // only pushes it away from the TWAP. A side not single-sided at spot is skipped; the larger side deploys.
        (int24 spotTick, int24 twapTick, bool ok) = spotAndTwapTick(pool, twapWindow);
        int24 spacing = IUniswapV3PoolState(pool).tickSpacing();
        (,, int24 bidLower, int24 bidUpper,,) =
            BaseLimitMath.ranges(ok && twapTick < spotTick ? twapTick : spotTick, spacing, baseThreshold, limitThreshold);
        (,,,, int24 askLower, int24 askUpper) =
            BaseLimitMath.ranges(ok && twapTick > spotTick ? twapTick : spotTick, spacing, baseThreshold, limitThreshold);

        uint128 bidL = sqrtP >= ShapeMath.sqrtRatioAtTick(bidUpper)
            ? LiquidityAmounts.getLiquidityForAmount1(ShapeMath.sqrtRatioAtTick(bidLower), ShapeMath.sqrtRatioAtTick(bidUpper), left1)
            : 0;
        uint128 askL = sqrtP <= ShapeMath.sqrtRatioAtTick(askLower)
            ? LiquidityAmounts.getLiquidityForAmount0(ShapeMath.sqrtRatioAtTick(askLower), ShapeMath.sqrtRatioAtTick(askUpper), left0)
            : 0;
        if (bidL == 0 && askL == 0) return;

        (int24 l, int24 u, uint128 lim) = bidL > askL ? (bidLower, bidUpper, bidL) : (askLower, askUpper, askL);
        // Never put the limit on the base's or floor's tick pair (the pool keys positions on the pair).
        if ((l == base.tickLower && u == base.tickUpper)
            || (ranges.length >= 3 && l == ranges[2].tickLower && u == ranges[2].tickUpper)) return;
        limit.tickLower = l;
        limit.tickUpper = u;
        IV3VaultMint(address(this)).mintPosition(l, u, lim);
    }

    function _liquidityOf(address pool, int24 tickLower, int24 tickUpper) private view returns (uint128 liquidity) {
        (liquidity,,,,) =
            IUniswapV3PoolActions(pool).positions(keccak256(abi.encodePacked(address(this), tickLower, tickUpper)));
    }

    /// @notice True when `centerTick` is within one base-width (at most 100 spacings) plus a spacing of a tick bound.
    /// @dev Computed in int256 so the sum cannot overflow int24.
    function centerNearBound(int24 centerTick, int24 baseThreshold, int24 tickSpacing) external pure returns (bool) {
        int256 spacing = int256(tickSpacing);
        int256 margin = (int256(baseThreshold) < 100 * spacing ? int256(baseThreshold) : 100 * spacing) + spacing;
        int256 c = int256(centerTick);
        return c - margin < int256(BaseLimitMath.MIN_TICK) || c + margin > int256(BaseLimitMath.MAX_TICK);
    }

    /// @notice Plan shape check: 1 = two entries share a tick pair; 2 = a third entry is not the weight-0 floor.
    function validateRanges(Range[] storage ranges) external view returns (uint8) {
        uint256 n = ranges.length;
        for (uint256 i = 1; i < n; i++) {
            if (_dup(ranges, i)) return 1;
        }
        if (n == 3 && (ranges[2].weightBps != 0 || !BaseLimitMath.isFullBand(ranges[2].tickLower, ranges[2].tickUpper))) {
            return 2;
        }
        return 0;
    }

    /// @dev True when `ranges[i]` repeats an earlier tick pair; the pool keys positions on the pair, so every walk
    ///      skips duplicates to avoid double counting.
    function _dup(Range[] storage ranges, uint256 i) private view returns (bool) {
        int24 lo = ranges[i].tickLower;
        int24 hi = ranges[i].tickUpper;
        for (uint256 j = 0; j < i; j++) {
            if (ranges[j].tickLower == lo && ranges[j].tickUpper == hi) return true;
        }
        return false;
    }

    uint256 internal constant BPS = 10_000;
    /// @dev Reported for a vault with no positions and only dust: above BPS, so the guard reads nothing idle.
    uint256 internal constant NO_POSITIONS = BPS + 1;
    /// @dev An adjacent limit counts as productive up to this multiple of the in-range value beside it,
    ///      so dust cannot make a one-sided vault read fully productive.
    uint256 internal constant ADJACENT_CAP_X = 2;
    /// @dev With no positions, raw and parked value under 1 bp of the supply's face value is dust.
    uint256 internal constant DUST_SHARES_PER_VALUE = 1e3 * BPS;

    /// @notice Everything the shares claim, with range legs valued at `sqrtPriceX96`, plus owed, idle and parked.
    function totalAmountsAt(
        Range[] storage ranges,
        address pool,
        IERC20 token0,
        IERC20 token1,
        address lendingPool,
        uint160 sqrtPriceX96
    ) public view returns (uint256 amount0, uint256 amount1) {
        uint256 count = ranges.length;
        for (uint256 i = 0; i < count; i++) {
            if (_dup(ranges, i)) continue;
            Range storage r = ranges[i];
            (uint128 liquidity,,, uint128 owed0, uint128 owed1) = IUniswapV3PoolActions(pool).positions(
                keccak256(abi.encodePacked(address(this), r.tickLower, r.tickUpper))
            );
            if (liquidity > 0) {
                (uint256 a0, uint256 a1) = ShapeMath.amountsForLiquidity(
                    sqrtPriceX96, ShapeMath.sqrtRatioAtTick(r.tickLower), ShapeMath.sqrtRatioAtTick(r.tickUpper), liquidity
                );
                amount0 += a0;
                amount1 += a1;
            }
            amount0 += owed0;
            amount1 += owed1;
        }
        amount0 += token0.balanceOf(address(this)) + _parkedOf(lendingPool, token0);
        amount1 += token1.balanceOf(address(this)) + _parkedOf(lendingPool, token1);
    }

    /// @notice Stores the vault's value at each deposit valuation point (TWAP, block start, spot, and the spot
    ///         composition at TWAP and block start); returns the TWAP price and spot composition.
    function depositQuote(
        Range[] storage ranges,
        address pool,
        IERC20 token0,
        IERC20 token1,
        address lendingPool,
        uint160 sqrtTwap
    ) external returns (uint256 twapPrice, uint256 existing0, uint256 existing1) {
        (uint160 sqrtSpot,,,,,,) = IUniswapV3PoolState(pool).slot0();
        // Block-start price from the one-second TWAP, which nothing in this block can move; a buffer that
        // cannot serve it reverts (`OLD`) and refuses the deposit.
        uint32[] memory ago = new uint32[](2);
        ago[0] = 1;
        (int56[] memory cum,) = IUniswapV3PoolState(pool).observe(ago);
        uint160 sqrtStart = ShapeMath.sqrtRatioAtTick(int24(cum[1] - cum[0]));
        uint160[5] memory at = [sqrtTwap, sqrtStart, sqrtSpot, sqrtTwap, sqrtStart];
        // Spot third, so existing0/existing1 end as the spot composition the zap sizes against.
        for (uint256 i; i < 5; ++i) {
            if (i < 3) (existing0, existing1) = totalAmountsAt(ranges, pool, token0, token1, lendingPool, at[i]);
            uint256 price = PriceLib.priceFromSqrt(at[i]);
            if (i == 0) twapPrice = price;
            PriceLib.storeQuote(i, price, PriceLib.valueInToken1(existing0, existing1, price));
        }
    }

    /// @notice The lowest share count over the quote `depositQuote` stored.
    function quotedShares(uint256 amount0, uint256 amount1, uint256 supply, uint256 virtualAssets) external view returns (uint256) {
        return PriceLib.quotedShares(amount0, amount1, supply, virtualAssets);
    }

    /// @dev Idle trigger used when the guard has no dial or none is wired.
    uint256 internal constant DEFAULT_IDLE_TRIGGER_BPS = 5_000;

    /// @notice Why the vault needs a recenter: 1 TWAP outside its concentrated ranges, 2 productive share under the
    ///         idle trigger, 0 neither. Read before the unwind, so only a vault that needed it swaps.
    function recenterNeeded(Range[] storage ranges, address pool, address clearing, int24 limitThreshold, address guard)
        external
        view
        returns (uint8)
    {
        if (clearing == address(0)) return 0;
        int24 twapTick;
        try IClearing(clearing).twapTick(address(this)) returns (int24 t) {
            twapTick = t;
        } catch {
            return 0;
        }
        int24 lo = type(int24).max;
        int24 hi = type(int24).min;
        for (uint256 i = 0; i < ranges.length; i++) {
            Range storage r = ranges[i];
            if (r.weightBps == 0 && BaseLimitMath.isFullBand(r.tickLower, r.tickUpper)) continue;
            if (r.tickLower < lo) lo = r.tickLower;
            if (r.tickUpper > hi) hi = r.tickUpper;
        }
        if (lo <= hi && (twapTick < lo || twapTick > hi)) return 1;
        uint256 trigger = DEFAULT_IDLE_TRIGGER_BPS;
        if (guard.code.length > 0) {
            try IGuardIdleTrigger(guard).idleTriggerBps(address(this)) returns (uint256 t) {
                if (t > 0) trigger = t;
            } catch {}
        }
        return _productiveShare(ranges, pool, twapTick, limitThreshold) < trigger ? 2 : 0;
    }

    /// @notice Bps of concentrated value at TWAP that is in range, plus adjacent limits up to `ADJACENT_CAP_X`.
    /// @dev The floor and raw balances are excluded; no clearing or a cold oracle returns BPS.
    function productiveShareBps(Range[] storage ranges, address pool, address clearing, int24 limitThreshold)
        external
        view
        returns (uint256)
    {
        if (clearing == address(0)) return BPS;
        int24 twapTick;
        try IClearing(clearing).twapTick(address(this)) returns (int24 t) {
            twapTick = t;
        } catch {
            return BPS;
        }
        return _productiveShare(ranges, pool, twapTick, limitThreshold);
    }

    function _productiveShare(Range[] storage ranges, address pool, int24 twapTick, int24 limitThreshold)
        private
        view
        returns (uint256)
    {
        uint160 sqrtTwap = ShapeMath.sqrtRatioAtTick(twapTick);
        uint256 priceX = PriceLib.priceFromSqrt(sqrtTwap);
        (, int24 spotTick,,,,,) = IUniswapV3PoolState(pool).slot0();

        uint256 inRange;
        uint256 adjacent;
        uint256 total;
        uint256 count = ranges.length;
        for (uint256 i = 0; i < count; i++) {
            if (_dup(ranges, i)) continue;
            Range storage r = ranges[i];
            if (r.weightBps == 0 && BaseLimitMath.isFullBand(r.tickLower, r.tickUpper)) continue; // the floor
            uint128 liquidity = _liquidityOf(pool, r.tickLower, r.tickUpper);
            if (liquidity == 0) continue;
            (uint256 a0, uint256 a1) = ShapeMath.amountsForLiquidity(
                sqrtTwap, ShapeMath.sqrtRatioAtTick(r.tickLower), ShapeMath.sqrtRatioAtTick(r.tickUpper), liquidity
            );
            uint256 v = PriceLib.valueInToken1(a0, a1, priceX);
            total += v;
            if (twapTick >= r.tickLower && twapTick < r.tickUpper) {
                inRange += v;
            } else if (_gap(r, twapTick) <= limitThreshold || _gap(r, spotTick) <= limitThreshold) {
                adjacent += v;
            }
        }
        if (total == 0) return _noConcentratedLiquidity(priceX);
        uint256 cap = inRange * ADJACENT_CAP_X;
        uint256 productive = inRange + (adjacent < cap ? adjacent : cap);
        return (productive * BPS) / total;
    }

    /// @dev With no concentrated liquidity: `NO_POSITIONS` for no shares or only dust, else 0 (wholly idle).
    function _noConcentratedLiquidity(uint256 priceX) private view returns (uint256) {
        IVaultState v = IVaultState(address(this));
        uint256 supply = v.totalSupply();
        if (supply == 0) return NO_POSITIONS;
        IERC20 t0 = IERC20(v.token0());
        IERC20 t1 = IERC20(v.token1());
        address lp = v.lendingPool();
        uint256 raw = PriceLib.valueInToken1(
            t0.balanceOf(address(this)) + _parkedOf(lp, t0), t1.balanceOf(address(this)) + _parkedOf(lp, t1), priceX
        );
        return raw * DUST_SHARES_PER_VALUE < supply ? NO_POSITIONS : 0;
    }

    /// @dev Ticks between `tick` and the nearest edge of `r`; 0 inside.
    function _gap(Range storage r, int24 tick) private view returns (int24) {
        if (tick < r.tickLower) return r.tickLower - tick;
        if (tick >= r.tickUpper) return tick - r.tickUpper + 1;
        return 0;
    }

    /// @dev Parked inventory for `token`; a reverting pool counts as 0.
    function _parkedOf(address lendingPool, IERC20 token) private view returns (uint256) {
        if (lendingPool == address(0)) return 0;
        try IRehypoLendingPool(lendingPool).sTokenAddressOf(address(token)) returns (address sTok) {
            if (sTok == address(0)) return 0;
        } catch {
            return 0;
        }
        try IRehypoLendingPool(lendingPool).supplyBalanceOf(address(token), address(this)) returns (uint256 bal) {
            return bal;
        } catch {
            return 0;
        }
    }

    /// @notice `VaultCore.setRehypo` validation; see `VaultConfigChecks`.
    function checkRehypo(
        address oldPool, address newPool, bool enabled, uint16 floorBps, uint16 capBps, IERC20 token0, IERC20 token1
    ) external view {
        VaultConfigChecks.checkRehypo(oldPool, newPool, enabled, floorBps, capBps, token0, token1);
    }

    function checkFactories(address fm, address ledger) external view {
        VaultConfigChecks.checkFactories(fm, ledger);
    }

    /// @notice Fees `realiseAndCollectAll` would collect now: `tokensOwed` plus fee growth since the last poke.
    /// @dev `owed0`/`owed1` is the `tokensOwed` part; an unreadable fee growth reverts `FeeGrowthUnreadable`.
    function unrealisedFees(Range[] storage ranges, address pool)
        external
        view
        returns (uint256 f0, uint256 f1, uint256 owed0, uint256 owed1)
    {
        (bool okG, uint256 g0, uint256 g1, int24 tick) = _feeGlobals(pool);
        uint256 count = ranges.length;
        for (uint256 i = 0; i < count; i++) {
            if (_dup(ranges, i)) continue;
            int24 lo = ranges[i].tickLower;
            int24 hi = ranges[i].tickUpper;
            (uint128 liq, uint256 last0, uint256 last1, uint128 o0, uint128 o1) =
                IUniswapV3PoolActions(pool).positions(keccak256(abi.encodePacked(address(this), lo, hi)));
            owed0 += o0;
            owed1 += o1;
            if (liq == 0) continue;
            if (!okG) revert FeeGrowthUnreadable();
            (bool okL, uint256 lo0, uint256 lo1) = _feeOutside(pool, lo);
            (bool okH, uint256 hi0, uint256 hi1) = _feeOutside(pool, hi);
            if (!okL || !okH) revert FeeGrowthUnreadable();
            unchecked {
                // Uniswap V3 Tick.getFeeGrowthInside, wrapping arithmetic as in the pool.
                uint256 in0 = g0 - (tick >= lo ? lo0 : g0 - lo0) - (tick < hi ? hi0 : g0 - hi0);
                uint256 in1 = g1 - (tick >= lo ? lo1 : g1 - lo1) - (tick < hi ? hi1 : g1 - hi1);
                f0 += Math.mulDiv(in0 - last0, liq, 1 << 128);
                f1 += Math.mulDiv(in1 - last1, liq, 1 << 128);
            }
        }
        (f0, f1) = (f0 + owed0, f1 + owed1);
    }

    function _feeGlobals(address pool) private view returns (bool ok, uint256 g0, uint256 g1, int24 tick) {
        (bool a, bytes memory r0) = pool.staticcall(abi.encodeWithSignature("feeGrowthGlobal0X128()"));
        (bool b, bytes memory r1) = pool.staticcall(abi.encodeWithSignature("feeGrowthGlobal1X128()"));
        (bool c, bytes memory rs) = pool.staticcall(abi.encodeWithSignature("slot0()"));
        if (!a || !b || !c || r0.length < 32 || r1.length < 32 || rs.length < 64) return (false, 0, 0, 0);
        int256 t;
        assembly ("memory-safe") {
            g0 := mload(add(r0, 32))
            g1 := mload(add(r1, 32))
            t := mload(add(rs, 64))
        }
        return (true, g0, g1, int24(t));
    }

    function _feeOutside(address pool, int24 t) private view returns (bool, uint256 o0, uint256 o1) {
        (bool ok, bytes memory r) = pool.staticcall(abi.encodeWithSignature("ticks(int24)", t));
        if (!ok || r.length < 128) return (false, 0, 0);
        assembly ("memory-safe") {
            o0 := mload(add(r, 96))
            o1 := mload(add(r, 128))
        }
        return (true, o0, o1);
    }


    /// @notice `VaultCore._update`'s pre-change settlement; see `ShareHookDispatch`.
    function beforeShareUpdate(address accountant, address ledger, address from, address to, uint256 value) external {
        if (accountant != address(0) || ledger != address(0)) ShareHookDispatch.dispatch(accountant, ledger, from, to, value);
    }

    /// @notice Best-effort reclaim of both legs' parked inventory; what the pool cannot pay stays parked.
    function reclaimAll(address pool, IERC20 token0, IERC20 token1) external {
        _reclaimOne(pool, token0);
        _reclaimOne(pool, token1);
    }

    function _reclaimOne(address pool, IERC20 token) private {
        // Defensive reads: a reverting lending pool skips this leg instead of reverting the exit.
        try IRehypoLendingPool(pool).sTokenAddressOf(address(token)) returns (address sTok) {
            if (sTok == address(0)) return;
        } catch { return; }
        uint256 parked;
        try IRehypoLendingPool(pool).supplyBalanceOf(address(token), address(this)) returns (uint256 p) {
            parked = p;
        } catch { return; }
        if (parked == 0) return;
        // `max` (burns every share, no dust) when cash covers the position, else the live cash, since a
        // `max` withdrawal is all-or-nothing.
        uint256 cash = token.balanceOf(pool);
        uint256 toReclaim = parked <= cash ? type(uint256).max : cash;
        if (toReclaim == 0) return;
        (bool ok, ) = pool.call(abi.encodeCall(IRehypoLendingPool.withdraw, (address(token), toReclaim)));
        ok;
    }

    /// @notice Spot tick and trailing-TWAP tick from the pool's oracle; `ok` false on a buffer too cold for `window`.
    function spotAndTwapTick(address pool, uint32 window) public view returns (int24 spot, int24 twap, bool ok) {
        (, spot,,,,,) = IUniswapV3PoolState(pool).slot0();
        uint32[] memory ago = new uint32[](2);
        ago[0] = window;
        ago[1] = 0;
        try IUniswapV3PoolState(pool).observe(ago) returns (int56[] memory cum, uint160[] memory) {
            int56 delta = cum[1] - cum[0];
            twap = int24(delta / int56(uint56(window)));
            // Round toward negative infinity, as OracleLibrary.consult does.
            if (delta < 0 && delta % int56(uint56(window)) != 0) twap--;
            ok = true;
        } catch {
            ok = false;
        }
    }

    /// @notice Park each leg's idle above the floor buffer; a refused supply clears the approval.
    function parkExcess(address pool, IERC20 token0, IERC20 token1, uint16 floorBps, uint16 capBps) external {
        _parkOne(pool, token0, floorBps, capBps);
        _parkOne(pool, token1, floorBps, capBps);
    }

    function _parkOne(address pool, IERC20 token, uint16 floorBps, uint16 capBps) private {
        // Registered vaults stay within capBps of other suppliers' depth (supplied, not raw cash, so
        // donations cannot inflate it); an empty reserve or unregistered vault parks nothing.
        uint256 room = VaultConfigChecks.rehypoRoom(pool, token, capBps);
        if (room == 0) return;
        uint256 raw = token.balanceOf(address(this));
        uint256 toPark = raw - (raw * floorBps) / 10_000;
        if (toPark > room) toPark = room;
        if (toPark == 0) return;
        token.forceApprove(pool, toPark);
        (bool ok, ) = pool.call(abi.encodeCall(IRehypoLendingPool.supply, (address(token), toPark)));
        if (!ok) token.forceApprove(pool, 0);
    }
}

project/contracts/vaults/libraries/V3SwapLogic.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;

import "../../libraries/PriceOracle.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "../../interfaces/IUniswapV3Minimal.sol";
import "./Range.sol";
import "./ShapeMath.sol";
import "./BaseLimitMath.sol";
import "./PriceLib.sol";
import "../interfaces/IRehypoLendingPool.sol";
import "../interfaces/IClearing.sol";

/// @notice The vault reads this library makes through self-calls.
interface ISwapVault {
    function pool() external view returns (address);
    function fee() external view returns (uint24);
    function clearing() external view returns (address);
    function swapRouter() external view returns (address);
    function swapToRatioConfig() external view returns (bool enabled, uint16 capBps, uint16 slippageBps);
    function lendingPool() external view returns (address);
    function token0() external view returns (address);
    function token1() external view returns (address);
    function baseThreshold() external view returns (int24);
}

/// @title V3SwapLogic
/// @notice `V3Vault`'s rebalance swap, fold and zap bodies, linked as an external library.
/// @dev Runs by delegatecall, so storage and `address(this)` are the vault's.
library V3SwapLogic {
    using SafeERC20 for IERC20;

    uint256 internal constant BPS = 10_000;
    /// @dev Nominal liquidity the base's ratio is read at; only the proportion matters.
    uint128 internal constant RATIO_PROBE_LIQUIDITY = 1e24;
    /// @dev A swap-to-ratio swap under this share of vault value is skipped as noise.
    uint256 internal constant MIN_SWAP_BPS = 200;
    /// @dev A fold slice under this share of vault value is skipped.
    uint256 internal constant MIN_FOLD_BPS = 10;
    /// @dev The zap budget's unit: millionths of the vault's value.
    uint256 internal constant PPM = 1e6;

    /// @dev keccak256("horizon.vault.slices") - 1, in the vault's storage.
    bytes32 internal constant SLICES_SLOT = 0x08c20845fc0aca809e907ebfb35698a8ccf3481e5fdf46d7de56b7bbebd1a12c;

    uint16 internal constant MIN_FOLD_SLICE_BPS = 10;
    uint16 internal constant MAX_FOLD_SLICE_BPS = 200;
    uint16 internal constant MIN_FOLD_TARGET_BPS = 500;
    uint16 internal constant MAX_FOLD_TARGET_BPS = 9_500;
    uint16 internal constant MAX_ZAP_BALANCE_BPS = 500;
    /// @dev A fold runs only while the pool's TWAPs over these two windows differ by at most `FOLD_MAX_TWAP_GAP` ticks.
    uint32 internal constant FOLD_SHORT_WINDOW = 900;
    uint32 internal constant FOLD_LONG_WINDOW = 1800;
    int256 internal constant FOLD_MAX_TWAP_GAP = 50;

    /// @notice The fold and balanced-zap dials, with the zap budget's last spend.
    struct Slices {
        uint16 foldSliceBps;
        uint16 foldTargetBps;
        uint16 zapBalanceBps;
        uint64 zapSpentPpm;
        uint40 zapSpentAt;
    }

    /// @notice The rebalance swap ran; `amountOut` is the measured balance delta.
    event SwapToRatio(bool tokenInIsToken0, uint256 amountIn, uint256 amountOut);
    /// @notice A fold slice ran at a recentre; `amountOut` is the measured balance delta.
    event Folded(bool tokenInIsToken0, uint256 amountIn, uint256 amountOut);
    /// @notice A planned fold slice did not fill; the recentre went on as with the fold off.
    event FoldFailed();
    /// @notice The fold and balanced-zap dials were set.
    event SlicesSet(uint16 foldSliceBps, uint16 foldTargetBps, uint16 zapBalanceBps);

    /// @notice A zap's swap delivered less than the depositor's floor, by measured balance.
    error ZapShortFill();
    /// @notice A dial outside its bounds.
    error BadSlices();
    /// @notice A filled fold slice left spot outside the clearing's stable band.
    error FoldUnstable();
    /// @notice Same signature as `GenesisOwned.NotGenesis`.
    error NotGenesis();

    /// @dev The vault's pool, clearing, tokens and lending pool, read through self-calls.
    struct Ctx {
        address pool;
        address clearing;
        IERC20 token0;
        IERC20 token1;
        address lendingPool;
    }

    function _ctx() private view returns (Ctx memory c) {
        ISwapVault v = ISwapVault(address(this));
        c = Ctx(v.pool(), v.clearing(), IERC20(v.token0()), IERC20(v.token1()), v.lendingPool());
    }

    function _slot() private pure returns (Slices storage s) {
        bytes32 slot = SLICES_SLOT;
        assembly ("memory-safe") {
            s.slot := slot
        }
    }

    /// @notice Sets the fold slice (0 = off), the target limit share and the balanced-zap budget per hour, all bps.
    /// @dev Turning on, a larger slice, a lower target or a larger budget needs `isGenesis`.
    function setSlices(uint16 foldSliceBps, uint16 foldTargetBps, uint16 zapBalanceBps, bool isGenesis) external {
        if (
            (foldSliceBps != 0
                && (foldSliceBps < MIN_FOLD_SLICE_BPS || foldSliceBps > MAX_FOLD_SLICE_BPS
                    || foldTargetBps < MIN_FOLD_TARGET_BPS || foldTargetBps > MAX_FOLD_TARGET_BPS))
                || foldTargetBps > MAX_FOLD_TARGET_BPS || zapBalanceBps > MAX_ZAP_BALANCE_BPS
        ) revert BadSlices();
        Slices storage s = _slot();
        bool looser = foldSliceBps > s.foldSliceBps || (foldSliceBps != 0 && foldTargetBps < s.foldTargetBps)
            || zapBalanceBps > s.zapBalanceBps;
        if (looser && !isGenesis) revert NotGenesis();
        s.foldSliceBps = foldSliceBps;
        s.foldTargetBps = foldTargetBps;
        s.zapBalanceBps = zapBalanceBps;
        emit SlicesSet(foldSliceBps, foldTargetBps, zapBalanceBps);
    }

    /// @notice The recentre's unwind: on the optimal path a due fold slice runs first, then every position is burnt.
    /// @return mode 2 when a fold slice filled, else 1 when `need` (`recenterNeeded`) is set, else 0
    function unwind(Range[] storage ranges, uint8 need, bool optimal)
        external
        returns (uint8 mode, uint256 fee0, uint256 fee1)
    {
        bool booked;
        if (optimal && need != 1) (mode, booked, fee0, fee1) = _fold(ranges);
        if (mode != 2) mode = need == 0 ? 0 : 1;
        address pool = ISwapVault(address(this)).pool();
        for (uint256 i = 0; i < ranges.length; i++) {
            if (_dup(ranges, i)) continue;
            Range storage r = ranges[i];
            (uint128 liquidity,,,,) =
                IUniswapV3PoolActions(pool).positions(keccak256(abi.encodePacked(address(this), r.tickLower, r.tickUpper)));
            uint256 p0;
            uint256 p1;
            if (liquidity > 0) (p0, p1) = IUniswapV3PoolActions(pool).burn(r.tickLower, r.tickUpper, liquidity);
            (uint128 c0, uint128 c1) =
                IUniswapV3PoolActions(pool).collect(address(this), r.tickLower, r.tickUpper, type(uint128).max, type(uint128).max);
            // Once the fold booked the fees, what a position gained since is the fold's own swap: principal.
            if (!booked) {
                fee0 += c0 - p0;
                fee1 += c1 - p1;
            }
        }
    }

    /// @dev The limit's and the whole vault's token amounts with the positions at `sqrtPrice`, owed fees and idle.
    function _amounts(Range[] storage ranges, Ctx memory c, uint160 sqrtPrice)
        private
        view
        returns (uint256 l0, uint256 l1, uint256 t0, uint256 t1)
    {
        for (uint256 i = 0; i < ranges.length; i++) {
            if (_dup(ranges, i)) continue;
            Range storage r = ranges[i];
            (uint128 liquidity,,, uint128 owed0, uint128 owed1) = IUniswapV3PoolActions(c.pool).positions(
                keccak256(abi.encodePacked(address(this), r.tickLower, r.tickUpper))
            );
            uint256 a0 = owed0;
            uint256 a1 = owed1;
            if (liquidity > 0) {
                (uint256 x0, uint256 x1) = ShapeMath.amountsForLiquidity(
                    sqrtPrice, ShapeMath.sqrtRatioAtTick(r.tickLower), ShapeMath.sqrtRatioAtTick(r.tickUpper), liquidity
                );
                a0 += x0;
                a1 += x1;
            }
            t0 += a0;
            t1 += a1;
            if (i == 1) (l0, l1) = (a0, a1);
        }
        t0 += c.token0.balanceOf(address(this)) + _parkedOf(c.lendingPool, c.token0);
        t1 += c.token1.balanceOf(address(this)) + _parkedOf(c.lendingPool, c.token1);
    }

    /// @notice Plans a rebalance swap: sells the surplus toward the base's ratio, capped at `capBps` of value.
    /// @dev Gated on `isPriceStable`; `minOut` is TWAP-anchored net of the pool fee; under `minBps` of value skips.
    function swapToRatioPlan(
        Range[] storage ranges,
        address pool,
        address clearing,
        IERC20 token0,
        IERC20 token1,
        uint24 feePips,
        uint256 capBps,
        uint256 minBps,
        uint16 slippageBps
    ) public view returns (bool tokenInIsToken0, uint256 swapAmount, uint256 minOut) {
        if (clearing == address(0)) return (false, 0, 0);
        try IClearing(clearing).isPriceStable(address(this)) returns (bool ok) {
            if (!ok) return (false, 0, 0);
        } catch (bytes memory r) {
            PriceOracle.bubbleInsufficientGas(r); // a starved external reference read is not "unstable"
            return (false, 0, 0);
        }
        int24 twapTick;
        try IClearing(clearing).twapTick(address(this)) returns (int24 t) {
            twapTick = t;
        } catch {
            return (false, 0, 0);
        }

        (uint160 sqrtP,,,,,,) = IUniswapV3PoolState(pool).slot0();
        uint256 priceX = PriceLib.priceFromSqrt(sqrtP); // spot: the price the deploy consumes at
        uint256 twapX = PriceLib.priceFromSqrt(ShapeMath.sqrtRatioAtTick(twapTick));
        // A price that floors to zero at PRECISION has no ratio to size against: skip.
        if (priceX == 0 || twapX == 0) return (false, 0, 0);
        (uint256 target0, uint256 target1) = _baseRatio(ranges, sqrtP);
        uint256 b0 = token0.balanceOf(address(this));
        uint256 b1 = token1.balanceOf(address(this));

        uint256 target0Value = PriceLib.valueInToken1(target0, 0, priceX);
        uint256 denom = target0Value + target1;
        if (denom == 0) return (false, 0, 0);
        uint256 held0Value = PriceLib.valueInToken1(b0, 0, priceX);
        uint256 total = held0Value + b1;
        uint256 desired0Value = Math.mulDiv(total, target0Value, denom);
        if (held0Value > desired0Value) {
            tokenInIsToken0 = true;
            swapAmount = Math.mulDiv(held0Value - desired0Value, PriceLib.PRECISION, priceX);
            if (swapAmount > b0) swapAmount = b0;
        } else {
            uint256 desired1 = total - desired0Value;
            swapAmount = b1 > desired1 ? b1 - desired1 : 0;
        }
        if (swapAmount == 0) return (tokenInIsToken0, 0, 0);

        // The per-rebalance cap: capBps of vault value, in tokenIn units.
        uint256 capValue = Math.mulDiv(total, capBps, BPS);
        uint256 capIn = tokenInIsToken0 ? Math.mulDiv(capValue, PriceLib.PRECISION, priceX) : capValue;
        if (swapAmount > capIn) swapAmount = capIn;
        uint256 swapValue = tokenInIsToken0 ? Math.mulDiv(swapAmount, priceX, PriceLib.PRECISION) : swapAmount;
        if (swapAmount == 0 || swapValue * BPS < total * minBps) return (tokenInIsToken0, 0, 0);

        minOut = PriceLib.minOutNetOfFee(tokenInIsToken0, swapAmount, twapX, slippageBps, feePips);
    }

    /// @notice Plans and runs the swap-to-ratio, best-effort: any failure returns (0, 0) and the rebalance goes on.
    function swapToRatio(Range[] storage ranges, uint16 capBps, uint16 slippageBps)
        external
        returns (uint256 amountIn, uint256 amountOut, bool planned)
    {
        bool tokenInIsToken0;
        (tokenInIsToken0, amountIn, amountOut, planned) = _swap(ranges, capBps, MIN_SWAP_BPS, slippageBps);
        if (amountIn != 0) emit SwapToRatio(tokenInIsToken0, amountIn, amountOut);
    }

    /// @dev A due fold slice: books every position's fees, burns the limit and sells up to `foldSliceBps` of value of
    ///      its token with the rest in place; `mode` is 2 when it filled, `booked` once the fees are collected.
    function _fold(Range[] storage ranges) private returns (uint8 mode, bool booked, uint256 fee0, uint256 fee1) {
        Slices memory s = _slot();
        if (s.foldSliceBps == 0 || ranges.length < 2 || _dup(ranges, 1)) return (0, false, 0, 0);
        ISwapVault v = ISwapVault(address(this));
        (bool enabled,, uint16 slippageBps) = v.swapToRatioConfig();
        address router = v.swapRouter();
        Ctx memory c = _ctx();
        if (!enabled || router.code.length == 0) return (0, false, 0, 0);
        (bool ok, int24 tw) = _twap(c.clearing);
        if (!ok || tw < ranges[0].tickLower || tw >= ranges[0].tickUpper) return (0, false, 0, 0);
        if (!_twapsAgree(c.pool)) return (0, false, 0, 0);
        (bool in0, uint256 amount, uint256 twapX) = _foldPlan(ranges, c, tw, s);
        if (amount == 0 || !_stable(c.clearing)) return (0, false, 0, 0);

        uint256 planned = amount;
        (fee0, fee1, amount) = _bookAndBurnLimit(ranges, c.pool, in0, amount);
        booked = true;
        // `planned` is `foldSliceBps` of value: this skips a slice cut under `MIN_FOLD_BPS` of value.
        if (amount * s.foldSliceBps < planned * MIN_FOLD_BPS) return (0, true, fee0, fee1);
        uint24 feePips = v.fee();
        uint256 minOut = PriceLib.minOutNetOfFee(in0, amount, twapX, slippageBps, feePips);
        uint256 allowTicks = (uint256(feePips) + 99) / 100 + slippageBps;
        (uint256 amountIn, uint256 amountOut) =
            _route(c, router, in0, amount, minOut, feePips, _priceLimit(c.clearing, tw, in0, allowTicks));
        if (amountIn == 0) {
            emit FoldFailed();
            return (0, true, fee0, fee1);
        }
        // The price limit keeps a fill inside the stable band; a router that ignores it reverts the recentre here.
        if (!_stable(c.clearing)) revert FoldUnstable();
        emit Folded(in0, amountIn, amountOut);
        mode = 2;
    }

    /// @dev The slice to sell, 0 unless the limit is over target and its token is the surplus the no-swap recentre
    ///      would leave over target; `twapX` is the TWAP price.
    function _foldPlan(Range[] storage ranges, Ctx memory c, int24 tw, Slices memory s)
        private
        view
        returns (bool in0, uint256 amount, uint256 twapX)
    {
        uint160 sqrtTw = ShapeMath.sqrtRatioAtTick(tw);
        twapX = PriceLib.priceFromSqrt(sqrtTw);
        if (twapX == 0) return (false, 0, 0);
        (uint256 l0, uint256 l1, uint256 t0, uint256 t1) = _amounts(ranges, c, sqrtTw);
        uint256 total = PriceLib.valueInToken1(t0, t1, twapX);
        if (total == 0 || (PriceLib.valueInToken1(l0, l1, twapX) * BPS) / total <= s.foldTargetBps) return (false, 0, 0);
        in0 = PriceLib.valueInToken1(l0, 0, twapX) > l1;
        if (_surplusBps(ranges, c, tw, in0) <= s.foldTargetBps) return (false, 0, 0);
        uint256 capValue = Math.mulDiv(total, s.foldSliceBps, BPS);
        amount = in0 ? Math.mulDiv(capValue, PriceLib.PRECISION, twapX) : capValue;
    }

    /// @dev Bps of value at spot that the base `rebalanceOptimal` deploys at `tw` leaves over in token0 (`in0`) or
    ///      token1: the limit share a recentre without a swap leaves.
    function _surplusBps(Range[] storage ranges, Ctx memory c, int24 tw, bool in0) private view returns (uint256) {
        (uint160 sqrtP,,,,,,) = IUniswapV3PoolState(c.pool).slot0();
        uint256 px = PriceLib.priceFromSqrt(sqrtP);
        (,, uint256 a0, uint256 a1) = _amounts(ranges, c, sqrtP);
        int24 spacing = IUniswapV3PoolState(c.pool).tickSpacing();
        int256 bt = ISwapVault(address(this)).baseThreshold();
        int24 f = BaseLimitMath.floorTick(tw, spacing);
        (int24 minT, int24 maxT) = BaseLimitMath.fullRange(spacing);
        // The base edges as `BaseLimitMath.ranges` sets them, clamped to the usable band.
        int256 lo = int256(f) - bt;
        int256 hi = int256(f) + spacing + bt;
        (uint256 r0, uint256 r1) = _ratio(sqrtP, lo < minT ? minT : int24(lo), hi > maxT ? maxT : int24(hi));
        uint256 r0Value = PriceLib.valueInToken1(r0, 0, px);
        uint256 held0Value = PriceLib.valueInToken1(a0, 0, px);
        uint256 total = held0Value + a1;
        if (total == 0) return 0;
        // The base takes all of the scarce token; the rest of the surplus token is what the limit gets.
        uint256 left = in0
            ? (r1 == 0 ? 0 : _delta(held0Value, Math.mulDiv(a1, r0Value, r1)))
            : (r0Value == 0 ? 0 : _delta(a1, Math.mulDiv(held0Value, r1, r0Value)));
        return (left * BPS) / total;
    }

    /// @dev Collects every other position's fees, then burns and collects the limit; caps `amount` at its principal.
    function _bookAndBurnLimit(Range[] storage ranges, address pool, bool in0, uint256 amount)
        private
        returns (uint256 fee0, uint256 fee1, uint256)
    {
        for (uint256 i = 0; i < ranges.length; i++) {
            if (i == 1 || _dup(ranges, i)) continue;
            Range storage r = ranges[i];
            // burn(0) on a never-minted position reverts, so only live liquidity is poked.
            if (_liquidityOf(pool, r) != 0) IUniswapV3PoolActions(pool).burn(r.tickLower, r.tickUpper, 0);
            (uint128 c0, uint128 c1) =
                IUniswapV3PoolActions(pool).collect(address(this), r.tickLower, r.tickUpper, type(uint128).max, type(uint128).max);
            fee0 += c0;
            fee1 += c1;
        }
        Range storage lim = ranges[1];
        uint128 liquidity = _liquidityOf(pool, lim);
        uint256 p0;
        uint256 p1;
        if (liquidity != 0) (p0, p1) = IUniswapV3PoolActions(pool).burn(lim.tickLower, lim.tickUpper, liquidity);
        (uint128 l0, uint128 l1) =
            IUniswapV3PoolActions(pool).collect(address(this), lim.tickLower, lim.tickUpper, type(uint128).max, type(uint128).max);
        fee0 += l0 - p0;
        fee1 += l1 - p1;
        uint256 held = in0 ? p0 : p1;
        return (fee0, fee1, amount > held ? held : amount);
    }

    /// @dev The swap's price limit: `allowTicks` (fee plus slippage, a tick per bps) from `tw`, at most the edge of the
    ///      clearing's stable band (500 ticks when unset).
    function _priceLimit(address clearing, int24 tw, bool in0, uint256 allowTicks) private view returns (uint160) {
        uint256 dev = 500;
        (bool ok, bytes memory r) = clearing.staticcall(abi.encodeWithSignature("vaultConfigs(address)", address(this)));
        if (ok && r.length >= 192) {
            uint256 d;
            assembly ("memory-safe") {
                d := and(mload(add(r, 192)), 0xffffff)
            }
            if (d != 0) dev = d;
        }
        if (allowTicks < dev) dev = allowTicks;
        // A sell of token0 can stop one tick under its limit, hence one tick inward.
        int256 t = in0 ? int256(tw) - int256(dev) + 1 : int256(tw) + int256(dev);
        if (t <= BaseLimitMath.MIN_TICK) t = BaseLimitMath.MIN_TICK + 1;
        if (t >= BaseLimitMath.MAX_TICK) t = BaseLimitMath.MAX_TICK - 1;
        return ShapeMath.sqrtRatioAtTick(int24(t));
    }

    /// @dev Whether the pool's short- and long-window TWAPs agree within `FOLD_MAX_TWAP_GAP`; a failed read is no.
    function _twapsAgree(address pool) private view returns (bool) {
        uint32[] memory ago = new uint32[](3);
        ago[0] = FOLD_LONG_WINDOW;
        ago[1] = FOLD_SHORT_WINDOW;
        try IUniswapV3PoolState(pool).observe(ago) returns (int56[] memory cum, uint160[] memory) {
            int256 d = (int256(cum[2]) - cum[1]) / int256(uint256(FOLD_SHORT_WINDOW))
                - (int256(cum[2]) - cum[0]) / int256(uint256(FOLD_LONG_WINDOW));
            return d <= FOLD_MAX_TWAP_GAP && -d <= FOLD_MAX_TWAP_GAP;
        } catch {
            return false;
        }
    }

    /// @dev The clearing's TWAP tick; `ok` is false with no clearing or a failed read.
    function _twap(address clearing) private view returns (bool ok, int24 tw) {
        if (clearing == address(0)) return (false, 0);
        try IClearing(clearing).twapTick(address(this)) returns (int24 t) {
            return (true, t);
        } catch {
            return (false, 0);
        }
    }

    function _liquidityOf(address pool, Range storage r) private view returns (uint128 liquidity) {
        (liquidity,,,,) =
            IUniswapV3PoolActions(pool).positions(keccak256(abi.encodePacked(address(this), r.tickLower, r.tickUpper)));
    }

    /// @dev Whether the clearing reads the price stable; a starved read reverts rather than read unstable.
    function _stable(address clearing) private view returns (bool) {
        if (clearing == address(0)) return false;
        try IClearing(clearing).isPriceStable(address(this)) returns (bool ok) {
            return ok;
        } catch (bytes memory r) {
            PriceOracle.bubbleInsufficientGas(r);
            return false;
        }
    }

    /// @dev The planned swap through `router`; a codeless or reverting router, or a fill under `minOut`, is (0, 0).
    function _swap(Range[] storage ranges, uint256 capBps, uint256 minBps, uint16 slippageBps)
        private
        returns (bool tokenInIsToken0, uint256 amountIn, uint256 amountOut, bool planned)
    {
        Ctx memory c = _ctx();
        address router = ISwapVault(address(this)).swapRouter();
        uint24 feePips = ISwapVault(address(this)).fee();
        uint256 swapAmount;
        uint256 minOut;
        (tokenInIsToken0, swapAmount, minOut) =
            swapToRatioPlan(ranges, c.pool, c.clearing, c.token0, c.token1, feePips, capBps, minBps, slippageBps);
        if (swapAmount == 0) return (tokenInIsToken0, 0, 0, false);
        planned = true;
        if (router.code.length == 0) return (tokenInIsToken0, 0, 0, true);
        (amountIn, amountOut) = _route(c, router, tokenInIsToken0, swapAmount, minOut, feePips, 0);
    }

    /// @dev One exact-input swap through `router`; a reverting router or a fill under `minOut` returns (0, 0).
    function _route(
        Ctx memory c,
        address router,
        bool tokenInIsToken0,
        uint256 amount,
        uint256 minOut,
        uint24 feePips,
        uint160 priceLimit
    ) private
        returns (uint256 amountIn, uint256 amountOut)
    {
        IERC20 tokenIn = tokenInIsToken0 ? c.token0 : c.token1;
        IERC20 tokenOut = tokenInIsToken0 ? c.token1 : c.token0;
        uint256 inBefore = tokenIn.balanceOf(address(this));
        uint256 outBefore = tokenOut.balanceOf(address(this));
        tokenIn.forceApprove(router, amount);
        // Raw call with no decoding, so a misbehaving router cannot revert the rebalance.
        (bool ok,) = router.call(
            abi.encodeCall(
                IV3SwapRouter.exactInputSingle,
                (
                    IV3SwapRouter.ExactInputSingleParams({
                        tokenIn: address(tokenIn), tokenOut: address(tokenOut), fee: feePips, recipient: address(this),
                        amountIn: amount, amountOutMinimum: minOut, sqrtPriceLimitX96: priceLimit
                    })
                )
            )
        );
        tokenIn.forceApprove(router, 0);
        if (!ok) return (0, 0);
        // Measured, saturating deltas; the floor is re-checked on what arrived.
        amountIn = _delta(inBefore, tokenIn.balanceOf(address(this)));
        amountOut = _delta(tokenOut.balanceOf(address(this)), outBefore);
        if (amountIn == 0 || amountOut < minOut) return (0, 0);
    }

    /// @notice The zap's inflow: pulls `amountIn`, swaps the sized amount with the depositor's floor, and returns
    ///         the measured, saturating balance deltas. A fill under `minOut` reverts the deposit.
    function zapIn(
        Range[] storage ranges,
        bool tokenInIsToken0,
        uint256 amountIn,
        uint256 existing0,
        uint256 existing1,
        uint256 twapPrice,
        uint256 slippageBps,
        bool untraded
    ) external returns (uint256 amount0, uint256 amount1) {
        Ctx memory c = _ctx();
        (IERC20 token0, IERC20 token1) = (c.token0, c.token1);
        address router = ISwapVault(address(this)).swapRouter();
        uint24 feePips = ISwapVault(address(this)).fee();
        uint256 idle0Before = token0.balanceOf(address(this));
        uint256 idle1Before = token1.balanceOf(address(this));
        IERC20 tokenIn = tokenInIsToken0 ? token0 : token1;
        IERC20 tokenOut = tokenInIsToken0 ? token1 : token0;
        tokenIn.safeTransferFrom(msg.sender, address(this), amountIn);
        uint256 actualIn = _delta(tokenIn.balanceOf(address(this)), tokenInIsToken0 ? idle0Before : idle1Before);

        (uint256 swapAmount, uint256 spentPpm, bool spend) =
            zapSwapAmount(ranges, c.pool, tokenInIsToken0, actualIn, existing0, existing1, twapPrice, untraded);
        if (spend) {
            Slices storage s = _slot();
            s.zapSpentPpm = uint64(spentPpm);
            s.zapSpentAt = uint40(block.timestamp);
        }
        if (swapAmount > 0) {
            uint256 minOut = PriceLib.minOutNetOfFee(tokenInIsToken0, swapAmount, twapPrice, slippageBps, feePips);
            uint256 outBefore = tokenOut.balanceOf(address(this));
            tokenIn.forceApprove(router, swapAmount);
            IV3SwapRouter(router).exactInputSingle(
                IV3SwapRouter.ExactInputSingleParams({
                    tokenIn: address(tokenIn), tokenOut: address(tokenOut), fee: feePips, recipient: address(this),
                    amountIn: swapAmount, amountOutMinimum: minOut, sqrtPriceLimitX96: 0
                })
            );
            tokenIn.forceApprove(router, 0);
            if (_delta(tokenOut.balanceOf(address(this)), outBefore) < minOut) revert ZapShortFill();
        }

        amount0 = _delta(token0.balanceOf(address(this)), idle0Before);
        amount1 = _delta(token1.balanceOf(address(this)), idle1Before);
    }

    /// @notice The part of `amountIn` a zap swaps: the holdings split, moved toward the base's in an untraded block.
    /// @dev The move is capped by the budget, `zapBalanceBps` of value per hour at `twapPrice`; `spend` charges it.
    function zapSwapAmount(
        Range[] storage ranges,
        address pool,
        bool tokenInIsToken0,
        uint256 amountIn,
        uint256 existing0,
        uint256 existing1,
        uint256 twapPrice,
        bool untraded
    ) public view returns (uint256 swapAmount, uint256 spentPpm, bool spend) {
        (uint160 sqrtP,,,,,,) = IUniswapV3PoolState(pool).slot0();
        uint256 spot = PriceLib.priceFromSqrt(sqrtP);
        swapAmount = PriceLib.valueWeightedSplit(tokenInIsToken0, amountIn, existing0, existing1, spot);
        Slices memory s = _slot();
        if (s.zapBalanceBps == 0 || !untraded) return (swapAmount, 0, false);
        (uint256 b0, uint256 b1) = _baseRatio(ranges, sqrtP);
        uint256 nav = PriceLib.valueInToken1(existing0, existing1, twapPrice);
        // Spot outside the base, or an empty vault, keeps the holdings split.
        if (b0 == 0 || b1 == 0 || nav == 0) return (swapAmount, 0, false);
        uint256 balanced = PriceLib.valueWeightedSplit(tokenInIsToken0, amountIn, b0, b1, spot);
        uint256 extra = balanced > swapAmount ? balanced - swapAmount : swapAmount - balanced;
        uint256 used = _used(s);
        uint256 cap = uint256(s.zapBalanceBps) * (PPM / BPS);
        if (extra == 0 || used >= cap) return (swapAmount, 0, false);
        uint256 extraValue = tokenInIsToken0 ? Math.mulDiv(extra, twapPrice, PriceLib.PRECISION) : extra;
        uint256 room = Math.mulDiv(cap - used, nav, PPM);
        if (extraValue > room) {
            extra = Math.mulDiv(extra, room, extraValue);
            extraValue = room;
        }
        swapAmount = balanced > swapAmount ? swapAmount + extra : swapAmount - extra;
        spentPpm = used + Math.mulDiv(extraValue, PPM, nav, Math.Rounding.Ceil);
        spend = true;
    }

    /// @dev The zap budget used now: the last spend less what has refilled since, at `zapBalanceBps` per hour.
    function _used(Slices memory s) private view returns (uint256) {
        uint256 refill = (block.timestamp - s.zapSpentAt) * uint256(s.zapBalanceBps) * (PPM / BPS) / 1 hours;
        return s.zapSpentPpm > refill ? s.zapSpentPpm - refill : 0;
    }

    /// @dev The base's token0:token1 proportion at `sqrtP` (amounts for a nominal liquidity).
    function _baseRatio(Range[] storage ranges, uint160 sqrtP) private view returns (uint256, uint256) {
        return _ratio(sqrtP, ranges[0].tickLower, ranges[0].tickUpper);
    }

    /// @dev The token0:token1 proportion of a range at `sqrtP` (amounts for a nominal liquidity).
    function _ratio(uint160 sqrtP, int24 lo, int24 hi) private pure returns (uint256, uint256) {
        return ShapeMath.amountsForLiquidity(
            sqrtP, ShapeMath.sqrtRatioAtTick(lo), ShapeMath.sqrtRatioAtTick(hi), RATIO_PROBE_LIQUIDITY
        );
    }

    /// @dev True when `ranges[i]` repeats an earlier tick pair (the pool keys positions on the pair).
    function _dup(Range[] storage ranges, uint256 i) private view returns (bool) {
        int24 lo = ranges[i].tickLower;
        int24 hi = ranges[i].tickUpper;
        for (uint256 j = 0; j < i; j++) {
            if (ranges[j].tickLower == lo && ranges[j].tickUpper == hi) return true;
        }
        return false;
    }

    /// @dev Parked inventory for `token`; a reverting pool counts as 0.
    function _parkedOf(address lendingPool, IERC20 token) private view returns (uint256) {
        if (lendingPool == address(0)) return 0;
        try IRehypoLendingPool(lendingPool).sTokenAddressOf(address(token)) returns (address sTok) {
            if (sTok == address(0)) return 0;
        } catch {
            return 0;
        }
        try IRehypoLendingPool(lendingPool).supplyBalanceOf(address(token), address(this)) returns (uint256 bal) {
            return bal;
        } catch {
            return 0;
        }
    }

    /// @dev `a - b`, saturating at 0.
    function _delta(uint256 a, uint256 b) private pure returns (uint256) {
        return a > b ? a - b : 0;
    }
}

project/contracts/vaults/libraries/VaultConfigChecks.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IRehypoLendingPool} from "../interfaces/IRehypoLendingPool.sol";

interface IFactoryPointerC {
    function vaultFactory() external view returns (address);
}

/// @notice The vault's stored geometry and root key, read back by `checkGeometry`.
interface IVaultGeometryC {
    function genesis() external view returns (address);
    function shapeHalfWidth() external view returns (int24);
    function shapePositionCount() external view returns (uint8);
    function widthConfig() external view returns (bool, int24, int24, uint32, uint32);
}

/// @title VaultConfigChecks
/// @notice Validation for `VaultCore` config setters, run by delegatecall so `address(this)` is the vault.
library VaultConfigChecks {
    uint256 internal constant BPS = 10_000;

    error ZeroAddress();
    error BadRehypoConfig();
    error RehypoOldPoolNotDrained();
    error RehypoVaultNotRegistered();
    error BadWidthConfig();
    error FactoryMismatch();
    error NotGenesis();

    /// @dev `VaultCore.setRehypo`'s checks.
    function checkRehypo(
        address oldPool, address newPool, bool enabled, uint16 floorBps, uint16 capBps, IERC20 token0, IERC20 token1
    ) internal view {
        if (enabled) {
            if (newPool == address(0)) revert ZeroAddress();
            if (floorBps > BPS) revert BadRehypoConfig(); // floor can't exceed 100%
            // capBps of the reserve's current liquid depth: zero with rehypo on, or above 50%, is a config error.
            if (capBps == 0 || capBps > 5_000) revert BadRehypoConfig();
            // Refuse while this vault's shares are a listed reserve of that pool (index-feedback loop).
            if (IRehypoLendingPool(newPool).sTokenAddressOf(address(this)) != address(0)) revert BadRehypoConfig();
            // Each reserve leg's emissions controller must register this vault (keeps parked sTokens out of the farm).
            if (!_registeredFor(newPool, token0) || !_registeredFor(newPool, token1)) revert RehypoVaultNotRegistered();
        }
        // Repointing or clearing the pool must not orphan inventory still parked in the old one.
        if (oldPool != address(0) && oldPool != newPool) {
            if (parkedBalanceIn(oldPool, token0) != 0 || parkedBalanceIn(oldPool, token1) != 0) {
                revert RehypoOldPoolNotDrained();
            }
        }
    }

    /// @dev FeeManager and the fee ledger must authenticate against the same vault registry.
    function checkFactories(address fm, address ledger) internal view {
        if (fm != address(0) && ledger != address(0)
            && IFactoryPointerC(fm).vaultFactory() != IFactoryPointerC(ledger).vaultFactory()) revert FactoryMismatch();
    }

    /// @dev True for a non-reserve leg or one whose emissions controller registers this vault.
    ///      A missing or unreadable controller reads as unregistered (fail closed).
    function _registeredFor(address pool, IERC20 token) private view returns (bool) {
        address sTok = IRehypoLendingPool(pool).sTokenAddressOf(address(token));
        return sTok == address(0)
            || _registry(sTok, abi.encodeWithSignature("isRehypoVault(address,address)", sTok, address(this))) != 0;
    }

    /// @dev How much more of `token` this vault may park in `pool`, per the reserve's emissions controller.
    ///      0 for a non-reserve leg or a missing or unreadable controller (fail closed).
    function rehypoRoom(address pool, IERC20 token, uint16 capBps) internal view returns (uint256) {
        address sTok = IRehypoLendingPool(pool).sTokenAddressOf(address(token));
        if (sTok == address(0)) return 0;
        return _registry(
            sTok, abi.encodeWithSignature("rehypoRoom(address,address,uint256)", sTok, address(this), uint256(capBps))
        );
    }

    /// @dev One-word answer of the sToken's `shareIncentives` controller to `data`; any failure reads as 0.
    function _registry(address sTok, bytes memory data) private view returns (uint256) {
        uint256 c = _word(sTok, abi.encodeWithSignature("shareIncentives()"));
        return c == 0 || c >> 160 != 0 ? 0 : _word(address(uint160(c)), data);
    }

    /// @dev First word of a static call's answer; 0 for no code, a revert or a short answer.
    function _word(address target, bytes memory data) private view returns (uint256 w) {
        if (target.code.length == 0) return 0;
        assembly ("memory-safe") {
            let out := mload(0x40)
            let ok := staticcall(gas(), target, add(data, 32), mload(data), out, 32)
            if lt(returndatasize(), 32) { ok := 0 }
            w := mul(ok, mload(out))
        }
    }

    /// @dev Parked balance of `token` in `p`; a reverting pool reads as 0.
    function parkedBalanceIn(address p, IERC20 token) internal view returns (uint256) {
        if (p == address(0)) return 0;
        try IRehypoLendingPool(p).sTokenAddressOf(address(token)) returns (address sTok) {
            if (sTok == address(0)) return 0;
        } catch {
            return 0;
        }
        try IRehypoLendingPool(p).supplyBalanceOf(address(token), address(this)) returns (uint256 bal) {
            return bal;
        } catch {
            return 0;
        }
    }

    /// @dev Hard bounds on every width dial for `VaultCore.setWidthConfig`.
    function checkWidth(bool enabled, int24 minHalfWidth, int24 maxHalfWidth, uint32 volWindow, uint32 volSaturationTicks)
        internal
        pure
    {
        if (!enabled) return;
        if (minHalfWidth <= 0 || minHalfWidth > maxHalfWidth) revert BadWidthConfig();
        if (maxHalfWidth > 400_000) revert BadWidthConfig();
        if (volWindow < 60 || volWindow > 3600) revert BadWidthConfig();
        if (volSaturationTicks == 0) revert BadWidthConfig();
    }

    /// @dev Bounds the shape (count 0 or 3/4/5/7/9, one tick spacing per bucket) and width; a non-genesis caller
    ///      may only widen: same count, `halfWidth` not lowered, width config per `checkWidthMonotone`.
    function checkGeometry(
        int24 halfWidth, uint8 count, bool enabled, int24 minHW, int24 maxHW, uint32 volWindow, uint32 volSat, int24 spacing
    ) internal view {
        checkWidth(enabled, minHW, maxHW, volWindow, volSat);
        if (
            count != 0
                && (
                    halfWidth <= 0 || halfWidth > 400_000 || (count != 3 && count != 4 && count != 5 && count != 7 && count != 9)
                        || (int256(halfWidth) * 2) / int256(uint256(count)) < int256(spacing)
                        || (enabled && (int256(minHW) * 2) / int256(uint256(count)) < int256(spacing))
                )
        ) revert BadWidthConfig();
        IVaultGeometryC v = IVaultGeometryC(address(this));
        if (msg.sender == v.genesis()) return;
        if (count != v.shapePositionCount() || halfWidth < v.shapeHalfWidth()) revert NotGenesis();
        checkWidthMonotone(v, enabled, minHW, maxHW, volWindow, volSat);
    }

    /// @dev `checkGeometry`'s rule for the width config (warm key only): `enabled` and `volWindow` unchanged,
    ///      `minHalfWidth` and `maxHalfWidth` non-decreasing, `volSaturationTicks` non-increasing.
    function checkWidthMonotone(
        IVaultGeometryC v, bool enabled, int24 minHW, int24 maxHW, uint32 volWindow, uint32 volSat
    ) private view {
        (bool oldEnabled, int24 oldMin, int24 oldMax, uint32 oldWindow, uint32 oldSat) = v.widthConfig();
        if (enabled != oldEnabled || minHW < oldMin || maxHW < oldMax || volSat > oldSat || volWindow != oldWindow) {
            revert NotGenesis();
        }
    }
}

project/contracts/vaults/libraries/VaultExitLogic.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;

/// @notice The clearing reads `VaultExitLogic.deployStable` makes.
interface IExitClearing {
    function isPriceStable(address vault) external view returns (bool);
    function twapTick(address vault) external view returns (int24);
}

/// @notice The vault read `clearPlainDeposit` makes: its spot composition.
interface IExitVault {
    function getTotalAmounts() external view returns (uint256 amount0, uint256 amount1);
}

/// @notice The clearing reads `clearPlainDeposit` makes (`ClearingBase`).
interface IExitDepositClearing {
    function clearDeposit(address vault, uint256 amount0, uint256 amount1, address from) external view;
    function freeDepositList(address vault, address depositor) external view returns (bool);
    function isFeeCompounder(address vault, address account) external view returns (bool);
    function twapValue(address vault, uint256 amount0, uint256 amount1) external view returns (uint256);
}

/// @notice The auto-compounder's claimed-but-not-re-deposited fees (`VaultAutoCompounder.feeCredit0/1`).
interface IExitFeeCompounder {
    function feeCredit0() external view returns (uint256);
    function feeCredit1() external view returns (uint256);
    function wrapDepositActive() external view returns (bool);
}

/// @notice The V4 reads `deployStable` makes: the vault's pool key, and its hook's same-block swap record.
interface IExitV4Vault {
    struct Key { address currency0; address currency1; uint24 fee; int24 tickSpacing; address hooks; }
    function poolKey() external view returns (Key memory);
}

interface IExitV4Hook {
    function swappedThisBlock(bytes32 id) external view returns (bool);
}

/// @notice The V3 reads `deployStable` makes: the vault's pool, and that pool's last oracle write.
interface IExitV3Vault {
    function pool() external view returns (address);
}

interface IExitV3Pool {
    function slot0() external view returns (uint160, int24, uint16 observationIndex, uint16, uint16, uint8, bool);
    function observations(uint256 index) external view returns (uint32 blockTimestamp, int56, uint160, bool);
}

/// @title VaultExitLogic - the vaults' deposit-gate and deploy-gate logic (linked into V3Vault and V4Vault)
/// @notice External, linked into both venues (`V3Vault`, `V4Vault`), so the bytecode lives outside the vaults.
library VaultExitLogic {
    /// The last block in which the vault minted shares to anyone, in the VAULT's storage (a namespaced slot,
    /// keccak256("horizon.vault.lastMintBlock"); read from outside through `VaultCore.extsload`).
    bytes32 internal constant LAST_MINT_BLOCK_SLOT = 0xf7dd692eab7e4303a666f013dc8ef2e24610455cc1f3576ead5e8638a39ee86d;

    /// The most spot may sit from the TWAP and from the block-start price for `compound` to deploy idle: 50 ticks
    /// (0.5%).
    int24 internal constant DEPLOY_MAX_TICKS = 50;

    /// Whether `compound` may deploy idle: spot within `DEPLOY_MAX_TICKS` of the TWAP and the block-start price, and
    /// (V3) the pool not yet traded in this block, or (V4) no same-block swap recorded by the hook.
    function deployStable(address clearing, int24 spot, int24 blockStart, bool ok) external view returns (bool) {
        if (!ok || !IExitClearing(clearing).isPriceStable(address(this))) return false;
        try IExitV3Vault(address(this)).pool() returns (address pool) {
            (,, uint16 idx,,,,) = IExitV3Pool(pool).slot0();
            (uint32 ts,,,) = IExitV3Pool(pool).observations(idx);
            if (ts == uint32(block.timestamp)) return false;
        } catch {
            // A V4 vault: the hook's same-block swap record, as the V3 pool's last observation above.
            try IExitV4Vault(address(this)).poolKey() returns (IExitV4Vault.Key memory key) {
                if (IExitV4Hook(key.hooks).swappedThisBlock(keccak256(abi.encode(key)))) return false;
            } catch {}
        }
        int24 twap = IExitClearing(clearing).twapTick(address(this));
        return _within(spot, blockStart) && _within(spot, twap);
    }

    /// The ratio band for the vault's own contracts (below): a deposit's token ratio may differ from the vault's
    /// composition by at most 1% (the clearing's `RATIO_BAND_BPS`).
    uint256 internal constant RATIO_BAND_BPS = 100;
    /// A vault leg worth under this share of the vault (bps, at the clearing's TWAP) counts as zero in the fit (the
    /// clearing's `DUST_LEG_BPS`), so a vault holding one real token takes that token alone.
    uint256 internal constant DUST_LEG_BPS = 10;

    /// A plain deposit with no part in the vault's token composition: deposit both tokens in the vault's ratio, or zap.
    error TryLater();

    /// The gate of a plain deposit (`VaultCore.deposit`), returning the amounts the vault takes.
    function clearPlainDeposit(address clearing, uint256 a0, uint256 a1) external view returns (uint256, uint256) {
        IExitDepositClearing c = IExitDepositClearing(clearing);
        (uint256 t0, uint256 t1) = IExitVault(address(this)).getTotalAmounts();
        bool whole = t0 == 0 && t1 == 0;
        if (!whole) {
            // Read as words (a clearing without the read answers no), as the clearing reads its own optional surfaces.
            (bool okF, uint256 free) = _word(clearing, abi.encodeCall(IExitDepositClearing.freeDepositList, (address(this), msg.sender)));
            whole = okF && free == 1;
        }
        bool own;
        if (!whole) {
            (bool okC, uint256 comp) = _word(clearing, abi.encodeCall(IExitDepositClearing.isFeeCompounder, (address(this), msg.sender)));
            // The compounder's fee re-deposit is never fitted; its `depositAndWrap` is.
            if (okC && comp == 1) {
                (bool okW, uint256 wrap) = _word(msg.sender, abi.encodeCall(IExitFeeCompounder.wrapDepositActive, ()));
                own = !(okW && wrap == 1);
            }
            if (own) {
                (bool ok0, uint256 c0) = _word(msg.sender, abi.encodeCall(IExitFeeCompounder.feeCredit0, ()));
                (bool ok1, uint256 c1) = _word(msg.sender, abi.encodeCall(IExitFeeCompounder.feeCredit1, ()));
                (uint256 r0, uint256 r1) = _offMix(a0, a1, t0, t1);
                whole = ok0 && ok1 && r0 <= c0 + (a0 * RATIO_BAND_BPS) / 10_000 && r1 <= c1 + (a1 * RATIO_BAND_BPS) / 10_000;
            }
        }
        if (!whole) {
            uint256 v0 = c.twapValue(address(this), t0, 0);
            uint256 v = v0 + c.twapValue(address(this), 0, t1);
            if (v0 * 10_000 < DUST_LEG_BPS * v) t0 = 0;
            else if ((v - v0) * 10_000 < DUST_LEG_BPS * v) t1 = 0;
            if (own) {
                if (!_inBand(a0, a1, t0, t1)) revert TryLater();
            } else {
                (uint256 r0, uint256 r1) = _offMix(a0, a1, t0, t1);
                a0 -= r0;
                a1 -= r1;
                if (a0 == 0 && a1 == 0) revert TryLater();
            }
        }
        c.clearDeposit(address(this), a0, a1, msg.sender);
        return (a0, a1);
    }

    /// The part of (a0, a1) beyond its largest part in the composition (t0, t1): one-sided by construction. A
    /// composition with no token1 takes token0 alone, and the reverse.
    function _offMix(uint256 a0, uint256 a1, uint256 t0, uint256 t1) private pure returns (uint256, uint256) {
        if (t0 == 0 && t1 == 0) return (0, 0);
        if (t0 == 0) return (a0, 0);
        if (t1 == 0) return (0, a1);
        uint256 m1 = (a0 * t1) / t0;
        if (m1 > a1) return (a0 - (a1 * t0) / t1, 0);
        return (0, a1 - m1);
    }

    /// |a0 * t1 - a1 * t0| <= RATIO_BAND_BPS * max(a0 * t1, a1 * t0); an empty composition or an empty deposit matches.
    function _inBand(uint256 a0, uint256 a1, uint256 t0, uint256 t1) private pure returns (bool) {
        if (t0 == 0 && t1 == 0) return true;
        uint256 x = a0 * t1;
        uint256 y = a1 * t0;
        uint256 hi = x > y ? x : y;
        if (hi == 0) return true;
        return (hi - (x > y ? y : x)) * 10_000 <= RATIO_BAND_BPS * hi;
    }

    /// The first word of a static call's answer: `ok` false for a target without code, a revert or a short answer.
    function _word(address target, bytes memory data) private view returns (bool ok, uint256 w) {
        bytes memory r;
        (ok, r) = target.staticcall(data);
        if (!ok || r.length < 32) return (false, 0);
        w = abi.decode(r, (uint256));
    }

    function _within(int24 a, int24 b) private pure returns (bool) {
        return (a > b ? a - b : b - a) <= DEPLOY_MAX_TICKS;
    }

    /// Record this block as the vault's last mint block (the vault's `_update` calls it on every mint).
    function recordMint() external {
        bytes32 mintSlot = LAST_MINT_BLOCK_SLOT;
        assembly { sstore(mintSlot, number()) }
    }
}
Настройки компилятораПоказать
{
  "viaIR": true,
  "libraries": {
    "project/contracts/vaults/libraries/ShapeMath.sol": {
      "ShapeMath": "0x9b33c66faed9ea39a8624dd3815a13ad4c619edb"
    },
    "project/contracts/vaults/libraries/V3SwapLogic.sol": {
      "V3SwapLogic": "0x8b977c29a17f2519d5e13bff173a56c94d0c21ed"
    },
    "project/contracts/vaults/libraries/BaseLimitMath.sol": {
      "BaseLimitMath": "0xb12095ad18c517bfe1f26e357dda8006a291b7e7"
    },
    "project/contracts/vaults/libraries/VaultExitLogic.sol": {
      "VaultExitLogic": "0xd1ae06441acf8da4a583d5e863fb696522eb6b71"
    },
    "project/contracts/vaults/libraries/V3PositionLogic.sol": {
      "V3PositionLogic": "0xabfabec60666a65f48957bef2b22dd282adc004d"
    }
  },
  "optimizer": {
    "runs": 1,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "npm/@openzeppelin/[email protected]/:@openzeppelin/contracts/=npm/@openzeppelin/[email protected]/",
    "project/:@openzeppelin/contracts-upgradeable/=npm/@openzeppelin/[email protected]/",
    "project/:@openzeppelin/contracts/=npm/@openzeppelin/[email protected]/",
    "project/:@uniswap/v4-core/=npm/@uniswap/[email protected]/"
  ]
}

Исходный код и метаданные: Sourcify.

Исходный код принадлежит авторам контракта.