Skip to content
Verified contractExactBUSL-1.1

CappedRateOrderBook

Address0xd08eeb32cb69674134045d0c8e8a7213190d9159
Balance

0 ETH

 

Transactions

391

 

Compiler

solc 0.8.34

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.34+commit.80d5c536
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
BUSL-1.1
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,401,458
Creation transaction
0xcb2337ec10…26141ec4aa

contracts/rateorderbook/CappedRateOrderBook.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.34;

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

import { ICappedRateOrderBook } from "./interfaces/ICappedRateOrderBook.sol";
import { ICumulativeIndexSource } from "./interfaces/ICumulativeIndexSource.sol";
import { CappedRateOrderBookBase } from "./CappedRateOrderBookBase.sol";
import { CappedIndexMath as C } from "./lib/CappedIndexMath.sol";
import { RateOrderBookMath as M } from "./lib/RateOrderBookMath.sol";
import { SourceRead } from "./lib/SourceRead.sol";

/// @title CappedRateOrderBook
/// @notice Fixed-vs-floating swaps of up to `MAX_SERIES_LENGTH` on a cumulative index (an Aave or
///         Compound USDC borrow index) whose growth counts only within a cap and floor around the
///         trailing ~7-day rate, with carried headroom (see CappedRateOrderBookBase).
///
///         Index. Each observation's growth is measured against the source's index at opening,
///         `(I - I_prev) / indexOpen`, so the steps sum exactly and the capped index is `RAY * I /
///         indexOpen` until the cap or floor binds, however often anyone observes. The cap and floor
///         therefore apply to growth on the opening index: late in a series they bind slightly before
///         the rate itself reaches them, by the series' own growth so far (about 0.8% of the rate
///         after 60 days at 5%).
///
///         Legs. Ratio legs on the capped index, as RateOrderBook's on its source: a fill at capped
///         index E_h pays a floating leg of `E / E_h - 1`, exactly the source's compounded growth from
///         that observation while nothing clips.
///
///         Observations. The first trade or `pokeSeries` in each clock hour before expiry reads the
///         source and steps the capped index to that moment; missed hours merge into one longer
///         interval, whose allowance is the cap and floor rates over its whole length: the bank limit
///         applies only to what an interval carries out, so the cap is as tight as designed only
///         while someone observes every hour. Every fill in an hour enters at that hour's
///         observation, its fixed leg and fee running from it to expiry, so a fill later in the hour
///         gains at most an hour of visible accrual. A trade waits for a source that cannot answer in a new hour. A withdrawal never
///         reads the source: it is margined on the stored range, which still bounds settlement, so
///         what `requiredCollateral` reports free is exactly what can leave (`multicall` a
///         `pokeSeries` first for the latest runoff).
///
///         Band centre. The realized rate since the checkpoint aged 5–8 days that is closest to 7 days
///         old (one per `CHECKPOINT_SPACING`, from `poke` and series openings).
///
///         Settlement. `finalize`, at or after expiry, reads the source, interpolates the index at
///         expiry between the latest observation and that reading, and takes the last step of the
///         capped index to expiry, all in the one call. If the source cannot answer, then once
///         `ORACLE_FAILURE_GRACE` has passed the last observation is carried to expiry at the band
///         centre, which lies inside the cap and floor.
contract CappedRateOrderBook is CappedRateOrderBookBase, ICappedRateOrderBook {
    using SafeCast for uint256;

    struct IndexCheckpoint {
        uint64 timestamp;
        uint192 index;
    }

    uint64 public constant MAX_BAND_HALF_WIDTH = 1e17; // 10%
    uint256 public constant CHECKPOINT_SPACING = 3 hours;
    uint256 public constant CHECKPOINT_RING = 64;
    uint256 public constant MIN_BAND_CHECKPOINT_AGE = 5 days;
    uint256 public constant TARGET_BAND_CHECKPOINT_AGE = 7 days;
    uint256 public constant MAX_BAND_CHECKPOINT_AGE = 8 days;

    ICumulativeIndexSource public immutable indexSource;

    uint256 public checkpointCount;
    IndexCheckpoint[64] private _checkpoints;

    /// @param seedTimestamp With `seedIndex`, a past checkpoint read from an archive node, so the first
    ///        series can open at once instead of 5 days after the first `poke`; 0 for none. See
    ///        `_seedCheckpoint`.
    constructor(
        Config memory cfg,
        uint32 bankDuration_,
        uint64 seedTimestamp,
        uint256 seedIndex
    ) CappedRateOrderBookBase(cfg, bankDuration_) {
        indexSource = ICumulativeIndexSource(cfg.indexSource);
        if (seedTimestamp != 0) _seedCheckpoint(seedTimestamp, seedIndex);
    }

    // ───────────────────────────── series lifecycle ─────────────────────────────

    /// @notice Owner only, for a book that runs one series to a fixed maturity: nothing else on its
    ///         expiry grid should open. A book that rolls series one after another needs this open to
    ///         anyone, as on the other books, so its keeper can open them: drop `onlyOwner` for those.
    function openSeries(uint64 expiry) external onlyOwner whenNotPaused nonReentrant {
        SeriesState storage s = _openSeries(expiry);

        uint256 index = _readIndex();
        uint256 centre = _bandCentre(index);
        _writeCheckpoint(index);

        uint256 w = bandHalfWidth;
        int256 floorRate = centre > w ? (centre - w).toInt256() : int256(0);
        _openCapped(s, expiry, centre.toInt256(), floorRate, uint64(block.timestamp), index, M.RAY);

        emit SeriesOpened(
            expiry,
            index,
            s.indexLo,
            s.indexHi,
            centre,
            s.takerFeeRate,
            s.makerRebateRate,
            s.maxOpenInterest
        );
    }

    /// @notice Records an index checkpoint for band centres (at most one per `CHECKPOINT_SPACING`).
    function poke() external returns (bool written) {
        written = _writeCheckpoint(_readIndex());
    }

    /// @notice Steps the capped index if this clock hour before expiry has no observation yet. After
    ///         expiry it does nothing: `finalize` reads the source itself.
    function pokeSeries(uint64 expiry) external {
        _observe(_activeSeries(expiry), expiry);
    }

    /// @notice Settles a series at or after its expiry. Anyone may call.
    function finalize(uint64 expiry) external nonReentrant {
        SeriesState storage s = _activeSeries(expiry);
        if (block.timestamp < expiry) revert NotExpired();
        CappedIndex memory c = _capped[expiry];

        (uint256 index, bool ok) = _tryReadIndex();
        int256 g;
        bool fallbackUsed;
        if (ok && index >= c.lastIndex) {
            index = M.interpolate(c.lastTimestamp, c.lastIndex, block.timestamp, index, expiry);
            g = _growth(index - c.lastIndex, s.indexOpen);
        } else {
            if (block.timestamp < expiry + ORACLE_FAILURE_GRACE) revert NoSettlementObservation();
            // No reading: the gap grows at the centre, inside [floor, cap], from the last one.
            (index, g) = (c.lastIndex, C.capTerm(s.bandCentre, expiry - c.lastTimestamp));
            fallbackUsed = true;
        }
        (uint256 lo, uint256 hi) = _step(expiry, c, g, expiry, index);
        _commit(s, expiry, c, lo, hi);
        _settle(s, expiry, c.e, fallbackUsed);
    }

    // ───────────────────────────── views ─────────────────────────────

    function latestCheckpoint() external view returns (uint64 timestamp, uint256 index) {
        uint256 n = checkpointCount;
        if (n == 0) return (0, 0);
        IndexCheckpoint memory cp = _checkpoints[(n - 1) % CHECKPOINT_RING];
        return (cp.timestamp, cp.index);
    }

    // ───────────────────────────── hooks ─────────────────────────────

    function _tradeTerms(
        SeriesState storage s,
        uint64 expiry
    ) internal override returns (uint256 index, uint256 lo, uint256 tau) {
        CappedIndex memory c = _observe(s, expiry);
        return (c.e, s.indexLo, expiry - c.lastTimestamp);
    }

    /// @dev From the latest observation: a trade in a new hour would take a fresh one first.
    function _previewTerms(
        SeriesState storage s,
        uint64 expiry
    ) internal view override returns (uint256 index, uint256 lo, uint256 tau) {
        CappedIndex storage c = _capped[expiry];
        uint256 t = c.lastTimestamp;
        return (c.e, s.indexLo, expiry > t ? expiry - t : 0);
    }

    function _floor(SeriesState storage s, uint64) internal view override returns (uint256) {
        return s.indexLo;
    }

    function _floorView(SeriesState storage s, uint64) internal view override returns (uint256) {
        return s.indexLo;
    }

    function _legs(
        TradeContext memory ctx,
        uint16 tick,
        uint256 notional
    ) internal view override returns (uint256 fixedLeg, uint256 units) {
        return M.legs(notional, uint256(tick) * tickSize, ctx.tau, ctx.index);
    }

    function _notionalOf(uint256 units, uint256 index) internal pure override returns (uint256) {
        return Math.mulDiv(units, index, M.UNIT_SCALE);
    }

    function _maxBandHalfWidth() internal pure override returns (uint256) {
        return MAX_BAND_HALF_WIDTH;
    }

    // ───────────────────────────── index internals ─────────────────────────────

    /// @dev Steps the capped index to now if this clock hour before expiry has no observation yet.
    function _observe(SeriesState storage s, uint64 expiry) internal returns (CappedIndex memory c) {
        c = _capped[expiry];
        if (block.timestamp >= expiry || block.timestamp / 1 hours == c.lastTimestamp / 1 hours) return c;
        uint256 index = _readIndex();
        if (index < c.lastIndex) revert IndexRollback();
        int256 g = _growth(index - c.lastIndex, s.indexOpen);
        (uint256 lo, uint256 hi) = _step(expiry, c, g, uint64(block.timestamp), index);
        _commit(s, expiry, c, lo, hi);
    }

    /// @dev The source's increase `diff` as a fraction of its opening index `base`, RAY. Growth past
    ///      int256 saturates rather than reverting: anything above an interval's cap allowance counts
    ///      as the allowance, so it settles exactly as the true growth would. An absurd reading before
    ///      expiry still becomes `lastIndex`, so later normal readings revert `IndexRollback`: trading
    ///      stops, and the series settles through the fallback after the grace.
    function _growth(uint256 diff, uint256 base) internal pure returns (int256) {
        if (diff / base > uint256(type(int256).max) / M.RAY) return type(int256).max;
        return int256(Math.min(Math.mulDiv(diff, M.RAY, base), uint256(type(int256).max)));
    }

    function _tryReadIndex() internal view returns (uint256 index, bool ok) {
        uint256 valid;
        (ok, index, valid) = SourceRead.words(
            address(indexSource),
            abi.encodeCall(ICumulativeIndexSource.getCumulativeIndex, ()),
            64
        );
        ok = ok && valid == 1 && index != 0;
    }

    function _readIndex() internal view returns (uint256 index) {
        bool ok;
        (index, ok) = _tryReadIndex();
        if (!ok) revert IndexUnavailable();
    }

    /// @dev A checkpoint above the source's later readings is never replaced: every later write
    ///      reverts `IndexRollback`, so no further series can open and the book must be redeployed.
    ///      Open series are unaffected.
    function _writeCheckpoint(uint256 index) internal returns (bool) {
        uint256 n = checkpointCount;
        if (n != 0) {
            IndexCheckpoint memory last = _checkpoints[(n - 1) % CHECKPOINT_RING];
            if (block.timestamp < last.timestamp + CHECKPOINT_SPACING) return false;
            if (index < last.index) revert IndexRollback();
        }
        _storeCheckpoint(n, uint64(block.timestamp), index);
        return true;
    }

    function _storeCheckpoint(uint256 n, uint64 timestamp, uint256 index) private {
        _checkpoints[n % CHECKPOINT_RING] = IndexCheckpoint(timestamp, index.toUint192());
        checkpointCount = n + 1;
        emit Checkpoint(timestamp, index);
    }

    /// @dev Records the deployer's past checkpoint, then the live index. The deployer supplies it, so it is
    ///      held to what a real checkpoint could be: old enough to centre a band (5–8 days), never above the
    ///      live index, and a realized rate since then within the book's tick range. Anyone can check it
    ///      against the index source at that time.
    function _seedCheckpoint(uint64 timestamp, uint256 index) private {
        if (
            index == 0 ||
            timestamp + MIN_BAND_CHECKPOINT_AGE > block.timestamp ||
            timestamp + MAX_BAND_CHECKPOINT_AGE < block.timestamp
        ) revert InvalidSeed();
        uint256 live = _readIndex();
        uint256 age = block.timestamp - timestamp;
        if (index > live || M.annualRate(index, live, age) > uint256(maxTick) * tickSize) revert InvalidSeed();
        _storeCheckpoint(0, timestamp, index);
        _storeCheckpoint(1, uint64(block.timestamp), live);
    }

    /// @dev Realized rate since the checkpoint aged 5–8 days that is closest to 7 days old.
    function _bandCentre(uint256 index) internal view returns (uint256) {
        uint256 n = checkpointCount;
        uint256 count = n < CHECKPOINT_RING ? n : CHECKPOINT_RING;
        bool found;
        uint256 bestDiff;
        IndexCheckpoint memory best;
        for (uint256 k = 1; k <= count; ++k) {
            IndexCheckpoint memory cp = _checkpoints[(n - k) % CHECKPOINT_RING];
            uint256 age = block.timestamp - cp.timestamp;
            if (age > MAX_BAND_CHECKPOINT_AGE) break;
            if (age < MIN_BAND_CHECKPOINT_AGE) continue;
            uint256 diff = age > TARGET_BAND_CHECKPOINT_AGE
                ? age - TARGET_BAND_CHECKPOINT_AGE
                : TARGET_BAND_CHECKPOINT_AGE - age;
            if (!found || diff < bestDiff) {
                found = true;
                bestDiff = diff;
                best = cp;
            }
        }
        if (!found) revert NoBandCheckpoint();
        if (index < best.index) revert IndexRollback();
        return M.annualRate(best.index, index, block.timestamp - best.timestamp);
    }
}

