Skip to content
Verified contractExactMIT

AutopilotLib

Address0x961340eea952fde80d5e07e48b8d12f546ffef78
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.26

 

Same code

2 more contracts

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 100 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,300,723
Creation transaction
0xe9ffb92d4e…a4662806b3

src/libraries/AutopilotLib.sol

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

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IndexToken} from "../IndexToken.sol";
import {PlanLib} from "./PlanLib.sol";
import {TwapLib} from "./TwapLib.sol";

/// @title AutopilotLib
/// @notice Autopilot's planning, band checks, and its own swap path, kept in an external library so Autopilot fits
///         under the contract size limit. It runs in Autopilot's context via DELEGATECALL, so approvals and
///         transfers are Autopilot's.
///
///         The swap path is used when a keeper brings no aggregator route: a leg is swapped hop by hop through the
///         very pools the basket prices from (token to its hub, hub to hub, hub to token), each hop on the router
///         of the venue that pool belongs to.
library AutopilotLib {
    using SafeERC20 for IERC20;

    /// @dev How a venue's router is called.
    uint8 internal constant STYLE_ROUTER02 = 0; // exactInputSingle without a deadline (Uniswap SwapRouter02, Pancake SmartRouter)
    uint8 internal constant STYLE_V3 = 1; // exactInputSingle with a deadline (Uniswap V3 periphery SwapRouter, Sushi)
    uint8 internal constant STYLE_SLIPSTREAM = 2; // exactInputSingle keyed by tick spacing (Aerodrome Slipstream)
    uint8 internal constant STYLE_CLASSIC = 3; // swapExactTokensForTokens over Solidly routes (Aerodrome classic)

    struct Venue {
        address router;
        uint8 style;
    }

    uint256 internal constant BPS = 10_000;
    /// @dev Legs executed per poke at most; the rest wait for the next poke (the plan is recomputed each time), so
    ///      a wide basket's rebalance always fits the gas reimbursement. An own-swap leg costs up to about 700k gas
    ///      when it crosses three pools, so three legs stay under the 3M cap with the planning on top.
    uint256 internal constant MAX_LEGS_PER_POKE = 3;

    error NoVenue(address pool);
    error RouterNotAllowed(address router);
    error PriceUnrepresentable();
    error RoutesStale();
    error BadSwapTarget();
    error LegTooLarge(uint256 leg);

    bytes4 internal constant SLOT0_SELECTOR = 0x3850c7bd; // slot0()
    bytes4 internal constant LIQUIDITY_SELECTOR = 0x1a686502; // liquidity()
    bytes4 internal constant EXECUTE_LEG_SELECTOR = bytes4(keccak256("executeLeg(address,uint256,uint256,address[])"));

    /// @dev What `buildExec` and `sliceLegs` need about an index besides its legs: the pricing inputs (pools,
    ///      kinds, decimals, hubs) as Autopilot assembled them for TwapLib, the TWAP prices, and the config caps.
    struct ExecIn {
        address index;
        address autopilot;
        TwapLib.PriceInput p;
        IndexToken.Component[] cs;
        uint256[] px;
        IndexToken.RebalanceLeg[] legs;
        IndexToken.SwapLeg[] routes; // empty, or one per leg (target 0 = Autopilot's own swap)
        uint16 slip;
        uint96 maxLegValue; // numeraire per leg per poke; 0 = no cap
        uint96 minLegValue; // numeraire; a leg sliced below this is not worth a swap and does not take a slot
    }

    // --------------------------------------------------------------- planning

    /// @notice The index's own planner evaluated at `px` (see PlanLib), using its live balances.
    function planAt(address index, IndexToken.Component[] memory cs, uint256[] memory px)
        external
        view
        returns (PlanLib.Plan memory)
    {
        uint256 n = cs.length;
        uint256[] memory bal = new uint256[](n);
        for (uint256 i; i < n; ++i) {
            bal[i] = IERC20(cs[i].token).balanceOf(index);
        }
        return PlanLib.planAt(cs, bal, px);
    }

    /// @notice The value (numeraire) of the largest planned leg at `px`.
    function maxLegValue(IndexToken.Component[] memory cs, uint256[] memory px, IndexToken.RebalanceLeg[] memory legs)
        external
        pure
        returns (uint256 maxV)
    {
        for (uint256 j; j < legs.length; ++j) {
            uint256 si = type(uint256).max;
            for (uint256 i; i < cs.length; ++i) {
                if (cs[i].token == legs[j].sellToken) si = i;
            }
            if (si == type(uint256).max) revert RoutesStale();
            uint256 v = Math.mulDiv(legs[j].sellAmount, px[si], 10 ** cs[si].decimals);
            if (v > maxV) maxV = v;
        }
    }

    // ------------------------------------------------------------------ bands

    /// @notice Symmetric bands whose midpoint is exactly the price, so the index's planner sees the TWAP itself.
    function bounds(uint256[] memory px, uint16 slip) external pure returns (uint128[] memory lo, uint128[] memory hi) {
        uint256 n = px.length;
        lo = new uint128[](n);
        hi = new uint128[](n);
        for (uint256 i; i < n; ++i) {
            uint256 d = px[i] * slip / BPS;
            uint256 high = px[i] + d;
            if (high > type(uint128).max) revert PriceUnrepresentable();
            lo[i] = uint128(px[i] - d);
            hi[i] = uint128(high);
        }
    }

    /// @notice Mirrors IndexToken._setBounds for an operator caller: would every band move be accepted?
    function bandsAllowed(address index, IndexToken.Component[] memory cs, uint256[] memory px, uint16 slip)
        external
        view
        returns (bool)
    {
        IndexToken t = IndexToken(index);
        (uint16 maxMove, uint16 maxHalfWidth) = t.operatorLimits();
        if (slip > maxHalfWidth) return false;
        if (maxMove >= BPS) return true; // the owner delegated the maximum: no move limit
        uint256 last = t.lastRebalance();
        for (uint256 i; i < cs.length; ++i) {
            (uint128 anchorMid, uint40 setAt) = t.bandAnchor(cs[i].token);
            uint256 base = anchorMid;
            if (base == 0 || setAt < last) base = (uint256(cs[i].priceLow) + cs[i].priceHigh) / 2;
            // measured against the larger of the two, so a doubling and a halving read the same
            uint256 move = px[i] > base ? px[i] - base : base - px[i];
            uint256 ref = px[i] > base ? px[i] : base;
            if (move * BPS > ref * maxMove) return false;
        }
        return true;
    }

    // ----------------------------------------------------------------- slicing

    /// @notice The planned legs with each sell amount capped to what one poke should trade: the per-poke value cap
    ///         and what the leg's two pricing pools can absorb within the slippage tolerance (see poolCapacity).
    ///         What a keeper should build routes for, and what Autopilot's own swap executes.
    function sliceLegs(ExecIn memory x) public view returns (IndexToken.RebalanceLeg[] memory legs) {
        uint256 n = x.legs.length;
        legs = new IndexToken.RebalanceLeg[](n);
        uint256[] memory budget = _budgets(x);
        uint256 taken;
        for (uint256 j; j < n; ++j) {
            legs[j] = IndexToken.RebalanceLeg(x.legs[j].sellToken, x.legs[j].buyToken, 0);
            if (taken == MAX_LEGS_PER_POKE) continue; // this poke is full; the leg waits for the next one
            uint256 amt = legCap(x, j, true, budget);
            if (!worth(x, j, amt)) continue; // dust (the remainder of a filled pair) does not take a slot
            legs[j].sellAmount = amt;
            ++taken;
        }
    }

    /// @dev Whether `amt` of leg `j`'s sell token is worth at least the basket's minimum trade value.
    function worth(ExecIn memory x, uint256 j, uint256 amt) internal pure returns (bool) {
        if (amt == 0) return false;
        if (x.minLegValue == 0) return true;
        (uint256 si,) = find(x.cs, x.legs[j].sellToken, x.legs[j].buyToken);
        return Math.mulDiv(amt, x.px[si], 10 ** x.cs[si].decimals) >= x.minLegValue;
    }

    /// @dev Per-component pool budgets for one poke, in each component's raw units, unknown until first used.
    function _budgets(ExecIn memory x) private pure returns (uint256[] memory budget) {
        budget = new uint256[](x.cs.length);
        for (uint256 i; i < budget.length; ++i) {
            budget[i] = type(uint256).max;
        }
    }

    /// @notice Over the planned legs as one poke could slice them (value cap and pool budgets, before the minimum
    ///         trade value is applied): the largest leg value and how many legs are not capped to zero. `isDue`
    ///         reads "nothing fillable" from the count and "nothing worth trading" from the value.
    function legStats(ExecIn memory x) external view returns (uint256 maxV, uint256 fillable) {
        uint256[] memory budget = _budgets(x);
        for (uint256 j; j < x.legs.length; ++j) {
            uint256 amt = legCap(x, j, true, budget);
            if (amt == 0) continue;
            ++fillable;
            (uint256 si,) = find(x.cs, x.legs[j].sellToken, x.legs[j].buyToken);
            uint256 v = Math.mulDiv(amt, x.px[si], 10 ** x.cs[si].decimals);
            if (v > maxV) maxV = v;
        }
    }

    /// @notice One SwapLeg per planned leg, ready for the index's rebalanceSwap: the caller's route when one is
    ///         given (its sell amount must fit the plan and the per-poke value cap; its minimum is raised to the
    ///         TWAP less slippage), otherwise Autopilot's own swap for the sliced amount through the leg's pricing
    ///         pools. A leg capped to zero is skipped (sellAmount 0).
    function buildExec(ExecIn memory x) external view returns (IndexToken.SwapLeg[] memory exec, uint256 fillable) {
        uint256 n = x.legs.length;
        exec = new IndexToken.SwapLeg[](n);
        uint256[] memory budget = _budgets(x);
        for (uint256 j; j < n; ++j) {
            if (fillable == MAX_LEGS_PER_POKE) break; // the remaining legs stay skipped (sellAmount 0)
            (uint256 si, uint256 bi) = find(x.cs, x.legs[j].sellToken, x.legs[j].buyToken);
            bool own = x.routes.length == 0 || x.routes[j].target == address(0);
            uint256 amt = legCap(x, j, own, budget);
            if (own && !worth(x, j, amt)) continue;
            if (!own) {
                IndexToken.SwapLeg memory r = x.routes[j];
                if (r.target == x.index || r.spender == x.index || r.target == x.autopilot || r.spender == x.autopilot)
                {
                    revert BadSwapTarget();
                }
                // type(uint256).max means "the whole capped leg"; an explicit amount must fit within the cap
                if (r.sellAmount != type(uint256).max) {
                    if (r.sellAmount > amt) revert LegTooLarge(j);
                    amt = r.sellAmount;
                }
            }
            if (amt == 0) continue;
            uint256 minOut = _minOut(amt, x.px[si], x.cs[si].decimals, x.px[bi], x.cs[bi].decimals, x.slip);
            if (!own) {
                exec[j] = x.routes[j];
                if (exec[j].minAmountOut < minOut) exec[j].minAmountOut = minOut;
            } else {
                address[] memory pools = legPools(
                    x.cs[si].token, x.p.pools[si], x.cs[bi].token, x.p.pools[bi], x.p.weth, x.p.stable, x.p.stablePool
                );
                exec[j] = IndexToken.SwapLeg({
                    spender: x.autopilot,
                    target: x.autopilot,
                    data: abi.encodeWithSelector(EXECUTE_LEG_SELECTOR, x.cs[si].token, amt, minOut, pools),
                    minAmountOut: minOut,
                    sellAmount: amt
                });
            }
            ++fillable;
        }
    }

    /// @dev The most of leg `j` one poke should sell, in the sell token's raw units: the planned amount, capped by
    ///      the per-poke value cap and, for Autopilot's own swap (`own`), by what is left of the sell token's pool
    ///      and the buy token's pool within the slippage tolerance (see poolCapacity). Each pool's capacity is a
    ///      budget shared by every leg of the poke that touches it, in either direction, so four legs selling the
    ///      same token cannot each take the whole pool. Caller routes trade wherever the aggregator finds depth, so
    ///      only the value cap applies to them; the TWAP-based minimum output bounds the rest.
    function legCap(ExecIn memory x, uint256 j, bool own, uint256[] memory budget) public view returns (uint256 amt) {
        (uint256 si, uint256 bi) = find(x.cs, x.legs[j].sellToken, x.legs[j].buyToken);
        amt = x.legs[j].sellAmount;
        uint256 dS = 10 ** x.cs[si].decimals;
        if (x.maxLegValue != 0) {
            uint256 capV = Math.mulDiv(x.maxLegValue, dS, x.px[si]);
            if (capV < amt) amt = capV;
        }
        if (!own) return amt;
        uint256 dB = 10 ** x.cs[bi].decimals;
        if (x.p.pools[si] != address(0)) {
            if (budget[si] == type(uint256).max) {
                budget[si] = poolCapacity(x.p.pools[si], x.p.kinds[si], x.cs[si].token, x.slip);
            }
            if (budget[si] < amt) amt = budget[si];
        }
        uint256 amtB; // the leg's size in buy-token units at the TWAP
        if (x.p.pools[bi] != address(0)) {
            if (budget[bi] == type(uint256).max) {
                budget[bi] = poolCapacity(x.p.pools[bi], x.p.kinds[bi], x.cs[bi].token, x.slip);
            }
            if (budget[bi] != type(uint256).max) {
                uint256 capBS = Math.mulDiv(Math.mulDiv(budget[bi], x.px[bi], dB), dS, x.px[si]);
                if (capBS < amt) amt = capBS;
                amtB = Math.mulDiv(Math.mulDiv(amt, x.px[si], dS), dB, x.px[bi]);
            }
        }
        if (x.p.pools[si] != address(0) && budget[si] != type(uint256).max) budget[si] -= amt;
        if (amtB != 0) budget[bi] -= amtB > budget[bi] ? budget[bi] : amtB;
    }

    /// @notice About how much `token` can be sold into or bought out of `pool` before its price moves by a quarter
    ///         of `slip` (bps), in `token`'s raw units: an eighth of the slippage worth of the pool's in-range
    ///         liquidity at the current sqrt price for a concentrated pool, an eighth of the slippage worth of the
    ///         token's reserve for a constant-product pool (both move the price by about slip / 4). A leg touches
    ///         two such pools, so its own impact stays within half the tolerance and the other half is left for
    ///         pool fees and the hub hop, since every leg's minimum output is measured from the TWAP.
    ///         type(uint256).max when the pool cannot be read (then only the TWAP minimum output bounds the leg).
    function poolCapacity(address pool, uint8 kind, address token, uint16 slip) public view returns (uint256) {
        if (kind == TwapLib.KIND_CLASSIC) {
            (bool ok, bytes memory ret) = pool.staticcall(abi.encodeWithSelector(IClassicReserves.getReserves.selector));
            if (!ok || ret.length < 96) return type(uint256).max;
            (uint256 r0, uint256 r1,) = abi.decode(ret, (uint256, uint256, uint256));
            uint256 r = IPoolFactoryRef(pool).token0() == token ? r0 : r1;
            return r * slip / (8 * BPS);
        }
        (bool ok0, bytes memory s0) = pool.staticcall(abi.encodeWithSelector(SLOT0_SELECTOR));
        (bool okL, bytes memory lq) = pool.staticcall(abi.encodeWithSelector(LIQUIDITY_SELECTOR));
        if (!ok0 || s0.length < 32 || !okL || lq.length < 32) return type(uint256).max;
        uint256 sqrtP;
        int256 tick;
        assembly {
            sqrtP := mload(add(s0, 32))
            tick := mload(add(s0, 64))
        }
        uint256 liq = abi.decode(lq, (uint256));
        // a pool that reports only its tick (test doubles) is priced from the tick instead
        if (sqrtP == 0 && s0.length >= 64) sqrtP = TwapLib.getSqrtRatioAtTick(int24(tick));
        if (sqrtP == 0) return type(uint256).max;
        uint256 cap;
        if (IPoolFactoryRef(pool).token0() == token) {
            // dx = L * d(1/sqrtP); a price move of slip/4 is a sqrtP move of about slip/8
            cap = Math.mulDiv(liq << 96, slip, sqrtP * 8 * BPS);
        } else {
            // dy = L * d(sqrtP); about slip/8 of sqrtP
            cap = Math.mulDiv(Math.mulDiv(liq, sqrtP, 1 << 96), slip, 8 * BPS);
        }
        // in-range liquidity says nothing about the ticks a trade may cross, so a slice is also kept to what would
        // move a constant-product pool with the same holdings by slip/4; the two together are conservative
        uint256 held = IERC20(token).balanceOf(pool);
        if (held != 0) {
            uint256 byBalance = held * slip / (8 * BPS);
            if (byBalance < cap) cap = byBalance;
        }
        return cap;
    }

    function _minOut(uint256 sellAmount, uint256 pS, uint8 dS, uint256 pB, uint8 dB, uint16 slip)
        internal
        pure
        returns (uint256)
    {
        uint256 fair = Math.mulDiv(Math.mulDiv(sellAmount, pS, 10 ** dS), 10 ** dB, pB);
        return fair * (BPS - slip) / BPS;
    }

    /// @notice Component positions of a leg's sell and buy tokens.
    function find(IndexToken.Component[] memory cs, address sell, address buy)
        public
        pure
        returns (uint256 si, uint256 bi)
    {
        uint256 n = cs.length;
        bool fs;
        bool fb;
        for (uint256 i; i < n; ++i) {
            if (cs[i].token == sell) (si, fs) = (i, true);
            if (cs[i].token == buy) (bi, fb) = (i, true);
        }
        if (!fs || !fb) revert RoutesStale();
    }

    // ------------------------------------------------------------------ swaps

    /// @notice The pools a leg passes through, in order: the sell token's pricing pool (unless it is WETH or the
    ///         stablecoin), the WETH/stablecoin pool when the two sides sit on different hubs, then the buy token's
    ///         pricing pool (unless it is WETH or the stablecoin).
    function legPools(
        address sell,
        address sellPool,
        address buy,
        address buyPool,
        address weth,
        address stable,
        address stablePool
    ) public view returns (address[] memory pools) {
        pools = new address[](3);
        uint256 n;
        address hubS = sell;
        if (sell != weth && sell != stable) {
            pools[n++] = sellPool;
            hubS = _other(sellPool, sell);
        }
        address hubB = buy;
        if (buy != weth && buy != stable) hubB = _other(buyPool, buy);
        if (hubS != hubB) pools[n++] = stablePool;
        if (buy != hubB) pools[n++] = buyPool;
        assembly {
            mstore(pools, n)
        }
    }

    /// @notice Swap `amountIn` of `tokenIn` (held by the caller's contract) through `pools` in order, paying the
    ///         final output to `recipient`. Each hop uses the router registered for its pool's factory, which must
    ///         also be an allowed swap target on the index factory. Intermediate outputs are measured by balance
    ///         change, so tokens that happen to sit in the contract are never swept into a trade.
    function swapThrough(
        address[] memory pools,
        address tokenIn,
        uint256 amountIn,
        uint256 minOut,
        address recipient,
        mapping(address => Venue) storage venues,
        address indexFactory
    ) external returns (uint256 amountOut) {
        address token = tokenIn;
        uint256 amount = amountIn;
        uint256 last = pools.length - 1;
        for (uint256 i; i < pools.length; ++i) {
            address pool = pools[i];
            address out = _other(pool, token);
            address fac = IPoolFactoryRef(pool).factory();
            Venue memory v = venues[fac];
            if (v.router == address(0)) revert NoVenue(pool);
            if (!ISwapTargets(indexFactory).isSwapTarget(v.router)) revert RouterNotAllowed(v.router);
            address to = i == last ? recipient : address(this);
            uint256 before = IERC20(out).balanceOf(to);
            IERC20(token).forceApprove(v.router, amount);
            _hop(v, pool, fac, token, out, amount, i == last ? minOut : 0, to);
            IERC20(token).forceApprove(v.router, 0);
            amount = IERC20(out).balanceOf(to) - before;
            token = out;
        }
        amountOut = amount;
    }

    function _hop(
        Venue memory v,
        address pool,
        address fac,
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 minOut,
        address to
    ) private {
        if (v.style == STYLE_ROUTER02) {
            IRouter02(v.router)
                .exactInputSingle(IRouter02.Params(tokenIn, tokenOut, IFeePool(pool).fee(), to, amountIn, minOut, 0));
        } else if (v.style == STYLE_V3) {
            IRouterV3(v.router)
                .exactInputSingle(
                    IRouterV3.Params(tokenIn, tokenOut, IFeePool(pool).fee(), to, block.timestamp, amountIn, minOut, 0)
                );
        } else if (v.style == STYLE_SLIPSTREAM) {
            ISlipstreamRouter(v.router)
                .exactInputSingle(
                    ISlipstreamRouter.Params(
                        tokenIn, tokenOut, ISpacingPool(pool).tickSpacing(), to, block.timestamp, amountIn, minOut, 0
                    )
                );
        } else {
            IClassicRouter.Route[] memory r = new IClassicRouter.Route[](1);
            r[0] = IClassicRouter.Route(tokenIn, tokenOut, false, fac);
            IClassicRouter(v.router).swapExactTokensForTokens(amountIn, minOut, r, to, block.timestamp);
        }
    }

    function _other(address pool, address token) private view returns (address) {
        address t0 = IPoolFactoryRef(pool).token0();
        return t0 == token ? IPoolFactoryRef(pool).token1() : t0;
    }
}

interface IPoolFactoryRef {
    function factory() external view returns (address);
    function token0() external view returns (address);
    function token1() external view returns (address);
}

interface IClassicReserves {
    function getReserves() external view returns (uint256 reserve0, uint256 reserve1, uint256 blockTimestampLast);
}

interface IFeePool {
    function fee() external view returns (uint24);
}

interface ISpacingPool {
    function tickSpacing() external view returns (int24);
}

interface ISwapTargets {
    function isSwapTarget(address) external view returns (bool);
}

interface IRouter02 {
    struct Params {
        address tokenIn;
        address tokenOut;
        uint24 fee;
        address recipient;
        uint256 amountIn;
        uint256 amountOutMinimum;
        uint160 sqrtPriceLimitX96;
    }

    function exactInputSingle(Params calldata p) external payable returns (uint256);
}

interface IRouterV3 {
    struct Params {
        address tokenIn;
        address tokenOut;
        uint24 fee;
        address recipient;
        uint256 deadline;
        uint256 amountIn;
        uint256 amountOutMinimum;
        uint160 sqrtPriceLimitX96;
    }

    function exactInputSingle(Params calldata p) external payable returns (uint256);
}

interface ISlipstreamRouter {
    struct Params {
        address tokenIn;
        address tokenOut;
        int24 tickSpacing;
        address recipient;
        uint256 deadline;
        uint256 amountIn;
        uint256 amountOutMinimum;
        uint160 sqrtPriceLimitX96;
    }

    function exactInputSingle(Params calldata p) external payable returns (uint256);
}

interface IClassicRouter {
    struct Route {
        address from;
        address to;
        bool stable;
        address factory;
    }

    function swapExactTokensForTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        Route[] calldata routes,
        address to,
        uint256 deadline
    ) external returns (uint256[] memory amounts);
}

lib/openzeppelin-contracts/contracts/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);
}

lib/openzeppelin-contracts/contracts/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";

lib/openzeppelin-contracts/contracts/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";

lib/openzeppelin-contracts/contracts/interfaces/IERC20Metadata.sol

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

pragma solidity >=0.6.2;

import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";

lib/openzeppelin-contracts/contracts/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);
}

lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol

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

pragma solidity ^0.8.20;