@openzeppelin/contracts/access/Ownable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

@openzeppelin/contracts/access/Ownable2Step.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable2Step.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module which provides access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is specified at deployment time in the constructor for `Ownable`. This
 * can later be changed with {transferOwnership} and {acceptOwnership}.
 *
 * This module is used through inheritance. It will make available all functions
 * from parent (Ownable).
 */
abstract contract Ownable2Step is Ownable {
    address private _pendingOwner;

    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Returns the address of the pending owner.
     */
    function pendingOwner() public view virtual returns (address) {
        return _pendingOwner;
    }

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual override onlyOwner {
        _pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner(), newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual override {
        delete _pendingOwner;
        super._transferOwnership(newOwner);
    }

    /**
     * @dev The new owner accepts the ownership transfer.
     */
    function acceptOwnership() public virtual {
        address sender = _msgSender();
        if (pendingOwner() != sender) {
            revert OwnableUnauthorizedAccount(sender);
        }
        _transferOwnership(sender);
    }
}

@openzeppelin/contracts/token/ERC20/IERC20.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
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);
}

@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * ==== Security Considerations
 *
 * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
 * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
 * considered as an intention to spend the allowance in any specific way. The second is that because permits have
 * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
 * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
 * generally recommended is:
 *
 * ```solidity
 * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
 *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
 *     doThing(..., value);
 * }
 *
 * function doThing(..., uint256 value) public {
 *     token.safeTransferFrom(msg.sender, address(this), value);
 *     ...
 * }
 * ```
 *
 * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
 * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
 * {SafeERC20-safeTransferFrom}).
 *
 * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
 * contracts should have entry points that don't rely on permit.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     *
     * CAUTION: See Security Considerations above.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol

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

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 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 {
    using Address for address;

    /**
     * @dev An operation with an ERC20 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 {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @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 {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    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.
     */
    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.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), 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 data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data);
        if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), 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 data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
    }
}

@openzeppelin/contracts/utils/Address.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error AddressInsufficientBalance(address account);

    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedInnerCall();

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert AddressInsufficientBalance(address(this));
        }

        (bool success, ) = recipient.call{value: amount}("");
        if (!success) {
            revert FailedInnerCall();
        }
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {FailedInnerCall} error.
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert AddressInsufficientBalance(address(this));
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
     * unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {FailedInnerCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
     */
    function _revert(bytes memory returndata) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert FailedInnerCall();
        }
    }
}

@openzeppelin/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;
    }
}

@openzeppelin/contracts/utils/Multicall.sol

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

pragma solidity ^0.8.20;

import {Address} from "./Address.sol";
import {Context} from "./Context.sol";

/**
 * @dev Provides a function to batch together multiple calls in a single external call.
 *
 * Consider any assumption about calldata validation performed by the sender may be violated if it's not especially
 * careful about sending transactions invoking {multicall}. For example, a relay address that filters function
 * selectors won't filter calls nested within a {multicall} operation.
 *
 * NOTE: Since 5.0.1 and 4.9.4, this contract identifies non-canonical contexts (i.e. `msg.sender` is not {_msgSender}).
 * If a non-canonical context is identified, the following self `delegatecall` appends the last bytes of `msg.data`
 * to the subcall. This makes it safe to use with {ERC2771Context}. Contexts that don't affect the resolution of
 * {_msgSender} are not propagated to subcalls.
 */
abstract contract Multicall is Context {
    /**
     * @dev Receives and executes a batch of function calls on this contract.
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function multicall(bytes[] calldata data) external virtual returns (bytes[] memory results) {
        bytes memory context = msg.sender == _msgSender()
            ? new bytes(0)
            : msg.data[msg.data.length - _contextSuffixLength():];

        results = new bytes[](data.length);
        for (uint256 i = 0; i < data.length; i++) {
            results[i] = Address.functionDelegateCall(address(this), bytes.concat(data[i], context));
        }
        return results;
    }
}

@openzeppelin/contracts/utils/Pausable.sol

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

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    bool private _paused;

    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    /**
     * @dev The operation failed because the contract is paused.
     */
    error EnforcedPause();

    /**
     * @dev The operation failed because the contract is not paused.
     */
    error ExpectedPause();

    /**
     * @dev Initializes the contract in unpaused state.
     */
    constructor() {
        _paused = false;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        if (paused()) {
            revert EnforcedPause();
        }
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        if (!paused()) {
            revert ExpectedPause();
        }
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}

@openzeppelin/contracts/utils/ReentrancyGuard.sol

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

pragma solidity ^0.8.20;

/**
 * @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 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].
 */
abstract contract ReentrancyGuard {
    // 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;

    uint256 private _status;

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

    constructor() {
        _status = 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();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        _status = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = 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 _status == ENTERED;
    }
}

@openzeppelin/contracts/utils/math/Math.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    /**
     * @dev Muldiv operation overflow.
     */
    error MathOverflowedMulDiv();

    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with an overflow flag.
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a division by zero flag.
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

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

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return 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) {
        // (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.
            return a / b;
        }

        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     * @dev 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 {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0 = x * y; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 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 prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            if (denominator <= prod1) {
                revert MathOverflowedMulDiv();
            }

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

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, 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 {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

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

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            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^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // 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^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @notice 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) {
        uint256 result = mulDiv(x, y, denominator);
        if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice 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 + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
        }
    }

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

    /**
     * @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 + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @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 + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
        }
    }

    /**
     * @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 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @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 + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
        }
    }

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

@openzeppelin/contracts/utils/math/SafeCast.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.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 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 an uint of `bits` size.
     */
    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);

    /**
     * @dev An int value doesn't fit in an 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 An 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);
    }
}

@openzeppelin/contracts/utils/math/SignedMath.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMath {
    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return a > b ? a : b;
    }

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

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // must be unchecked in order to support `n = type(int256).min`
            return uint256(n >= 0 ? n : -n);
        }
    }
}

contracts/rateorderbook/CappedRateOrderBookBase.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.34;

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

import { ICappedOrderBook } from "./interfaces/ICappedOrderBook.sol";
import { RateOrderBookCore } from "./RateOrderBookCore.sol";
import { CappedIndexMath as C } from "./lib/CappedIndexMath.sol";

/// @title CappedRateOrderBookBase
/// @notice A rate book whose payouts follow a capped index `E` instead of the source's own index.
///         At opening a series fixes `capRate = centre + bandHalfWidth` and a floor rate below the
///         centre; each observation then counts the source's growth since the last one only within
///         those rates' allowance plus what earlier observations left unused (see CappedIndexMath).
///
///         Range. Every observation writes the range the final `E` can still reach into the series'
///         [indexLo, indexHi]. It only narrows, so the core's margin, its re-check of makers at fill
///         and its clamp at settlement all work unchanged, a read of either end taken before a later
///         observation stays conservative, and a position's requirement never rises without trading.
///         Margin runs off as the series ages, to about `bandHalfWidth` times the time left plus a
///         bank.
abstract contract CappedRateOrderBookBase is RateOrderBookCore, ICappedOrderBook {
    using SafeCast for uint256;
    using SafeCast for int256;

    uint32 public bankDuration;

    mapping(uint64 expiry => CappedIndex) internal _capped;

    constructor(Config memory cfg, uint32 bankDuration_) RateOrderBookCore(cfg) {
        _checkBankDuration(bankDuration_);
        bankDuration = bankDuration_;
        emit BankDurationSet(bankDuration_);
    }

    // ───────────────────────────── admin ─────────────────────────────

    /// @notice Sets the bank limit later series snapshot at opening; zero disables carrying.
    function setBankDuration(uint32 bankDuration_) external onlyOwner {
        _checkBankDuration(bankDuration_);
        bankDuration = bankDuration_;
        emit BankDurationSet(bankDuration_);
    }

    // ───────────────────────────── views ─────────────────────────────

    function getSeries(uint64 expiry) external view returns (Series memory) {
        SeriesState storage s = _series[expiry];
        return
            Series({
                openedAt: s.openedAt,
                finalized: s.finalized,
                fallbackSettled: s.fallbackSettled,
                takerFeeRate: s.takerFeeRate,
                makerRebateRate: s.makerRebateRate,
                maxOpenInterest: s.maxOpenInterest,
                bandCentre: s.bandCentre,
                indexOpen: s.indexOpen,
                indexLo: s.indexLo,
                indexHi: s.indexHi,
                settlementIndex: s.settlementIndex,
                indexUnitsPos: s.indexUnitsPos
            });
    }

    function getCappedIndex(uint64 expiry) external view returns (CappedIndex memory) {
        return _capped[expiry];
    }

    /// @notice Open interest in collateral-token units of notional, at the latest observation.
    function openInterest(uint64 expiry) external view returns (uint256) {
        return _notionalOf(_series[expiry].indexUnitsPos, _capped[expiry].e);
    }

    // ───────────────────────────── capped index ─────────────────────────────

    /// @dev Fixes the series' rates and bank limit, and records the opening observation at `t`: the
    ///      source at `index`, which becomes `indexOpen`, and the capped index starting at `e0`.
    function _openCapped(
        SeriesState storage s,
        uint64 expiry,
        int256 centre,
        int256 floorRate,
        uint64 t,
        uint256 index,
        uint256 e0
    ) internal {
        uint256 w = bandHalfWidth;
        CappedIndex memory c = CappedIndex({
            lastTimestamp: t,
            capRate: centre + w.toInt256(),
            floorRate: floorRate,
            bankUp: 0,
            bankDown: 0,
            bankMax: C.bankLimit(w, bankDuration),
            lastIndex: index,
            e: e0
        });
        s.bandCentre = centre;
        s.indexOpen = index;
        (uint256 lo, uint256 hi) = _observed(expiry, c, 0);
        _commit(s, expiry, c, lo, hi);
    }

    /// @dev Steps `c` (in memory) over the interval ending at `t`, in which the source grew by `g`
    ///      to `index`, and returns the range from there. The caller commits it.
    function _step(
        uint64 expiry,
        CappedIndex memory c,
        int256 g,
        uint64 t,
        uint256 index
    ) internal returns (uint256 lo, uint256 hi) {
        (uint256 e, uint256 bankUp, uint256 bankDown, int256 clipped) = C.step(
            c.e,
            c.bankUp,
            c.bankDown,
            g,
            t - c.lastTimestamp,
            c.capRate,
            c.floorRate,
            c.bankMax
        );
        (c.e, c.bankUp, c.bankDown) = (e, bankUp, bankDown);
        (c.lastTimestamp, c.lastIndex) = (t, index);
        return _observed(expiry, c, clipped);
    }

    function _observed(uint64 expiry, CappedIndex memory c, int256 clipped) internal returns (uint256 lo, uint256 hi) {
        uint256 tau = expiry > c.lastTimestamp ? expiry - c.lastTimestamp : 0;
        (lo, hi) = C.range(c.e, c.bankUp, c.bankDown, tau, c.capRate, c.floorRate);
        emit CappedIndexObserved(expiry, c.lastTimestamp, c.lastIndex, c.e, c.bankUp, c.bankDown, lo, hi, clipped);
    }

    function _commit(SeriesState storage s, uint64 expiry, CappedIndex memory c, uint256 lo, uint256 hi) internal {
        _capped[expiry] = c;
        s.indexLo = lo;
        s.indexHi = hi;
    }

    function _checkBankDuration(uint32 bankDuration_) internal view {
        if (bankDuration_ > seriesLength) revert InvalidBankDuration();
    }
}

contracts/rateorderbook/RateOrderBookCore.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.34;

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { Ownable2Step } from "@openzeppelin/contracts/access/Ownable2Step.sol";
import { Pausable } from "@openzeppelin/contracts/utils/Pausable.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import { Multicall } from "@openzeppelin/contracts/utils/Multicall.sol";
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";

import { IRateOrderBookCore } from "./interfaces/IRateOrderBookCore.sol";
import { RateOrderBookMath as M } from "./lib/RateOrderBookMath.sol";
import { TickBitmap } from "./lib/TickBitmap.sol";

/// @title RateOrderBookCore
/// @notice The order book every rate book shares: series, collateral, orders, matching, fees, caps
///         and pause. A book built on it supplies its index through the hooks at the end of this
///         contract (the index and margin range a trade uses, how a fill becomes legs, the
///         withdrawal floor, how open interest is measured) and opens and settles its own series.
///
///         Series. Expiries fall every `seriesSpacing` seconds; a series opens `seriesLength` before
///         its expiry and trades until `cutoff` before it. Every fill in a series covers
///         [fill time, expiry], so positions in a series are fungible and net against each other.
///
///         Band. At opening the book fixes [indexLo, indexHi], and the settlement index is clamped
///         into it, which bounds every payout. A book may narrow the band as the series runs, never
///         widen it.
///
///         Margin. An account's payout is linear in the settlement index, so its worst case is at
///         one end of the reachable range [floor, indexHi], where the floor is the book's lowest
///         reachable settlement index. Collateral must cover the worst case after every trade and
///         withdrawal. Without trading the position's requirement never rises (the upper end never
///         rises and the floor never falls), so nothing is ever liquidated.
///         What resting orders add can rise: their losses are valued when placed, while a narrowing
///         range lowers a position's payoff at the end that moves (a rising floor for receive fixed,
///         a falling upper end for pay fixed). An account can then show nothing free, or fail a
///         further trade, until it cancels; its position stays covered.
///
///         Orders. A resting order records what its fill would lose at each end of the reachable
///         range, valued when it is placed, and an account sums these per end. Payouts are linear,
///         so collateral covering the position's payoff at each end less that end's sum covers any
///         combination of its orders filling. A bid only loses at the low end and an offer at the
///         high end, so a two-sided quote is margined for its larger side, and an order that would
///         reduce the position adds little or nothing. The values can drift below what a later fill
///         needs, so the maker is re-checked at fill time and an underfunded order is cancelled
///         rather than filled; a taker never reverts on it.
///
///         Caps. `maxOpenInterest` bounds a series' notional (the owner can raise it on a live
///         series); `maxTotalCollateral` bounds the collateral held across all series. Both only
///         stop new exposure or deposits: withdrawals and claims are never capped.
///
///         Batching. `multicall` runs several of this contract's calls in one transaction as the
///         caller (deposit + take, claimInto + place to roll into the next series, cancel + place),
///         each with its own checks; one failing call reverts the batch.
abstract contract RateOrderBookCore is IRateOrderBookCore, Ownable2Step, Pausable, ReentrancyGuard, Multicall {
    using SafeERC20 for IERC20;
    using SafeCast for uint256;

    struct Level {
        uint64 head;
        uint64 tail;
        uint128 total;
    }

    /// @dev What every book stores for a series. Index values are RAY. `indexUnitsPos` is the sum
    ///      of positive account index units (open interest).
    struct SeriesState {
        uint64 openedAt;
        bool finalized;
        bool fallbackSettled;
        uint64 takerFeeRate;
        uint64 makerRebateRate;
        uint128 maxOpenInterest;
        int256 bandCentre; // WAD per year
        uint256 indexOpen;
        uint256 indexLo;
        uint256 indexHi;
        uint256 settlementIndex; // clamped to [indexLo, indexHi]
        uint256 indexUnitsPos;
    }

    /// @dev Per-trade values shared by every fill in one `place`/`take`.
    struct TradeContext {
        uint64 expiry;
        uint256 index;
        uint256 lo; // lowest reachable settlement index
        uint256 hi; // indexHi
        uint256 tau; // seconds the fixed leg and fees accrue for
        uint64 takerFeeRate;
        uint64 makerRebateRate;
    }

    /// @notice Fills per `place`/`take` at most (the caller's `maxFills` is bounded by it).
    uint256 public constant MAX_FILLS = 32;
    /// @notice Resting orders one walk may visit, fills and cancellations of expired, underfunded or
    ///         self-trade orders together: dead orders cost a taker gas, never its fill budget.
    uint256 public constant MAX_VISITS = 128;
    /// @notice Shortest life an order with a `goodTill` may have. An order that expires sooner
    ///         would sit dead at the front of the book, costing takers visits at no risk to its
    ///         owner; this keeps it live and fillable for a while first.
    uint256 public constant MIN_ORDER_LIFETIME = 15 minutes;
    uint64 public constant MAX_TAKER_FEE_RATE = 25e14; // 25 bp per year
    uint64 public constant MIN_BAND_HALF_WIDTH = 1e15; // 10 bp
    uint256 public constant MAX_SERIES_LENGTH = 60 days;
    uint256 public constant ORACLE_FAILURE_GRACE = 7 days;

    IERC20 public immutable collateralToken;
    uint32 public immutable seriesLength;
    uint32 public immutable seriesSpacing;
    uint32 public immutable expiryOffset;
    uint32 public immutable cutoff;
    uint64 public immutable tickSize;
    uint16 public immutable maxTick;
    uint128 public immutable minOrderNotional;

    address public treasury;
    uint64 public takerFeeRate;
    uint64 public makerRebateRate;
    uint64 public bandHalfWidth;
    uint128 public maxOpenInterest;
    uint128 public maxTotalCollateral;
    uint256 public treasuryAccrued;
    /// @notice Tokens held for accounts and fees across all series (deposits less withdrawals,
    ///         claims paid and fees collected): what the deposit cap bounds.
    uint256 public totalCollateral;

    uint64 public nextOrderId = 1;

    mapping(uint64 expiry => SeriesState) internal _series;
    mapping(uint64 expiry => mapping(address account => Account)) private _accounts;
    /// @dev Word key: side << 8 | (tick >> 8).
    mapping(uint64 expiry => mapping(uint256 key => uint256 word)) private _bitmap;
    /// @dev Level key: side << 16 | tick.
    mapping(uint64 expiry => mapping(uint256 key => Level)) private _levels;
    mapping(uint64 orderId => Order) private _orders;

    constructor(Config memory cfg) Ownable(cfg.owner) {
        if (cfg.indexSource == address(0) || cfg.collateralToken == address(0) || cfg.treasury == address(0)) {
            revert ZeroAddress();
        }
        if (cfg.seriesLength == 0 || cfg.seriesLength > MAX_SERIES_LENGTH) revert InvalidConfig();
        if (cfg.seriesSpacing == 0 || cfg.seriesSpacing > MAX_SERIES_LENGTH) revert InvalidConfig();
        if (cfg.expiryOffset >= cfg.seriesSpacing || cfg.cutoff >= cfg.seriesLength) revert InvalidConfig();
        if (cfg.tickSize == 0 || cfg.maxTick == 0 || uint256(cfg.maxTick) * cfg.tickSize > M.WAD) {
            revert InvalidConfig();
        }
        if (cfg.minOrderNotional == 0 || cfg.maxOpenInterest == 0 || cfg.maxTotalCollateral == 0) {
            revert InvalidConfig();
        }
        _checkFees(cfg.takerFeeRate, cfg.makerRebateRate);
        _checkBand(cfg.bandHalfWidth);

        collateralToken = IERC20(cfg.collateralToken);
        seriesLength = cfg.seriesLength;
        seriesSpacing = cfg.seriesSpacing;
        expiryOffset = cfg.expiryOffset;
        cutoff = cfg.cutoff;
        tickSize = cfg.tickSize;
        maxTick = cfg.maxTick;
        minOrderNotional = cfg.minOrderNotional;

        treasury = cfg.treasury;
        takerFeeRate = cfg.takerFeeRate;
        makerRebateRate = cfg.makerRebateRate;
        bandHalfWidth = cfg.bandHalfWidth;
        maxOpenInterest = cfg.maxOpenInterest;
        maxTotalCollateral = cfg.maxTotalCollateral;
    }

    // ───────────────────────────── series lifecycle ─────────────────────────────

    function claim(uint64 expiry, address to) external nonReentrant returns (uint256 amount) {
        _checkRecipient(to);
        amount = _settleAccount(expiry);

        // Saturating: the counter must never stand between an account and its payout.
        uint256 total = totalCollateral;
        totalCollateral = total > amount ? total - amount : 0;
        if (amount != 0) collateralToken.safeTransfer(to, amount);
        emit Claimed(expiry, msg.sender, to, amount);
    }

    /// @notice Claims a settled series straight into the caller's collateral in a live one, with no
    ///         token transfer. The tokens never leave the book, so the deposit cap is not re-applied.
    ///         Emits `Claimed` (to this contract) and `Deposited`, so each series' flows still add up.
    function claimInto(uint64 expiry, uint64 toExpiry) external whenNotPaused nonReentrant returns (uint256 amount) {
        _activeSeries(toExpiry);
        amount = _settleAccount(expiry);
        _accounts[toExpiry][msg.sender].collateral += amount;
        emit Claimed(expiry, msg.sender, address(this), amount);
        emit Deposited(toExpiry, msg.sender, amount);
    }

    // ───────────────────────────── collateral ─────────────────────────────

    function deposit(uint64 expiry, uint256 amount) external whenNotPaused nonReentrant {
        if (amount == 0) revert ZeroAmount();
        _activeSeries(expiry);
        uint256 total = totalCollateral + amount;
        if (total > maxTotalCollateral) revert DepositCapExceeded();
        totalCollateral = total;
        _accounts[expiry][msg.sender].collateral += amount;
        collateralToken.safeTransferFrom(msg.sender, address(this), amount);
        emit Deposited(expiry, msg.sender, amount);
    }

    function withdraw(uint64 expiry, uint256 amount, address to) external nonReentrant {
        if (amount == 0) revert ZeroAmount();
        _checkRecipient(to);
        SeriesState storage s = _activeSeries(expiry);
        Account storage a = _accounts[expiry][msg.sender];
        if (a.collateral < amount) revert InsufficientCollateral();
        a.collateral -= amount;
        totalCollateral -= amount;

        _requireSolvent(a, _floor(s, expiry), s.indexHi);

        collateralToken.safeTransfer(to, amount);
        emit Withdrawn(expiry, msg.sender, to, amount);
    }

    // ───────────────────────────── trading ─────────────────────────────

    function place(
        uint64 expiry,
        Side side,
        uint16 tick,
        uint128 notional,
        bool postOnly,
        uint64 goodTill
    ) external whenNotPaused nonReentrant returns (uint64 orderId, uint128 filled) {
        if (tick > maxTick) revert InvalidTick();
        if (goodTill != 0 && goodTill < block.timestamp + MIN_ORDER_LIFETIME) revert InvalidGoodTill();
        (SeriesState storage s, TradeContext memory ctx) = _tradeContext(expiry);
        // The upper bound keeps an order priced where it needs no lock from swelling its level.
        if (notional < minOrderNotional || notional > s.maxOpenInterest) revert InvalidNotional();

        Side opposite = _opposite(side);
        bool crossing = _crosses(expiry, opposite, tick);
        if (crossing) {
            if (postOnly) revert WouldCross();
            filled = _match(s, ctx, side, tick, notional, MAX_FILLS);
            // A walk that ran out of fills or visits can leave orders the remainder would cross.
            crossing = filled < notional && _crosses(expiry, opposite, tick);
        }

        Account storage a = _accounts[expiry][msg.sender];
        uint128 rest = notional - filled;
        if (!crossing && rest >= minOrderNotional) orderId = _rest(ctx, a, side, tick, rest, goodTill);
        _requireSolvent(a, ctx.lo, ctx.hi);
    }

    /// @param minFilled Reverts unless at least this much fills, so a book that moved before the
    ///        transaction landed cannot leave the caller with less than they meant to trade.
    function take(
        uint64 expiry,
        Side side,
        uint16 limitTick,
        uint128 notional,
        uint128 minFilled,
        uint256 maxFills
    ) external whenNotPaused nonReentrant returns (uint128 filled) {
        if (limitTick > maxTick) revert InvalidTick();
        // Below the minimum, a taker could cancel a resting order as dust without really trading.
        if (notional < minOrderNotional) revert InvalidNotional();
        if (maxFills == 0 || maxFills > MAX_FILLS) revert InvalidMaxFills();
        (SeriesState storage s, TradeContext memory ctx) = _tradeContext(expiry);
        filled = _match(s, ctx, side, limitTick, notional, maxFills);
        if (filled < minFilled) revert FillBelowMinimum();
        _requireSolvent(_accounts[expiry][msg.sender], ctx.lo, ctx.hi);
    }

    function cancel(uint64[] calldata orderIds) external nonReentrant {
        for (uint256 i; i < orderIds.length; ++i) {
            Order storage o = _orders[orderIds[i]];
            if (o.owner == address(0)) revert UnknownOrder();
            if (o.owner != msg.sender) revert NotOrderOwner();
            _cancel(orderIds[i], o, CancelReason.USER);
        }
    }

    /// @notice Removes resting orders that have expired, releasing their owners' margin. Anyone may
    ///         call it: an expired order only uses up takers' visits and blocks post-only orders that
    ///         would cross it. Ids that are gone or still live are skipped, so a batch built from a
    ///         slightly stale view never reverts.
    function cleanExpired(uint64[] calldata orderIds) external nonReentrant returns (uint256 removed) {
        for (uint256 i; i < orderIds.length; ++i) {
            Order storage o = _orders[orderIds[i]];
            if (o.owner == address(0) || o.goodTill == 0 || block.timestamp <= o.goodTill) continue;
            _cancel(orderIds[i], o, CancelReason.EXPIRED);
            ++removed;
        }
    }

    function collectFees() external nonReentrant returns (uint256 amount) {
        amount = treasuryAccrued;
        if (amount == 0) revert ZeroAmount();
        treasuryAccrued = 0;
        totalCollateral -= amount;
        collateralToken.safeTransfer(treasury, amount);
        emit FeesCollected(treasury, amount);
    }

    // ───────────────────────────── admin ─────────────────────────────
    // Series parameters are snapshotted when a series opens; changes reach only later series,
    // except `raiseSeriesOpenInterest`. The deposit cap is global and applies at once.

    function setFees(uint64 takerFeeRate_, uint64 makerRebateRate_) external onlyOwner {
        _checkFees(takerFeeRate_, makerRebateRate_);
        takerFeeRate = takerFeeRate_;
        makerRebateRate = makerRebateRate_;
        emit FeesSet(takerFeeRate_, makerRebateRate_);
    }

    function setMaxOpenInterest(uint128 maxOpenInterest_) external onlyOwner {
        maxOpenInterest = maxOpenInterest_;
        emit MaxOpenInterestSet(maxOpenInterest_);
    }

    /// @notice Raises a live series' open-interest cap, e.g. after offsetting accounts filled it.
    ///         Raise-only, so orders resting under the old cap stay valid.
    function raiseSeriesOpenInterest(uint64 expiry, uint128 maxOpenInterest_) external onlyOwner {
        SeriesState storage s = _activeSeries(expiry);
        if (maxOpenInterest_ <= s.maxOpenInterest) revert OpenInterestNotRaised();
        s.maxOpenInterest = maxOpenInterest_;
        emit SeriesOpenInterestRaised(expiry, maxOpenInterest_);
    }

    /// @notice Caps `totalCollateral`. Lowering it below the current total only stops deposits.
    function setMaxTotalCollateral(uint128 maxTotalCollateral_) external onlyOwner {
        maxTotalCollateral = maxTotalCollateral_;
        emit MaxTotalCollateralSet(maxTotalCollateral_);
    }

    function setBandHalfWidth(uint64 bandHalfWidth_) external onlyOwner {
        _checkBand(bandHalfWidth_);
        bandHalfWidth = bandHalfWidth_;
        emit BandHalfWidthSet(bandHalfWidth_);
    }

    function setTreasury(address treasury_) external onlyOwner {
        _checkRecipient(treasury_);
        treasury = treasury_;
        emit TreasurySet(treasury_);
    }

    /// @notice Stops opening series, placing, taking and new collateral (deposits, claims into
    ///         another series). Cancels, cleaning expired orders, withdrawals, settlement and claims to
    ///         a wallet are never paused.
    function pause() external onlyOwner {
        _pause();
    }

    function unpause() external onlyOwner {
        _unpause();
    }

    /// @notice Disabled: a book without an owner could never be unpaused or have its caps changed.
    ///         Hand it over with `transferOwnership` and `acceptOwnership` instead.
    function renounceOwnership() public pure override {
        revert RenounceDisabled();
    }

    // ───────────────────────────── views ─────────────────────────────

    function getAccount(uint64 expiry, address account) external view returns (Account memory) {
        return _accounts[expiry][account];
    }

    function getOrder(uint64 orderId) external view returns (Order memory) {
        return _orders[orderId];
    }

    function getLevel(
        uint64 expiry,
        Side side,
        uint16 tick
    ) external view returns (uint64 head, uint64 tail, uint128 total, bool active) {
        Level storage l = _levels[expiry][_levelKey(side, tick)];
        return (l.head, l.tail, l.total, TickBitmap.isSet(_bitmap[expiry], uint256(side) << 8, tick));
    }

    /// @notice Best resting price on `side`: the highest bid (PAY_FIXED) or lowest ask (RECEIVE_FIXED).
    function bestTick(uint64 expiry, Side side) external view returns (bool found, uint16 tick, uint128 total) {
        (found, tick) = side == Side.RECEIVE_FIXED
            ? TickBitmap.nextAtOrAbove(_bitmap[expiry], uint256(side) << 8, 0, maxTick)
            : TickBitmap.nextAtOrBelow(_bitmap[expiry], uint256(side) << 8, maxTick, 0);
        if (found) total = _levels[expiry][_levelKey(side, tick)].total;
    }

    /// @notice Collateral the account's position needs now, and what is free to withdraw once its
    ///         resting orders are covered too.
    function requiredCollateral(uint64 expiry, address account) external view returns (uint256 required, uint256 free) {
        uint256 used;
        (required, used) = _margins(expiry, account);
        uint256 collateral = _accounts[expiry][account].collateral;
        free = collateral > used ? collateral - used : 0;
    }

    /// @notice Collateral the account must hold: its position's worst case with any combination of
    ///         its resting orders filled.
    function marginUsed(uint64 expiry, address account) external view returns (uint256 used) {
        (, used) = _margins(expiry, account);
    }

    /// @notice Collateral a resting order of this size would need if placed now by an account with no
    ///         position or other orders. Against a position it can need less: one that reduces the
    ///         position adds little or nothing.
    function previewLock(uint64 expiry, Side side, uint16 tick, uint128 notional) external view returns (uint128) {
        SeriesState storage s = _series[expiry];
        if (s.openedAt == 0) revert SeriesNotOpen();
        (uint256 index, uint256 lo, uint256 tau) = _previewTerms(s, expiry);
        TradeContext memory ctx = TradeContext({
            expiry: expiry,
            index: index,
            lo: lo,
            hi: s.indexHi,
            tau: tau,
            takerFeeRate: s.takerFeeRate,
            makerRebateRate: s.makerRebateRate
        });
        (uint128 lossLo, uint128 lossHi) = _orderLosses(ctx, side, tick, notional);
        return lossLo > lossHi ? lossLo : lossHi;
    }

    // ───────────────────────────── hooks ─────────────────────────────

    /// @dev The index, lowest reachable settlement index and accrual time a trade now uses, after
    ///      the book's own checks on the index. May record what settlement must respect.
    function _tradeTerms(
        SeriesState storage s,
        uint64 expiry
    ) internal virtual returns (uint256 index, uint256 lo, uint256 tau);

    /// @dev The same terms for a read-only preview.
    function _previewTerms(
        SeriesState storage s,
        uint64 expiry
    ) internal view virtual returns (uint256 index, uint256 lo, uint256 tau);

    /// @dev Lowest reachable settlement index for a withdrawal; may record an observation.
    function _floor(SeriesState storage s, uint64 expiry) internal virtual returns (uint256);

    function _floorView(SeriesState storage s, uint64 expiry) internal view virtual returns (uint256);

    /// @dev Legs of a fill of `notional` at `tick`: at settlement index I the receive-fixed side is
    ///      paid `fixedLeg - units * I / UNIT_SCALE` and the pay-fixed side the negation.
    function _legs(
        TradeContext memory ctx,
        uint16 tick,
        uint256 notional
    ) internal view virtual returns (uint256 fixedLeg, uint256 units);

    /// @dev Notional, in collateral-token units, that `units` index units stand for at `index`.
    function _notionalOf(uint256 units, uint256 index) internal pure virtual returns (uint256);

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

    // ───────────────────────────── series internals ─────────────────────────────

    /// @dev Opening checks and the parameters a series snapshots; the book then fixes its band.
    function _openSeries(uint64 expiry) internal returns (SeriesState storage s) {
        s = _series[expiry];
        if (s.openedAt != 0) revert SeriesExists();
        if (expiry < expiryOffset || (expiry - expiryOffset) % seriesSpacing != 0) revert MisalignedExpiry();
        if (block.timestamp + seriesLength < expiry) revert SeriesNotOpenYet();
        if (block.timestamp + cutoff >= expiry) revert TradingClosed();
        s.openedAt = uint64(block.timestamp);
        s.takerFeeRate = takerFeeRate;
        s.makerRebateRate = makerRebateRate;
        s.maxOpenInterest = maxOpenInterest;
    }

    function _settle(SeriesState storage s, uint64 expiry, uint256 raw, bool fallbackUsed) internal {
        s.settlementIndex = M.clamp(raw, s.indexLo, s.indexHi);
        s.finalized = true;
        s.fallbackSettled = fallbackUsed;
        emit Finalized(expiry, raw, s.settlementIndex, fallbackUsed);
    }

    /// @dev Closes the caller's account in a finalized series: its collateral plus payout.
    function _settleAccount(uint64 expiry) internal returns (uint256 amount) {
        SeriesState storage s = _series[expiry];
        if (!s.finalized) revert SeriesNotFinalized();
        Account storage a = _accounts[expiry][msg.sender];
        if (a.claimed) revert AlreadyClaimed();

        int256 value = a.collateral.toInt256() + M.payoff(a.fixedCash, a.indexUnits, s.settlementIndex);
        if (value < 0) revert InsolventAccount();
        amount = uint256(value);

        // The loss sums stay: orders left resting can still be cancelled, which releases them.
        a.collateral = 0;
        a.fixedCash = 0;
        a.indexUnits = 0;
        a.claimed = true;
    }

    // ───────────────────────────── matching internals ─────────────────────────────

    /// @dev Walks the opposite side best-first, price then time, filling at each resting order's
    ///      tick. Stops after `maxFills` fills or `MAX_VISITS` orders visited, cancelled ones included.
    function _match(
        SeriesState storage s,
        TradeContext memory ctx,
        Side takerSide,
        uint16 limitTick,
        uint128 want,
        uint256 maxFills
    ) internal returns (uint128 filled) {
        Side makerSide = _opposite(takerSide);
        bool ascending = makerSide == Side.RECEIVE_FIXED;
        uint256 base = uint256(makerSide) << 8;
        mapping(uint256 => uint256) storage bitmap = _bitmap[ctx.expiry];
        uint256 unitsBefore = s.indexUnitsPos;
        uint256 fills;
        uint256 visits;
        uint256 cursor = ascending ? 0 : maxTick;

        while (filled < want && fills < maxFills && visits < MAX_VISITS) {
            (bool found, uint16 tick) = ascending
                ? TickBitmap.nextAtOrAbove(bitmap, base, cursor, limitTick)
                : TickBitmap.nextAtOrBelow(bitmap, base, cursor, limitTick);
            if (!found) break;
            cursor = tick;

            uint64 id = _levels[ctx.expiry][_levelKey(makerSide, tick)].head;
            while (id != 0 && filled < want && fills < maxFills && visits < MAX_VISITS) {
                ++visits;
                Order storage o = _orders[id];
                uint64 next = o.next;
                if (o.owner == msg.sender) {
                    _cancel(id, o, CancelReason.SELF_TRADE);
                } else if (o.goodTill != 0 && block.timestamp > o.goodTill) {
                    _cancel(id, o, CancelReason.EXPIRED);
                } else {
                    uint128 n = o.remaining < want - filled ? o.remaining : want - filled;
                    if (_fill(s, ctx, id, o, n)) {
                        filled += n;
                        ++fills;
                    }
                }
                id = next;
            }
        }

        if (s.indexUnitsPos > unitsBefore && _notionalOf(s.indexUnitsPos, ctx.index) > s.maxOpenInterest)
            revert OpenInterestCap();
    }

    /// @return filled False when the maker could not cover the fill and the order was cancelled.
    function _fill(
        SeriesState storage s,
        TradeContext memory ctx,
        uint64 id,
        Order storage o,
        uint128 n
    ) internal returns (bool filled) {
        Account storage maker = _accounts[ctx.expiry][o.owner];
        Account storage taker = _accounts[ctx.expiry][msg.sender];

        (uint256 fixedLeg, uint256 units) = _legs(ctx, o.tick, n);
        // The maker's deltas; the taker takes the negation.
        int256 dCash = o.side == Side.RECEIVE_FIXED ? fixedLeg.toInt256() : -fixedLeg.toInt256();
        int256 dUnits = o.side == Side.RECEIVE_FIXED ? -units.toInt256() : units.toInt256();

        // The filled share of the order's losses (rounded down, so what stays resting keeps at least
        // its share) comes off the maker's resting sums; the fill itself now sits in the position.
        (uint128 relLo, uint128 relHi) = n == o.remaining
            ? (o.lossLo, o.lossHi)
            : (uint128((uint256(o.lossLo) * n) / o.remaining), uint128((uint256(o.lossHi) * n) / o.remaining));
        uint256 rebate = M.accrual(n, ctx.makerRebateRate, ctx.tau, Math.Rounding.Floor);
        int256 makerCash = maker.fixedCash + dCash;
        int256 makerUnits = maker.indexUnits + dUnits;
        uint256 makerCollateral = maker.collateral + rebate;
        if (
            makerCollateral <
            M.requiredWithOrders(
                makerCash,
                makerUnits,
                ctx.lo,
                ctx.hi,
                maker.restingLossLo - relLo,
                maker.restingLossHi - relHi
            )
        ) {
            _cancel(id, o, CancelReason.UNDERFUNDED);
            return false;
        }

        uint256 fee = M.accrual(n, ctx.takerFeeRate, ctx.tau, Math.Rounding.Ceil);
        if (taker.collateral < fee) revert InsufficientCollateral();
        // Emitted before the writes below (none touch its values) so the legs leave the stack.
        emit Filled(
            id,
            ctx.expiry,
            o.owner,
            msg.sender,
            o.side,
            o.tick,
            n,
            ctx.index,
            fixedLeg,
            units,
            fee,
            rebate,
            relLo,
            relHi
        );
        int256 takerUnits = taker.indexUnits - dUnits;
        s.indexUnitsPos =
            s.indexUnitsPos -
            _positive(maker.indexUnits) -
            _positive(taker.indexUnits) +
            _positive(makerUnits) +
            _positive(takerUnits);

        maker.fixedCash = makerCash;
        maker.indexUnits = makerUnits;
        maker.collateral = makerCollateral;
        maker.restingLossLo -= relLo;
        maker.restingLossHi -= relHi;
        taker.fixedCash -= dCash;
        taker.indexUnits = takerUnits;
        taker.collateral -= fee;
        treasuryAccrued += fee - rebate;

        o.lossLo -= relLo;
        o.lossHi -= relHi;
        o.remaining -= n;
        _levels[ctx.expiry][_levelKey(o.side, o.tick)].total -= n;

        // A remainder under the minimum would only spend later takers' visits.
        if (o.remaining == 0) _removeOrder(id, o);
        else if (o.remaining < minOrderNotional) _cancel(id, o, CancelReason.DUST);
        return true;
    }

    function _rest(
        TradeContext memory ctx,
        Account storage a,
        Side side,
        uint16 tick,
        uint128 notional,
        uint64 goodTill
    ) internal returns (uint64 orderId) {
        (uint128 lossLo, uint128 lossHi) = _orderLosses(ctx, side, tick, notional);
        orderId = nextOrderId++;
        Order storage o = _orders[orderId];
        o.owner = msg.sender;
        o.expiry = ctx.expiry;
        o.tick = tick;
        o.side = side;
        o.goodTill = goodTill;
        o.remaining = notional;
        o.lossLo = lossLo;
        o.lossHi = lossHi;
        a.restingLossLo += lossLo;
        a.restingLossHi += lossHi;

        Level storage l = _levels[ctx.expiry][_levelKey(side, tick)];
        uint64 tail = l.tail;
        if (tail == 0) {
            l.head = orderId;
            TickBitmap.set(_bitmap[ctx.expiry], uint256(side) << 8, tick);
        } else {
            _orders[tail].next = orderId;
            o.prev = tail;
        }
        l.tail = orderId;
        l.total += notional;

        emit OrderPlaced(orderId, ctx.expiry, msg.sender, side, tick, notional, goodTill, lossLo, lossHi);
    }

    function _cancel(uint64 id, Order storage o, CancelReason reason) internal {
        Account storage a = _accounts[o.expiry][o.owner];
        a.restingLossLo -= o.lossLo;
        a.restingLossHi -= o.lossHi;
        emit OrderCancelled(id, o.expiry, o.owner, reason, o.remaining, o.lossLo, o.lossHi);
        _removeOrder(id, o);
    }

    function _removeOrder(uint64 id, Order storage o) internal {
        uint64 expiry = o.expiry;
        Level storage l = _levels[expiry][_levelKey(o.side, o.tick)];
        l.total -= o.remaining;
        uint64 prev = o.prev;
        uint64 next = o.next;
        if (prev == 0) l.head = next;
        else _orders[prev].next = next;
        if (next == 0) l.tail = prev;
        else _orders[next].prev = prev;
        if (l.head == 0) TickBitmap.clear(_bitmap[expiry], uint256(o.side) << 8, o.tick);
        delete _orders[id];
    }

    /// @dev What the order's fill, now at its own tick, would lose at each end of [lo, hi].
    function _orderLosses(
        TradeContext memory ctx,
        Side side,
        uint16 tick,
        uint128 notional
    ) internal view returns (uint128 lossLo, uint128 lossHi) {
        (uint256 fixedLeg, uint256 units) = _legs(ctx, tick, notional);
        int256 cash = side == Side.RECEIVE_FIXED ? fixedLeg.toInt256() : -fixedLeg.toInt256();
        int256 u = side == Side.RECEIVE_FIXED ? -units.toInt256() : units.toInt256();
        lossLo = M.lossAt(cash, u, ctx.lo).toUint128();
        lossHi = M.lossAt(cash, u, ctx.hi).toUint128();
    }

    function _crosses(uint64 expiry, Side restingSide, uint16 tick) internal view returns (bool found) {
        uint256 base = uint256(restingSide) << 8;
        (found, ) = restingSide == Side.RECEIVE_FIXED
            ? TickBitmap.nextAtOrAbove(_bitmap[expiry], base, 0, tick)
            : TickBitmap.nextAtOrBelow(_bitmap[expiry], base, maxTick, tick);
    }

    // ───────────────────────────── shared internals ─────────────────────────────

    function _tradeContext(uint64 expiry) internal returns (SeriesState storage s, TradeContext memory ctx) {
        s = _activeSeries(expiry);
        if (block.timestamp + cutoff >= expiry) revert TradingClosed();
        (uint256 index, uint256 lo, uint256 tau) = _tradeTerms(s, expiry);
        ctx = TradeContext({
            expiry: expiry,
            index: index,
            lo: lo,
            hi: s.indexHi,
            tau: tau,
            takerFeeRate: s.takerFeeRate,
            makerRebateRate: s.makerRebateRate
        });
    }

    function _activeSeries(uint64 expiry) internal view returns (SeriesState storage s) {
        s = _series[expiry];
        if (s.openedAt == 0) revert SeriesNotOpen();
        if (s.finalized) revert SeriesFinalized();
    }

    function _margins(uint64 expiry, address account) internal view returns (uint256 required, uint256 used) {
        SeriesState storage s = _series[expiry];
        Account storage a = _accounts[expiry][account];
        if (s.finalized) {
            // Nothing fills any more: only the position counts.
            required = M.required(a.fixedCash, a.indexUnits, s.settlementIndex, s.settlementIndex);
            return (required, required);
        }
        uint256 lo = _floorView(s, expiry);
        required = M.required(a.fixedCash, a.indexUnits, lo, s.indexHi);
        used = _required(a, lo, s.indexHi);
    }

    function _requireSolvent(Account storage a, uint256 lo, uint256 hi) internal view {
        if (a.collateral < _required(a, lo, hi)) revert InsufficientCollateral();
    }

    /// @dev Collateral the account needs: its position's worst case with any of its orders filled.
    function _required(Account storage a, uint256 lo, uint256 hi) internal view returns (uint256) {
        return M.requiredWithOrders(a.fixedCash, a.indexUnits, lo, hi, a.restingLossLo, a.restingLossHi);
    }

    /// @dev Tokens sent to the book itself would sit outside every account, with no way out.
    function _checkRecipient(address to) internal view {
        if (to == address(0)) revert ZeroAddress();
        if (to == address(this)) revert InvalidRecipient();
    }

    function _checkFees(uint64 takerFeeRate_, uint64 makerRebateRate_) internal pure {
        if (takerFeeRate_ > MAX_TAKER_FEE_RATE || makerRebateRate_ > takerFeeRate_) revert InvalidFees();
    }

    function _checkBand(uint64 bandHalfWidth_) internal pure {
        if (bandHalfWidth_ < MIN_BAND_HALF_WIDTH || bandHalfWidth_ > _maxBandHalfWidth()) {
            revert InvalidBandHalfWidth();
        }
    }

    function _opposite(Side side) internal pure returns (Side) {
        return side == Side.PAY_FIXED ? Side.RECEIVE_FIXED : Side.PAY_FIXED;
    }

    function _levelKey(Side side, uint16 tick) internal pure returns (uint256) {
        return (uint256(side) << 16) | tick;
    }

    function _positive(int256 x) internal pure returns (uint256) {
        return x > 0 ? uint256(x) : 0;
    }
}

contracts/rateorderbook/interfaces/ICappedOrderBook.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.34;

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

/// @title ICappedOrderBook
/// @notice What the capped rate books share: payouts follow a capped index (see CappedIndexMath)
///         instead of the source's own, and each observation narrows the series' settlement range
///         [indexLo, indexHi], so margin runs off as a series ages.
interface ICappedOrderBook is IRateOrderBookCore {
    /// @dev `indexOpen` is the source's index at opening; the other index values are the capped index
    ///      (RAY). [indexLo, indexHi] is the settlement range still reachable at the latest
    ///      observation; `indexUnitsPos` is the sum of positive account index units.
    struct Series {
        uint64 openedAt;
        bool finalized;
        bool fallbackSettled;
        uint64 takerFeeRate;
        uint64 makerRebateRate;
        uint128 maxOpenInterest;
        int256 bandCentre; // WAD per year
        uint256 indexOpen;
        uint256 indexLo;
        uint256 indexHi;
        uint256 settlementIndex; // the capped index at expiry
        uint256 indexUnitsPos;
    }

    /// @dev A series' capped index at its latest observation. `e`, the banks and their limit are
    ///      RAY; `lastIndex` is the source's index there, in the book's own index units.
    struct CappedIndex {
        uint64 lastTimestamp;
        int256 capRate; // WAD per year
        int256 floorRate; // WAD per year
        uint256 bankUp;
        uint256 bankDown;
        uint256 bankMax;
        uint256 lastIndex;
        uint256 e;
    }

    /// @param clipped Growth the observation did not count (negative where it counted more).
    event CappedIndexObserved(
        uint64 indexed expiry,
        uint64 timestamp,
        uint256 index,
        uint256 cappedIndex,
        uint256 bankUp,
        uint256 bankDown,
        uint256 indexLo,
        uint256 indexHi,
        int256 clipped
    );
    event BankDurationSet(uint32 bankDuration);

    error InvalidBankDuration();

    /// @notice Seconds of band width each bank may hold, snapshotted when a series opens.
    function bankDuration() external view returns (uint32);
    function setBankDuration(uint32 bankDuration_) external;
    function getSeries(uint64 expiry) external view returns (Series memory);
    function getCappedIndex(uint64 expiry) external view returns (CappedIndex memory);
    function openInterest(uint64 expiry) external view returns (uint256);
}

contracts/rateorderbook/interfaces/ICappedRateOrderBook.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.34;

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

/// @title ICappedRateOrderBook
/// @notice The capped rate book on a cumulative index (an Aave borrow index). Its events and errors
///         keep the rate book's signatures, so their topics and selectors are the same.
interface ICappedRateOrderBook is ICappedOrderBook {
    /// @param indexOpen The source's index at opening; the capped index starts at RAY.
    /// @param bandCentre WAD per year.
    event SeriesOpened(
        uint64 indexed expiry,
        uint256 indexOpen,
        uint256 indexLo,
        uint256 indexHi,
        uint256 bandCentre,
        uint64 takerFeeRate,
        uint64 makerRebateRate,
        uint128 maxOpenInterest
    );
    event Checkpoint(uint64 timestamp, uint256 index);

    error IndexUnavailable();
    error IndexRollback();
    error NoBandCheckpoint();
    error InvalidSeed();

    function poke() external returns (bool written);
    function pokeSeries(uint64 expiry) external;
    function latestCheckpoint() external view returns (uint64 timestamp, uint256 index);
}

contracts/rateorderbook/interfaces/ICumulativeIndexSource.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.34;

/// @notice The one call RateOrderBook makes to its rate source: a non-decreasing cumulative
///         index in RAY (1e27).
/// @dev Same signature as the deployed `CumulativeIndexBorrowAave` adapters, so one of those is
///      the source. Declared here so this module imports nothing from SwapCore.
interface ICumulativeIndexSource {
    function getCumulativeIndex() external view returns (uint256 cumulativeIndex, bool isValid);
}

contracts/rateorderbook/interfaces/IRateOrderBookCore.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.34;

/// @title IRateOrderBookCore
/// @notice What every rate order book shares: peer-to-peer fixed-vs-floating swaps on one index,
///         traded on an on-chain order book. Every swap in a series shares the series expiry; each
///         account's payout is linear in the clamped settlement index, and collateral always covers
///         its worst case, so nothing is ever liquidated. Each book defines its own index, how a fill
///         becomes legs, and how a series opens and settles.
interface IRateOrderBookCore {
    /// @dev PAY_FIXED pays the fixed rate and receives the floating leg (resting orders are bids:
    ///      the highest fixed rate they will pay). RECEIVE_FIXED is the reverse (resting orders are
    ///      asks: the lowest fixed rate they will accept).
    enum Side {
        PAY_FIXED,
        RECEIVE_FIXED
    }

    enum CancelReason {
        USER,
        EXPIRED,
        SELF_TRADE,
        UNDERFUNDED,
        DUST // a partial fill left less than the minimum order
    }

    struct Config {
        address indexSource;
        address collateralToken;
        address owner;
        address treasury;
        uint32 seriesLength; // seconds from a series' opening to its expiry
        uint32 seriesSpacing; // seconds between consecutive expiries
        uint32 expiryOffset; // expiries fall at expiryOffset + k * seriesSpacing (unix seconds)
        uint32 cutoff; // no trading in the last `cutoff` seconds before expiry
        uint64 tickSize; // WAD per year per tick
        uint16 maxTick;
        uint128 minOrderNotional; // collateral-token units
        uint64 takerFeeRate; // WAD per year, charged for the time to expiry
        uint64 makerRebateRate; // WAD per year, paid out of the taker fee
        uint128 maxOpenInterest; // collateral-token units of notional
        uint64 bandHalfWidth; // WAD per year
        uint128 maxTotalCollateral; // deposit cap, collateral-token units, across all series
    }

    /// @dev `fixedCash` and `indexUnits` encode the whole position: its payout at settlement
    ///      index I is `fixedCash + indexUnits * I / (WAD * RAY)`. `restingLossLo`/`restingLossHi`
    ///      add up what the account's resting orders would lose at each end of the reachable
    ///      settlement range if they filled (see `Order`). Collateral covers the position's payoff
    ///      at each end less that end's sum: the worst case of any combination of its orders filling.
    struct Account {
        uint256 collateral;
        int256 fixedCash;
        int256 indexUnits;
        uint128 restingLossLo;
        uint128 restingLossHi;
        bool claimed;
    }

    struct Order {
        address owner;
        uint64 expiry;
        uint16 tick;
        Side side;
        uint64 goodTill; // 0 = good until expiry; otherwise at least MIN_ORDER_LIFETIME after placing
        uint64 prev;
        uint64 next;
        uint128 remaining;
        // What the order's fill would lose at the low and high ends of the reachable settlement
        // range, valued when it was placed (0 where it would gain); a fill releases its share.
        uint128 lossLo;
        uint128 lossHi;
    }

    event Deposited(uint64 indexed expiry, address indexed account, uint256 amount);
    event Withdrawn(uint64 indexed expiry, address indexed account, address to, uint256 amount);
    event OrderPlaced(
        uint64 indexed orderId,
        uint64 indexed expiry,
        address indexed owner,
        Side side,
        uint16 tick,
        uint128 notional,
        uint64 goodTill,
        uint128 lossLo,
        uint128 lossHi
    );
    event OrderCancelled(
        uint64 indexed orderId,
        uint64 indexed expiry,
        address indexed owner,
        CancelReason reason,
        uint128 remaining,
        uint128 releasedLo, // the order's remaining losses, taken off its owner's resting sums
        uint128 releasedHi
    );
    event Filled(
        uint64 indexed orderId,
        uint64 indexed expiry,
        address indexed maker,
        address taker,
        Side makerSide,
        uint16 tick,
        uint128 notional,
        uint256 indexAtFill,
        uint256 fixedLeg,
        uint256 indexUnits,
        uint256 fee,
        uint256 rebate,
        uint128 releasedLo, // the filled part of the order's losses, taken off the maker's resting sums
        uint128 releasedHi
    );
    event Finalized(uint64 indexed expiry, uint256 rawIndex, uint256 settlementIndex, bool fallbackUsed);
    event Claimed(uint64 indexed expiry, address indexed account, address to, uint256 amount);
    event FeesCollected(address indexed treasury, uint256 amount);
    event FeesSet(uint64 takerFeeRate, uint64 makerRebateRate);
    event MaxOpenInterestSet(uint128 maxOpenInterest);
    event SeriesOpenInterestRaised(uint64 indexed expiry, uint128 maxOpenInterest);
    event MaxTotalCollateralSet(uint128 maxTotalCollateral);
    event BandHalfWidthSet(uint64 bandHalfWidth);
    event TreasurySet(address treasury);

    error InvalidConfig();
    error InvalidFees();
    error InvalidBandHalfWidth();
    error ZeroAddress();
    /// @dev A claim or withdrawal to the book itself, which would strand the tokens.
    error InvalidRecipient();
    /// @dev Ownership can be handed over (two steps) but never given up: pause and the caps need an owner.
    error RenounceDisabled();
    error ZeroAmount();
    error MisalignedExpiry();
    error SeriesExists();
    error SeriesNotOpenYet();
    error SeriesNotOpen();
    error SeriesFinalized();
    error SeriesNotFinalized();
    error TradingClosed();
    error NotExpired();
    error InvalidTick();
    error InvalidNotional();
    error InvalidGoodTill();
    error InvalidMaxFills();
    error WouldCross();
    error UnknownOrder();
    error NotOrderOwner();
    error InsufficientCollateral();
    error OpenInterestCap();
    error OpenInterestNotRaised();
    error DepositCapExceeded();
    error NoSettlementObservation();
    error AlreadyClaimed();
    error InsolventAccount();
    error FillBelowMinimum();

    function openSeries(uint64 expiry) external;
    function deposit(uint64 expiry, uint256 amount) external;
    function withdraw(uint64 expiry, uint256 amount, address to) external;
    function place(
        uint64 expiry,
        Side side,
        uint16 tick,
        uint128 notional,
        bool postOnly,
        uint64 goodTill
    ) external returns (uint64 orderId, uint128 filled);
    function take(
        uint64 expiry,
        Side side,
        uint16 limitTick,
        uint128 notional,
        uint128 minFilled,
        uint256 maxFills
    ) external returns (uint128 filled);
    function cancel(uint64[] calldata orderIds) external;
    function cleanExpired(uint64[] calldata orderIds) external returns (uint256 removed);
    function finalize(uint64 expiry) external;
    function claim(uint64 expiry, address to) external returns (uint256 amount);
    function claimInto(uint64 expiry, uint64 toExpiry) external returns (uint256 amount);
    function collectFees() external returns (uint256 amount);
}

contracts/rateorderbook/lib/CappedIndexMath.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.34;

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

/// @title CappedIndexMath
/// @notice The capped index of the capped rate books. Rates are signed WAD per year; the index, its
///         growth and the banks are RAY.
///
///         Step. An interval of `dt` seconds in which the source grew by `g` adds `g` to the index `e`,
///         clamped to [floorRate * dt - bankDown, capRate * dt + bankUp]. Allowance an interval leaves
///         unused on either side carries forward in that side's bank, up to `bankMax`, so a short
///         spike can draw on headroom the calmer intervals before it left.
///
///         Range. With `tau` left to expiry, the final index can only land in
///
///             [e + floorRate * tau - bankDown,  e + capRate * tau + bankUp],
///
///         and a step never widens it: what an interval counts above `capRate * dt` comes out of
///         `bankUp`, and what it leaves unused goes back into `bankUp` (capped), so the top cannot
///         rise; the bottom mirrors it. Cap terms round toward negative infinity and floor terms
///         toward positive infinity, so this holds exactly in integers:
///         floor(a) + floor(b) <= floor(a + b) and ceil(a) + ceil(b) >= ceil(a + b).
///
/// @dev Every function requires `capRate > floorRate`: the gap is then at least 1e9 / YEAR RAY a
///      second, so the rounded cap allowance of any interval is at least its rounded floor allowance.
library CappedIndexMath {
    using SafeCast for uint256;
    using SafeCast for int256;

    uint256 internal constant YEAR = 365 days;
    /// @dev A WAD-per-year rate accrues `rate * RATE_TO_RAY * dt / YEAR` RAY over `dt` seconds.
    uint256 internal constant RATE_TO_RAY = 1e9;

    /// @return e_ The index after the step.
    /// @return bankUp_ Unused headroom above the cap carried forward.
    /// @return bankDown_ Unused headroom below the floor carried forward.
    /// @return clipped Growth the step did not count (negative where it counted more than `g`).
    function step(
        uint256 e,
        uint256 bankUp,
        uint256 bankDown,
        int256 g,
        uint256 dt,
        int256 capRate,
        int256 floorRate,
        uint256 bankMax
    ) internal pure returns (uint256 e_, uint256 bankUp_, uint256 bankDown_, int256 clipped) {
        int256 up = bankUp.toInt256() + capTerm(capRate, dt);
        int256 down = floorTerm(floorRate, dt) - bankDown.toInt256();
        int256 inc = g > up
            ? up
            : g < down
                ? down
                : g;
        e_ = (e.toInt256() + inc).toUint256();
        bankUp_ = Math.min((up - inc).toUint256(), bankMax);
        bankDown_ = Math.min((inc - down).toUint256(), bankMax);
        clipped = g - inc;
    }

    /// @notice The settlement range still reachable from `e` and the banks with `tau` seconds left.
    function range(
        uint256 e,
        uint256 bankUp,
        uint256 bankDown,
        uint256 tau,
        int256 capRate,
        int256 floorRate
    ) internal pure returns (uint256 lo, uint256 hi) {
        int256 base = e.toInt256();
        lo = (base + floorTerm(floorRate, tau) - bankDown.toInt256()).toUint256();
        hi = (base + capTerm(capRate, tau) + bankUp.toInt256()).toUint256();
    }

    /// @notice A bank limit of `duration` seconds of `width` (WAD per year), in RAY.
    function bankLimit(uint256 width, uint256 duration) internal pure returns (uint256) {
        return Math.mulDiv(width, RATE_TO_RAY * duration, YEAR);
    }

    /// @notice `rate` accrued over `dt`, rounded toward negative infinity.
    function capTerm(int256 rate, uint256 dt) internal pure returns (int256) {
        return _accrue(rate, dt, false);
    }

    /// @notice `rate` accrued over `dt`, rounded toward positive infinity.
    function floorTerm(int256 rate, uint256 dt) internal pure returns (int256) {
        return _accrue(rate, dt, true);
    }

    function _accrue(int256 rate, uint256 dt, bool roundUp) private pure returns (int256) {
        // Rounding the magnitude up moves a positive value up and a negative one down.
        Math.Rounding rounding = (rate >= 0) == roundUp ? Math.Rounding.Ceil : Math.Rounding.Floor;
        int256 magnitude = Math.mulDiv(SignedMath.abs(rate), RATE_TO_RAY * dt, YEAR, rounding).toInt256();
        return rate >= 0 ? magnitude : -magnitude;
    }
}

contracts/rateorderbook/lib/RateOrderBookMath.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.34;

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

/// @title RateOrderBookMath
/// @notice Pure payoff, margin and fee math for RateOrderBook. Rates are WAD per year, indices RAY.
/// @dev A fill of notional N at fixed rate r, index I_e and time-to-expiry tau pays the
///      receive-fixed side, at settlement index I,
///
///          N*r*tau/YEAR - N*(I/I_e - 1)  =  fixedLeg - units*I/UNIT_SCALE,
///          fixedLeg = N + N*r*tau/YEAR,   units = N*UNIT_SCALE/I_e,
///
///      and the pay-fixed side the negation. Payouts are linear in I, so an account is the pair
///      (fixedCash, indexUnits) and its worst case over an index range sits at one end of it.
library RateOrderBookMath {
    uint256 internal constant WAD = 1e18;
    uint256 internal constant RAY = 1e27;
    uint256 internal constant YEAR = 365 days;
    /// @dev Index units carry WAD of extra precision over the collateral token's own decimals.
    uint256 internal constant UNIT_SCALE = WAD * RAY;

    function legs(
        uint256 notional,
        uint256 rate,
        uint256 tau,
        uint256 index
    ) internal pure returns (uint256 fixedLeg, uint256 units) {
        fixedLeg = notional + Math.mulDiv(notional, rate * tau, WAD * YEAR);
        units = Math.mulDiv(notional, UNIT_SCALE, index);
    }

    /// @notice Value of `units` at `index`, rounded toward negative infinity.
    function unitValue(int256 units, uint256 index) internal pure returns (int256) {
        if (units >= 0) return SafeCast.toInt256(Math.mulDiv(uint256(units), index, UNIT_SCALE));
        return -SafeCast.toInt256(Math.mulDiv(uint256(-units), index, UNIT_SCALE, Math.Rounding.Ceil));
    }

    function payoff(int256 fixedCash, int256 units, uint256 index) internal pure returns (int256) {
        return fixedCash + unitValue(units, index);
    }

    /// @notice Collateral needed to cover the position's worst payout for any settlement index in
    ///         [lo, hi]: rising payouts (units > 0) are worst at lo, falling ones at hi.
    function required(int256 fixedCash, int256 units, uint256 lo, uint256 hi) internal pure returns (uint256) {
        int256 worst = payoff(fixedCash, units, units >= 0 ? lo : hi);
        return worst >= 0 ? 0 : uint256(-worst);
    }

    /// @notice `required`, with resting orders that may fill: at each end of [lo, hi] the position's
    ///         payoff there less `lossLo`/`lossHi`, what the orders would lose there if they filled.
    function requiredWithOrders(
        int256 fixedCash,
        int256 units,
        uint256 lo,
        uint256 hi,
        uint256 lossLo,
        uint256 lossHi
    ) internal pure returns (uint256) {
        int256 atLo = payoff(fixedCash, units, lo) - SafeCast.toInt256(lossLo);
        int256 atHi = payoff(fixedCash, units, hi) - SafeCast.toInt256(lossHi);
        int256 worst = atLo < atHi ? atLo : atHi;
        return worst >= 0 ? 0 : uint256(-worst);
    }

    /// @notice What a position change loses at `index` (0 if it gains there).
    function lossAt(int256 fixedCash, int256 units, uint256 index) internal pure returns (uint256) {
        int256 p = payoff(fixedCash, units, index);
        return p >= 0 ? 0 : uint256(-p);
    }

    /// @notice `notional * rate * tau / YEAR`, for fees and rebates.
    function accrual(
        uint256 notional,
        uint256 rate,
        uint256 tau,
        Math.Rounding rounding
    ) internal pure returns (uint256) {
        return Math.mulDiv(notional, rate * tau, WAD * YEAR, rounding);
    }

    /// @notice `index` grown at `rate` simple interest over `dt` seconds.
    function grow(uint256 index, uint256 rate, uint256 dt) internal pure returns (uint256) {
        return index + Math.mulDiv(index, rate * dt, WAD * YEAR);
    }

    /// @notice Simple annualised rate implied by an index moving `fromIndex` -> `toIndex` over `dt`.
    function annualRate(uint256 fromIndex, uint256 toIndex, uint256 dt) internal pure returns (uint256) {
        return Math.mulDiv(toIndex - fromIndex, WAD * YEAR, fromIndex * dt);
    }

    /// @notice Linear interpolation of the index at `t`, with t0 <= t <= t1 and i0 <= i1.
    function interpolate(uint256 t0, uint256 i0, uint256 t1, uint256 i1, uint256 t) internal pure returns (uint256) {
        if (t1 == t0) return i1;
        return i0 + Math.mulDiv(i1 - i0, t - t0, t1 - t0);
    }

    function clamp(uint256 x, uint256 lo, uint256 hi) internal pure returns (uint256) {
        if (x < lo) return lo;
        if (x > hi) return hi;
        return x;
    }
}

contracts/rateorderbook/lib/SourceRead.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.34;

/// @title SourceRead
/// @notice A read of an index source that cannot revert in the caller. A `try` only catches a revert
///         inside the source: a source with no code, or return data too short to decode, reverts in
///         the caller instead, which would put a settlement fallback out of reach.
library SourceRead {
    /// @dev Staticcalls `source` with `data` and returns its first two return words. `ok` is false,
    ///      and both words zero, if the call fails or returns fewer than `size` bytes (32 or 64); a
    ///      one-word read leaves `b` unspecified. Only the two words are copied, whatever the source
    ///      returns. A flag is true only as the word 1.
    function words(
        address source,
        bytes memory data,
        uint256 size
    ) internal view returns (bool ok, uint256 a, uint256 b) {
        assembly ("memory-safe") {
            ok := staticcall(gas(), source, add(data, 0x20), mload(data), 0x00, 0x40)
            ok := and(ok, iszero(lt(returndatasize(), size)))
            if ok {
                a := mload(0x00)
                b := mload(0x20)
            }
        }
    }
}

contracts/rateorderbook/lib/TickBitmap.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.34;

import { LibBit } from "solady/src/utils/LibBit.sol";

/// @title TickBitmap
/// @notice One bit per price tick, 256 ticks per word, so the order book finds its next non-empty
///         level without walking empty ones. `base` keys an independent bitmap inside the same
///         mapping (one per book side).
library TickBitmap {
    function set(mapping(uint256 => uint256) storage words, uint256 base, uint16 tick) internal {
        words[base + (tick >> 8)] |= uint256(1) << (tick & 0xff);
    }

    function clear(mapping(uint256 => uint256) storage words, uint256 base, uint16 tick) internal {
        words[base + (tick >> 8)] &= ~(uint256(1) << (tick & 0xff));
    }

    function isSet(mapping(uint256 => uint256) storage words, uint256 base, uint16 tick) internal view returns (bool) {
        return words[base + (tick >> 8)] & (uint256(1) << (tick & 0xff)) != 0;
    }

    /// @notice Lowest set tick in [from, limit].
    function nextAtOrAbove(
        mapping(uint256 => uint256) storage words,
        uint256 base,
        uint256 from,
        uint256 limit
    ) internal view returns (bool found, uint16 tick) {
        if (from > limit) return (false, 0);
        uint256 wordPos = from >> 8;
        uint256 lastWord = limit >> 8;
        uint256 word = words[base + wordPos] & (type(uint256).max << (from & 0xff));
        while (true) {
            if (word != 0) {
                uint256 t = (wordPos << 8) | LibBit.ffs(word);
                if (t > limit) return (false, 0);
                return (true, uint16(t));
            }
            if (wordPos >= lastWord) return (false, 0);
            unchecked {
                ++wordPos;
            }
            word = words[base + wordPos];
        }
    }

    /// @notice Highest set tick in [limit, from].
    function nextAtOrBelow(
        mapping(uint256 => uint256) storage words,
        uint256 base,
        uint256 from,
        uint256 limit
    ) internal view returns (bool found, uint16 tick) {
        if (from < limit) return (false, 0);
        uint256 wordPos = from >> 8;
        uint256 firstWord = limit >> 8;
        uint256 word = words[base + wordPos] & (type(uint256).max >> (255 - (from & 0xff)));
        while (true) {
            if (word != 0) {
                uint256 t = (wordPos << 8) | LibBit.fls(word);
                if (t < limit) return (false, 0);
                return (true, uint16(t));
            }
            if (wordPos <= firstWord) return (false, 0);
            unchecked {
                --wordPos;
            }
            word = words[base + wordPos];
        }
    }
}

solady/src/utils/LibBit.sol

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

/// @notice Library for bit twiddling and boolean operations.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/LibBit.sol)
/// @author Inspired by (https://graphics.stanford.edu/~seander/bithacks.html)
library LibBit {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                  BIT TWIDDLING OPERATIONS                  */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Find last set.
    /// Returns the index of the most significant bit of `x`,
    /// counting from the least significant bit position.
    /// If `x` is zero, returns 256.
    function fls(uint256 x) internal pure returns (uint256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            r := or(shl(8, iszero(x)), shl(7, lt(0xffffffffffffffffffffffffffffffff, x)))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))
            // forgefmt: disable-next-item
            r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                0x0706060506020504060203020504030106050205030304010505030400000000))
        }
    }

    /// @dev Count leading zeros.
    /// Returns the number of zeros preceding the most significant one bit.
    /// If `x` is zero, returns 256.
    function clz(uint256 x) internal pure returns (uint256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))
            // forgefmt: disable-next-item
            r := add(xor(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                0xf8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff)), iszero(x))
        }
    }

    /// @dev Find first set.
    /// Returns the index of the least significant bit of `x`,
    /// counting from the least significant bit position.
    /// If `x` is zero, returns 256.
    /// Equivalent to `ctz` (count trailing zeros), which gives
    /// the number of zeros following the least significant one bit.
    function ffs(uint256 x) internal pure returns (uint256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            // Isolate the least significant bit.
            x := and(x, add(not(x), 1))
            // For the upper 3 bits of the result, use a De Bruijn-like lookup.
            // Credit to adhusson: https://blog.adhusson.com/cheap-find-first-set-evm/
            // forgefmt: disable-next-item
            r := shl(5, shr(252, shl(shl(2, shr(250, mul(x,
                0xb6db6db6ddddddddd34d34d349249249210842108c6318c639ce739cffffffff))),
                0x8040405543005266443200005020610674053026020000107506200176117077)))
            // For the lower 5 bits of the result, use a De Bruijn lookup.
            // forgefmt: disable-next-item
            r := or(r, byte(and(div(0xd76453e0, shr(r, x)), 0x1f),
                0x001f0d1e100c1d070f090b19131c1706010e11080a1a141802121b1503160405))
        }
    }

    /// @dev Returns the number of set bits in `x`.
    function popCount(uint256 x) internal pure returns (uint256 c) {
        /// @solidity memory-safe-assembly
        assembly {
            let max := not(0)
            let isMax := eq(x, max)
            x := sub(x, and(shr(1, x), div(max, 3)))
            x := add(and(x, div(max, 5)), and(shr(2, x), div(max, 5)))
            x := and(add(x, shr(4, x)), div(max, 17))
            c := or(shl(8, isMax), shr(248, mul(x, div(max, 255))))
        }
    }

    /// @dev Returns the number of zero bytes in `x`.
    /// To get the number of non-zero bytes, simply do `32 - countZeroBytes(x)`.
    function countZeroBytes(uint256 x) internal pure returns (uint256 c) {
        /// @solidity memory-safe-assembly
        assembly {
            let m := 0x7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f
            c := byte(0, mul(shr(7, not(m)), shr(7, not(or(or(add(and(x, m), m), x), m)))))
        }
    }

    /// @dev Returns the number of zero bytes in `s`.
    /// To get the number of non-zero bytes, simply do `s.length - countZeroBytes(s)`.
    function countZeroBytes(bytes memory s) internal pure returns (uint256 c) {
        /// @solidity memory-safe-assembly
        assembly {
            function czb(x_) -> _c {
                let _m := 0x7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f
                _c := shr(7, not(or(or(add(and(x_, _m), _m), x_), _m)))
                _c := byte(0, mul(shr(7, not(_m)), _c))
            }
            let n := mload(s)
            let l := shl(5, shr(5, n))
            s := add(s, 0x20)
            for { let i } xor(i, l) { i := add(i, 0x20) } { c := add(czb(mload(add(s, i))), c) }
            if lt(l, n) { c := add(czb(or(shr(shl(3, sub(n, l)), not(0)), mload(add(s, l)))), c) }
        }
    }

    /// @dev Returns the number of zero bytes in `s`.
    /// To get the number of non-zero bytes, simply do `s.length - countZeroBytes(s)`.
    function countZeroBytesCalldata(bytes calldata s) internal pure returns (uint256 c) {
        /// @solidity memory-safe-assembly
        assembly {
            function czb(x_) -> _c {
                let _m := 0x7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f
                _c := shr(7, not(or(or(add(and(x_, _m), _m), x_), _m)))
                _c := byte(0, mul(shr(7, not(_m)), _c))
            }
            let l := shl(5, shr(5, s.length))
            for { let i } xor(i, l) { i := add(i, 0x20) } {
                c := add(czb(calldataload(add(s.offset, i))), c)
            }
            if lt(l, s.length) {
                let m := shr(shl(3, sub(s.length, l)), not(0))
                c := add(czb(or(m, calldataload(add(s.offset, l)))), c)
            }
        }
    }

    /// @dev Returns whether `x` is a power of 2.
    function isPo2(uint256 x) internal pure returns (bool result) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to `x && !(x & (x - 1))`.
            result := iszero(add(and(x, sub(x, 1)), iszero(x)))
        }
    }

    /// @dev Returns `x` reversed at the bit level.
    function reverseBits(uint256 x) internal pure returns (uint256 r) {
        uint256 m0 = 0x0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f;
        uint256 m1 = m0 ^ (m0 << 2);
        uint256 m2 = m1 ^ (m1 << 1);
        r = reverseBytes(x);
        r = (m2 & (r >> 1)) | ((m2 & r) << 1);
        r = (m1 & (r >> 2)) | ((m1 & r) << 2);
        r = (m0 & (r >> 4)) | ((m0 & r) << 4);
    }

    /// @dev Returns `x` reversed at the byte level.
    function reverseBytes(uint256 x) internal pure returns (uint256 r) {
        unchecked {
            // Computing masks on-the-fly reduces bytecode size by about 200 bytes.
            uint256 m0 = 0x100000000000000000000000000000001 * (~toUint(x == uint256(0)) >> 192);
            uint256 m1 = m0 ^ (m0 << 32);
            uint256 m2 = m1 ^ (m1 << 16);
            uint256 m3 = m2 ^ (m2 << 8);
            r = (m3 & (x >> 8)) | ((m3 & x) << 8);
            r = (m2 & (r >> 16)) | ((m2 & r) << 16);
            r = (m1 & (r >> 32)) | ((m1 & r) << 32);
            r = (m0 & (r >> 64)) | ((m0 & r) << 64);
            r = (r >> 128) | (r << 128);
        }
    }

    /// @dev Returns the common prefix of `x` and `y` at the bit level.
    function commonBitPrefix(uint256 x, uint256 y) internal pure returns (uint256) {
        unchecked {
            uint256 s = 256 - clz(x ^ y);
            return (x >> s) << s;
        }
    }

    /// @dev Returns the common prefix of `x` and `y` at the nibble level.
    function commonNibblePrefix(uint256 x, uint256 y) internal pure returns (uint256) {
        unchecked {
            uint256 s = (64 - (clz(x ^ y) >> 2)) << 2;
            return (x >> s) << s;
        }
    }

    /// @dev Returns the common prefix of `x` and `y` at the byte level.
    function commonBytePrefix(uint256 x, uint256 y) internal pure returns (uint256) {
        unchecked {
            uint256 s = (32 - (clz(x ^ y) >> 3)) << 3;
            return (x >> s) << s;
        }
    }

    /// @dev hex"ABCD" -> hex"0A0B0C0D".
    function toNibbles(bytes memory s) internal pure returns (bytes memory result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := mload(0x40)
            let n := mload(s)
            mstore(result, add(n, n)) // Store the new length.
            s := add(s, 0x20)
            let o := add(result, 0x20)
            // forgefmt: disable-next-item
            for { let i := 0 } lt(i, n) { i := add(i, 0x10) } {
                let x := shr(128, mload(add(s, i)))
                x := and(0x0000000000000000ffffffffffffffff0000000000000000ffffffffffffffff, or(shl(64, x), x))
                x := and(0x00000000ffffffff00000000ffffffff00000000ffffffff00000000ffffffff, or(shl(32, x), x))
                x := and(0x0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff, or(shl(16, x), x))
                x := and(0x00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff, or(shl(8, x), x))
                mstore(add(o, add(i, i)),
                    and(0x0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f, or(shl(4, x), x)))
            }
            mstore(add(o, add(s, s)), 0) // Zeroize slot after result.
            mstore(0x40, add(0x40, add(o, add(s, s)))) // Allocate memory.
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                     BOOLEAN OPERATIONS                     */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    // A Solidity bool on the stack or memory is represented as a 256-bit word.
    // Non-zero values are true, zero is false.
    // A clean bool is either 0 (false) or 1 (true) under the hood.
    // Usually, if not always, the bool result of a regular Solidity expression,
    // or the argument of a public/external function will be a clean bool.
    // You can usually use the raw variants for more performance.
    // If uncertain, test (best with exact compiler settings).
    // Or use the non-raw variants (compiler can sometimes optimize out the double `iszero`s).

    /// @dev Returns `x & y`. Inputs must be clean.
    function rawAnd(bool x, bool y) internal pure returns (bool z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := and(x, y)
        }
    }

    /// @dev Returns `x & y`.
    function and(bool x, bool y) internal pure returns (bool z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := and(iszero(iszero(x)), iszero(iszero(y)))
        }
    }

    /// @dev Returns `w & x & y`.
    function and(bool w, bool x, bool y) internal pure returns (bool z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := iszero(or(iszero(w), or(iszero(x), iszero(y))))
        }
    }

    /// @dev Returns `v & w & x & y`.
    function and(bool v, bool w, bool x, bool y) internal pure returns (bool z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := iszero(or(or(iszero(v), iszero(w)), or(iszero(x), iszero(y))))
        }
    }

    /// @dev Returns `x | y`. Inputs must be clean.
    function rawOr(bool x, bool y) internal pure returns (bool z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := or(x, y)
        }
    }

    /// @dev Returns `x | y`.
    function or(bool x, bool y) internal pure returns (bool z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := iszero(iszero(or(x, y)))
        }
    }

    /// @dev Returns `w | x | y`.
    function or(bool w, bool x, bool y) internal pure returns (bool z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := iszero(iszero(or(w, or(x, y))))
        }
    }

    /// @dev Returns `v | w | x | y`.
    function or(bool v, bool w, bool x, bool y) internal pure returns (bool z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := iszero(iszero(or(v, or(w, or(x, y)))))
        }
    }

    /// @dev Returns 1 if `b` is true, else 0. Input must be clean.
    function rawToUint(bool b) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := b
        }
    }

    /// @dev Returns 1 if `b` is true, else 0.
    function toUint(bool b) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := iszero(iszero(b))
        }
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "useLiteralContent": true
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.