import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.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 ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
    mapping(address account => uint256) private _balances;

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

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * Both values are immutable: they can only be set once during construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

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

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual returns (string memory) {
        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) {
        return _totalSupply;
    }

    /// @inheritdoc IERC20
    function balanceOf(address account) public view virtual returns (uint256) {
        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) {
        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 {
        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 {
        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);
            }
        }
    }
}

lib/openzeppelin-contracts/contracts/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);
}

lib/openzeppelin-contracts/contracts/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);
}

lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol

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

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {IERC20Metadata} from "../../../interfaces/IERC20Metadata.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 Attempts to fetch the token decimals. A return value of false indicates that the attempt failed in some way.
    function tryGetDecimals(IERC20 token) internal view returns (bool success, uint8 decimals) {
        bytes4 selector = IERC20Metadata.decimals.selector;
        assembly ("memory-safe") {
            mstore(0x00, selector)
            success := staticcall(gas(), token, 0x00, 4, 0x00, 0x20)
            success := and(and(success, gt(returndatasize(), 0x1f)), lt(mload(0x00), 0x100))
            decimals := mul(success, mload(0x00))
        }
    }

    /**
     * @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 approve
     * @param bubble Behavior switch if the approve 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)
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/Context.sol

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

pragma solidity ^0.8.20;

/**
 * @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 Context {
    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;
    }
}

lib/openzeppelin-contracts/contracts/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)
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 *
 * IMPORTANT: Deprecated. This storage-based reentrancy guard will be removed and replaced
 * by the {ReentrancyGuardTransient} variant in v6.0.
 *
 * @custom:stateless
 */
abstract contract ReentrancyGuard {
    using StorageSlot for bytes32;

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

    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

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

    constructor() {
        _reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
    }

    /**
     * @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, _status will be NOT_ENTERED
        _nonReentrantBeforeView();

        // Any calls to nonReentrant after this point will fail
        _reentrancyGuardStorageSlot().getUint256Slot().value = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
    }

    /**
     * @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().getUint256Slot().value == ENTERED;
    }

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

lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC-1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Int256Slot` with member `value` located at `slot`.
     */
    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns a `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }
}

lib/openzeppelin-contracts/contracts/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);
}

lib/openzeppelin-contracts/contracts/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));
    }
}

lib/openzeppelin-contracts/contracts/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))
        }
    }
}

src/IndexToken.sol

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

import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {Types, IIndexFactory} from "./interfaces/IIndexFactory.sol";
import {IndexLib} from "./libraries/IndexLib.sol";

/// @title IndexToken
/// @notice An ERC-20 that is 1:1 redeemable for a basket of tokens held by the contract.
///
/// Design:
/// - Mint and redeem are in-kind and pro-rata. No price oracle is needed to issue or redeem.
/// - Fees are taken as share dilution (mint fee + annual TVL fee), split between the index creator and the protocol.
/// - Rebalancing is oracle-free: when a rebalance opens, the contract pairs over-weight tokens with under-weight
///   tokens and runs Dutch auctions. Each auction starts at the price most favorable to the vault (derived from
///   creator-set per-token price bounds) and decays linearly to the least favorable. Anyone can fill.
/// - The creator chooses the rebalance interval, drift threshold, auction length, and whether anyone can open a
///   rebalance once it is due (auto) or only the owner/operator can (manual).
/// - The planner, the auction bookkeeping, and swap-leg execution live in IndexLib, an external library this
///   contract DELEGATECALLs, so the whole index fits under the bytecode limit. Its events and errors are this
///   contract's own.
contract IndexToken is ERC20, ReentrancyGuard {
    using SafeERC20 for IERC20;

    // ------------------------------------------------------------------ types

    struct Component {
        address token;
        uint8 decimals;
        uint16 targetWeightBps; // 0 means "sell down to zero"
        uint16 anchorWeightBps; // the target the operator's weight moves are measured against
        uint128 priceLow; // numeraire (1e18) per whole token
        uint128 priceHigh;
    }

    struct Auction {
        address sellToken;
        address buyToken;
        uint128 sellRemaining; // raw sellToken units still for sale
        uint128 startRate; // buy raw units per 1e18 sell raw units at start (best for vault)
        uint128 endRate; // at end (worst for vault)
        uint40 startTime;
        uint40 endTime;
    }

    /// @dev One planned trade: sell `sellAmount` raw units of `sellToken` for `buyToken`.
    struct RebalanceLeg {
        address sellToken;
        address buyToken;
        uint256 sellAmount;
    }

    /// @dev Caller-supplied execution for one planned leg, in the shape aggregator APIs return it: the vault
    ///      approves `spender` for exactly `sellAmount`, calls `target` with `data`, and expects the buy token to
    ///      land in this contract. Both addresses must be whitelisted on the factory. `sellAmount` is how much of
    ///      the planned leg to execute now: 0 skips the leg, anything at or above the planned amount sells all of
    ///      it, anything in between is a slice (see rebalanceSwap).
    struct SwapLeg {
        address spender;
        address target;
        bytes data;
        uint256 minAmountOut;
        uint256 sellAmount;
    }

    struct Plan {
        uint256 nav;
        uint256 maxDrift;
        uint256 count;
        RebalanceLeg[] legs;
        uint8[] sIdx;
        uint8[] bIdx;
    }

    /// @dev The mid the operator's moves are measured against. Re-anchored to the live mid on the operator's first
    ///      move after each rebalance, and to the owner's mid whenever the owner sets a band.
    struct BandAnchor {
        uint128 mid;
        uint40 setAt;
    }

    // -------------------------------------------------------------- constants

    uint256 public constant BPS = 10_000;
    uint256 public constant WAD = 1e18;
    uint256 public constant MAX_COMPONENTS = 20;
    uint256 internal constant YEAR = 365 days;
    uint256 internal constant DUST_VALUE = 1e15; // 0.001 numeraire units

    // ---------------------------------------------------------------- storage

    IIndexFactory public factory;
    bool private _initialized;
    string private _tokenName;
    string private _tokenSymbol;

    address public owner;
    address public pendingOwner;
    address public operator;
    address public feeRecipient;

    uint16 public mintFeeBps;
    uint16 public tvlFeeBps;
    uint256 public lastFeeAccrual;
    bool public mintPaused;

    Component[] public components;
    mapping(address => bool) public isComponent;
    /// @dev raw units backing 1e18 shares when totalSupply == 0 (bootstraps the first mint)
    mapping(address => uint256) public initialUnits;

    Types.RebalanceConfig public rebalanceConfig;
    uint256 public lastRebalance;
    uint256 public rebalanceCount;
    Auction[] public auctions;
    /// @notice True while a swap rebalance has executed some of its legs but the basket is still above the drift
    ///         threshold: the next rebalanceSwap continues it and the clock does not reset until it completes.
    bool public rebalanceOpen;

    Types.OperatorLimits public operatorLimits;
    mapping(address => BandAnchor) public bandAnchor;
    Types.WeightPolicy public weightPolicy;

    // ----------------------------------------------------------------- events

    event OwnershipTransferStarted(address indexed from, address indexed to);
    event OwnershipTransferred(address indexed from, address indexed to);
    event OperatorSet(address indexed operator);
    event FeeRecipientSet(address indexed recipient);
    event FeesSet(uint16 mintFeeBps, uint16 tvlFeeBps);
    event MintPausedSet(bool paused);
    event ComponentAdded(address indexed token);
    event ComponentRemoved(address indexed token);
    event TargetWeightsSet(uint16[] weightsBps);
    event PriceBoundsSet(address indexed token, uint128 low, uint128 high);
    event InitialUnitsSet(address indexed token, uint256 units);
    event RebalanceConfigSet(Types.RebalanceConfig config);
    event Minted(address indexed sender, address indexed to, uint256 shares, uint256 feeShares);
    event Redeemed(address indexed sender, address indexed to, uint256 shares);
    event FeesAccrued(uint256 creatorShares, uint256 protocolShares);
    event RebalanceOpened(uint256 indexed round, uint256 auctionCount, uint256 navWad);
    event AuctionCreated(
        uint256 indexed round,
        uint256 indexed id,
        address sellToken,
        address buyToken,
        uint256 sellAmount,
        uint256 startRate,
        uint256 endRate
    );
    event AuctionFilled(
        uint256 indexed id, address indexed bidder, uint256 sellAmount, uint256 buyAmount, uint256 rate
    );
    event AuctionsCancelled();
    event RebalanceSwapped(uint256 indexed round, uint256 swapCount, uint256 navWad);
    event RebalancePartial(uint256 indexed round, uint256 swapCount, uint256 navWad, uint256 maxDriftBps);
    event SwapExecuted(
        uint256 indexed round, address indexed sellToken, address indexed buyToken, uint256 sold, uint256 bought
    );
    event OperatorLimitsSet(uint16 maxBandMoveBps, uint16 maxHalfWidthBps);
    event WeightPolicySet(Types.WeightPolicy policy);

    // ----------------------------------------------------------------- errors

    error NotOwner();
    error NotAuthorized();
    error ZeroAddress();
    error ZeroAmount();
    error Paused();
    error TooManyComponents();
    error DuplicateToken();
    error UnknownToken();
    error LengthMismatch();
    error WeightsMustSumToBps();
    error BadPriceBounds();
    error FeeTooHigh();
    error Slippage();
    error ComponentNotEmpty();
    error SupplyNotZero();
    error NotDue();
    error BelowDriftThreshold();
    error AuctionsActive();
    error AuctionNotActive();
    error RateUnrepresentable();
    error BadConfig();
    error AlreadyInitialized();
    error BadSwapTarget();
    error Overspend();
    error OperatorLimitExceeded();
    error TransferShortfall();
    error WeightsNotDelegated();
    error WeightLimitExceeded();

    // -------------------------------------------------------------- modifiers

    modifier onlyOwner() {
        if (msg.sender != owner) revert NotOwner();
        _;
    }

    modifier onlyOwnerOrOperator() {
        if (msg.sender != owner && msg.sender != operator) revert NotAuthorized();
        _;
    }

    // ------------------------------------------------------- initialization

    /// @dev The implementation is deployed once and cloned (EIP-1167) by the factory. Brick the implementation.
    constructor() ERC20("", "") {
        _initialized = true;
    }

    /// @param _owner Governor of the index. The factory passes `p.owner` or a freshly deployed timelock.
    function initialize(Types.CreateParams calldata p, address _factory, address _owner) external {
        if (_initialized) revert AlreadyInitialized();
        _initialized = true;
        if (_owner == address(0) || p.feeRecipient == address(0) || _factory == address(0)) revert ZeroAddress();
        _tokenName = p.name;
        _tokenSymbol = p.symbol;
        factory = IIndexFactory(_factory);
        owner = _owner;
        feeRecipient = p.feeRecipient;
        operator = p.operator;

        uint256 n = p.tokens.length;
        if (n == 0 || n > MAX_COMPONENTS) revert TooManyComponents();
        if (p.weightsBps.length != n || p.initialUnits.length != n || p.priceLow.length != n || p.priceHigh.length != n)
        {
            revert LengthMismatch();
        }

        uint256 sum;
        for (uint256 i; i < n; ++i) {
            _addComponent(p.tokens[i], p.weightsBps[i], p.priceLow[i], p.priceHigh[i]);
            initialUnits[p.tokens[i]] = p.initialUnits[i];
            sum += p.weightsBps[i];
        }
        if (sum != BPS) revert WeightsMustSumToBps();

        _setFees(p.mintFeeBps, p.tvlFeeBps);
        _setRebalanceConfig(p.rebalance);
        _setWeightPolicy(p.weightPolicy);
        Types.OperatorLimits memory lim = p.operatorLimits;
        if (lim.maxBandMoveBps == 0 && lim.maxHalfWidthBps == 0) {
            lim = Types.OperatorLimits({maxBandMoveBps: 2_000, maxHalfWidthBps: 1_000});
        } else if (lim.maxHalfWidthBps == 0) {
            revert BadConfig();
        }
        _setOperatorLimits(lim);
        lastFeeAccrual = block.timestamp;
        lastRebalance = block.timestamp;
    }

    function name() public view override returns (string memory) {
        return _tokenName;
    }

    function symbol() public view override returns (string memory) {
        return _tokenSymbol;
    }

    // ------------------------------------------------------------------ views

    function getComponents() external view returns (Component[] memory) {
        return components;
    }

    function getAuctions() external view returns (Auction[] memory) {
        return auctions;
    }

    /// @notice Raw units of each component required to mint `grossShares` (before mint fee).
    function requiredAmounts(uint256 grossShares) public view returns (uint256[] memory amounts) {
        uint256 n = components.length;
        amounts = new uint256[](n);
        uint256 supply = totalSupply() + _pendingFeeShares();
        for (uint256 i; i < n; ++i) {
            address t = components[i].token;
            if (supply == 0) {
                amounts[i] = Math.mulDiv(grossShares, initialUnits[t], WAD, Math.Rounding.Ceil);
            } else {
                amounts[i] = Math.mulDiv(grossShares, IERC20(t).balanceOf(address(this)), supply, Math.Rounding.Ceil);
            }
        }
    }

    /// @notice Gross shares that must be issued so the minter nets `netShares` after the mint fee.
    function grossSharesFor(uint256 netShares) public view returns (uint256) {
        return Math.mulDiv(netShares, BPS, BPS - mintFeeBps, Math.Rounding.Ceil);
    }

    /// @notice Raw units of each component needed so the minter nets `netShares`.
    function previewMint(uint256 netShares) external view returns (uint256[] memory) {
        return requiredAmounts(grossSharesFor(netShares));
    }

    /// @notice Raw units of each component returned for redeeming `shares`.
    function previewRedeem(uint256 shares) external view returns (uint256[] memory amounts) {
        uint256 n = components.length;
        amounts = new uint256[](n);
        uint256 supply = totalSupply() + _pendingFeeShares();
        if (supply == 0) return amounts;
        for (uint256 i; i < n; ++i) {
            amounts[i] = Math.mulDiv(shares, IERC20(components[i].token).balanceOf(address(this)), supply);
        }
    }

    /// @notice Maximum net shares mintable given `amounts` of each component (same order as `components`).
    function maxMintable(uint256[] calldata amounts) external view returns (uint256 netShares) {
        uint256 n = components.length;
        if (amounts.length != n) revert LengthMismatch();
        uint256 supply = totalSupply() + _pendingFeeShares();
        uint256 gross = type(uint256).max;
        for (uint256 i; i < n; ++i) {
            address t = components[i].token;
            uint256 cap;
            if (supply == 0) {
                uint256 u = initialUnits[t];
                if (u == 0) continue;
                cap = Math.mulDiv(amounts[i], WAD, u);
            } else {
                uint256 bal = IERC20(t).balanceOf(address(this));
                if (bal == 0) continue;
                cap = Math.mulDiv(amounts[i], supply, bal);
            }
            if (cap < gross) gross = cap;
        }
        if (gross == type(uint256).max) return 0;
        netShares = Math.mulDiv(gross, BPS - mintFeeBps, BPS);
        // guard against ceil rounding in grossSharesFor pushing requirements above `amounts`
        while (netShares > 0 && grossSharesFor(netShares) > gross) netShares--;
    }

    /// @notice NAV in numeraire (1e18) using mid prices, plus per-component values and current weights.
    function navSnapshot()
        external
        view
        returns (uint256 navWad, uint256[] memory values, uint256[] memory currentWeightsBps)
    {
        uint256 n = components.length;
        values = new uint256[](n);
        currentWeightsBps = new uint256[](n);
        for (uint256 i; i < n; ++i) {
            values[i] = _value(components[i], IERC20(components[i].token).balanceOf(address(this)));
            navWad += values[i];
        }
        if (navWad == 0) return (navWad, values, currentWeightsBps);
        for (uint256 i; i < n; ++i) {
            currentWeightsBps[i] = Math.mulDiv(values[i], BPS, navWad);
        }
    }

    /// @notice Whether a rebalance can be opened right now by `caller`.
    function canOpenRebalance(address caller) public view returns (bool) {
        Types.RebalanceConfig memory c = rebalanceConfig;
        if (c.autoRebalance) {
            if (block.timestamp < lastRebalance + c.interval) return false;
        } else if (caller != owner && caller != operator) {
            return false;
        }
        return !hasActiveAuctions();
    }

    function hasActiveAuctions() public view returns (bool) {
        return IndexLib.hasActiveAuctions(auctions);
    }

    /// @notice Current rate (buy raw units per 1e18 sell raw units) of auction `id`.
    function currentRate(uint256 id) public view returns (uint256) {
        return IndexLib.currentRate(auctions, id);
    }

    /// @notice Buy amount a bidder must pay right now to take `sellAmount` from auction `id`.
    function quoteBid(uint256 id, uint256 sellAmount) external view returns (uint256 buyAmount) {
        return Math.mulDiv(sellAmount, currentRate(id), WAD, Math.Rounding.Ceil);
    }

    /// @notice The exact legs `openRebalance` or `rebalanceSwap` would execute right now, in order.
    /// @dev Does not enforce the drift threshold; `maxDriftBps` lets callers decide. Empty when NAV is zero.
    function previewRebalance()
        external
        view
        returns (uint256 navWad, uint256 maxDriftBps, RebalanceLeg[] memory legs)
    {
        Plan memory p = _planRebalance();
        legs = p.legs;
        uint256 count = p.count;
        assembly {
            mstore(legs, count)
        }
        return (p.nav, p.maxDrift, legs);
    }

    // ------------------------------------------------------------ mint/redeem

    /// @notice Mint `netShares` to `to` by depositing the required pro-rata amounts of every component.
    function mint(uint256 netShares, address to) external nonReentrant returns (uint256[] memory amountsIn) {
        if (mintPaused) revert Paused();
        if (netShares == 0) revert ZeroAmount();
        if (to == address(0)) revert ZeroAddress();
        _accrueFees();

        uint256 gross = grossSharesFor(netShares);
        amountsIn = requiredAmounts(gross);
        uint256 n = components.length;
        for (uint256 i; i < n; ++i) {
            if (amountsIn[i] > 0) {
                IndexLib.pullExact(IERC20(components[i].token), amountsIn[i]);
            }
        }
        _mint(to, netShares);
        uint256 feeShares = gross - netShares;
        _distributeFeeShares(feeShares, 0);
        emit Minted(msg.sender, to, netShares, feeShares);
    }

    /// @notice Burn `shares` and receive the pro-rata amount of every component.
    function redeem(uint256 shares, address to, uint256[] calldata minAmountsOut)
        external
        nonReentrant
        returns (uint256[] memory amountsOut)
    {
        if (shares == 0) revert ZeroAmount();
        if (to == address(0)) revert ZeroAddress();
        _accrueFees();

        uint256 n = components.length;
        if (minAmountsOut.length != n) revert LengthMismatch();
        uint256 supply = totalSupply();
        _burn(msg.sender, shares);
        amountsOut = new uint256[](n);
        for (uint256 i; i < n; ++i) {
            IERC20 t = IERC20(components[i].token);
            amountsOut[i] = Math.mulDiv(shares, t.balanceOf(address(this)), supply);
            if (amountsOut[i] < minAmountsOut[i]) revert Slippage();
            if (amountsOut[i] > 0) t.safeTransfer(to, amountsOut[i]);
        }
        emit Redeemed(msg.sender, to, shares);
    }

    /// @notice Accrue the TVL fee as share dilution. Public so anyone can crystallize fees.
    function accrueFees() external {
        _accrueFees();
    }

    // -------------------------------------------------------------- rebalance

    /// @notice Open a rebalance round. Pairs over-weight components with under-weight ones and starts auctions.
    function openRebalance() external nonReentrant {
        Types.RebalanceConfig memory c = rebalanceConfig;
        if (c.autoRebalance) {
            if (block.timestamp < lastRebalance + c.interval) revert NotDue();
        } else if (msg.sender != owner && msg.sender != operator) {
            revert NotAuthorized();
        }
        if (hasActiveAuctions()) revert AuctionsActive();
        _accrueFees();
        delete auctions;

        Plan memory p = _planRebalance();
        _requireActionable(p);

        uint256 round = ++rebalanceCount;
        IndexLib.openAuctions(
            auctions, components, p, round, uint40(block.timestamp), uint40(block.timestamp + c.auctionLength)
        );
        lastRebalance = block.timestamp;
        rebalanceOpen = false;
        _anchorWeights();
        emit RebalanceOpened(round, p.count, p.nav);
    }

    /// @notice Buy up to `sellAmount` of the auction's sell token at the current Dutch-auction rate.
    /// @param maxBuyAmount Revert if the bidder would have to pay more than this.
    function bid(uint256 id, uint256 sellAmount, uint256 maxBuyAmount)
        external
        nonReentrant
        returns (uint256 filled, uint256 buyAmount)
    {
        (filled, buyAmount) = IndexLib.bid(auctions, id, sellAmount, maxBuyAmount);
    }

    /// @notice Cancel all open auctions. Owner or operator.
    function cancelAuctions() external onlyOwnerOrOperator {
        delete auctions;
        emit AuctionsCancelled();
    }

    /// @notice Rebalance by executing each planned leg against a whitelisted swap target (an aggregator or
    ///         AMM router) instead of posting Dutch auctions. Owner or operator, no interval wait.
    /// @param legs One SwapLeg per planned leg, in `previewRebalance` order. Each leg must deliver at least
    ///             max(minAmountOut, the Dutch-auction floor for that pair) of the buy token to this contract.
    ///             A leg may sell less than planned (`sellAmount`, see SwapLeg): large rebalances are then done
    ///             in slices across several calls. The round completes, resetting the clock and the operator's
    ///             anchors, once every leg was executed in full or the remaining drift is at or below the drift
    ///             threshold; otherwise it stays open (`rebalanceOpen`) for the next call to continue.
    function rebalanceSwap(SwapLeg[] calldata legs) external nonReentrant onlyOwnerOrOperator {
        if (hasActiveAuctions()) revert AuctionsActive();
        _accrueFees();
        delete auctions;

        Plan memory p = _planRebalance();
        _requireActionable(p);

        uint256 round = rebalanceCount + 1;
        bool complete = IndexLib.executeLegs(factory, isComponent, components, p, legs, round);
        uint256 driftAfter;
        if (!complete) {
            driftAfter = _planRebalance().maxDrift;
            complete = driftAfter <= rebalanceConfig.driftThresholdBps;
        }
        if (complete) {
            rebalanceCount = round;
            lastRebalance = block.timestamp;
            rebalanceOpen = false;
            _anchorWeights();
            emit RebalanceSwapped(round, p.count, p.nav);
        } else {
            rebalanceOpen = true;
            emit RebalancePartial(round, p.count, p.nav, driftAfter);
        }
    }

    // ------------------------------------------------------------- governance

    function transferOwnership(address to) external onlyOwner {
        pendingOwner = to;
        emit OwnershipTransferStarted(owner, to);
    }

    function acceptOwnership() external {
        if (msg.sender != pendingOwner) revert NotAuthorized();
        emit OwnershipTransferred(owner, msg.sender);
        owner = msg.sender;
        pendingOwner = address(0);
    }

    /// @dev Fees are settled first so a switch between Autopilot and a manual operator is charged at the right
    ///      protocol rate up to the second (see IIndexFactory.protocolTvlFeeFor).
    function setOperator(address op) external onlyOwner {
        _accrueFees();
        operator = op;
        emit OperatorSet(op);
    }

    function setFeeRecipient(address r) external onlyOwner {
        if (r == address(0)) revert ZeroAddress();
        feeRecipient = r;
        emit FeeRecipientSet(r);
    }

    function setFees(uint16 _mintFeeBps, uint16 _tvlFeeBps) external onlyOwner {
        _accrueFees();
        _setFees(_mintFeeBps, _tvlFeeBps);
    }

    function setMintPaused(bool paused) external onlyOwnerOrOperator {
        mintPaused = paused;
        emit MintPausedSet(paused);
    }

    function setRebalanceConfig(Types.RebalanceConfig calldata c) external onlyOwner {
        _setRebalanceConfig(c);
    }

    /// @notice Cap how far and how wide the operator may set price bands per rebalance window. Owner calls to the
    ///         band setters are never limited; put the owner behind the timelock instead.
    function setOperatorLimits(uint16 maxBandMoveBps, uint16 maxHalfWidthBps) external onlyOwner {
        _setOperatorLimits(Types.OperatorLimits({maxBandMoveBps: maxBandMoveBps, maxHalfWidthBps: maxHalfWidthBps}));
    }

    /// @notice Choose who may maintain target weights and how far the operator may move them per window.
    function setWeightPolicy(Types.WeightPolicy calldata w) external onlyOwner {
        _setWeightPolicy(w);
    }

    /// @notice Add a component with weight 0. Call setTargetWeights afterwards to give it a target.
    function addComponent(address token, uint128 low, uint128 high) external onlyOwner {
        if (components.length >= MAX_COMPONENTS) revert TooManyComponents();
        _addComponent(token, 0, low, high);
    }

    /// @notice Remove a component whose target is 0 and whose remaining balance is dust. Dust goes to feeRecipient.
    function removeComponent(uint256 idx) external onlyOwner {
        Component memory c = components[idx];
        if (c.targetWeightBps != 0) revert ComponentNotEmpty();
        uint256 bal = IERC20(c.token).balanceOf(address(this));
        if (_value(c, bal) > DUST_VALUE) revert ComponentNotEmpty();
        if (bal > 0) IERC20(c.token).safeTransfer(feeRecipient, bal);
        isComponent[c.token] = false;
        delete bandAnchor[c.token];
        uint256 last = components.length - 1;
        if (idx != last) components[idx] = components[last];
        components.pop();
        emit ComponentRemoved(c.token);
    }

    /// @notice Set target weights. The owner may set anything and re-anchors every component. Under an Equal or
    ///         MarketCap policy the operator may also set weights, bounded per component by `maxWeightBps` (when
    ///         nonzero) and by `maxWeightMoveBps` against the anchor, which resets after each rebalance. Under
    ///         Custom only the owner sets weights.
    function setTargetWeights(uint16[] calldata weightsBps) external onlyOwnerOrOperator {
        uint256 n = components.length;
        if (weightsBps.length != n) revert LengthMismatch();
        bool isOwner = msg.sender == owner;
        Types.WeightPolicy storage pol = weightPolicy;
        if (!isOwner && pol.scheme == Types.WeightScheme.Custom) revert WeightsNotDelegated();
        uint256 sum;
        for (uint256 i; i < n; ++i) {
            uint16 w = weightsBps[i];
            Component storage c = components[i];
            if (isOwner) {
                c.anchorWeightBps = w;
            } else {
                if (pol.maxWeightBps != 0 && w > pol.maxWeightBps) revert WeightLimitExceeded();
                uint16 a = c.anchorWeightBps;
                uint256 move = w > a ? w - a : a - w;
                if (move > pol.maxWeightMoveBps) revert WeightLimitExceeded();
            }
            c.targetWeightBps = w;
            sum += w;
        }
        if (sum != BPS) revert WeightsMustSumToBps();
        emit TargetWeightsSet(weightsBps);
    }

    function setPriceBounds(uint256 idx, uint128 low, uint128 high) external onlyOwnerOrOperator {
        _setBounds(idx, low, high);
    }

    function setAllPriceBounds(uint128[] calldata low, uint128[] calldata high) external onlyOwnerOrOperator {
        uint256 n = components.length;
        if (low.length != n || high.length != n) revert LengthMismatch();
        for (uint256 i; i < n; ++i) {
            _setBounds(i, low[i], high[i]);
        }
    }

    /// @notice Set the bootstrap backing per 1e18 shares. Only meaningful while totalSupply == 0.
    function setInitialUnits(address token, uint256 units) external onlyOwner {
        if (totalSupply() != 0) revert SupplyNotZero();
        if (!isComponent[token]) revert UnknownToken();
        initialUnits[token] = units;
        emit InitialUnitsSet(token, units);
    }

    // --------------------------------------------------------------- internal

    function _addComponent(address token, uint16 weight, uint128 low, uint128 high) internal {
        if (token == address(0)) revert ZeroAddress();
        if (isComponent[token]) revert DuplicateToken();
        if (low == 0 || high < low) revert BadPriceBounds();
        uint8 dec = IERC20Metadata(token).decimals();
        // 10 ** decimals must stay far inside uint256 for the rate math; no real token needs more than 36
        if (dec > 36) revert BadConfig();
        components.push(
            Component({
                token: token,
                decimals: dec,
                targetWeightBps: weight,
                anchorWeightBps: weight,
                priceLow: low,
                priceHigh: high
            })
        );
        isComponent[token] = true;
        emit ComponentAdded(token);
    }

    function _setFees(uint16 _mintFeeBps, uint16 _tvlFeeBps) internal {
        if (_mintFeeBps > factory.maxMintFeeBps() || _tvlFeeBps > factory.maxTvlFeeBps()) revert FeeTooHigh();
        mintFeeBps = _mintFeeBps;
        tvlFeeBps = _tvlFeeBps;
        emit FeesSet(_mintFeeBps, _tvlFeeBps);
    }

    function _setRebalanceConfig(Types.RebalanceConfig memory c) internal {
        if (c.auctionLength < 5 minutes || c.auctionLength > 7 days) revert BadConfig();
        if (c.driftThresholdBps > BPS) revert BadConfig();
        rebalanceConfig = c;
        emit RebalanceConfigSet(c);
    }

    function _setWeightPolicy(Types.WeightPolicy memory w) internal {
        if (w.maxWeightBps > BPS || w.maxWeightMoveBps > BPS) revert BadConfig();
        weightPolicy = w;
        emit WeightPolicySet(w);
    }

    function _setOperatorLimits(Types.OperatorLimits memory lim) internal {
        if (lim.maxBandMoveBps > BPS || lim.maxHalfWidthBps > BPS) revert BadConfig();
        operatorLimits = lim;
        emit OperatorLimitsSet(lim.maxBandMoveBps, lim.maxHalfWidthBps);
    }

    /// @dev After a rebalance the current targets become the baseline for the operator's next weight moves.
    function _anchorWeights() internal {
        uint256 n = components.length;
        for (uint256 i; i < n; ++i) {
            components[i].anchorWeightBps = components[i].targetWeightBps;
        }
    }

    /// @dev Owner sets are unrestricted and re-anchor the band. Operator sets are measured against the anchor:
    ///      the mid may drift at most `maxBandMoveBps` from it per rebalance window and the half-width may not
    ///      exceed `maxHalfWidthBps`, so a rogue operator key is bounded to roughly one band move per window.
    function _setBounds(uint256 idx, uint128 low, uint128 high) internal {
        if (low == 0 || high < low) revert BadPriceBounds();
        Component storage c = components[idx];
        uint256 newMid = (uint256(low) + high) / 2;
        if (msg.sender == owner) {
            bandAnchor[c.token] = BandAnchor({mid: uint128(newMid), setAt: uint40(block.timestamp)});
        } else {
            Types.OperatorLimits memory lim = operatorLimits;
            BandAnchor memory a = bandAnchor[c.token];
            uint256 base = a.mid;
            if (base == 0 || a.setAt < lastRebalance) {
                base = (uint256(c.priceLow) + c.priceHigh) / 2;
                bandAnchor[c.token] = BandAnchor({mid: uint128(base), setAt: uint40(block.timestamp)});
            }
            // a limit of 10,000 means none; below that the move is measured against the larger of the two mids,
            // so a doubling and a halving read the same and an honest big move cannot strand the index
            if (lim.maxBandMoveBps < BPS) {
                uint256 move = newMid > base ? newMid - base : base - newMid;
                uint256 ref = newMid > base ? newMid : base;
                if (move * BPS > ref * lim.maxBandMoveBps) revert OperatorLimitExceeded();
            }
            if ((uint256(high) - low) * BPS > 2 * newMid * lim.maxHalfWidthBps) revert OperatorLimitExceeded();
        }
        c.priceLow = low;
        c.priceHigh = high;
        emit PriceBoundsSet(c.token, low, high);
    }

    function _mid(Component memory c) internal pure returns (uint256) {
        return (uint256(c.priceLow) + uint256(c.priceHigh)) / 2;
    }

    function _value(Component memory c, uint256 rawAmount) internal pure returns (uint256) {
        return Math.mulDiv(rawAmount, _mid(c), 10 ** c.decimals);
    }

    /// @dev The planner lives in IndexLib (see planRebalance there); kept as one call site so openRebalance,
    ///      rebalanceSwap, and previewRebalance can never diverge.
    function _planRebalance() internal view returns (Plan memory) {
        return IndexLib.planRebalance(components);
    }

    function _requireActionable(Plan memory p) internal view {
        if (p.nav == 0) revert ZeroAmount();
        if (p.maxDrift < rebalanceConfig.driftThresholdBps) revert BelowDriftThreshold();
    }

    /// @dev Annual fees pending since `lastFeeAccrual`: the maker's (`tvlFeeBps`) and the protocol's own
    ///      (`factory.protocolTvlFeeFor(this)`), each as shares to mint.
    function _pendingFees() internal view returns (uint256 maker, uint256 protocol) {
        uint256 supply = totalSupply();
        if (supply == 0) return (0, 0);
        uint256 elapsed = block.timestamp - lastFeeAccrual;
        if (elapsed == 0) return (0, 0);
        uint256 pBps = factory.protocolTvlFeeFor(address(this));
        if (tvlFeeBps != 0) maker = Math.mulDiv(supply, uint256(tvlFeeBps) * elapsed, BPS * YEAR);
        if (pBps != 0) protocol = Math.mulDiv(supply, pBps * elapsed, BPS * YEAR);
    }

    function _pendingFeeShares() internal view returns (uint256) {
        (uint256 maker, uint256 protocol) = _pendingFees();
        return maker + protocol;
    }

    function _accrueFees() internal {
        (uint256 maker, uint256 protocol) = _pendingFees();
        lastFeeAccrual = block.timestamp;
        if (maker + protocol > 0) _distributeFeeShares(maker, protocol);
    }

    /// @dev `shares` is a maker-side fee (mint or annual), of which the protocol takes `protocolFeeShareBps`;
    ///      `protocolOwn` is the protocol's own annual fee, minted whole to the protocol recipient.
    function _distributeFeeShares(uint256 shares, uint256 protocolOwn) internal {
        uint256 protocolShares = Math.mulDiv(shares, factory.protocolFeeShareBps(), BPS);
        uint256 creatorShares = shares - protocolShares;
        protocolShares += protocolOwn;
        if (protocolShares > 0) _mint(factory.protocolFeeRecipient(), protocolShares);
        if (creatorShares > 0) _mint(feeRecipient, creatorShares);
        emit FeesAccrued(creatorShares, protocolShares);
    }
}

src/interfaces/IIndexFactory.sol

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

/// @notice Shared types for the Basket protocol.
library Types {
    /// @dev Per-index rebalancing policy, set by the index creator.
    struct RebalanceConfig {
        uint32 interval; // seconds between rebalance windows
        uint32 auctionLength; // seconds each Dutch auction runs
        uint16 driftThresholdBps; // open only if max |current - target| >= threshold (bps of NAV)
        bool autoRebalance; // true: anyone may open once due; false: owner/operator only
    }

    /// @dev How target weights are meant to be maintained. The contract never computes 1/n or market caps
    ///      itself; the app and the bot do and submit the result through setTargetWeights. The scheme decides who
    ///      may submit: under Custom only the owner; under Equal and MarketCap the operator too, bounded by the
    ///      caps in WeightPolicy so a bot key cannot reshape the basket in one move.
    enum WeightScheme {
        Custom,
        Equal,
        MarketCap
    }

    struct WeightPolicy {
        WeightScheme scheme;
        uint16 maxWeightBps; // operator may not set any component above this; 0 means no cap
        uint16 maxWeightMoveBps; // operator may not move a component more than this from its anchor per window
    }

    /// @dev Caps on what the operator (not the owner) may do to a price band within one rebalance window.
    struct OperatorLimits {
        uint16 maxBandMoveBps; // max |newMid - anchorMid| / anchorMid since the last rebalance or owner set
        uint16 maxHalfWidthBps; // max (high - low) / (2 * mid)
    }

    /// @dev Parameters for IndexFactory.createIndex.
    struct CreateParams {
        string name;
        string symbol;
        address owner; // governor of the index (EOA, multisig, or DAO)
        address feeRecipient; // receives the creator share of fees
        address operator; // optional: a bot key or the Autopilot contract; address(0) for none
        uint16 mintFeeBps; // taken as share dilution on mint
        uint16 tvlFeeBps; // annual, taken as share dilution over time
        address[] tokens;
        uint16[] weightsBps; // must sum to 10_000
        uint256[] initialUnits; // raw units of each token backing 1e18 shares at inception
        uint128[] priceLow; // numeraire (1e18) per whole token, lower bound
        uint128[] priceHigh; // numeraire (1e18) per whole token, upper bound
        RebalanceConfig rebalance;
        WeightPolicy weightPolicy;
        OperatorLimits operatorLimits; // both zero keeps the defaults (2,000 / 1,000)
    }
}

interface IIndexFactory {
    function protocolFeeRecipient() external view returns (address);
    function protocolFeeShareBps() external view returns (uint16);
    function maxMintFeeBps() external view returns (uint16);
    function maxTvlFeeBps() external view returns (uint16);
    /// @notice Annual fee (bps of supply per year) that `index` pays the protocol as share dilution, on top of
    ///         the maker's own annual fee: the per-index override when one is set, else the autopilot default when
    ///         the index's operator is a recognized Autopilot, else the manual default. Read at every accrual, so
    ///         a mode switch (which settles fees first) is charged exactly.
    function protocolTvlFeeFor(address index) external view returns (uint16);
    function isIndex(address) external view returns (bool);
    /// @notice Routers and aggregators that indexes and the zap may call with an exact-amount approval.
    function isSwapTarget(address) external view returns (bool);
}

src/interfaces/IUniswapV3.sol

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

/// @notice The slices of Uniswap V3 that Autopilot and its library read and call. Aerodrome Slipstream pools expose
///         the same `observe`, `token0`, `token1`, `fee`, and `liquidity`; their `slot0` returns six words, so the
///         library reads it through a raw staticcall rather than this signature.
interface IUniswapV3Factory {
    function getPool(address tokenA, address tokenB, uint24 fee) external view returns (address pool);
}

interface IUniswapV3Pool {
    function observe(uint32[] calldata secondsAgos)
        external
        view
        returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);

    function slot0()
        external
        view
        returns (
            uint160 sqrtPriceX96,
            int24 tick,
            uint16 observationIndex,
            uint16 observationCardinality,
            uint16 observationCardinalityNext,
            uint8 feeProtocol,
            bool unlocked
        );

    function liquidity() external view returns (uint128);

    function token0() external view returns (address);

    function token1() external view returns (address);

    function fee() external view returns (uint24);
}

/// @notice SwapRouter02 exactInput (no deadline field; SwapRouter02 takes the deadline from the multicall wrapper).
interface ISwapRouter02 {
    struct ExactInputParams {
        bytes path;
        address recipient;
        uint256 amountIn;
        uint256 amountOutMinimum;
    }

    function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
}

src/libraries/IndexLib.sol

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

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IndexToken} from "../IndexToken.sol";
import {IIndexFactory} from "../interfaces/IIndexFactory.sol";

/// @title IndexLib
/// @notice IndexToken's rebalance planner, Dutch-auction bookkeeping, and swap-leg execution, kept in an external
///         library (linked at deploy) so IndexToken stays under the bytecode limit. Every function runs in the
///         index's own context through DELEGATECALL: storage, token balances, approvals, and `msg.sender` are the
///         index's, and the events and errors are IndexToken's own, so logs and reverts look exactly as before.
library IndexLib {
    using SafeERC20 for IERC20;

    uint256 internal constant BPS = 10_000;
    uint256 internal constant WAD = 1e18;
    uint256 internal constant DUST_VALUE = 1e15; // 0.001 numeraire units; mirrors IndexToken

    // ---------------------------------------------------------------- planner

    /// @notice Values the basket at band midpoints and greedily pairs over-weight components with under-weight
    ///         ones. Shared by openRebalance, rebalanceSwap, and previewRebalance so the preview can never diverge
    ///         from execution. Never reverts; callers check `nav` and `maxDrift`.
    function planRebalance(IndexToken.Component[] storage components) external view returns (IndexToken.Plan memory p) {
        uint256 n = components.length;
        p.legs = new IndexToken.RebalanceLeg[](n);
        p.sIdx = new uint8[](n);
        p.bIdx = new uint8[](n);
        uint256[] memory values = new uint256[](n);
        for (uint256 i; i < n; ++i) {
            values[i] = value(components[i], IERC20(components[i].token).balanceOf(address(this)));
            p.nav += values[i];
        }
        if (p.nav == 0) return p;

        int256[] memory diff = new int256[](n);
        for (uint256 i; i < n; ++i) {
            uint256 target = Math.mulDiv(p.nav, components[i].targetWeightBps, BPS);
            diff[i] = int256(values[i]) - int256(target);
            uint256 d = diff[i] >= 0 ? uint256(diff[i]) : uint256(-diff[i]);
            uint256 driftBps = Math.mulDiv(d, BPS, p.nav);
            if (driftBps > p.maxDrift) p.maxDrift = driftBps;
        }

        for (uint256 s; s < n; ++s) {
            if (diff[s] <= 0) continue;
            // sub-dust remainders of a dropped component are left for removeComponent rather than
            // emitted as swap legs no router could fill
            if (components[s].targetWeightBps == 0 && values[s] <= DUST_VALUE) continue;
            uint256 remaining = IERC20(components[s].token).balanceOf(address(this));
            for (uint256 b; b < n && diff[s] > 0; ++b) {
                if (diff[b] >= 0) continue;
                uint256 v = uint256(diff[s]);
                uint256 need = uint256(-diff[b]);
                if (need < v) v = need;
                uint256 sellRaw = Math.mulDiv(v, 10 ** components[s].decimals, mid(components[s]));
                diff[s] -= int256(v);
                diff[b] += int256(v);
                if (sellRaw > remaining) sellRaw = remaining;
                if (sellRaw == 0) {
                    // a zero-weight seller must never skip a buyer while it still holds balance
                    if (components[s].targetWeightBps != 0 || remaining == 0) continue;
                    sellRaw = remaining;
                }
                remaining -= sellRaw;
                p.legs[p.count] = IndexToken.RebalanceLeg(components[s].token, components[b].token, sellRaw);
                p.sIdx[p.count] = uint8(s);
                p.bIdx[p.count] = uint8(b);
                ++p.count;
            }
            // Targets floor per component, so total need can fall a few wei short of a zero-weight
            // component's surplus. Fold whatever is left into its last leg so it sells to exactly zero.
            if (components[s].targetWeightBps == 0 && remaining > 0 && p.count > 0 && p.sIdx[p.count - 1] == s) {
                p.legs[p.count - 1].sellAmount += remaining;
            }
        }
    }

    // --------------------------------------------------------------- auctions

    function hasActiveAuctions(IndexToken.Auction[] storage auctions) external view returns (bool) {
        uint256 n = auctions.length;
        for (uint256 i; i < n; ++i) {
            if (auctions[i].sellRemaining > 0 && block.timestamp < auctions[i].endTime) return true;
        }
        return false;
    }

    /// @notice Current rate (buy raw units per 1e18 sell raw units) of auction `id`.
    function currentRate(IndexToken.Auction[] storage auctions, uint256 id) public view returns (uint256) {
        IndexToken.Auction memory a = auctions[id];
        if (block.timestamp <= a.startTime) return a.startRate;
        if (block.timestamp >= a.endTime) return a.endRate;
        uint256 elapsed = block.timestamp - a.startTime;
        uint256 len = a.endTime - a.startTime;
        return a.startRate - Math.mulDiv(a.startRate - a.endRate, elapsed, len);
    }

    /// @notice One Dutch auction per planned leg, from the rate best for the vault to the worst.
    function openAuctions(
        IndexToken.Auction[] storage auctions,
        IndexToken.Component[] storage components,
        IndexToken.Plan memory p,
        uint256 round,
        uint40 start,
        uint40 end
    ) external {
        for (uint256 i; i < p.count; ++i) {
            IndexToken.Component memory s = components[p.sIdx[i]];
            IndexToken.Component memory b = components[p.bIdx[i]];
            uint256 sellRaw = p.legs[i].sellAmount;
            if (sellRaw > type(uint128).max) revert IndexToken.RateUnrepresentable();
            uint128 startRate = rate(s, b, s.priceHigh, b.priceLow);
            uint128 endRate = rate(s, b, s.priceLow, b.priceHigh);
            auctions.push(
                IndexToken.Auction({
                    sellToken: s.token,
                    buyToken: b.token,
                    sellRemaining: uint128(sellRaw),
                    startRate: startRate,
                    endRate: endRate,
                    startTime: start,
                    endTime: end
                })
            );
            emit IndexToken.AuctionCreated(round, auctions.length - 1, s.token, b.token, sellRaw, startRate, endRate);
        }
    }

    /// @notice Buy up to `sellAmount` of the auction's sell token at the current Dutch-auction rate, paying at most
    ///         `maxBuyAmount` of the buy token. The bidder is `msg.sender` (preserved through DELEGATECALL).
    function bid(IndexToken.Auction[] storage auctions, uint256 id, uint256 sellAmount, uint256 maxBuyAmount)
        external
        returns (uint256 filled, uint256 buyAmount)
    {
        IndexToken.Auction storage a = auctions[id];
        if (a.sellRemaining == 0 || block.timestamp >= a.endTime) revert IndexToken.AuctionNotActive();
        if (sellAmount == 0) revert IndexToken.ZeroAmount();
        filled = sellAmount > a.sellRemaining ? a.sellRemaining : sellAmount;
        uint256 r = currentRate(auctions, id);
        buyAmount = Math.mulDiv(filled, r, WAD, Math.Rounding.Ceil);
        if (buyAmount > maxBuyAmount) revert IndexToken.Slippage();
        if (buyAmount == 0) revert IndexToken.ZeroAmount();
        a.sellRemaining -= uint128(filled);
        pullExact(IERC20(a.buyToken), buyAmount);
        IERC20(a.sellToken).safeTransfer(msg.sender, filled);
        emit IndexToken.AuctionFilled(id, msg.sender, filled, buyAmount, r);
    }

    // ------------------------------------------------------------------ swaps

    /// @notice Execute the planned legs against the caller's routes: each leg approves exactly its sell amount to
    ///         a whitelisted spender, calls the whitelisted target, resets the approval, and must give up at most
    ///         the sell amount and receive at least max(the caller's minimum, the Dutch-auction floor). A leg's
    ///         `sellAmount` of 0 skips it and anything below the planned amount is a slice; the floor and the
    ///         minimum scale with what is actually sold.
    /// @return full True when every leg was executed for its whole planned amount.
    function executeLegs(
        IIndexFactory factory,
        mapping(address => bool) storage isComponent,
        IndexToken.Component[] storage components,
        IndexToken.Plan memory p,
        IndexToken.SwapLeg[] calldata legs,
        uint256 round
    ) external returns (bool full) {
        if (legs.length != p.count) revert IndexToken.LengthMismatch();
        full = true;
        for (uint256 i; i < p.count; ++i) {
            uint256 planned = p.legs[i].sellAmount;
            uint256 sellAmount = legs[i].sellAmount;
            if (sellAmount == 0) {
                full = false;
                continue;
            }
            uint256 callerMin = legs[i].minAmountOut;
            if (sellAmount >= planned) {
                // type(uint256).max means "the whole planned amount"; an explicit larger request was quoted for
                // more than the plan, so its minimum scales down with the cap
                if (sellAmount != type(uint256).max) callerMin = Math.mulDiv(callerMin, planned, sellAmount);
                sellAmount = planned;
            } else {
                full = false;
            }
            IndexToken.Component memory s = components[p.sIdx[i]];
            IndexToken.Component memory b = components[p.bIdx[i]];
            uint256 floorOut = Math.mulDiv(sellAmount, rate(s, b, s.priceLow, b.priceHigh), WAD);
            uint256 minOut = callerMin > floorOut ? callerMin : floorOut;
            (uint256 sold, uint256 bought) =
                _executeSwap(factory, isComponent, s.token, b.token, sellAmount, minOut, legs[i]);
            emit IndexToken.SwapExecuted(round, s.token, b.token, sold, bought);
        }
    }

    function _executeSwap(
        IIndexFactory factory,
        mapping(address => bool) storage isComponent,
        address sellToken,
        address buyToken,
        uint256 sellAmount,
        uint256 minOut,
        IndexToken.SwapLeg calldata leg
    ) private returns (uint256 sold, uint256 bought) {
        if (!factory.isSwapTarget(leg.spender) || !factory.isSwapTarget(leg.target)) {
            revert IndexToken.BadSwapTarget();
        }
        // even a misconfigured whitelist must never let the vault call itself or one of its own holdings
        if (leg.target == address(this) || isComponent[leg.target]) revert IndexToken.BadSwapTarget();
        uint256 sellBefore = IERC20(sellToken).balanceOf(address(this));
        uint256 buyBefore = IERC20(buyToken).balanceOf(address(this));
        IERC20(sellToken).forceApprove(leg.spender, sellAmount);
        (bool ok, bytes memory ret) = leg.target.call(leg.data);
        if (!ok) {
            assembly {
                revert(add(ret, 0x20), mload(ret))
            }
        }
        IERC20(sellToken).forceApprove(leg.spender, 0);
        uint256 sellAfter = IERC20(sellToken).balanceOf(address(this));
        if (sellAfter < sellBefore) {
            sold = sellBefore - sellAfter;
            if (sold > sellAmount) revert IndexToken.Overspend();
        }
        bought = IERC20(buyToken).balanceOf(address(this)) - buyBefore;
        if (bought < minOut) revert IndexToken.Slippage();
    }

    // ---------------------------------------------------------------- helpers

    /// @notice Pull exactly `amount` of `t` from msg.sender. Fee-on-transfer tokens deliver less and are rejected
    ///         so a minter or bidder can never dilute existing holders.
    function pullExact(IERC20 t, uint256 amount) public {
        uint256 before = t.balanceOf(address(this));
        t.safeTransferFrom(msg.sender, address(this), amount);
        if (t.balanceOf(address(this)) - before < amount) revert IndexToken.TransferShortfall();
    }

    function mid(IndexToken.Component memory c) internal pure returns (uint256) {
        return (uint256(c.priceLow) + uint256(c.priceHigh)) / 2;
    }

    function value(IndexToken.Component memory c, uint256 rawAmount) internal pure returns (uint256) {
        return Math.mulDiv(rawAmount, mid(c), 10 ** c.decimals);
    }

    /// @dev rate = buy raw units per 1e18 sell raw units, given a sell price and a buy price.
    function rate(IndexToken.Component memory s, IndexToken.Component memory b, uint256 priceSell, uint256 priceBuy)
        internal
        pure
        returns (uint128)
    {
        uint256 r = Math.mulDiv(priceSell * WAD, 10 ** b.decimals, priceBuy * 10 ** s.decimals);
        if (r > type(uint128).max) revert IndexToken.RateUnrepresentable();
        return uint128(r);
    }
}

src/libraries/PlanLib.sol

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

import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IndexToken} from "../IndexToken.sol";

/// @title PlanLib
/// @notice IndexToken._planRebalance evaluated at caller-supplied prices instead of the stored band midpoints.
///         Kept identical in structure (greedy pairing, dust rules) so Autopilot's `plan` matches what the index
///         executes after `poke` sets the bands to those prices. Internal (inlined) library.
library PlanLib {
    uint256 internal constant BPS = 10_000;
    uint256 internal constant DUST_VALUE = 1e15; // mirrors IndexToken

    struct Plan {
        uint256 nav;
        uint256 maxDrift;
        uint256 count;
        IndexToken.RebalanceLeg[] legs;
    }

    /// @param cs The index's components (decimals and target weights are read from them)
    /// @param bal The index's raw balance of each component
    /// @param px The price of each component, numeraire (1e18) per whole token
    function planAt(IndexToken.Component[] memory cs, uint256[] memory bal, uint256[] memory px)
        internal
        pure
        returns (Plan memory p)
    {
        uint256 n = cs.length;
        int256[] memory diff = new int256[](n); // values first, then value minus target
        for (uint256 i; i < n; ++i) {
            uint256 v = Math.mulDiv(bal[i], px[i], 10 ** cs[i].decimals);
            diff[i] = int256(v);
            p.nav += v;
        }
        if (p.nav == 0) {
            p.legs = new IndexToken.RebalanceLeg[](0);
            return p;
        }
        for (uint256 i; i < n; ++i) {
            diff[i] -= int256(Math.mulDiv(p.nav, cs[i].targetWeightBps, BPS));
            uint256 d = diff[i] >= 0 ? uint256(diff[i]) : uint256(-diff[i]);
            uint256 driftBps = Math.mulDiv(d, BPS, p.nav);
            if (driftBps > p.maxDrift) p.maxDrift = driftBps;
        }
        p.legs = new IndexToken.RebalanceLeg[](n);
        _pair(cs, px, bal, diff, p);
        IndexToken.RebalanceLeg[] memory legs = p.legs;
        uint256 count = p.count;
        assembly {
            mstore(legs, count)
        }
    }

    /// @dev The greedy over-weight to under-weight pairing, writing legs into `p`.
    function _pair(
        IndexToken.Component[] memory cs,
        uint256[] memory px,
        uint256[] memory bal,
        int256[] memory diff,
        Plan memory p
    ) internal pure {
        uint256 n = cs.length;
        for (uint256 s; s < n; ++s) {
            if (diff[s] <= 0) continue;
            // for a zero-weight component the target is zero, so diff equals value
            if (cs[s].targetWeightBps == 0 && uint256(diff[s]) <= DUST_VALUE) continue;
            uint256 remaining = bal[s];
            for (uint256 b; b < n && diff[s] > 0; ++b) {
                if (diff[b] >= 0) continue;
                uint256 v = uint256(diff[s]);
                uint256 need = uint256(-diff[b]);
                if (need < v) v = need;
                uint256 sellRaw = Math.mulDiv(v, 10 ** cs[s].decimals, px[s]);
                diff[s] -= int256(v);
                diff[b] += int256(v);
                if (sellRaw > remaining) sellRaw = remaining;
                if (sellRaw == 0) {
                    if (cs[s].targetWeightBps != 0 || remaining == 0) continue;
                    sellRaw = remaining;
                }
                remaining -= sellRaw;
                p.legs[p.count] = IndexToken.RebalanceLeg(cs[s].token, cs[b].token, sellRaw);
                ++p.count;
            }
            if (
                cs[s].targetWeightBps == 0 && remaining > 0 && p.count > 0
                    && p.legs[p.count - 1].sellToken == cs[s].token
            ) {
                p.legs[p.count - 1].sellAmount += remaining;
            }
        }
    }
}

src/libraries/TwapLib.sol

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

import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IUniswapV3Pool} from "../interfaces/IUniswapV3.sol";

/// @notice The classic (Solidly-style) pool surface read for pricing: Aerodrome classic on Base, Velodrome V2.
interface IClassicPool {
    function token0() external view returns (address);
    function stable() external view returns (bool);
    function observationLength() external view returns (uint256);
    function observations(uint256 i)
        external
        view
        returns (uint256 timestamp, uint256 reserve0Cumulative, uint256 reserve1Cumulative);
    function currentCumulativePrices()
        external
        view
        returns (uint256 reserve0Cumulative, uint256 reserve1Cumulative, uint256 blockTimestamp);
    function getReserves() external view returns (uint256 reserve0, uint256 reserve1, uint256 blockTimestampLast);
}

/// @title TwapLib
/// @notice Autopilot's pricing, as an external (linked) library to keep Autopilot under the bytecode limit. Two
///         pool kinds:
///         - KIND_CONCENTRATED (0): any pool with Uniswap V3's `observe`, `token0`, `token1`, and a `slot0` whose
///           first two words are sqrtPriceX96 and tick (Uniswap V3, PancakeSwap V3, SushiSwap V3, Aerodrome
///           Slipstream, whose `slot0` returns six words; only the leading words are read).
///         - KIND_CLASSIC (1): volatile Solidly-style pools (Aerodrome classic, Velodrome V2), which record
///           cumulative reserves roughly every 30 minutes. The average is the ratio of time-averaged reserves
///           since the newest stored observation at least `window` seconds old. Stable-curve pools are refused:
///           their price is not the reserve ratio.
library TwapLib {
    int24 internal constant MIN_TICK = -887272;
    int24 internal constant MAX_TICK = 887272;
    uint256 internal constant WAD = 1e18;
    uint8 internal constant KIND_CONCENTRATED = 0;
    uint8 internal constant KIND_CLASSIC = 1;
    uint256 internal constant MAX_OBSERVATION_STEPS = 400; // about 8 days of 30-minute observations
    bytes4 internal constant SLOT0_SELECTOR = 0x3850c7bd; // slot0()
    bytes4 internal constant TOKEN0_SELECTOR = 0x0dfe1681; // token0()
    bytes4 internal constant TOKEN1_SELECTOR = 0xd21220a7; // token1()
    bytes4 internal constant FACTORY_SELECTOR = 0xc45a0155; // factory()
    bytes4 internal constant FEE_SELECTOR = 0xddca3f43; // fee()
    bytes4 internal constant TICK_SPACING_SELECTOR = 0xd0c93a7c; // tickSpacing()
    bytes4 internal constant GET_POOL_FEE = 0x1698ee82; // getPool(address,address,uint24): Uniswap, PancakeSwap, SushiSwap V3
    bytes4 internal constant GET_POOL_TICK_SPACING = 0x28af8d0b; // getPool(address,address,int24): Aerodrome Slipstream
    bytes4 internal constant GET_POOL_STABLE = 0x79bc57d5; // getPool(address,address,bool): Aerodrome classic
    bytes4 internal constant IS_POOL = 0x5b16ebb7; // isPool(address): Aerodrome classic

    error TickOutOfRange();
    error ZeroWindow();
    error BadPool(address token);
    error PriceUnavailable(address token);
    error PriceDiverged(address token);

    /// @dev Everything `priceAll` needs, copied from Autopilot's storage. `pools[i]` is address(0) for the
    ///      stablecoin (always 1) and for WETH (priced from `stablePool`). `kinds[i]` is the pool kind.
    struct PriceInput {
        address[] tokens;
        address[] pools;
        uint8[] kinds;
        uint8[] decimals;
        address weth;
        address stable;
        uint8 wethDecimals;
        uint8 stableDecimals;
        address stablePool;
        uint8 stablePoolKind;
        uint32 window;
        int24 maxDelta;
    }

    /// @notice Numeraire price (1e18 per whole token) of every token from the time-weighted average of its pool,
    ///         refusing any pool whose spot tick sits more than `maxDelta` ticks from its average.
    function priceAll(PriceInput memory p) external view returns (uint256[] memory px) {
        uint256 n = p.tokens.length;
        px = new uint256[](n);
        uint256 stablePerWeth; // raw stablecoin per whole WETH, computed once if needed
        for (uint256 i; i < n; ++i) {
            address token = p.tokens[i];
            uint256 price;
            if (token == p.stable) {
                price = WAD;
            } else if (token == p.weth) {
                if (stablePerWeth == 0) stablePerWeth = _stablePerWeth(p);
                price = Math.mulDiv(stablePerWeth, WAD, 10 ** p.stableDecimals);
            } else {
                address pool = p.pools[i];
                address other = counterpart(pool, token);
                uint256 quote =
                    quoteAverage(pool, p.kinds[i], p.window, p.maxDelta, token, other, uint128(10 ** p.decimals[i]));
                if (other == p.weth) {
                    if (stablePerWeth == 0) stablePerWeth = _stablePerWeth(p);
                    price = Math.mulDiv(
                        Math.mulDiv(quote, stablePerWeth, 10 ** p.wethDecimals), WAD, 10 ** p.stableDecimals
                    );
                } else if (other == p.stable) {
                    price = Math.mulDiv(quote, WAD, 10 ** p.stableDecimals);
                } else {
                    revert BadPool(token);
                }
            }
            if (price == 0) revert PriceUnavailable(token);
            px[i] = price;
        }
    }

    function _stablePerWeth(PriceInput memory p) internal view returns (uint256) {
        return quoteAverage(
            p.stablePool, p.stablePoolKind, p.window, p.maxDelta, p.weth, p.stable, uint128(10 ** p.wethDecimals)
        );
    }

    /// @notice How much `quoteToken` (raw) `baseAmount` of `baseToken` (raw) is worth at the pool's average over
    ///         `window`, refusing a pool whose spot price sits more than `maxDelta` (ticks, about one bps each)
    ///         from that average.
    function quoteAverage(
        address pool,
        uint8 kind,
        uint32 window,
        int24 maxDelta,
        address baseToken,
        address quoteToken,
        uint128 baseAmount
    ) public view returns (uint256) {
        if (kind == KIND_CONCENTRATED) {
            return quoteAtTick(checkedTick(pool, window, maxDelta, baseToken), baseAmount, baseToken, quoteToken);
        }
        if (kind == KIND_CLASSIC) return classicQuote(pool, window, maxDelta, baseToken, baseAmount);
        revert BadPool(baseToken);
    }

    /// @notice A route's pool checked for its kind: it must contain `token` (returning the other token), a classic
    ///         pool must be volatile, and the factory the pool names must confirm it (so a contract that merely
    ///         claims a whitelisted factory is refused). Returns that factory for the caller's whitelist check.
    ///         Concentrated pools are confirmed by fee tier (Uniswap, PancakeSwap, SushiSwap V3) or by tick
    ///         spacing (Aerodrome Slipstream); classic pools by `getPool(.., stable)` or `isPool`. Unknown kinds
    ///         are refused.
    function validate(address pool, uint8 kind, address token) external view returns (address other, address fac) {
        other = counterpart(pool, token);
        bool ok;
        (ok, fac) = _addressCall(pool, FACTORY_SELECTOR);
        if (!ok || fac == address(0)) revert BadPool(token);
        (, address t0) = _addressCall(pool, TOKEN0_SELECTOR);
        (, address t1) = _addressCall(pool, TOKEN1_SELECTOR);
        if (kind == KIND_CLASSIC) {
            (bool okS, bytes memory ret) = pool.staticcall(abi.encodeWithSelector(IClassicPool.stable.selector));
            if (!okS || ret.length < 32 || abi.decode(ret, (bool))) revert BadPool(token);
            if (
                !_confirms(fac, abi.encodeWithSelector(GET_POOL_STABLE, t0, t1, false), pool)
                    && !_flag(fac, abi.encodeWithSelector(IS_POOL, pool))
            ) revert BadPool(token);
        } else if (kind == KIND_CONCENTRATED) {
            (bool okFee, uint256 fee) = _wordCall(pool, FEE_SELECTOR);
            bool confirmed = okFee && fee <= type(uint24).max
                && _confirms(fac, abi.encodeWithSelector(GET_POOL_FEE, t0, t1, uint24(fee)), pool);
            if (!confirmed) {
                (bool okTs, uint256 raw) = _wordCall(pool, TICK_SPACING_SELECTOR);
                int256 ts = int256(raw);
                confirmed = okTs && ts > 0 && ts <= type(int24).max
                    && _confirms(fac, abi.encodeWithSelector(GET_POOL_TICK_SPACING, t0, t1, int24(ts)), pool);
            }
            if (!confirmed) revert BadPool(token);
        } else {
            revert BadPool(token);
        }
    }

    /// @notice The factory a pool names, or address(0) if it does not answer.
    function factoryOf(address pool) external view returns (address fac) {
        (, fac) = _addressCall(pool, FACTORY_SELECTOR);
    }

    function _confirms(address fac, bytes memory call, address pool) internal view returns (bool) {
        (bool ok, bytes memory ret) = fac.staticcall(call);
        return ok && ret.length >= 32 && abi.decode(ret, (address)) == pool;
    }

    function _flag(address fac, bytes memory call) internal view returns (bool) {
        (bool ok, bytes memory ret) = fac.staticcall(call);
        return ok && ret.length >= 32 && abi.decode(ret, (uint256)) == 1;
    }

    function _wordCall(address target, bytes4 selector) internal view returns (bool ok, uint256 out) {
        bytes memory ret;
        (ok, ret) = target.staticcall(abi.encodeWithSelector(selector));
        if (!ok || ret.length < 32) return (false, 0);
        out = abi.decode(ret, (uint256));
    }

    /// @notice Average quote from a volatile classic pool: the ratio of its time-averaged reserves between now
    ///         and the newest stored observation at least `window` seconds old. Reverts PriceUnavailable when the
    ///         stored history does not reach that far back (within MAX_OBSERVATION_STEPS observations) and
    ///         PriceDiverged when the current reserve ratio is more than `maxDelta` bps off the average.
    function classicQuote(address pool, uint32 window, int24 maxDelta, address token, uint256 baseAmount)
        public
        view
        returns (uint256 quote)
    {
        if (window == 0) revert ZeroWindow();
        IClassicPool cp = IClassicPool(pool);
        (uint256 c0, uint256 c1, uint256 nowTs) = cp.currentCumulativePrices();
        uint256 len = cp.observationLength();
        if (len == 0 || nowTs <= window) revert PriceUnavailable(token);
        uint256 target = nowTs - window;
        uint256 i = len - 1;
        uint256 steps;
        uint256 t;
        uint256 o0;
        uint256 o1;
        while (true) {
            (t, o0, o1) = cp.observations(i);
            if (t <= target) break;
            if (i == 0 || ++steps >= MAX_OBSERVATION_STEPS) revert PriceUnavailable(token);
            --i;
        }
        uint256 elapsed = nowTs - t;
        bool isToken0 = cp.token0() == token;
        uint256 rT = (isToken0 ? c0 - o0 : c1 - o1) / elapsed;
        uint256 rO = (isToken0 ? c1 - o1 : c0 - o0) / elapsed;
        if (rT == 0 || rO == 0) revert PriceUnavailable(token);
        quote = Math.mulDiv(baseAmount, rO, rT);

        (uint256 s0, uint256 s1,) = cp.getReserves();
        (uint256 sT, uint256 sO) = isToken0 ? (s0, s1) : (s1, s0);
        if (sT == 0) revert PriceUnavailable(token);
        uint256 spot = Math.mulDiv(baseAmount, sO, sT);
        uint256 d = spot > quote ? spot - quote : quote - spot;
        if (d * 10_000 > quote * uint256(uint24(maxDelta))) revert PriceDiverged(token);
    }

    /// @notice The other token of a two-token pool, or BadPool(token) if the pool does not contain `token` or
    ///         does not answer `token0`/`token1`.
    function counterpart(address pool, address token) public view returns (address other) {
        (bool ok0, address t0) = _addressCall(pool, TOKEN0_SELECTOR);
        (bool ok1, address t1) = _addressCall(pool, TOKEN1_SELECTOR);
        if (!ok0 || !ok1) revert BadPool(token);
        if (t0 == token) return t1;
        if (t1 == token) return t0;
        revert BadPool(token);
    }

    /// @notice Mean tick over `window`, reverting PriceDiverged(token) when the pool's current tick has drifted
    ///         more than `maxDelta` ticks (about one bps each) from it: the signature of an in-progress
    ///         manipulation or a price still moving.
    function checkedTick(address pool, uint32 window, int24 maxDelta, address token) public view returns (int24 mean) {
        int24 spot;
        (mean, spot) = consultWithSpot(pool, window);
        int24 d = spot > mean ? spot - mean : mean - spot;
        if (d > maxDelta) revert PriceDiverged(token);
    }

    /// @notice Arithmetic mean tick of `pool` over the last `window` seconds.
    /// @dev Reverts with the pool's own error ("OLD") when its observation history does not reach back far
    ///      enough. Pools extrapolate from their latest observation, so a quiet pool is fine as long as its
    ///      last trade is at least `window` seconds old or an older observation exists.
    function consult(address pool, uint32 window) public view returns (int24 meanTick) {
        if (window == 0) revert ZeroWindow();
        uint32[] memory secondsAgos = new uint32[](2);
        secondsAgos[0] = window;
        secondsAgos[1] = 0;
        (int56[] memory tickCumulatives,) = IUniswapV3Pool(pool).observe(secondsAgos);
        int56 delta = tickCumulatives[1] - tickCumulatives[0];
        int56 w = int56(uint56(window));
        meanTick = int24(delta / w);
        // round toward negative infinity, as the pool does
        if (delta < 0 && (delta % w != 0)) meanTick--;
    }

    /// @notice Mean tick over `window` plus the pool's current tick.
    function consultWithSpot(address pool, uint32 window) public view returns (int24 meanTick, int24 spotTick) {
        meanTick = consult(pool, window);
        spotTick = spotTickOf(pool);
    }

    /// @notice The pool's current tick, read as the second word of `slot0()` so both the seven-word (Uniswap V3)
    ///         and six-word (Aerodrome Slipstream) layouts decode.
    function spotTickOf(address pool) public view returns (int24 spotTick) {
        (bool ok, bytes memory ret) = pool.staticcall(abi.encodeWithSelector(SLOT0_SELECTOR));
        if (!ok || ret.length < 64) revert BadPool(pool);
        assembly {
            spotTick := mload(add(ret, 64))
        }
    }

    /// @notice The pool's observation cardinality, the fourth word of `slot0()`; both layouts agree.
    function cardinalityOf(address pool) public view returns (uint16 cardinality) {
        (bool ok, bytes memory ret) = pool.staticcall(abi.encodeWithSelector(SLOT0_SELECTOR));
        if (!ok || ret.length < 128) revert BadPool(pool);
        assembly {
            cardinality := mload(add(ret, 128))
        }
    }

    /// @notice How much `quoteToken` (raw) `baseAmount` of `baseToken` (raw) is worth at `tick`.
    function quoteAtTick(int24 tick, uint128 baseAmount, address baseToken, address quoteToken)
        public
        pure
        returns (uint256 quoteAmount)
    {
        uint160 sqrtRatioX96 = getSqrtRatioAtTick(tick);
        if (sqrtRatioX96 <= type(uint128).max) {
            uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96;
            quoteAmount = baseToken < quoteToken
                ? Math.mulDiv(ratioX192, baseAmount, 1 << 192)
                : Math.mulDiv(1 << 192, baseAmount, ratioX192);
        } else {
            uint256 ratioX128 = Math.mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64);
            quoteAmount = baseToken < quoteToken
                ? Math.mulDiv(ratioX128, baseAmount, 1 << 128)
                : Math.mulDiv(1 << 128, baseAmount, ratioX128);
        }
    }

    /// @notice sqrt(1.0001^tick) as a Q64.96, exactly as Uniswap V3 computes it.
    function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
        unchecked {
            uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
            if (absTick > uint256(int256(MAX_TICK))) revert TickOutOfRange();

            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;

            // Q128.128 to Q64.96, rounding up
            sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
        }
    }

    function _addressCall(address target, bytes4 selector) internal view returns (bool ok, address out) {
        bytes memory ret;
        (ok, ret) = target.staticcall(abi.encodeWithSelector(selector));
        if (!ok || ret.length < 32) return (false, address(0));
        out = abi.decode(ret, (address));
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 100,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "forge-std/=lib/forge-std/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.